From 467586ff649949bb61c35cebcd30ce9a5867aa88 Mon Sep 17 00:00:00 2001 From: Guillaume Bernos Date: Tue, 21 Feb 2023 07:50:40 +0100 Subject: [PATCH 01/65] feat: integration of C++ desktop SDK --- .../firebase_core/firebase_core/.gitignore | 30 + .../firebase_core/firebase_core/.metadata | 30 + .../firebase_core/.vscode/settings.json | 3 + .../firebase_core/firebase_core/CHANGELOG.md | 3 + .../firebase_core/GoogleService-Info.plist | 38 + .../firebase_core/firebase_core/LICENSE | 1 + .../firebase_core/firebase_core/README.md | 15 + .../firebase_core/analysis_options.yaml | 4 + .../firebase_core/example/.gitignore | 44 + .../firebase_core/example/README.md | 16 + .../example/analysis_options.yaml | 29 + .../firebase_core/example/lib/main.dart | 63 + .../firebase_core/example/linux/.gitignore | 1 + .../example/linux/CMakeLists.txt | 150 +++ .../example/linux/flutter/CMakeLists.txt | 88 ++ .../flutter/generated_plugin_registrant.cc | 15 + .../flutter/generated_plugin_registrant.h | 15 + .../linux/flutter/generated_plugins.cmake | 24 + .../firebase_core/example/linux/main.cc | 6 + .../example/linux/my_application.cc | 104 ++ .../example/linux/my_application.h | 18 + .../firebase_core/example/pubspec.yaml | 83 ++ .../example/test/widget_test.dart | 27 + .../firebase_core/firebase/admob.h | 215 +++ .../firebase/admob/banner_view.h | 427 ++++++ .../firebase/admob/interstitial_ad.h | 259 ++++ .../firebase/admob/native_express_ad_view.h | 446 ++++++ .../firebase/admob/rewarded_video.h | 407 ++++++ .../firebase_core/firebase/admob/types.h | 244 ++++ .../firebase_core/firebase/analytics.h | 569 ++++++++ .../firebase/analytics/event_names.h | 472 +++++++ .../firebase/analytics/parameter_names.h | 755 +++++++++++ .../firebase/analytics/user_property_names.h | 50 + .../firebase_core/firebase/app.h | 787 +++++++++++ .../firebase_core/firebase/auth.h | 939 +++++++++++++ .../firebase_core/firebase/auth/credential.h | 633 +++++++++ .../firebase_core/firebase/auth/types.h | 473 +++++++ .../firebase_core/firebase/auth/user.h | 501 +++++++ .../firebase_core/firebase/database.h | 199 +++ .../firebase_core/firebase/database/common.h | 83 ++ .../firebase/database/data_snapshot.h | 205 +++ .../firebase/database/database_reference.h | 477 +++++++ .../firebase/database/disconnection.h | 156 +++ .../firebase/database/listener.h | 112 ++ .../firebase/database/mutable_data.h | 165 +++ .../firebase_core/firebase/database/query.h | 358 +++++ .../firebase/database/transaction.h | 102 ++ .../firebase_core/firebase/dynamic_links.h | 117 ++ .../firebase/dynamic_links/components.h | 336 +++++ .../firebase_core/firebase/firestore.h | 458 +++++++ .../firebase/firestore/collection_reference.h | 183 +++ .../firebase/firestore/document_change.h | 203 +++ .../firebase/firestore/document_reference.h | 351 +++++ .../firebase/firestore/document_snapshot.h | 297 ++++ .../firebase/firestore/field_path.h | 205 +++ .../firebase/firestore/field_value.h | 436 ++++++ .../firebase/firestore/firestore_errors.h | 116 ++ .../firebase/firestore/firestore_version.h | 29 + .../firebase/firestore/geo_point.h | 120 ++ .../firestore/listener_registration.h | 130 ++ .../firestore/load_bundle_task_progress.h | 101 ++ .../firebase/firestore/map_field_value.h | 37 + .../firebase/firestore/metadata_changes.h | 41 + .../firebase_core/firebase/firestore/query.h | 683 ++++++++++ .../firebase/firestore/query_snapshot.h | 194 +++ .../firebase/firestore/set_options.h | 161 +++ .../firebase/firestore/settings.h | 247 ++++ .../firebase/firestore/snapshot_metadata.h | 159 +++ .../firebase_core/firebase/firestore/source.h | 59 + .../firebase/firestore/timestamp.h | 252 ++++ .../firebase/firestore/transaction.h | 143 ++ .../firebase/firestore/transaction_options.h | 137 ++ .../firebase/firestore/write_batch.h | 188 +++ .../firebase_core/firebase/functions.h | 115 ++ .../firebase/functions/callable_reference.h | 124 ++ .../firebase/functions/callable_result.h | 96 ++ .../firebase_core/firebase/functions/common.h | 202 +++ .../firebase_core/firebase/future.h | 533 ++++++++ .../firebase_core/firebase/gma.h | 207 +++ .../firebase_core/firebase/gma/ad_view.h | 267 ++++ .../firebase/gma/interstitial_ad.h | 128 ++ .../firebase_core/firebase/gma/rewarded_ad.h | 152 +++ .../firebase_core/firebase/gma/types.h | 939 +++++++++++++ .../firebase_core/firebase/installations.h | 123 ++ .../firebase_core/firebase/internal/common.h | 128 ++ .../firebase/internal/future_impl.h | 359 +++++ .../firebase_core/firebase/internal/mutex.h | 100 ++ .../firebase/internal/platform.h | 110 ++ .../firebase/internal/type_traits.h | 134 ++ .../firebase_core/firebase/log.h | 54 + .../firebase_core/firebase/messaging.h | 728 ++++++++++ .../firebase_core/firebase/remote_config.h | 526 ++++++++ .../firebase_core/firebase/storage.h | 161 +++ .../firebase_core/firebase/storage/common.h | 62 + .../firebase/storage/controller.h | 146 ++ .../firebase_core/firebase/storage/listener.h | 74 + .../firebase_core/firebase/storage/metadata.h | 276 ++++ .../firebase/storage/storage_reference.h | 361 +++++ .../firebase_core/firebase/util.h | 101 ++ .../firebase_core/firebase/variant.h | 1197 +++++++++++++++++ .../firebase_core/firebase/version.h | 68 + .../generate_xml_from_google_services_json.py | 496 +++++++ .../firebase_core/generated_bindings.dart | 26 + .../google-services-desktop.json | 37 + .../firebase_core/lib/firebase_core.dart | 8 + .../lib/firebase_core_method_channel.dart | 17 + .../lib/firebase_core_platform_interface.dart | 29 + .../firebase_core/linux/CMakeLists.txt | 47 + .../linux/firebase_core_plugin.cc | 70 + .../firebase_core/firebase_core_plugin.h | 26 + .../firebase_core/firebase_core/pubspec.yaml | 34 + .../firebase_core_method_channel_test.dart | 24 + .../test/firebase_core_test.dart | 29 + 113 files changed, 23538 insertions(+) create mode 100644 packages/firebase_core/firebase_core/firebase_core/.gitignore create mode 100644 packages/firebase_core/firebase_core/firebase_core/.metadata create mode 100644 packages/firebase_core/firebase_core/firebase_core/.vscode/settings.json create mode 100644 packages/firebase_core/firebase_core/firebase_core/CHANGELOG.md create mode 100644 packages/firebase_core/firebase_core/firebase_core/GoogleService-Info.plist create mode 100644 packages/firebase_core/firebase_core/firebase_core/LICENSE create mode 100644 packages/firebase_core/firebase_core/firebase_core/README.md create mode 100644 packages/firebase_core/firebase_core/firebase_core/analysis_options.yaml create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/.gitignore create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/README.md create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/analysis_options.yaml create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/lib/main.dart create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/linux/.gitignore create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/linux/CMakeLists.txt create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/linux/flutter/CMakeLists.txt create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/linux/flutter/generated_plugin_registrant.cc create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/linux/flutter/generated_plugin_registrant.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/linux/flutter/generated_plugins.cmake create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/linux/main.cc create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/linux/my_application.cc create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/linux/my_application.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/pubspec.yaml create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/test/widget_test.dart create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/admob.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/admob/banner_view.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/admob/interstitial_ad.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/admob/native_express_ad_view.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/admob/rewarded_video.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/admob/types.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/analytics.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/analytics/event_names.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/analytics/parameter_names.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/analytics/user_property_names.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/app.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/auth.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/auth/credential.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/auth/types.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/auth/user.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/database.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/database/common.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/database/data_snapshot.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/database/database_reference.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/database/disconnection.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/database/listener.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/database/mutable_data.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/database/query.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/database/transaction.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/dynamic_links.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/dynamic_links/components.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/collection_reference.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/document_change.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/document_reference.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/document_snapshot.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/field_path.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/field_value.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/firestore_errors.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/firestore_version.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/geo_point.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/listener_registration.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/load_bundle_task_progress.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/map_field_value.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/metadata_changes.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/query.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/query_snapshot.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/set_options.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/settings.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/snapshot_metadata.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/source.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/timestamp.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/transaction.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/transaction_options.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/write_batch.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/functions.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/functions/callable_reference.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/functions/callable_result.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/functions/common.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/future.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/gma.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/gma/ad_view.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/gma/interstitial_ad.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/gma/rewarded_ad.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/gma/types.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/installations.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/internal/common.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/internal/future_impl.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/internal/mutex.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/internal/platform.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/internal/type_traits.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/log.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/messaging.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/remote_config.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/storage.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/storage/common.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/storage/controller.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/storage/listener.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/storage/metadata.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/storage/storage_reference.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/util.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/variant.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/version.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/generate_xml_from_google_services_json.py create mode 100644 packages/firebase_core/firebase_core/firebase_core/generated_bindings.dart create mode 100644 packages/firebase_core/firebase_core/firebase_core/google-services-desktop.json create mode 100644 packages/firebase_core/firebase_core/firebase_core/lib/firebase_core.dart create mode 100644 packages/firebase_core/firebase_core/firebase_core/lib/firebase_core_method_channel.dart create mode 100644 packages/firebase_core/firebase_core/firebase_core/lib/firebase_core_platform_interface.dart create mode 100644 packages/firebase_core/firebase_core/firebase_core/linux/CMakeLists.txt create mode 100644 packages/firebase_core/firebase_core/firebase_core/linux/firebase_core_plugin.cc create mode 100644 packages/firebase_core/firebase_core/firebase_core/linux/include/firebase_core/firebase_core_plugin.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/pubspec.yaml create mode 100644 packages/firebase_core/firebase_core/firebase_core/test/firebase_core_method_channel_test.dart create mode 100644 packages/firebase_core/firebase_core/firebase_core/test/firebase_core_test.dart diff --git a/packages/firebase_core/firebase_core/firebase_core/.gitignore b/packages/firebase_core/firebase_core/firebase_core/.gitignore new file mode 100644 index 000000000000..96486fd93024 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/.gitignore @@ -0,0 +1,30 @@ +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.buildlog/ +.history +.svn/ +migrate_working_dir/ + +# IntelliJ related +*.iml +*.ipr +*.iws +.idea/ + +# The .vscode folder contains launch configuration and tasks you configure in +# VS Code which you may wish to be included in version control, so this line +# is commented out by default. +#.vscode/ + +# Flutter/Dart/Pub related +# Libraries should not include pubspec.lock, per https://dart.dev/guides/libraries/private-files#pubspeclock. +/pubspec.lock +**/doc/api/ +.dart_tool/ +.packages +build/ diff --git a/packages/firebase_core/firebase_core/firebase_core/.metadata b/packages/firebase_core/firebase_core/firebase_core/.metadata new file mode 100644 index 000000000000..74867a0b132b --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/.metadata @@ -0,0 +1,30 @@ +# This file tracks properties of this Flutter project. +# Used by Flutter tool to assess capabilities and perform upgrades etc. +# +# This file should be version controlled. + +version: + revision: 9944297138845a94256f1cf37beb88ff9a8e811a + channel: stable + +project_type: plugin + +# Tracks metadata for the flutter migrate command +migration: + platforms: + - platform: root + create_revision: 9944297138845a94256f1cf37beb88ff9a8e811a + base_revision: 9944297138845a94256f1cf37beb88ff9a8e811a + - platform: linux + create_revision: 9944297138845a94256f1cf37beb88ff9a8e811a + base_revision: 9944297138845a94256f1cf37beb88ff9a8e811a + + # User provided section + + # List of Local paths (relative to this file) that should be + # ignored by the migrate tool. + # + # Files that are not part of the templates will be ignored by default. + unmanaged_files: + - 'lib/main.dart' + - 'ios/Runner.xcodeproj/project.pbxproj' diff --git a/packages/firebase_core/firebase_core/firebase_core/.vscode/settings.json b/packages/firebase_core/firebase_core/firebase_core/.vscode/settings.json new file mode 100644 index 000000000000..deec1e1d3994 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/.vscode/settings.json @@ -0,0 +1,3 @@ +{ + "cmake.sourceDirectory": "${workspaceFolder}/linux" +} diff --git a/packages/firebase_core/firebase_core/firebase_core/CHANGELOG.md b/packages/firebase_core/firebase_core/firebase_core/CHANGELOG.md new file mode 100644 index 000000000000..41cc7d8192ec --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/CHANGELOG.md @@ -0,0 +1,3 @@ +## 0.0.1 + +* TODO: Describe initial release. diff --git a/packages/firebase_core/firebase_core/firebase_core/GoogleService-Info.plist b/packages/firebase_core/firebase_core/firebase_core/GoogleService-Info.plist new file mode 100644 index 000000000000..f325ead98dbc --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/GoogleService-Info.plist @@ -0,0 +1,38 @@ + + + + + CLIENT_ID + 406099696497-134k3722m01rtrsklhf3b7k8sqa5r7in.apps.googleusercontent.com + REVERSED_CLIENT_ID + com.googleusercontent.apps.406099696497-134k3722m01rtrsklhf3b7k8sqa5r7in + ANDROID_CLIENT_ID + 406099696497-17qn06u8a0dc717u8ul7s49ampk13lul.apps.googleusercontent.com + API_KEY + AIzaSyDooSUGSf63Ghq02_iIhtnmwMDs4HlWS6c + GCM_SENDER_ID + 406099696497 + PLIST_VERSION + 1 + BUNDLE_ID + io.flutter.plugins.firebase.auth.example + PROJECT_ID + flutterfire-e2e-tests + STORAGE_BUCKET + flutterfire-e2e-tests.appspot.com + IS_ADS_ENABLED + + IS_ANALYTICS_ENABLED + + IS_APPINVITE_ENABLED + + IS_GCM_ENABLED + + IS_SIGNIN_ENABLED + + GOOGLE_APP_ID + 1:406099696497:ios:58cbc26aca8e5cf83574d0 + DATABASE_URL + https://flutterfire-e2e-tests-default-rtdb.europe-west1.firebasedatabase.app + + \ No newline at end of file diff --git a/packages/firebase_core/firebase_core/firebase_core/LICENSE b/packages/firebase_core/firebase_core/firebase_core/LICENSE new file mode 100644 index 000000000000..ba75c69f7f21 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/LICENSE @@ -0,0 +1 @@ +TODO: Add your license here. diff --git a/packages/firebase_core/firebase_core/firebase_core/README.md b/packages/firebase_core/firebase_core/firebase_core/README.md new file mode 100644 index 000000000000..b373aba55a5f --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/README.md @@ -0,0 +1,15 @@ +# firebase_core + +A new Flutter plugin project. + +## Getting Started + +This project is a starting point for a Flutter +[plug-in package](https://flutter.dev/developing-packages/), +a specialized package that includes platform-specific implementation code for +Android and/or iOS. + +For help getting started with Flutter development, view the +[online documentation](https://flutter.dev/docs), which offers tutorials, +samples, guidance on mobile development, and a full API reference. + diff --git a/packages/firebase_core/firebase_core/firebase_core/analysis_options.yaml b/packages/firebase_core/firebase_core/firebase_core/analysis_options.yaml new file mode 100644 index 000000000000..a5744c1cfbe7 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/analysis_options.yaml @@ -0,0 +1,4 @@ +include: package:flutter_lints/flutter.yaml + +# Additional information about this file can be found at +# https://dart.dev/guides/language/analysis-options diff --git a/packages/firebase_core/firebase_core/firebase_core/example/.gitignore b/packages/firebase_core/firebase_core/firebase_core/example/.gitignore new file mode 100644 index 000000000000..24476c5d1eb5 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/.gitignore @@ -0,0 +1,44 @@ +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.buildlog/ +.history +.svn/ +migrate_working_dir/ + +# IntelliJ related +*.iml +*.ipr +*.iws +.idea/ + +# The .vscode folder contains launch configuration and tasks you configure in +# VS Code which you may wish to be included in version control, so this line +# is commented out by default. +#.vscode/ + +# Flutter/Dart/Pub related +**/doc/api/ +**/ios/Flutter/.last_build_id +.dart_tool/ +.flutter-plugins +.flutter-plugins-dependencies +.packages +.pub-cache/ +.pub/ +/build/ + +# Symbolication related +app.*.symbols + +# Obfuscation related +app.*.map.json + +# Android Studio will place build artifacts here +/android/app/debug +/android/app/profile +/android/app/release diff --git a/packages/firebase_core/firebase_core/firebase_core/example/README.md b/packages/firebase_core/firebase_core/firebase_core/example/README.md new file mode 100644 index 000000000000..d1f452146bce --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/README.md @@ -0,0 +1,16 @@ +# firebase_core_example + +Demonstrates how to use the firebase_core plugin. + +## Getting Started + +This project is a starting point for a Flutter application. + +A few resources to get you started if this is your first Flutter project: + +- [Lab: Write your first Flutter app](https://docs.flutter.dev/get-started/codelab) +- [Cookbook: Useful Flutter samples](https://docs.flutter.dev/cookbook) + +For help getting started with Flutter development, view the +[online documentation](https://docs.flutter.dev/), which offers tutorials, +samples, guidance on mobile development, and a full API reference. diff --git a/packages/firebase_core/firebase_core/firebase_core/example/analysis_options.yaml b/packages/firebase_core/firebase_core/firebase_core/example/analysis_options.yaml new file mode 100644 index 000000000000..61b6c4de17c9 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/analysis_options.yaml @@ -0,0 +1,29 @@ +# This file configures the analyzer, which statically analyzes Dart code to +# check for errors, warnings, and lints. +# +# The issues identified by the analyzer are surfaced in the UI of Dart-enabled +# IDEs (https://dart.dev/tools#ides-and-editors). The analyzer can also be +# invoked from the command line by running `flutter analyze`. + +# The following line activates a set of recommended lints for Flutter apps, +# packages, and plugins designed to encourage good coding practices. +include: package:flutter_lints/flutter.yaml + +linter: + # The lint rules applied to this project can be customized in the + # section below to disable rules from the `package:flutter_lints/flutter.yaml` + # included above or to enable additional rules. A list of all available lints + # and their documentation is published at + # https://dart-lang.github.io/linter/lints/index.html. + # + # Instead of disabling a lint rule for the entire project in the + # section below, it can also be suppressed for a single line of code + # or a specific dart file by using the `// ignore: name_of_lint` and + # `// ignore_for_file: name_of_lint` syntax on the line or in the file + # producing the lint. + rules: + # avoid_print: false # Uncomment to disable the `avoid_print` rule + # prefer_single_quotes: true # Uncomment to enable the `prefer_single_quotes` rule + +# Additional information about this file can be found at +# https://dart.dev/guides/language/analysis-options diff --git a/packages/firebase_core/firebase_core/firebase_core/example/lib/main.dart b/packages/firebase_core/firebase_core/firebase_core/example/lib/main.dart new file mode 100644 index 000000000000..4e2b473ad9e0 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/lib/main.dart @@ -0,0 +1,63 @@ +import 'package:flutter/material.dart'; +import 'dart:async'; + +import 'package:flutter/services.dart'; +import 'package:firebase_core/firebase_core.dart'; + +void main() { + runApp(const MyApp()); +} + +class MyApp extends StatefulWidget { + const MyApp({super.key}); + + @override + State createState() => _MyAppState(); +} + +class _MyAppState extends State { + String _platformVersion = 'Unknown'; + final _firebaseCorePlugin = FirebaseCore(); + + @override + void initState() { + super.initState(); + initPlatformState(); + } + + // Platform messages are asynchronous, so we initialize in an async method. + Future initPlatformState() async { + String platformVersion; + // Platform messages may fail, so we use a try/catch PlatformException. + // We also handle the message potentially returning null. + try { + platformVersion = + await _firebaseCorePlugin.getPlatformVersion() ?? 'Unknown platform version'; + } on PlatformException { + platformVersion = 'Failed to get platform version.'; + } + + // If the widget was removed from the tree while the asynchronous platform + // message was in flight, we want to discard the reply rather than calling + // setState to update our non-existent appearance. + if (!mounted) return; + + setState(() { + _platformVersion = platformVersion; + }); + } + + @override + Widget build(BuildContext context) { + return MaterialApp( + home: Scaffold( + appBar: AppBar( + title: const Text('Plugin example app'), + ), + body: Center( + child: Text('Running on: $_platformVersion\n'), + ), + ), + ); + } +} diff --git a/packages/firebase_core/firebase_core/firebase_core/example/linux/.gitignore b/packages/firebase_core/firebase_core/firebase_core/example/linux/.gitignore new file mode 100644 index 000000000000..d3896c98444f --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/linux/.gitignore @@ -0,0 +1 @@ +flutter/ephemeral diff --git a/packages/firebase_core/firebase_core/firebase_core/example/linux/CMakeLists.txt b/packages/firebase_core/firebase_core/firebase_core/example/linux/CMakeLists.txt new file mode 100644 index 000000000000..9ae42276201e --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/linux/CMakeLists.txt @@ -0,0 +1,150 @@ +# Project-level configuration. +cmake_minimum_required(VERSION 3.10) +project(runner LANGUAGES CXX) + +# The name of the executable created for the application. Change this to change +# the on-disk name of your application. +set(BINARY_NAME "firebase_core_example") +# The unique GTK application identifier for this application. See: +# https://wiki.gnome.org/HowDoI/ChooseApplicationID +set(APPLICATION_ID "com.example.firebase_core") + +# Explicitly opt in to modern CMake behaviors to avoid warnings with recent +# versions of CMake. +cmake_policy(SET CMP0063 NEW) + +# Load bundled libraries from the lib/ directory relative to the binary. +set(CMAKE_INSTALL_RPATH "$ORIGIN/lib") + +# Root filesystem for cross-building. +if(FLUTTER_TARGET_PLATFORM_SYSROOT) + set(CMAKE_SYSROOT ${FLUTTER_TARGET_PLATFORM_SYSROOT}) + set(CMAKE_FIND_ROOT_PATH ${CMAKE_SYSROOT}) + set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) + set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY) + set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) + set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) +endif() + +# Define build configuration options. +if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) + set(CMAKE_BUILD_TYPE "Debug" CACHE + STRING "Flutter build mode" FORCE) + set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS + "Debug" "Profile" "Release") +endif() + +# Compilation settings that should be applied to most targets. +# +# Be cautious about adding new options here, as plugins use this function by +# default. In most cases, you should add new options to specific targets instead +# of modifying this function. +function(APPLY_STANDARD_SETTINGS TARGET) + target_compile_features(${TARGET} PUBLIC cxx_std_14) + target_compile_options(${TARGET} PRIVATE -Wall -Werror) + target_compile_options(${TARGET} PRIVATE "$<$>:-O3>") + target_compile_definitions(${TARGET} PRIVATE "$<$>:NDEBUG>") +endfunction() + +# Flutter library and tool build rules. +set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") +add_subdirectory(${FLUTTER_MANAGED_DIR}) + +# Add Firebase libraries to the target using the function from the SDK. +add_subdirectory(${FIREBASE_CPP_SDK_DIR} bin/ EXCLUDE_FROM_ALL) + +# The Firebase C++ library `firebase_app` is required, +# and it must always be listed last. + +# Add the Firebase SDKs for the products you want to use in your app +# For example, to use Firebase Authentication and Firebase Realtime Database +set(firebase_libs firebase_auth firebase_database firebase_app) +target_link_libraries(${target_name} "${firebase_libs}") + + +# System-level dependencies. +find_package(PkgConfig REQUIRED) +pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) + +add_definitions(-DAPPLICATION_ID="${APPLICATION_ID}") + +# Define the application target. To change its name, change BINARY_NAME above, +# not the value here, or `flutter run` will no longer work. +# +# Any new source files that you add to the application should be added here. +add_executable(${BINARY_NAME} + "main.cc" + "my_application.cc" + "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" +) + +# Apply the standard set of build settings. This can be removed for applications +# that need different build settings. +apply_standard_settings(${BINARY_NAME}) + +# Add dependency libraries. Add any application-specific dependencies here. +target_link_libraries(${BINARY_NAME} PRIVATE flutter) +target_link_libraries(${BINARY_NAME} PRIVATE PkgConfig::GTK) + +# Run the Flutter tool portions of the build. This must not be removed. +add_dependencies(${BINARY_NAME} flutter_assemble) + +# Only the install-generated bundle's copy of the executable will launch +# correctly, since the resources must in the right relative locations. To avoid +# people trying to run the unbundled copy, put it in a subdirectory instead of +# the default top-level location. +set_target_properties(${BINARY_NAME} + PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/intermediates_do_not_run" +) + +# Generated plugin build rules, which manage building the plugins and adding +# them to the application. +include(flutter/generated_plugins.cmake) + + +# === Installation === +# By default, "installing" just makes a relocatable bundle in the build +# directory. +set(BUILD_BUNDLE_DIR "${PROJECT_BINARY_DIR}/bundle") +if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) + set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) +endif() + +# Start with a clean build bundle directory every time. +install(CODE " + file(REMOVE_RECURSE \"${BUILD_BUNDLE_DIR}/\") + " COMPONENT Runtime) + +set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") +set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}/lib") + +install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +foreach(bundled_library ${PLUGIN_BUNDLED_LIBRARIES}) + install(FILES "${bundled_library}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endforeach(bundled_library) + +# Fully re-copy the assets directory on each build to avoid having stale files +# from a previous install. +set(FLUTTER_ASSET_DIR_NAME "flutter_assets") +install(CODE " + file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") + " COMPONENT Runtime) +install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" + DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) + +# Install the AOT library on non-Debug builds only. +if(NOT CMAKE_BUILD_TYPE MATCHES "Debug") + install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endif() diff --git a/packages/firebase_core/firebase_core/firebase_core/example/linux/flutter/CMakeLists.txt b/packages/firebase_core/firebase_core/firebase_core/example/linux/flutter/CMakeLists.txt new file mode 100644 index 000000000000..d5bd01648a96 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/linux/flutter/CMakeLists.txt @@ -0,0 +1,88 @@ +# This file controls Flutter-level build steps. It should not be edited. +cmake_minimum_required(VERSION 3.10) + +set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") + +# Configuration provided via flutter tool. +include(${EPHEMERAL_DIR}/generated_config.cmake) + +# TODO: Move the rest of this into files in ephemeral. See +# https://github.com/flutter/flutter/issues/57146. + +# Serves the same purpose as list(TRANSFORM ... PREPEND ...), +# which isn't available in 3.10. +function(list_prepend LIST_NAME PREFIX) + set(NEW_LIST "") + foreach(element ${${LIST_NAME}}) + list(APPEND NEW_LIST "${PREFIX}${element}") + endforeach(element) + set(${LIST_NAME} "${NEW_LIST}" PARENT_SCOPE) +endfunction() + +# === Flutter Library === +# System-level dependencies. +find_package(PkgConfig REQUIRED) +pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) +pkg_check_modules(GLIB REQUIRED IMPORTED_TARGET glib-2.0) +pkg_check_modules(GIO REQUIRED IMPORTED_TARGET gio-2.0) + +set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/libflutter_linux_gtk.so") + +# Published to parent scope for install step. +set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) +set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) +set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) +set(AOT_LIBRARY "${PROJECT_DIR}/build/lib/libapp.so" PARENT_SCOPE) + +list(APPEND FLUTTER_LIBRARY_HEADERS + "fl_basic_message_channel.h" + "fl_binary_codec.h" + "fl_binary_messenger.h" + "fl_dart_project.h" + "fl_engine.h" + "fl_json_message_codec.h" + "fl_json_method_codec.h" + "fl_message_codec.h" + "fl_method_call.h" + "fl_method_channel.h" + "fl_method_codec.h" + "fl_method_response.h" + "fl_plugin_registrar.h" + "fl_plugin_registry.h" + "fl_standard_message_codec.h" + "fl_standard_method_codec.h" + "fl_string_codec.h" + "fl_value.h" + "fl_view.h" + "flutter_linux.h" +) +list_prepend(FLUTTER_LIBRARY_HEADERS "${EPHEMERAL_DIR}/flutter_linux/") +add_library(flutter INTERFACE) +target_include_directories(flutter INTERFACE + "${EPHEMERAL_DIR}" +) +target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}") +target_link_libraries(flutter INTERFACE + PkgConfig::GTK + PkgConfig::GLIB + PkgConfig::GIO +) +add_dependencies(flutter flutter_assemble) + +# === Flutter tool backend === +# _phony_ is a non-existent file to force this command to run every time, +# since currently there's no way to get a full input/output list from the +# flutter tool. +add_custom_command( + OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} + ${CMAKE_CURRENT_BINARY_DIR}/_phony_ + COMMAND ${CMAKE_COMMAND} -E env + ${FLUTTER_TOOL_ENVIRONMENT} + "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.sh" + ${FLUTTER_TARGET_PLATFORM} ${CMAKE_BUILD_TYPE} + VERBATIM +) +add_custom_target(flutter_assemble DEPENDS + "${FLUTTER_LIBRARY}" + ${FLUTTER_LIBRARY_HEADERS} +) diff --git a/packages/firebase_core/firebase_core/firebase_core/example/linux/flutter/generated_plugin_registrant.cc b/packages/firebase_core/firebase_core/firebase_core/example/linux/flutter/generated_plugin_registrant.cc new file mode 100644 index 000000000000..15034725064f --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/linux/flutter/generated_plugin_registrant.cc @@ -0,0 +1,15 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#include "generated_plugin_registrant.h" + +#include + +void fl_register_plugins(FlPluginRegistry* registry) { + g_autoptr(FlPluginRegistrar) firebase_core_registrar = + fl_plugin_registry_get_registrar_for_plugin(registry, "FirebaseCorePlugin"); + firebase_core_plugin_register_with_registrar(firebase_core_registrar); +} diff --git a/packages/firebase_core/firebase_core/firebase_core/example/linux/flutter/generated_plugin_registrant.h b/packages/firebase_core/firebase_core/firebase_core/example/linux/flutter/generated_plugin_registrant.h new file mode 100644 index 000000000000..e0f0a47bc08f --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/linux/flutter/generated_plugin_registrant.h @@ -0,0 +1,15 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#ifndef GENERATED_PLUGIN_REGISTRANT_ +#define GENERATED_PLUGIN_REGISTRANT_ + +#include + +// Registers Flutter plugins. +void fl_register_plugins(FlPluginRegistry* registry); + +#endif // GENERATED_PLUGIN_REGISTRANT_ diff --git a/packages/firebase_core/firebase_core/firebase_core/example/linux/flutter/generated_plugins.cmake b/packages/firebase_core/firebase_core/firebase_core/example/linux/flutter/generated_plugins.cmake new file mode 100644 index 000000000000..1d55b5b0bf79 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/linux/flutter/generated_plugins.cmake @@ -0,0 +1,24 @@ +# +# Generated file, do not edit. +# + +list(APPEND FLUTTER_PLUGIN_LIST + firebase_core +) + +list(APPEND FLUTTER_FFI_PLUGIN_LIST +) + +set(PLUGIN_BUNDLED_LIBRARIES) + +foreach(plugin ${FLUTTER_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/linux plugins/${plugin}) + target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) + list(APPEND PLUGIN_BUNDLED_LIBRARIES $) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) +endforeach(plugin) + +foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/linux plugins/${ffi_plugin}) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries}) +endforeach(ffi_plugin) diff --git a/packages/firebase_core/firebase_core/firebase_core/example/linux/main.cc b/packages/firebase_core/firebase_core/firebase_core/example/linux/main.cc new file mode 100644 index 000000000000..e7c5c5437037 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/linux/main.cc @@ -0,0 +1,6 @@ +#include "my_application.h" + +int main(int argc, char** argv) { + g_autoptr(MyApplication) app = my_application_new(); + return g_application_run(G_APPLICATION(app), argc, argv); +} diff --git a/packages/firebase_core/firebase_core/firebase_core/example/linux/my_application.cc b/packages/firebase_core/firebase_core/firebase_core/example/linux/my_application.cc new file mode 100644 index 000000000000..b699538ff8ee --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/linux/my_application.cc @@ -0,0 +1,104 @@ +#include "my_application.h" + +#include +#ifdef GDK_WINDOWING_X11 +#include +#endif + +#include "flutter/generated_plugin_registrant.h" + +struct _MyApplication { + GtkApplication parent_instance; + char** dart_entrypoint_arguments; +}; + +G_DEFINE_TYPE(MyApplication, my_application, GTK_TYPE_APPLICATION) + +// Implements GApplication::activate. +static void my_application_activate(GApplication* application) { + MyApplication* self = MY_APPLICATION(application); + GtkWindow* window = + GTK_WINDOW(gtk_application_window_new(GTK_APPLICATION(application))); + + // Use a header bar when running in GNOME as this is the common style used + // by applications and is the setup most users will be using (e.g. Ubuntu + // desktop). + // If running on X and not using GNOME then just use a traditional title bar + // in case the window manager does more exotic layout, e.g. tiling. + // If running on Wayland assume the header bar will work (may need changing + // if future cases occur). + gboolean use_header_bar = TRUE; +#ifdef GDK_WINDOWING_X11 + GdkScreen* screen = gtk_window_get_screen(window); + if (GDK_IS_X11_SCREEN(screen)) { + const gchar* wm_name = gdk_x11_screen_get_window_manager_name(screen); + if (g_strcmp0(wm_name, "GNOME Shell") != 0) { + use_header_bar = FALSE; + } + } +#endif + if (use_header_bar) { + GtkHeaderBar* header_bar = GTK_HEADER_BAR(gtk_header_bar_new()); + gtk_widget_show(GTK_WIDGET(header_bar)); + gtk_header_bar_set_title(header_bar, "firebase_core_example"); + gtk_header_bar_set_show_close_button(header_bar, TRUE); + gtk_window_set_titlebar(window, GTK_WIDGET(header_bar)); + } else { + gtk_window_set_title(window, "firebase_core_example"); + } + + gtk_window_set_default_size(window, 1280, 720); + gtk_widget_show(GTK_WIDGET(window)); + + g_autoptr(FlDartProject) project = fl_dart_project_new(); + fl_dart_project_set_dart_entrypoint_arguments(project, self->dart_entrypoint_arguments); + + FlView* view = fl_view_new(project); + gtk_widget_show(GTK_WIDGET(view)); + gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(view)); + + fl_register_plugins(FL_PLUGIN_REGISTRY(view)); + + gtk_widget_grab_focus(GTK_WIDGET(view)); +} + +// Implements GApplication::local_command_line. +static gboolean my_application_local_command_line(GApplication* application, gchar*** arguments, int* exit_status) { + MyApplication* self = MY_APPLICATION(application); + // Strip out the first argument as it is the binary name. + self->dart_entrypoint_arguments = g_strdupv(*arguments + 1); + + g_autoptr(GError) error = nullptr; + if (!g_application_register(application, nullptr, &error)) { + g_warning("Failed to register: %s", error->message); + *exit_status = 1; + return TRUE; + } + + g_application_activate(application); + *exit_status = 0; + + return TRUE; +} + +// Implements GObject::dispose. +static void my_application_dispose(GObject* object) { + MyApplication* self = MY_APPLICATION(object); + g_clear_pointer(&self->dart_entrypoint_arguments, g_strfreev); + G_OBJECT_CLASS(my_application_parent_class)->dispose(object); +} + +static void my_application_class_init(MyApplicationClass* klass) { + G_APPLICATION_CLASS(klass)->activate = my_application_activate; + G_APPLICATION_CLASS(klass)->local_command_line = my_application_local_command_line; + G_OBJECT_CLASS(klass)->dispose = my_application_dispose; +} + +static void my_application_init(MyApplication* self) {} + +MyApplication* my_application_new() { + return MY_APPLICATION(g_object_new(my_application_get_type(), + "application-id", APPLICATION_ID, + "flags", G_APPLICATION_NON_UNIQUE, + nullptr)); +} diff --git a/packages/firebase_core/firebase_core/firebase_core/example/linux/my_application.h b/packages/firebase_core/firebase_core/firebase_core/example/linux/my_application.h new file mode 100644 index 000000000000..72271d5e4170 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/linux/my_application.h @@ -0,0 +1,18 @@ +#ifndef FLUTTER_MY_APPLICATION_H_ +#define FLUTTER_MY_APPLICATION_H_ + +#include + +G_DECLARE_FINAL_TYPE(MyApplication, my_application, MY, APPLICATION, + GtkApplication) + +/** + * my_application_new: + * + * Creates a new Flutter-based application. + * + * Returns: a new #MyApplication. + */ +MyApplication* my_application_new(); + +#endif // FLUTTER_MY_APPLICATION_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/example/pubspec.yaml b/packages/firebase_core/firebase_core/firebase_core/example/pubspec.yaml new file mode 100644 index 000000000000..dd3d2b2c7b7e --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/pubspec.yaml @@ -0,0 +1,83 @@ +name: firebase_core_example +description: Demonstrates how to use the firebase_core plugin. +# The following line prevents the package from being accidentally published to +# pub.dev using `flutter pub publish`. This is preferred for private packages. +publish_to: 'none' # Remove this line if you wish to publish to pub.dev + +environment: + sdk: '>=2.19.2 <3.0.0' + +# Dependencies specify other packages that your package needs in order to work. +# To automatically upgrade your package dependencies to the latest versions +# consider running `flutter pub upgrade --major-versions`. Alternatively, +# dependencies can be manually updated by changing the version numbers below to +# the latest version available on pub.dev. To see which dependencies have newer +# versions available, run `flutter pub outdated`. +dependencies: + flutter: + sdk: flutter + + firebase_core: + # When depending on this package from a real application you should use: + # firebase_core: ^x.y.z + # See https://dart.dev/tools/pub/dependencies#version-constraints + # The example app is bundled with the plugin so we use a path dependency on + # the parent directory to use the current plugin's version. + path: ../ + + # The following adds the Cupertino Icons font to your application. + # Use with the CupertinoIcons class for iOS style icons. + cupertino_icons: ^1.0.2 + +dev_dependencies: + flutter_test: + sdk: flutter + + # The "flutter_lints" package below contains a set of recommended lints to + # encourage good coding practices. The lint set provided by the package is + # activated in the `analysis_options.yaml` file located at the root of your + # package. See that file for information about deactivating specific lint + # rules and activating additional ones. + flutter_lints: ^2.0.0 + +# For information on the generic Dart part of this file, see the +# following page: https://dart.dev/tools/pub/pubspec + +# The following section is specific to Flutter packages. +flutter: + + # The following line ensures that the Material Icons font is + # included with your application, so that you can use the icons in + # the material Icons class. + uses-material-design: true + + # To add assets to your application, add an assets section, like this: + # assets: + # - images/a_dot_burr.jpeg + # - images/a_dot_ham.jpeg + + # An image asset can refer to one or more resolution-specific "variants", see + # https://flutter.dev/assets-and-images/#resolution-aware + + # For details regarding adding assets from package dependencies, see + # https://flutter.dev/assets-and-images/#from-packages + + # To add custom fonts to your application, add a fonts section here, + # in this "flutter" section. Each entry in this list should have a + # "family" key with the font family name, and a "fonts" key with a + # list giving the asset and other descriptors for the font. For + # example: + # fonts: + # - family: Schyler + # fonts: + # - asset: fonts/Schyler-Regular.ttf + # - asset: fonts/Schyler-Italic.ttf + # style: italic + # - family: Trajan Pro + # fonts: + # - asset: fonts/TrajanPro.ttf + # - asset: fonts/TrajanPro_Bold.ttf + # weight: 700 + # + # For details regarding fonts from package dependencies, + # see https://flutter.dev/custom-fonts/#from-packages diff --git a/packages/firebase_core/firebase_core/firebase_core/example/test/widget_test.dart b/packages/firebase_core/firebase_core/firebase_core/example/test/widget_test.dart new file mode 100644 index 000000000000..d343f68407e8 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/test/widget_test.dart @@ -0,0 +1,27 @@ +// This is a basic Flutter widget test. +// +// To perform an interaction with a widget in your test, use the WidgetTester +// utility in the flutter_test package. For example, you can send tap and scroll +// gestures. You can also use WidgetTester to find child widgets in the widget +// tree, read text, and verify that the values of widget properties are correct. + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'package:firebase_core_example/main.dart'; + +void main() { + testWidgets('Verify Platform version', (WidgetTester tester) async { + // Build our app and trigger a frame. + await tester.pumpWidget(const MyApp()); + + // Verify that platform version is retrieved. + expect( + find.byWidgetPredicate( + (Widget widget) => widget is Text && + widget.data!.startsWith('Running on:'), + ), + findsOneWidget, + ); + }); +} diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/admob.h b/packages/firebase_core/firebase_core/firebase_core/firebase/admob.h new file mode 100644 index 000000000000..957c86b7e168 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/admob.h @@ -0,0 +1,215 @@ +/* + * Copyright 2016 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_H_ +#define FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_H_ + +#include "firebase/internal/platform.h" + +#if FIREBASE_PLATFORM_ANDROID +#include +#endif // FIREBASE_PLATFORM_ANDROID + +#include "firebase/admob/banner_view.h" +#include "firebase/admob/interstitial_ad.h" +#include "firebase/admob/rewarded_video.h" +#include "firebase/admob/types.h" +#include "firebase/app.h" +#include "firebase/internal/common.h" + +#if !defined(DOXYGEN) && !defined(SWIG) +FIREBASE_APP_REGISTER_CALLBACKS_REFERENCE(admob) +#endif // !defined(DOXYGEN) && !defined(SWIG) + +namespace firebase { + +/// @deprecated The functionality in the firebase::admob namespace +/// has been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the new +/// SDK in our migration guide. +/// +/// @brief API for AdMob with Firebase. +/// +/// The AdMob API allows you to load and display mobile ads using the Google +/// Mobile Ads SDK. Each ad format has its own header file. +namespace admob { + +/// @deprecated +/// @brief Initializes AdMob via Firebase. +/// +/// The functionality in the firebase::admob namespace has +/// been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the +/// new SDK in our migration +/// guide. +/// +/// @param app The Firebase app for which to initialize mobile ads. +/// +/// @return kInitResultSuccess if initialization succeeded, or +/// kInitResultFailedMissingDependency on Android if Google Play services is not +/// available on the current device and the Google Mobile Ads SDK requires +/// Google Play services (for example, when using 'play-services-ads-lite'). +FIREBASE_DEPRECATED InitResult Initialize(const ::firebase::App& app); + +/// @deprecated +/// @brief Initializes AdMob via Firebase with the publisher's AdMob app ID. +/// +/// The functionality in the firebase::admob namespace has +/// been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the +/// new SDK in our migration +/// guide. +/// +/// Initializing the Google Mobile Ads SDK with the AdMob app ID at app launch +/// allows the SDK to fetch app-level settings and perform configuration tasks +/// as early as possible. This can help reduce latency for the initial ad +/// request. AdMob app IDs are unique identifiers given to mobile apps when +/// they're registered in the AdMob console. To find your app ID in the AdMob +/// console, click the App management (https://apps.admob.com/#account/appmgmt:) +/// option under the settings dropdown (located in the upper right-hand corner). +/// App IDs have the form ca-app-pub-XXXXXXXXXXXXXXXX~NNNNNNNNNN. +/// +/// @param[in] app The Firebase app for which to initialize mobile ads. +/// @param[in] admob_app_id The publisher's AdMob app ID. +/// +/// @return kInitResultSuccess if initialization succeeded, or +/// kInitResultFailedMissingDependency on Android if Google Play services is not +/// available on the current device and the Google Mobile Ads SDK requires +/// Google Play services (for example, when using 'play-services-ads-lite'). +FIREBASE_DEPRECATED InitResult Initialize(const ::firebase::App& app, + const char* admob_app_id); + +#if FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) +/// @deprecated +/// @brief Initializes AdMob without Firebase for Android. +/// +/// The functionality in the firebase::admob namespace has +/// been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the +/// new SDK in our migration +/// guide. +/// +/// The arguments to @ref Initialize are platform-specific so the caller must do +/// something like this: +/// @code +/// #if defined(__ANDROID__) +/// firebase::admob::Initialize(jni_env, activity); +/// #else +/// firebase::admob::Initialize(); +/// #endif +/// @endcode +/// +/// @param[in] jni_env JNIEnv pointer. +/// @param[in] activity Activity used to start the application. +/// +/// @return kInitResultSuccess if initialization succeeded, or +/// kInitResultFailedMissingDependency on Android if Google Play services is not +/// available on the current device and the AdMob SDK requires +/// Google Play services (for example when using 'play-services-ads-lite'). +FIREBASE_DEPRECATED InitResult Initialize(JNIEnv* jni_env, jobject activity); + +/// @deprecated +/// @brief Initializes AdMob via Firebase with the publisher's AdMob app ID. +/// +/// The functionality in the firebase::admob namespace has +/// been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the +/// new SDK in our migration +/// guide. +/// +/// Initializing the Google Mobile Ads SDK with the AdMob app ID at app launch +/// allows the SDK to fetch app-level settings and perform configuration tasks +/// as early as possible. This can help reduce latency for the initial ad +/// request. AdMob app IDs are unique identifiers given to mobile apps when +/// they're registered in the AdMob console. To find your app ID in the AdMob +/// console, click the App management (https://apps.admob.com/#account/appmgmt:) +/// option under the settings dropdown (located in the upper right-hand corner). +/// App IDs have the form ca-app-pub-XXXXXXXXXXXXXXXX~NNNNNNNNNN. +/// +/// The arguments to @ref Initialize are platform-specific so the caller must do +/// something like this: +/// @code +/// #if defined(__ANDROID__) +/// firebase::admob::Initialize(jni_env, activity, admob_app_id); +/// #else +/// firebase::admob::Initialize(admob_app_id); +/// #endif +/// @endcode +/// +/// @param[in] jni_env JNIEnv pointer. +/// @param[in] activity Activity used to start the application. +/// @param[in] admob_app_id The publisher's AdMob app ID. +/// +/// @return kInitResultSuccess if initialization succeeded, or +/// kInitResultFailedMissingDependency on Android if Google Play services is not +/// available on the current device and the AdMob SDK requires +/// Google Play services (for example when using 'play-services-ads-lite'). +FIREBASE_DEPRECATED InitResult Initialize(JNIEnv* jni_env, jobject activity, + const char* admob_app_id); +#endif // defined(__ANDROID__) || defined(DOXYGEN) +#if !FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) +/// @deprecated +/// @brief Initializes AdMob without Firebase for iOS. +/// +/// The functionality in the firebase::admob namespace has +/// been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the +/// new SDK in our migration +/// guide. +FIREBASE_DEPRECATED InitResult Initialize(); + +/// @deprecated +/// @brief Initializes AdMob with the publisher's AdMob app ID and without +/// Firebase for iOS. +/// +/// The functionality in the firebase::admob namespace has +/// been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the +/// new SDK in our migration +/// guide. +/// +/// Initializing the Google Mobile Ads SDK with the AdMob app ID at app launch +/// allows the SDK to fetch app-level settings and perform configuration tasks +/// as early as possible. This can help reduce latency for the initial ad +/// request. AdMob app IDs are unique identifiers given to mobile apps when +/// they're registered in the AdMob console. To find your app ID in the AdMob +/// console, click the App management (https://apps.admob.com/#account/appmgmt:) +/// option under the settings dropdown (located in the upper right-hand corner). +/// App IDs have the form ca-app-pub-XXXXXXXXXXXXXXXX~NNNNNNNNNN. +/// +/// @param[in] admob_app_id The publisher's AdMob app ID. +/// +/// @return kInitResultSuccess if initialization succeeded +FIREBASE_DEPRECATED InitResult Initialize(const char* admob_app_id); +#endif // !defined(__ANDROID__) || defined(DOXYGEN) + +/// @deprecated +/// @brief Terminate AdMob. +/// +/// The functionality in the firebase::admob namespace has +/// been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the +/// new SDK in our migration +/// guide. +/// +/// Frees resources associated with AdMob that were allocated during +/// @ref firebase::admob::Initialize(). +FIREBASE_DEPRECATED void Terminate(); + +} // namespace admob +} // namespace firebase + +#endif // FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/admob/banner_view.h b/packages/firebase_core/firebase_core/firebase_core/firebase/admob/banner_view.h new file mode 100644 index 000000000000..2d691f2d3a77 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/admob/banner_view.h @@ -0,0 +1,427 @@ +/* + * Copyright 2016 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_BANNER_VIEW_H_ +#define FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_BANNER_VIEW_H_ + +#include "firebase/admob/types.h" +#include "firebase/future.h" +#include "firebase/internal/common.h" + +namespace firebase { +namespace admob { + +namespace internal { +// Forward declaration for platform-specific data, implemented in each library. +class BannerViewInternal; +} // namespace internal + +/// @deprecated The functionality in the firebase::admob namespace +/// has been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the new +/// SDK in our migration guide. +/// +/// @brief Loads and displays AdMob banner ads. +/// +/// Each BannerView object corresponds to a single AdMob banner placement. There +/// are methods to load an ad, move it, show it and hide it, and retrieve the +/// bounds of the ad onscreen. +/// +/// BannerView objects maintain a presentation state that indicates whether +/// or not they're currently onscreen, as well as a set of bounds (stored in a +/// @ref BoundingBox struct), but otherwise provide information about +/// their current state through Futures. Methods like @ref Initialize, +/// @ref LoadAd, and @ref Hide each have a corresponding @ref Future from which +/// the result of the last call can be determined. The two variants of +/// @ref MoveTo share a single result @ref Future, since they're essentially the +/// same action. +/// +/// In addition, applications can create their own subclasses of +/// @ref BannerView::Listener, pass an instance to the @ref SetListener method, +/// and receive callbacks whenever the presentation state or bounding box of the +/// ad changes. +/// +/// For example, you could initialize, load, and show a banner view while +/// checking the result of the previous action at each step as follows: +/// +/// @code +/// namespace admob = ::firebase::admob; +/// admob::BannerView* banner_view = new admob::BannerView(); +/// banner_view->Initialize(ad_parent, "YOUR_AD_UNIT_ID", desired_ad_size) +/// @endcode +/// +/// Then, later: +/// +/// @code +/// if (banner_view->InitializeLastResult().status() == +/// ::firebase::kFutureStatusComplete && +/// banner_view->InitializeLastResult().error() == +/// firebase::admob::kAdMobErrorNone) { +/// banner_view->LoadAd(your_ad_request); +/// } +/// @endcode +/// +class BannerView { + public: +#ifdef INTERNAL_EXPERIMENTAL +// LINT.IfChange +#endif // INTERNAL_EXPERIMENTAL + /// @deprecated + /// @brief The presentation state of a @ref BannerView. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + enum PresentationState { + /// BannerView is currently hidden. + kPresentationStateHidden = 0, + /// BannerView is visible, but does not contain an ad. + kPresentationStateVisibleWithoutAd, + /// BannerView is visible and contains an ad. + kPresentationStateVisibleWithAd, + /// BannerView is visible and has opened a partial overlay on the screen. + kPresentationStateOpenedPartialOverlay, + /// BannerView is completely covering the screen or has caused focus to + /// leave the application (for example, when opening an external browser + /// during a clickthrough). + kPresentationStateCoveringUI, + }; +#ifdef INTERNAL_EXPERIMENTAL +// LINT.ThenChange(//depot_firebase_cpp/admob/client/cpp/src_java/com/google/firebase/admob/internal/cpp/ConstantsHelper.java) +#endif // INTERNAL_EXPERIMENTAL + +#ifdef INTERNAL_EXPERIMENTAL +// LINT.IfChange +#endif // INTERNAL_EXPERIMENTAL + /// @deprecated + /// @brief The possible screen positions for a @ref BannerView. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + enum Position { + /// Top of the screen, horizontally centered. + kPositionTop = 0, + /// Bottom of the screen, horizontally centered. + kPositionBottom, + /// Top-left corner of the screen. + kPositionTopLeft, + /// Top-right corner of the screen. + kPositionTopRight, + /// Bottom-left corner of the screen. + kPositionBottomLeft, + /// Bottom-right corner of the screen. + kPositionBottomRight, + }; +#ifdef INTERNAL_EXPERIMENTAL +// LINT.ThenChange(//depot_firebase_cpp/admob/client/cpp/src_java/com/google/firebase/admob/internal/cpp/ConstantsHelper.java) +#endif // INTERNAL_EXPERIMENTAL + + /// @deprecated + /// @brief A listener class that developers can extend and pass to a @ref + /// BannerView object's @ref SetListener method to be notified of changes to + /// the presentation state and bounding box. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + class Listener { + public: + /// @deprecated + /// @brief This method is called when the @ref BannerView object's + /// presentation state changes. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + /// @param[in] banner_view The banner view whose presentation state changed. + /// @param[in] state The new presentation state. + virtual void OnPresentationStateChanged(BannerView* banner_view, + PresentationState state) = 0; + /// @deprecated + /// @brief This method is called when the @ref BannerView object's bounding + /// box changes. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + /// @param[in] banner_view The banner view whose bounding box changed. + /// @param[in] box The new bounding box. + virtual void OnBoundingBoxChanged(BannerView* banner_view, + BoundingBox box) = 0; + virtual ~Listener(); + }; + + /// @deprecated + /// @brief Creates an uninitialized @ref BannerView object. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + /// + /// @ref Initialize must be called before the object is used. + FIREBASE_DEPRECATED BannerView(); + + ~BannerView(); + + /// @deprecated + /// @brief Initializes the @ref BannerView object. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + /// @param[in] parent The platform-specific UI element that will host the ad. + /// @param[in] ad_unit_id The ad unit ID to use when requesting ads. + /// @param[in] size The desired ad size for the banner. + FIREBASE_DEPRECATED Future Initialize(AdParent parent, + const char* ad_unit_id, + AdSize size); + + /// @deprecated + /// @brief Returns a @ref Future that has the status of the last call to + /// @ref Initialize. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + FIREBASE_DEPRECATED Future InitializeLastResult() const; + + /// @deprecated + /// @brief Begins an asynchronous request for an ad. If successful, the ad + /// will automatically be displayed in the BannerView. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + /// @param[in] request An AdRequest struct with information about the request + /// to be made (such as targeting info). + FIREBASE_DEPRECATED Future LoadAd(const AdRequest& request); + + /// @deprecated + /// @brief Returns a @ref Future containing the status of the last call to + /// @ref LoadAd. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + FIREBASE_DEPRECATED Future LoadAdLastResult() const; + + /// @deprecated + /// @brief Hides the BannerView. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + FIREBASE_DEPRECATED Future Hide(); + + /// @deprecated + /// @brief Returns a @ref Future containing the status of the last call to + /// @ref Hide. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + FIREBASE_DEPRECATED Future HideLastResult() const; + + /// @deprecated + /// @brief Shows the @ref BannerView. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + FIREBASE_DEPRECATED Future Show(); + + /// @deprecated + /// @brief Returns a @ref Future containing the status of the last call to + /// @ref Show. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + FIREBASE_DEPRECATED Future ShowLastResult() const; + + /// @deprecated + /// @brief Pauses the @ref BannerView. Should be called whenever the C++ + /// engine pauses or the application loses focus. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + FIREBASE_DEPRECATED Future Pause(); + + /// @deprecated + /// @brief Returns a @ref Future containing the status of the last call to + /// @ref Pause. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + FIREBASE_DEPRECATED Future PauseLastResult() const; + + /// @deprecated + /// @brief Resumes the @ref BannerView after pausing. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + FIREBASE_DEPRECATED Future Resume(); + + /// @deprecated + /// @brief Returns a @ref Future containing the status of the last call to + /// @ref Resume. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + FIREBASE_DEPRECATED Future ResumeLastResult() const; + + /// @deprecated + /// @brief Cleans up and deallocates any resources used by the @ref + /// BannerView. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + FIREBASE_DEPRECATED Future Destroy(); + + /// @deprecated + /// @brief Returns a @ref Future containing the status of the last call to + /// @ref Destroy. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + FIREBASE_DEPRECATED Future DestroyLastResult() const; + + /// @deprecated + /// @brief Moves the @ref BannerView so that its top-left corner is located at + /// (x, y). Coordinates are in pixels from the top-left corner of the screen. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + /// @param[in] x The desired horizontal coordinate. + /// @param[in] y The desired vertical coordinate. + FIREBASE_DEPRECATED Future MoveTo(int x, int y); + + /// @deprecated + /// @brief Moves the @ref BannerView so that it's located at the given + /// pre-defined position. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + /// @param[in] position The pre-defined position to which to move the + /// @ref BannerView. + FIREBASE_DEPRECATED Future MoveTo(Position position); + + /// @deprecated + /// @brief Returns a @ref Future containing the status of the last call to + /// either version of @ref MoveTo. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + FIREBASE_DEPRECATED Future MoveToLastResult() const; + + /// @deprecated + /// @brief Returns the current presentation state of the @ref BannerView. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + /// @return The current presentation state. + FIREBASE_DEPRECATED PresentationState presentation_state() const; + + /// @deprecated + /// @brief Retrieves the @ref BannerView's current onscreen size and location. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + FIREBASE_DEPRECATED BoundingBox bounding_box() const; + + /// @deprecated + /// @brief Sets the @ref Listener for this object. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + /// @param[in] listener A valid BannerView::Listener to receive callbacks. + FIREBASE_DEPRECATED void SetListener(Listener* listener); + + private: + // An internal, platform-specific implementation object that this class uses + // to interact with the Google Mobile Ads SDKs for iOS and Android. + internal::BannerViewInternal* internal_; +}; + +} // namespace admob +} // namespace firebase + +#endif // FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_BANNER_VIEW_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/admob/interstitial_ad.h b/packages/firebase_core/firebase_core/firebase_core/firebase/admob/interstitial_ad.h new file mode 100644 index 000000000000..b201ab7c3487 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/admob/interstitial_ad.h @@ -0,0 +1,259 @@ +/* + * Copyright 2016 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_INTERSTITIAL_AD_H_ +#define FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_INTERSTITIAL_AD_H_ + +#include "firebase/admob/types.h" +#include "firebase/future.h" +#include "firebase/internal/common.h" + +namespace firebase { +namespace admob { + +namespace internal { +// Forward declaration for platform-specific data, implemented in each library. +class InterstitialAdInternal; +} // namespace internal + +/// @deprecated The functionality in the firebase::admob namespace +/// has been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the new +/// SDK in our migration guide. +/// +/// @brief Loads and displays AdMob interstitial ads. +/// +/// @ref InterstitialAd is a single-use object that can load and show a +/// single AdMob interstitial ad. +/// +/// InterstitialAd objects maintain a presentation state that indicates whether +/// or not they're currently onscreen, but otherwise provide information about +/// their current state through Futures. @ref Initialize, @ref LoadAd, and +/// @ref Show each have a corresponding @ref Future from which you can determine +/// result of the previous call. +/// +/// In addition, applications can create their own subclasses of +/// @ref InterstitialAd::Listener, pass an instance to the @ref SetListener +/// method, and receive callbacks whenever the presentation state changes. +/// +/// Here's how one might initialize, load, and show an interstitial ad while +/// checking against the result of the previous action at each step: +/// +/// @code +/// namespace admob = ::firebase::admob; +/// admob::InterstitialAd* interstitial = new admob::InterstitialAd(); +/// interstitial->Initialize(ad_parent, "YOUR_AD_UNIT_ID") +/// @endcode +/// +/// Then, later: +/// +/// @code +/// if (interstitial->InitializeLastResult().status() == +/// ::firebase::kFutureStatusComplete && +/// interstitial->InitializeLastResult().error() == +/// firebase::admob::kAdMobErrorNone) { +/// interstitial->LoadAd(my_ad_request); +/// } +/// @endcode +/// +/// And after that: +/// +/// @code +/// if (interstitial->LoadAdLastResult().status() == +/// ::firebase::kFutureStatusComplete && +/// interstitial->LoadAdLastResult().error() == +/// firebase::admob::kAdMobErrorNone)) { +/// interstitial->Show(); +/// } +/// @endcode +/// +class InterstitialAd { + public: +#ifdef INTERNAL_EXPERIMENTAL +// LINT.IfChange +#endif // INTERNAL_EXPERIMENTAL + /// @deprecated + /// @brief The presentation states of an @ref InterstitialAd. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + enum PresentationState { + /// InterstitialAd is not currently being shown. + kPresentationStateHidden = 0, + /// InterstitialAd is being shown or has caused focus to leave the + /// application (for example, when opening an external browser during a + /// clickthrough). + kPresentationStateCoveringUI, + }; +#ifdef INTERNAL_EXPERIMENTAL +// LINT.ThenChange(//depot_firebase_cpp/admob/client/cpp/src_java/com/google/firebase/admob/internal/cpp/InterstitialAdHelper.java) +#endif // INTERNAL_EXPERIMENTAL + + /// @deprecated + /// @brief A listener class that developers can extend and pass to an + /// @ref InterstitialAd object's @ref SetListener method to be notified of + /// presentation state changes. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + /// @param[in] interstitial_ad The interstitial ad whose presentation state + /// changed. + /// @param[in] state The new presentation state. + virtual void OnPresentationStateChanged(InterstitialAd* interstitial_ad, + PresentationState state) = 0; + virtual ~Listener(); + }; + + /// @deprecated + /// @brief Creates an uninitialized @ref InterstitialAd object. + /// @ref Initialize must be called before the object is used. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + FIREBASE_DEPRECATED InterstitialAd(); + + ~InterstitialAd(); + + /// @deprecated + /// @brief Initialize the @ref InterstitialAd object. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + /// @param[in] parent The platform-specific UI element that will host the ad. + /// @param[in] ad_unit_id The ad unit ID to use in loading the ad. + FIREBASE_DEPRECATED Future Initialize(AdParent parent, + const char* ad_unit_id); + + /// @deprecated + /// @brief Returns a @ref Future containing the status of the last call to + /// @ref Initialize. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + FIREBASE_DEPRECATED Future InitializeLastResult() const; + + /// @deprecated + /// @brief Begins an asynchronous request for an ad. + /// + /// The @ref InterstitialAd::presentation_state method can be used to track + /// the progress of the request. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + /// @param[in] request An AdRequest struct with information about the request + /// to be made (such as targeting info). + FIREBASE_DEPRECATED Future LoadAd(const AdRequest& request); + + /// @deprecated + /// @brief Returns a @ref Future containing the status of the last call to + /// @ref LoadAd. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + FIREBASE_DEPRECATED Future LoadAdLastResult() const; + + /// @deprecated + /// @brief Shows the @ref InterstitialAd. This should not be called unless an + /// ad has already been loaded. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + FIREBASE_DEPRECATED Future Show(); + + /// @deprecated + /// @brief Returns a @ref Future containing the status of the last call to + /// @ref Show. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + FIREBASE_DEPRECATED Future ShowLastResult() const; + + /// @deprecated + /// @brief Returns the current presentation state of the @ref InterstitialAd. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + /// @return The current presentation state. + FIREBASE_DEPRECATED PresentationState presentation_state() const; + + /// @deprecated + /// @brief Sets the @ref Listener for this @ref InterstitialAd. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + /// @param[in] listener A valid InterstititalAd::Listener to receive + /// callbacks. + FIREBASE_DEPRECATED void SetListener(Listener* listener); + + private: + // An internal, platform-specific implementation object that this class uses + // to interact with the Google Mobile Ads SDKs for iOS and Android. + internal::InterstitialAdInternal* internal_; +}; + +} // namespace admob +} // namespace firebase + +#endif // FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_INTERSTITIAL_AD_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/admob/native_express_ad_view.h b/packages/firebase_core/firebase_core/firebase_core/firebase/admob/native_express_ad_view.h new file mode 100644 index 000000000000..7e571967825e --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/admob/native_express_ad_view.h @@ -0,0 +1,446 @@ +/* + * Copyright 2016 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_NATIVE_EXPRESS_AD_VIEW_H_ +#define FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_NATIVE_EXPRESS_AD_VIEW_H_ + +#include "firebase/admob/types.h" +#include "firebase/future.h" +#include "firebase/internal/common.h" + +namespace firebase { +namespace admob { + +namespace internal { +// Forward declaration for platform-specific data, implemented in each library. +class NativeExpressAdViewInternal; +} // namespace internal + +/// @deprecated The functionality in the firebase::admob namespace +/// has been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the new +/// SDK in our migration guide. +/// Native Express Ads has been discontinued, and are no longer served. +/// +/// @brief Loads and displays ads from AdMob Native Ads Express. +/// +/// Each NativeExpressAdView object corresponds to a single AdMob Native Express +/// ad placement. There are methods to load an ad, move it, show it and hide it, +/// and retrieve the bounds of the ad onscreen. +/// +/// NativeExpressAdView objects maintain a presentation state that indicates +/// whether or not they're currently onscreen, as well as a set of bounds +/// (stored in a @ref BoundingBox struct), but otherwise provide information +/// about their current state through Futures. Methods like @ref Initialize, +/// @ref LoadAd, and @ref Hide each have a corresponding @ref Future from which +/// the result of the last call can be determined. The two variants of +/// @ref MoveTo share a single result @ref Future, since they're essentially the +/// same action. +/// +/// In addition, applications can create their own subclasses of +/// @ref NativeExpressAdView::Listener, pass an instance to the @ref SetListener +/// method, and receive callbacks whenever the presentation state or bounding +/// box of the ad changes. +/// +/// For example, you could initialize, load, and show a native express ad view +/// while checking the result of the previous action at each step as follows: +/// +/// @code +/// namespace admob = ::firebase::admob; +/// admob::NativeExpressAdView* ad_view = new admob::NativeExpressAdView(); +/// ad_view->Initialize(ad_parent, "YOUR_AD_UNIT_ID", desired_ad_size) +/// @endcode +/// +/// Then, later: +/// +/// @code +/// if (ad_view->InitializeLastResult().Status() == +/// ::firebase::kFutureStatusComplete && +/// ad_view->InitializeLastResult().Error() == +/// firebase::admob::kAdMobErrorNone) { +/// ad_view->LoadAd(your_ad_request); +/// } +/// @endcode +class NativeExpressAdView { + public: +#ifdef INTERNAL_EXPERIMENTAL +// LINT.IfChange +#endif // INTERNAL_EXPERIMENTAL + /// @deprecated + /// @brief The presentation state of a @ref NativeExpressAdView. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + enum PresentationState { + /// NativeExpressAdView is currently hidden. + kPresentationStateHidden = 0, + /// NativeExpressAdView is visible, but does not contain an ad. + kPresentationStateVisibleWithoutAd, + /// NativeExpressAdView is visible and contains an ad. + kPresentationStateVisibleWithAd, + /// NativeExpressAdView is visible and has opened a partial overlay on the + /// screen. + kPresentationStateOpenedPartialOverlay, + /// NativeExpressAdView is completely covering the screen or has caused + /// focus to leave the application (for example, when opening an external + /// browser during a clickthrough). + kPresentationStateCoveringUI, + }; +#ifdef INTERNAL_EXPERIMENTAL +// LINT.ThenChange(//depot_firebase_cpp/admob/client/cpp/src_java/com/google/firebase/admob/internal/cpp/ConstantsHelper.java) +#endif // INTERNAL_EXPERIMENTAL + +#ifdef INTERNAL_EXPERIMENTAL +// LINT.IfChange +#endif // INTERNAL_EXPERIMENTAL + /// @deprecated + /// @brief The possible screen positions for a @ref NativeExpressAdView. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + enum Position { + /// Top of the screen, horizontally centered. + kPositionTop = 0, + /// Bottom of the screen, horizontally centered. + kPositionBottom, + /// Top-left corner of the screen. + kPositionTopLeft, + /// Top-right corner of the screen. + kPositionTopRight, + /// Bottom-left corner of the screen. + kPositionBottomLeft, + /// Bottom-right corner of the screen. + kPositionBottomRight, + }; +#ifdef INTERNAL_EXPERIMENTAL +// LINT.ThenChange(//depot_firebase_cpp/admob/client/cpp/src_java/com/google/firebase/admob/internal/cpp/ConstantsHelper.java) +#endif // INTERNAL_EXPERIMENTAL + + /// @deprecated + /// @brief A listener class that developers can extend and pass to a + /// @ref NativeExpressAdView object's @ref SetListener method to be notified + /// of changes to the presentation state and bounding box. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + class Listener { + public: + /// @deprecated + /// @brief This method is called when the @ref NativeExpressAdView object's + /// presentation state changes. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + /// @param[in] ad_view The native express ad view whose presentation state + /// changed. + /// @param[in] state The new presentation state. + FIREBASE_DEPRECATED virtual void OnPresentationStateChanged( + NativeExpressAdView* ad_view, PresentationState state) = 0; + + /// @deprecated + /// @brief This method is called when the @ref NativeExpressAdView object's + /// bounding box changes. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + /// + /// @ref Initialize must be called before the object is used. + FIREBASE_DEPRECATED NativeExpressAdView(); + + ~NativeExpressAdView(); + + /// @deprecated + /// @brief Initializes the @ref NativeExpressAdView object. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + /// @param[in] parent The platform-specific UI element that will host the ad. + /// @param[in] ad_unit_id The ad unit ID to use when requesting ads. + /// @param[in] size The desired ad size for the native express ad. + FIREBASE_DEPRECATED Future Initialize(AdParent parent, + const char* ad_unit_id, + AdSize size); + + /// @deprecated + /// @brief Returns a @ref Future that has the status of the last call to + /// @ref Initialize. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + FIREBASE_DEPRECATED Future InitializeLastResult() const; + + /// @deprecated + /// @brief Begins an asynchronous request for an ad. If successful, the ad + /// will automatically be displayed in the NativeExpressAdView. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + /// @param[in] request An AdRequest struct with information about the request + /// to be made (such as targeting info). + FIREBASE_DEPRECATED Future LoadAd(const AdRequest& request); + + /// @deprecated + /// @brief Returns a @ref Future containing the status of the last call to + /// @ref LoadAd. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + FIREBASE_DEPRECATED Future LoadAdLastResult() const; + + /// @deprecated + /// @brief Hides the NativeExpressAdView. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + FIREBASE_DEPRECATED Future Hide(); + + /// @deprecated + /// @brief Returns a @ref Future containing the status of the last call to + /// @ref Hide. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + FIREBASE_DEPRECATED Future HideLastResult() const; + + /// @deprecated + /// @brief Shows the @ref NativeExpressAdView. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + FIREBASE_DEPRECATED Future Show(); + + /// @deprecated + /// @brief Returns a @ref Future containing the status of the last call to + /// @ref Show. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + FIREBASE_DEPRECATED Future ShowLastResult() const; + + /// @deprecated + /// @brief Pauses the @ref NativeExpressAdView. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + /// + /// Should be called whenever the C++ engine pauses or the application loses + /// focus. + FIREBASE_DEPRECATED Future Pause(); + + /// @deprecated + /// @brief Returns a @ref Future containing the status of the last call to + /// @ref Pause. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + FIREBASE_DEPRECATED Future PauseLastResult() const; + + /// @deprecated + /// @brief Resumes the @ref NativeExpressAdView after pausing. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + FIREBASE_DEPRECATED Future Resume(); + + /// @deprecated + /// @brief Returns a @ref Future containing the status of the last call to + /// @ref Resume. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + FIREBASE_DEPRECATED Future ResumeLastResult() const; + + /// @deprecated + /// @brief Cleans up and deallocates any resources used by the + /// @ref NativeExpressAdView. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + FIREBASE_DEPRECATED Future Destroy(); + + /// @deprecated + /// @brief Returns a @ref Future containing the status of the last call to + /// @ref Destroy. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + FIREBASE_DEPRECATED Future DestroyLastResult() const; + + /// @deprecated + /// @brief Moves the @ref NativeExpressAdView so that its top-left corner is + /// located at (x, y). Coordinates are in pixels from the top-left corner of + /// the screen. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + /// + /// When built for Android, the library will not display an ad on top of or + /// beneath an Activity's status bar. If a call to MoveTo would result in an + /// overlap, the @ref NativeExpressAdView is placed just below the status bar, + /// so no overlap occurs. + /// @param[in] x The desired horizontal coordinate. + /// @param[in] y The desired vertical coordinate. + FIREBASE_DEPRECATED Future MoveTo(int x, int y); + + /// @deprecated + /// @brief Moves the @ref NativeExpressAdView so that it's located at the + /// given pre-defined position. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + /// @param[in] position The pre-defined position to which to move the + /// @ref NativeExpressAdView. + FIREBASE_DEPRECATED Future MoveTo(Position position); + + /// @deprecated + /// @brief Returns a @ref Future containing the status of the last call to + /// either version of @ref MoveTo. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + FIREBASE_DEPRECATED Future MoveToLastResult() const; + + /// @deprecated + /// @brief Returns the current presentation state of the + /// @ref NativeExpressAdView. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + /// @return The current presentation state. + FIREBASE_DEPRECATED PresentationState GetPresentationState() const; + + /// @deprecated + /// @brief Retrieves the @ref NativeExpressAdView's current onscreen size and + /// location. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + /// @return The current size and location. Values are in pixels, and location + /// coordinates originate from the top-left corner of the screen. + FIREBASE_DEPRECATED BoundingBox GetBoundingBox() const; + + /// @deprecated + /// @brief Sets the @ref Listener for this object. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + /// @param[in] listener A valid NativeExpressAdView::Listener to receive + /// callbacks. + FIREBASE_DEPRECATED void SetListener(Listener* listener); + + private: + // An internal, platform-specific implementation object that this class uses + // to interact with the Google Mobile Ads SDKs for iOS and Android. + internal::NativeExpressAdViewInternal* internal_; +}; + +} // namespace admob +} // namespace firebase + +#endif // FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_NATIVE_EXPRESS_AD_VIEW_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/admob/rewarded_video.h b/packages/firebase_core/firebase_core/firebase_core/firebase/admob/rewarded_video.h new file mode 100644 index 000000000000..32bea80b5550 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/admob/rewarded_video.h @@ -0,0 +1,407 @@ +/* + * Copyright 2016 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_REWARDED_VIDEO_H_ +#define FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_REWARDED_VIDEO_H_ + +#include +#include + +#include "firebase/admob/types.h" +#include "firebase/future.h" + +namespace firebase { + +// Forward declaration of Firebase's internal Mutex. +class Mutex; + +namespace admob { + +/// @deprecated The functionality in the firebase::admob namespace +/// has been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the new +/// SDK in our migration guide. +/// +/// @brief Loads and displays rewarded video ads via AdMob mediation. +/// +/// The rewarded_video namespace contains methods to load and display rewarded +/// video ads via the Google Mobile Ads SDK. The underlying SDK objects for +/// rewarded video on Android and iOS are singletons, so there are no objects +/// to represent individual ads here. Instead, methods in the rewarded_video +/// namespace are invoked to initialize, load, and show. +/// +/// The basic steps for loading and displaying an ad are: +/// +/// 1. Call @ref Initialize to init the library and mediation adapters. +/// 2. Call @ref LoadAd to load an ad (some SDKs may have cached an ad at init +/// time). +/// 3. Call @ref Show to show the ad to the user. +/// 4. Repeat steps 2 and 3 as desired. +/// 5. Call @ref Destroy when your app is completely finished showing rewarded +/// video ads. +/// +/// Note that Initialize must be the very first thing called, and @ref Destroy +/// must be the very last. +/// +/// The library maintains a presentation state that indicates whether or not an +/// ad is currently onscreen, but otherwise provides information about its +/// current state through Futures. @ref Initialize, @ref LoadAd, and so on each +/// have a corresponding @ref Future from which apps can determine the result of +/// the previous call. +/// +/// In addition, applications can create their own subclasses of @ref Listener, +/// pass an instance to the @ref SetListener method, and receive callbacks +/// whenever the presentation state changes or an ad has been viewed in full and +/// the user is due a reward. +/// +/// Here's how one might initialize, load, and show a rewarded video ad while +/// checking against the result of the previous action at each step: +/// +/// @code +/// firebase::admob::rewarded_video::Initialize(); +/// @endcode +/// +/// Then, later: +/// +/// @code +/// if (firebase::admob::rewarded_video::InitializeLastResult().status() == +/// firebase::kFutureStatusComplete && +/// firebase::admob::rewarded_video::InitializeLastResult().error() == +/// firebase::admob::kAdMobErrorNone) { +/// firebase::admob::rewarded_video::LoadAd(my_ad_unit_str, my_ad_request); +/// } +/// @endcode +/// +/// And after that: +/// +/// @code +/// if (firebase::admob::rewarded_video::LoadAdLastResult().status() == +/// firebase::kFutureStatusComplete && +/// firebase::admob::rewarded_video::LoadAdLastResult().error() == +/// firebase::admob::kAdMobErrorNone) { +/// firebase::admob::rewarded_video::Show(my_ad_parent); +/// } +/// @endcode +namespace rewarded_video { +#ifdef INTERNAL_EXPERIMENTAL +// LINT.IfChange +#endif // INTERNAL_EXPERIMENTAL +/// @deprecated +/// @brief The possible presentation states for rewarded video. +/// +/// The functionality in the firebase::admob namespace has +/// been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the +/// new SDK in our migration +/// guide. +enum PresentationState { + /// No ad is currently being shown. + kPresentationStateHidden = 0, + /// A rewarded video ad is completely covering the screen or has caused + /// focus to leave the application (for example, when opening an external + /// browser during a clickthrough), but the video associated with the ad has + /// yet to begin playing. + kPresentationStateCoveringUI, + /// All of the above conditions are true *except* that the video associated + /// with the ad began playing at some point in the past. + kPresentationStateVideoHasStarted, + /// The rewarded video has played and completed. + kPresentationStateVideoHasCompleted, +}; +#ifdef INTERNAL_EXPERIMENTAL +// LINT.ThenChange(//depot_firebase_cpp/admob/client/cpp/src_java/com/google/firebase/admob/internal/cpp/RewardedVideoHelper.java) +#endif // INTERNAL_EXPERIMENTAL + +/// @deprecated +/// @brief A reward to be given to the user in exchange for watching a rewarded +/// video ad. +/// +/// The functionality in the firebase::admob namespace has +/// been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the +/// new SDK in our migration +/// guide. +struct RewardItem { + /// The reward amount. + float amount; + /// A string description of the type of reward (such as "coins" or "points"). + std::string reward_type; +}; + +/// @deprecated +/// @brief A listener class that developers can extend and pass to @ref +/// SetListener to be notified of rewards and changes to the presentation state. +/// +/// The functionality in the firebase::admob namespace has +/// been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the +/// new SDK in our migration +/// guide. +class Listener { + public: + /// @deprecated + /// @brief Invoked when the user should be given a reward for watching an ad. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + /// @param[in] reward The user's reward. + FIREBASE_DEPRECATED virtual void OnRewarded(RewardItem reward) = 0; + + /// @deprecated + /// @brief Invoked when the presentation state of the ad changes. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + /// @param[in] state The new presentation state. + FIREBASE_DEPRECATED virtual void OnPresentationStateChanged( + PresentationState state) = 0; + + virtual ~Listener(); +}; + +/// @deprecated +/// @brief A polling-based listener that developers can instantiate and pass to +/// @ref SetListener in order to queue rewards for later retrieval. +/// +/// The functionality in the firebase::admob namespace has +/// been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the +/// new SDK in our migration +/// guide. +/// +/// The @ref PollReward method should be used to retrieve awards granted by the +/// Mobile Ads SDK and queued by this class. +/// @ref rewarded_video::presentation_state can be used to poll the current +/// presentation state, so no additional method has been added for it. +class PollableRewardListener : public Listener { + public: + /// @deprecated + /// @brief Default constructor. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + FIREBASE_DEPRECATED PollableRewardListener(); + ~PollableRewardListener(); + + /// @deprecated + /// @brief Invoked when the user should be given a reward for watching an ad. + /// + /// Deprecated. The functionality in the firebase::admob + /// namespace has been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the new + /// SDK in our migration + /// guide. + FIREBASE_DEPRECATED void OnRewarded(RewardItem reward); + + /// @deprecated + /// @brief nvoked when the presentation state of the ad changes. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + FIREBASE_DEPRECATED void OnPresentationStateChanged(PresentationState state); + + /// @deprecated + /// @brief Pop the oldest queued reward, and copy its data into the provided + /// RewardItem. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + /// + /// If no reward is available, the struct is unchanged. + /// @param reward Pointer to a struct that reward data can be copied into. + /// @returns true if a reward was popped and data was copied, false otherwise. + FIREBASE_DEPRECATED bool PollReward(RewardItem* reward); + + private: + Mutex* mutex_; + + // Rewards granted by the Mobile Ads SDK. + std::queue rewards_; +}; + +/// @deprecated +/// @brief Initializes rewarded video. This must be the first method invoked in +/// this namespace. +/// +/// The functionality in the firebase::admob namespace has +/// been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the +/// new SDK in our migration +/// guide. +FIREBASE_DEPRECATED Future Initialize(); + +/// @deprecated +/// @brief Returns a @ref Future that has the status of the last call to +/// @ref Initialize. +/// +/// The functionality in the firebase::admob namespace has +/// been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the +/// new SDK in our migration +/// guide. +FIREBASE_DEPRECATED Future InitializeLastResult(); + +/// @deprecated +/// @brief Begins an asynchronous request for an ad. +/// +/// The functionality in the firebase::admob namespace has +/// been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the +/// new SDK in our migration +/// guide. +/// @param[in] ad_unit_id The ad unit ID to use in the request. +/// @param[in] request An AdRequest struct with information about the request +/// to be made (such as targeting info). +FIREBASE_DEPRECATED Future LoadAd(const char* ad_unit_id, + const AdRequest& request); + +/// @deprecated +/// @brief Returns a @ref Future containing the status of the last call to +/// @ref LoadAd. +/// +/// The functionality in the firebase::admob namespace has +/// been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the +/// new SDK in our migration +/// guide. +FIREBASE_DEPRECATED Future LoadAdLastResult(); + +/// @deprecated +/// @brief Shows an ad, assuming one has loaded. +/// +/// The functionality in the firebase::admob namespace has +/// been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the +/// new SDK in our migration +/// guide. +/// +/// @ref LoadAd must be called before this method. +/// @param[in] parent An @ref AdParent that is a reference to an iOS +/// UIView or an Android Activity. +FIREBASE_DEPRECATED Future Show(AdParent parent); + +/// @deprecated +/// @brief Returns a @ref Future containing the status of the last call to +/// @ref Show. +/// +/// Deprecated. The functionality in the firebase::admob +/// namespace has been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the new +/// SDK in our migration +/// guide. +FIREBASE_DEPRECATED Future ShowLastResult(); + +/// @deprecated +/// @brief Pauses any background processing associated with rewarded video. +/// +/// The functionality in the firebase::admob namespace has +/// been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the +/// new SDK in our migration +/// guide. +/// +/// Should be called whenever the C++ engine pauses or the application loses +/// focus. +FIREBASE_DEPRECATED Future Pause(); + +/// @deprecated +/// @brief Returns a @ref Future containing the status of the last call to +/// @ref Pause. +/// +/// The functionality in the firebase::admob namespace has +/// been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the +/// new SDK in our migration +/// guide. +FIREBASE_DEPRECATED Future PauseLastResult(); + +/// @deprecated +/// @brief Resumes the rewarded video system after pausing. +/// +/// The functionality in the firebase::admob namespace has +/// been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the +/// new SDK in our migration +/// guide. +FIREBASE_DEPRECATED Future Resume(); + +/// @deprecated +/// @brief Returns a @ref Future containing the status of the last call to +/// @ref Resume. +/// +/// The functionality in the firebase::admob namespace has +/// been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the +/// new SDK in our migration +/// guide. +FIREBASE_DEPRECATED Future ResumeLastResult(); + +/// @deprecated +/// @brief Cleans up and deallocates any resources used by rewarded video. +/// +/// The functionality in the firebase::admob namespace has +/// been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the +/// new SDK in our migration +/// guide. +/// +/// No other methods in rewarded_video should be called once this method has +/// been invoked. The system is closed for business at that point. +FIREBASE_DEPRECATED void Destroy(); + +/// @deprecated +/// @brief Returns the current presentation state, indicating if an ad is +/// visible or if a video has started playing. +/// +/// The functionality in the firebase::admob namespace has +/// been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the +/// new SDK in our migration +/// guide. +/// @return The current presentation state. +FIREBASE_DEPRECATED PresentationState presentation_state(); + +/// @deprecated +/// @brief Sets the @ref Listener that should receive callbacks. +/// +/// The functionality in the firebase::admob namespace has +/// been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the +/// new SDK in our migration +/// guide. +/// @param[in] listener A valid Listener. +FIREBASE_DEPRECATED void SetListener(Listener* listener); + +} // namespace rewarded_video +} // namespace admob +} // namespace firebase + +#endif // FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_REWARDED_VIDEO_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/admob/types.h b/packages/firebase_core/firebase_core/firebase_core/firebase/admob/types.h new file mode 100644 index 000000000000..21a8379f2d96 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/admob/types.h @@ -0,0 +1,244 @@ +/* + * Copyright 2016 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_TYPES_H_ +#define FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_TYPES_H_ + +#include "firebase/internal/platform.h" + +#if FIREBASE_PLATFORM_ANDROID +#include +#elif FIREBASE_PLATFORM_IOS || FIREBASE_PLATFORM_TVOS +extern "C" { +#include +} // extern "C" +#endif // FIREBASE_PLATFORM_ANDROID, FIREBASE_PLATFORM_IOS, + // FIREBASE_PLATFORM_TVOS + +namespace firebase { +namespace admob { + +/// @deprecated The functionality in the firebase::admob namespace +/// has been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the new +/// SDK in our migration guide. +/// +/// @brief This is a platform specific datatype that is required to create an +/// AdMob ad. +/// +/// The following defines the datatype on each platform: +///
    +///
  • Android: A `jobject` which references an Android Activity.
  • +///
  • iOS: An `id` which references an iOS UIView.
  • +///
+/// +#if FIREBASE_PLATFORM_ANDROID +/// An Android Activity from Java. +typedef jobject AdParent; +#elif FIREBASE_PLATFORM_IOS || FIREBASE_PLATFORM_TVOS +/// A pointer to an iOS UIView. +typedef id AdParent; +#else +/// A void pointer for stub classes. +typedef void *AdParent; +#endif // FIREBASE_PLATFORM_ANDROID, FIREBASE_PLATFORM_IOS, + // FIREBASE_PLATFORM_TVOS + +#ifdef INTERNAL_EXPERIMENTAL +// LINT.IfChange +#endif // INTERNAL_EXPERIMENTAL +/// @deprecated +/// @brief Error codes returned by Future::error(). +/// +/// The functionality in the firebase::admob namespace has +/// been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the +/// new SDK in our migration +/// guide. +enum AdMobError { + /// Call completed successfully. + kAdMobErrorNone, + /// The ad has not been fully initialized. + kAdMobErrorUninitialized, + /// The ad is already initialized (repeat call). + kAdMobErrorAlreadyInitialized, + /// A call has failed because an ad is currently loading. + kAdMobErrorLoadInProgress, + /// A call to load an ad has failed due to an internal SDK error. + kAdMobErrorInternalError, + /// A call to load an ad has failed due to an invalid request. + kAdMobErrorInvalidRequest, + /// A call to load an ad has failed due to a network error. + kAdMobErrorNetworkError, + /// A call to load an ad has failed because no ad was available to serve. + kAdMobErrorNoFill, + /// An attempt has been made to show an ad on an Android Activity that has + /// no window token (such as one that's not done initializing). + kAdMobErrorNoWindowToken, + /// Fallback error for any unidentified cases. + kAdMobErrorUnknown, +}; +#ifdef INTERNAL_EXPERIMENTAL +// LINT.ThenChange(//depot_firebase_cpp/admob/client/cpp/src_java/com/google/firebase/admob/internal/cpp/ConstantsHelper.java) +#endif // INTERNAL_EXPERIMENTAL + +/// @deprecated +/// @brief Types of ad sizes. +/// +/// The functionality in the firebase::admob namespace has +/// been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the +/// new SDK in our migration +/// guide. +enum AdSizeType { kAdSizeStandard = 0 }; + +/// @deprecated +/// @brief An ad size value to be used in requesting ads. +/// +/// The functionality in the firebase::admob namespace has +/// been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the +/// new SDK in our migration +/// guide. +struct AdSize { + /// The type of ad size. + AdSizeType ad_size_type; + /// Height of the ad (in points or dp). + int height; + /// Width of the ad (in points or dp). + int width; +}; + +/// @deprecated +/// @brief Gender information used as part of the +/// @ref firebase::admob::AdRequest struct. +/// +/// The functionality in the firebase::admob namespace has +/// been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the +/// new SDK in our migration +/// guide. +enum Gender { + /// The gender of the current user is unknown or unspecified by the + /// publisher. + kGenderUnknown = 0, + /// The current user is known to be male. + kGenderMale, + /// The current user is known to be female. + kGenderFemale +}; + +/// @deprecated +/// @brief Indicates whether an ad request is considered tagged for +/// child-directed treatment. +/// +/// The functionality in the firebase::admob namespace has +/// been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the +/// new SDK in our migration +/// guide. +enum ChildDirectedTreatmentState { + /// The child-directed status for the request is not indicated. + kChildDirectedTreatmentStateUnknown = 0, + /// The request is tagged for child-directed treatment. + kChildDirectedTreatmentStateTagged, + /// The request is not tagged for child-directed treatment. + kChildDirectedTreatmentStateNotTagged +}; + +/// @deprecated +/// @brief Generic Key-Value container used for the "extras" values in an +/// @ref firebase::admob::AdRequest. +/// +/// The functionality in the firebase::admob namespace has +/// been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the +/// new SDK in our migration +/// guide. +struct KeyValuePair { + /// The name for an "extra." + const char *key; + /// The value for an "extra." + const char *value; +}; + +/// @deprecated +/// @brief The information needed to request an ad. +/// +/// The functionality in the firebase::admob namespace has +/// been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the +/// new SDK in our migration +/// guide. +struct AdRequest { + /// An array of test device IDs specifying devices that test ads will be + /// returned for. + const char **test_device_ids; + /// The number of entries in the array referenced by test_device_ids. + unsigned int test_device_id_count; + /// An array of keywords or phrases describing the current user activity, such + /// as "Sports Scores" or "Football." + const char **keywords; + /// The number of entries in the array referenced by keywords. + unsigned int keyword_count; + /// A @ref KeyValuePair specifying additional parameters accepted by an ad + /// network. + const KeyValuePair *extras; + /// The number of entries in the array referenced by extras. + unsigned int extras_count; + /// The day the user was born. Specify the user's birthday to increase ad + /// relevancy. + int birthday_day; + /// The month the user was born. Specify the user's birthday to increase ad + /// relevancy. + int birthday_month; + /// The year the user was born. Specify the user's birthday to increase ad + /// relevancy. + int birthday_year; + /// The user's @ref Gender. Specify the user's gender to increase ad + /// relevancy. + Gender gender; + /// Specifies whether the request should be considered as child-directed for + /// purposes of the Children’s Online Privacy Protection Act (COPPA). + ChildDirectedTreatmentState tagged_for_child_directed_treatment; +}; + +/// @deprecated +/// @brief The screen location and dimensions of an ad view once it has been +/// initialized. +/// +/// The functionality in the firebase::admob namespace has +/// been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the +/// new SDK in our migration +/// guide. +struct BoundingBox { + /// Default constructor which initializes all member variables to 0. + BoundingBox() : height(0), width(0), x(0), y(0) {} + /// Height of the ad in pixels. + int height; + /// Width of the ad in pixels. + int width; + /// Horizontal position of the ad in pixels from the left. + int x; + /// Vertical position of the ad in pixels from the top. + int y; +}; + +} // namespace admob +} // namespace firebase + +#endif // FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_TYPES_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/analytics.h b/packages/firebase_core/firebase_core/firebase_core/firebase/analytics.h new file mode 100644 index 000000000000..973890b20fce --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/analytics.h @@ -0,0 +1,569 @@ +/* + * Copyright 2016 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_ANALYTICS_SRC_INCLUDE_FIREBASE_ANALYTICS_H_ +#define FIREBASE_ANALYTICS_SRC_INCLUDE_FIREBASE_ANALYTICS_H_ + +#include +#include +#include +#include + +#include "firebase/app.h" +#include "firebase/future.h" +#include "firebase/internal/common.h" +#include "firebase/variant.h" + +#if !defined(DOXYGEN) && !defined(SWIG) +FIREBASE_APP_REGISTER_CALLBACKS_REFERENCE(analytics) +#endif // !defined(DOXYGEN) && !defined(SWIG) + +/// @brief Namespace that encompasses all Firebase APIs. +namespace firebase { + +/// @brief Firebase Analytics API. +/// +/// See the developer guides for general +/// information on using Firebase Analytics in your apps. +namespace analytics { + +/// @brief Event parameter. +/// +/// Parameters supply information that contextualize events (see @ref LogEvent). +/// You can associate up to 25 unique Parameters with each event type (name). +/// +/// +/// @if swig_examples +/// Common event types are provided as static properties of the +/// FirebaseAnalytics class (e.g FirebaseAnalytics.EventPostScore) where +/// parameters of these events are also provided in this FirebaseAnalytics +/// class (e.g FirebaseAnalytics.ParameterScore). +/// +/// You are not limited to the set of event types and parameter names +/// suggested in FirebaseAnalytics class properties. Additional Parameters can +/// be supplied for suggested event types or custom Parameters for custom event +/// types. +/// @endif +/// +/// @if cpp_examples +/// Common event types (names) are suggested in @ref event_names +/// (%event_names.h) with parameters of common event types defined in +/// @ref parameter_names (%parameter_names.h). +/// +/// You are not limited to the set of event types and parameter names suggested +/// in @ref event_names (%event_names.h) and %parameter_names.h respectively. +/// Additional Parameters can be supplied for suggested event types or custom +/// Parameters for custom event types. +/// @endif +/// +/// Parameter names must be a combination of letters and digits +/// (matching the regular expression [a-zA-Z0-9]) between 1 and 40 characters +/// long starting with a letter [a-zA-Z] character. The "firebase_", +/// "google_" and "ga_" prefixes are reserved and should not be used. +/// +/// Parameter string values can be up to 100 characters long. +/// +/// +/// @if swig_examples +/// An array of Parameter class instances can be passed to LogEvent in order +/// to associate parameters's of an event with values where each value can be +/// a double, 64-bit integer or string. +/// @endif +/// +/// @if cpp_examples +/// An array of this structure is passed to LogEvent in order to associate +/// parameter's of an event (Parameter::name) with values (Parameter::value) +/// where each value can be a double, 64-bit integer or string. +/// @endif +/// +/// For example, a game may log an achievement event along with the +/// character the player is using and the level they're currently on: +/// +/// +/// @if swig_examples +/// @code{.cs} +/// using Firebase.Analytics; +/// +/// int currentLevel = GetCurrentLevel(); +/// Parameter[] AchievementParameters = { +/// new Parameter(FirebaseAnalytics.ParameterAchievementID, +/// "ultimate_wizard"), +/// new Parameter(FirebaseAnalytics.ParameterCharacter, "mysterion"), +/// new Parameter(FirebaseAnalytics.ParameterLevel, currentLevel), +/// }; +/// FirebaseAnalytics.LogEvent(FirebaseAnalytics.EventLevelUp, +/// AchievementParameters); +/// @endcode +/// @endif +/// +/// @if cpp_examples +/// @code{.cpp} +/// using namespace firebase::analytics; +/// int64_t current_level = GetCurrentLevel(); +/// const Parameter achievement_parameters[] = { +/// Parameter(kParameterAchievementID, "ultimate_wizard"), +/// Parameter(kParameterCharacter, "mysterion"), +/// Parameter(kParameterLevel, current_level), +/// }; +/// LogEvent(kEventUnlockAchievement, achievement_parameters, +/// sizeof(achievement_parameters) / +/// sizeof(achievement_parameters[0])); +/// @endcode +/// @endif +/// +struct Parameter { +#ifndef SWIG + /// Construct an empty parameter. + /// + /// This is provided to allow initialization after construction. + Parameter() : name(nullptr) {} +#endif // !SWIG + +// +// We don't want to pull in Variant in the C# interface. +// +#ifndef SWIG + /// Construct a parameter. + /// + /// @param parameter_name Name of the parameter (see Parameter::name). + /// @param parameter_value Value for the parameter. Variants can + /// hold numbers and strings. + Parameter(const char* parameter_name, Variant parameter_value) + : name(parameter_name) { + value = parameter_value; + } +#endif // !SWIG + + /// Construct a 64-bit integer parameter. + /// + /// @param parameter_name Name of the parameter. + /// @if cpp_examples + /// (see Parameter::name). + /// @endif + /// + /// @if swig_examples + /// Parameter names must be a combination of letters and digits + /// (matching the regular expression [a-zA-Z0-9]) between 1 and 40 characters + /// long starting with a letter [a-zA-Z] character. + /// @endif + /// + /// @param parameter_value Integer value for the parameter. + Parameter(const char* parameter_name, int parameter_value) + : name(parameter_name) { + value = parameter_value; + } + + /// Construct a 64-bit integer parameter. + /// + /// @param parameter_name Name of the parameter. + /// @if cpp_examples + /// (see Parameter::name). + /// @endif + /// + /// @if swig_examples + /// Parameter names must be a combination of letters and digits + /// (matching the regular expression [a-zA-Z0-9]) between 1 and 40 characters + /// long starting with a letter [a-zA-Z] character. + /// @endif + /// + /// @param parameter_value Integer value for the parameter. + Parameter(const char* parameter_name, int64_t parameter_value) + : name(parameter_name) { + value = parameter_value; + } + + /// Construct a floating point parameter. + /// + /// @param parameter_name Name of the parameter. + /// @if cpp_examples + /// (see Parameter::name). + /// @endif + /// + /// @if swig_examples + /// Parameter names must be a combination of letters and digits + /// (matching the regular expression [a-zA-Z0-9]) between 1 and 40 characters + /// long starting with a letter [a-zA-Z] character. + /// @endif + /// + /// @param parameter_value Floating point value for the parameter. + Parameter(const char* parameter_name, double parameter_value) + : name(parameter_name) { + value = parameter_value; + } + + /// Construct a string parameter. + /// + /// @param parameter_name Name of the parameter. + /// @if cpp_examples + /// (see Parameter::name). + /// @endif + /// + /// @if swig_examples + /// Parameter names must be a combination of letters and digits + /// (matching the regular expression [a-zA-Z0-9]) between 1 and 40 characters + /// long starting with a letter [a-zA-Z] character. + /// @endif + /// + /// @param parameter_value String value for the parameter, can be up to 100 + /// characters long. + Parameter(const char* parameter_name, const char* parameter_value) + : name(parameter_name) { + value = parameter_value; + } + +#ifndef SWIG + // + // Skipping implementation values because the C# API members are + // immutable, and there's no other need to read these values in + // C#. The class just needs to be passed to the C++ layers. + // This also avoids having to solve the nested union, which is + // unsupported in swig. + // + + /// @brief Name of the parameter. + /// + /// Parameter names must be a combination of letters and digits + /// (matching the regular expression [a-zA-Z0-9]) between 1 and 40 characters + /// long starting with a letter [a-zA-Z] character. The "firebase_", + /// "google_" and "ga_" prefixes are reserved and should not be used. + const char* name; + /// @brief Value of the parameter. + /// + /// See firebase::Variant for usage information. + /// @note String values can be up to 100 characters long. + Variant value; +#endif // SWIG +}; + +/// @brief Initialize the Analytics API. +/// +/// This must be called prior to calling any other methods in the +/// firebase::analytics namespace. +/// +/// @param[in] app Default @ref firebase::App instance. +/// +/// @see firebase::App::GetInstance(). +void Initialize(const App& app); + +/// @brief Terminate the Analytics API. +/// +/// Cleans up resources associated with the API. +void Terminate(); + +/// @brief Sets whether analytics collection is enabled for this app on this +/// device. +/// +/// This setting is persisted across app sessions. By default it is enabled. +/// +/// @param[in] enabled true to enable analytics collection, false to disable. +void SetAnalyticsCollectionEnabled(bool enabled); + +/// @brief The type of consent to set. +/// +/// Supported consent types are kConsentTypeAdStorage and +/// kConsentTypeAnalyticsStorage. Omitting a type retains its previous status. +enum ConsentType { kConsentTypeAdStorage = 0, kConsentTypeAnalyticsStorage }; + +/// @brief The status value of the consent type. +/// +/// Supported statuses are kConsentStatusGranted and kConsentStatusDenied. +enum ConsentStatus { kConsentStatusGranted = 0, kConsentStatusDenied }; + +/// @brief Sets the applicable end user consent state (e.g., for device +/// identifiers) for this app on this device. +/// +/// Use the consent map to specify individual consent type values. Settings are +/// persisted across app sessions. By default consent types are set to +/// "granted". +void SetConsent(const std::map& consent_settings); + +/// @brief Log an event with one string parameter. +/// +/// @param[in] name Name of the event to log. Should contain 1 to 40 +/// alphanumeric characters or underscores. The name must start with an +/// alphabetic character. Some event names are reserved. +/// +/// @if swig_examples +/// See the FirebaseAnalytics.Event properties for the list of reserved event +/// names. +/// @endif +/// +/// @if cpp_examples +/// See @ref event_names (%event_names.h) for the list of reserved event names. +/// @endif +/// The "firebase_" prefix is reserved and should not be used. Note that event +/// names are case-sensitive and that logging two events whose names differ +/// only in case will result in two distinct events. +/// @param[in] parameter_name Name of the parameter to log. +/// For more information, see @ref Parameter. +/// @param[in] parameter_value Value of the parameter to log. +/// +/// +/// @if swig_examples +/// @see LogEvent(string, Parameter[]) +/// @endif +/// +/// @if cpp_examples +/// @see LogEvent(const char*, const Parameter*, size_t) +/// @endif +void LogEvent(const char* name, const char* parameter_name, + const char* parameter_value); + +/// @brief Log an event with one float parameter. +/// +/// @param[in] name Name of the event to log. Should contain 1 to 40 +/// alphanumeric characters or underscores. The name must start with an +/// alphabetic character. Some event names are reserved. +/// +/// @if swig_examples +/// See the FirebaseAnalytics.Event properties for the list of reserved event +/// names. +/// @endif +/// +/// @if cpp_examples +/// See @ref event_names (%event_names.h) for the list of reserved event names. +/// @endif +/// The "firebase_" prefix is reserved and should not be used. Note that event +/// names are case-sensitive and that logging two events whose names differ +/// only in case will result in two distinct events. +/// @param[in] parameter_name Name of the parameter to log. +/// For more information, see @ref Parameter. +/// @param[in] parameter_value Value of the parameter to log. +/// +/// +/// @if swig_examples +/// @see LogEvent(string, Parameter[]) +/// @endif +/// +/// @if cpp_examples +/// @see LogEvent(const char*, const Parameter*, size_t) +/// @endif +void LogEvent(const char* name, const char* parameter_name, + const double parameter_value); + +/// @brief Log an event with one 64-bit integer parameter. +/// +/// @param[in] name Name of the event to log. Should contain 1 to 40 +/// alphanumeric characters or underscores. The name must start with an +/// alphabetic character. Some event names are reserved. +/// +/// @if swig_examples +/// See the FirebaseAnalytics.Event properties for the list of reserved event +/// names. +/// @endif +/// +/// @if cpp_examples +/// See @ref event_names (%event_names.h) for the list of reserved event names. +/// @endif +/// The "firebase_" prefix is reserved and should not be used. Note that event +/// names are case-sensitive and that logging two events whose names differ +/// only in case will result in two distinct events. +/// @param[in] parameter_name Name of the parameter to log. +/// For more information, see @ref Parameter. +/// @param[in] parameter_value Value of the parameter to log. +/// +/// +/// @if swig_examples +/// @see LogEvent(string, Parameter[]) +/// @endif +/// +/// @if cpp_examples +/// @see LogEvent(const char*, const Parameter*, size_t) +/// @endif +void LogEvent(const char* name, const char* parameter_name, + const int64_t parameter_value); + +/// @brief Log an event with one integer parameter +/// (stored as a 64-bit integer). +/// +/// @param[in] name Name of the event to log. Should contain 1 to 40 +/// alphanumeric characters or underscores. The name must start with an +/// alphabetic character. Some event names are reserved. +/// +/// @if swig_examples +/// See the FirebaseAnalytics.Event properties for the list of reserved event +/// names. +/// @endif +/// +/// @if cpp_examples +/// See @ref event_names (%event_names.h) for the list of reserved event names. +/// @endif +/// The "firebase_" prefix is reserved and should not be used. Note that event +/// names are case-sensitive and that logging two events whose names differ +/// only in case will result in two distinct events. +/// @param[in] parameter_name Name of the parameter to log. +/// For more information, see @ref Parameter. +/// @param[in] parameter_value Value of the parameter to log. +/// +/// +/// @if swig_examples +/// @see LogEvent(string, Parameter[]) +/// @endif +/// +/// @if cpp_examples +/// @see LogEvent(const char*, const Parameter*, size_t) +/// @endif +void LogEvent(const char* name, const char* parameter_name, + const int parameter_value); + +/// @brief Log an event with no parameters. +/// +/// @param[in] name Name of the event to log. Should contain 1 to 40 +/// alphanumeric characters or underscores. The name must start with an +/// alphabetic character. Some event names are reserved. +/// +/// @if swig_examples +/// See the FirebaseAnalytics.Event properties for the list of reserved event +/// names. +/// @endif +/// +/// @if cpp_examples +/// See @ref event_names (%event_names.h) for the list of reserved event names. +/// @endif +/// The "firebase_" prefix is reserved and should not be used. Note that event +/// names are case-sensitive and that logging two events whose names differ +/// only in case will result in two distinct events. +/// +/// +/// @if swig_examples +/// @see LogEvent(string, Parameter[]) +/// @endif +/// +/// @if cpp_examples +/// @see LogEvent(const char*, const Parameter*, size_t) +/// @endif +void LogEvent(const char* name); + +// clang-format off +#ifdef SWIG +// Modify the following overload with unsafe, so that we can do some pinning +// in the C# code. +%csmethodmodifiers LogEvent "public unsafe" +#endif // SWIG +// clang-format on + +/// @brief Log an event with associated parameters. +/// +/// An Event is an important occurrence in your app that you want to +/// measure. You can report up to 500 different types of events per app and +/// you can associate up to 25 unique parameters with each Event type. +/// +/// Some common events are documented in @ref event_names (%event_names.h), +/// but you may also choose to specify custom event types that are associated +/// with your specific app. +/// +/// @param[in] name Name of the event to log. Should contain 1 to 40 +/// alphanumeric characters or underscores. The name must start with an +/// alphabetic character. Some event names are reserved. See @ref event_names +/// (%event_names.h) for the list of reserved event names. The "firebase_" +/// prefix is reserved and should not be used. Note that event names are +/// case-sensitive and that logging two events whose names differ only in +/// case will result in two distinct events. +/// @param[in] parameters Array of Parameter structures. +/// @param[in] number_of_parameters Number of elements in the parameters +/// array. +void LogEvent(const char* name, const Parameter* parameters, + size_t number_of_parameters); + +/// Initiates on-device conversion measurement given a user email address on iOS +/// and tvOS (no-op on Android). On iOS and tvOS, this method requires the +/// dependency GoogleAppMeasurementOnDeviceConversion to be linked in, +/// otherwise the invocation results in a no-op. +/// @param[in] email_address User email address. Include a domain name for all +/// email addresses (e.g. gmail.com or hotmail.co.jp). +void InitiateOnDeviceConversionMeasurementWithEmailAddress( + const char* email_address); + +/// @brief Set a user property to the given value. +/// +/// Properties associated with a user allow a developer to segment users +/// into groups that are useful to their application. Up to 25 properties +/// can be associated with a user. +/// +/// Suggested property names are listed @ref user_property_names +/// (%user_property_names.h) but you're not limited to this set. For example, +/// the "gamertype" property could be used to store the type of player where +/// a range of values could be "casual", "mid_core", or "core". +/// +/// @param[in] name Name of the user property to set. This must be a +/// combination of letters and digits (matching the regular expression +/// [a-zA-Z0-9] between 1 and 40 characters long starting with a letter +/// [a-zA-Z] character. +/// @param[in] property Value to set the user property to. Set this +/// argument to NULL or nullptr to remove the user property. The value can be +/// between 1 to 100 characters long. +void SetUserProperty(const char* name, const char* property); + +/// @brief Sets the user ID property. +/// +/// This feature must be used in accordance with +/// Google's Privacy +/// Policy +/// +/// @param[in] user_id The user ID associated with the user of this app on this +/// device. The user ID must be non-empty and no more than 256 characters long. +/// Setting user_id to NULL or nullptr removes the user ID. +void SetUserId(const char* user_id); + +/// @brief Sets the duration of inactivity that terminates the current session. +/// +/// @note The default value is 1800000 (30 minutes). +/// +/// @param milliseconds The duration of inactivity that terminates the current +/// session. +void SetSessionTimeoutDuration(int64_t milliseconds); + +/// Clears all analytics data for this app from the device and resets the app +/// instance id. +void ResetAnalyticsData(); + +/// Get the instance ID from the analytics service. +/// +/// @note This is *not* the same ID as the ID returned by +/// @if cpp_examples +/// firebase::instance_id::InstanceId. +/// @else +/// Firebase.InstanceId.FirebaseInstanceId. +/// @endif +/// +/// @returns Object which can be used to retrieve the analytics instance ID. +Future GetAnalyticsInstanceId(); + +/// Get the result of the most recent GetAnalyticsInstanceId() call. +/// +/// @returns Object which can be used to retrieve the analytics instance ID. +Future GetAnalyticsInstanceIdLastResult(); + +/// Asynchronously retrieves the identifier of the current app +/// session. +/// +/// The session ID retrieval could fail due to Analytics collection +/// disabled, or if the app session was expired. +/// +/// @returns Object which can be used to retrieve the identifier of the current +/// app session. +Future GetSessionId(); + +/// Get the result of the most recent GetSessionId() call. +/// +/// @returns Object which can be used to retrieve the identifier of the current +/// app session. +Future GetSessionIdLastResult(); + +} // namespace analytics +} // namespace firebase + +#endif // FIREBASE_ANALYTICS_SRC_INCLUDE_FIREBASE_ANALYTICS_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/analytics/event_names.h b/packages/firebase_core/firebase_core/firebase_core/firebase/analytics/event_names.h new file mode 100644 index 000000000000..4f1d4e5a0e2b --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/analytics/event_names.h @@ -0,0 +1,472 @@ +// Copyright 2023 Google Inc. All Rights Reserved. + +#ifndef FIREBASE_ANALYTICS_CLIENT_CPP_INCLUDE_FIREBASE_ANALYTICS_EVENT_NAMES_H_ +#define FIREBASE_ANALYTICS_CLIENT_CPP_INCLUDE_FIREBASE_ANALYTICS_EVENT_NAMES_H_ + +/// @brief Namespace that encompasses all Firebase APIs. +namespace firebase { +/// @brief Firebase Analytics API. +namespace analytics { + + + +/// @defgroup event_names Analytics Events +/// +/// Predefined event names. +/// +/// An Event is an important occurrence in your app that you want to +/// measure. You can report up to 500 different types of Events per app +/// and you can associate up to 25 unique parameters with each Event type. +/// Some common events are suggested below, but you may also choose to +/// specify custom Event types that are associated with your specific app. +/// Each event type is identified by a unique name. Event names can be up +/// to 40 characters long, may only contain alphanumeric characters and +/// underscores ("_"), and must start with an alphabetic character. The +/// "firebase_", "google_", and "ga_" prefixes are reserved and should not +/// be used. +/// @{ + + +/// Ad Impression event. This event signifies when a user sees an ad +/// impression. Note: If you supply the @c AnalyticsParameterValue +/// parameter, you must also supply the @c AnalyticsParameterCurrency +/// parameter so that revenue metrics can be computed accurately. Params: +/// +///
    +///
  • @c AnalyticsParameterAdPlatform (String) (optional)
  • +///
  • @c AnalyticsParameterAdFormat (String) (optional)
  • +///
  • @c AnalyticsParameterAdSource (String) (optional)
  • +///
  • @c AnalyticsParameterAdUnitName (String) (optional)
  • +///
  • @c AnalyticsParameterCurrency (String) (optional)
  • +///
  • @c AnalyticsParameterValue (Double) (optional)
  • +///
+static const char*const kEventAdImpression = + "ad_impression"; + +/// Add Payment Info event. This event signifies that a user has submitted +/// their payment information. Note: If you supply the @c +/// AnalyticsParameterValue parameter, you must also supply the @c +/// AnalyticsParameterCurrency parameter so that revenue metrics can be +/// computed accurately. Params: +/// +///
    +///
  • @c AnalyticsParameterCoupon (String) (optional)
  • +///
  • @c AnalyticsParameterCurrency (String) (optional)
  • +///
  • @c AnalyticsParameterItems ([[String: Any]]) (optional)
  • +///
  • @c AnalyticsParameterPaymentType (String) (optional)
  • +///
  • @c AnalyticsParameterValue (Double) (optional)
  • +///
+static const char*const kEventAddPaymentInfo = + "add_payment_info"; + +/// Add Shipping Info event. This event signifies that a user has +/// submitted their shipping information. Note: If you supply the @c +/// AnalyticsParameterValue parameter, you must also supply the @c +/// AnalyticsParameterCurrency parameter so that revenue metrics can be +/// computed accurately. Params: +/// +///
    +///
  • @c AnalyticsParameterCoupon (String) (optional)
  • +///
  • @c AnalyticsParameterCurrency (String) (optional)
  • +///
  • @c AnalyticsParameterItems ([[String: Any]]) (optional)
  • +///
  • @c AnalyticsParameterShippingTier (String) (optional)
  • +///
  • @c AnalyticsParameterValue (Double) (optional)
  • +///
+static const char*const kEventAddShippingInfo = + "add_shipping_info"; + +/// E-Commerce Add To Cart event. This event signifies that an item(s) was +/// added to a cart for purchase. Add this event to a funnel with @c +/// AnalyticsEventPurchase to gauge the effectiveness of your +/// checParameter(kout, If you supply the @c AnalyticsParameterValue +/// parameter), you must also supply the @c AnalyticsParameterCurrency +/// parameter so that revenue metrics can be computed accurately. Params: +/// +///
    +///
  • @c AnalyticsParameterCurrency (String) (optional)
  • +///
  • @c AnalyticsParameterItems ([[String: Any]]) (optional)
  • +///
  • @c AnalyticsParameterValue (Double) (optional)
  • +///
+static const char*const kEventAddToCart = "add_to_cart"; + +/// E-Commerce Add To Wishlist event. This event signifies that an item +/// was added to a wishlist. Use this event to identify popular gift +/// items. Note: If you supply the @c AnalyticsParameterValue parameter, +/// you must also supply the @c AnalyticsParameterCurrency parameter so +/// that revenue metrics can be computed accurately. Params: +/// +///
    +///
  • @c AnalyticsParameterCurrency (String) (optional)
  • +///
  • @c AnalyticsParameterItems ([[String: Any]]) (optional)
  • +///
  • @c AnalyticsParameterValue (Double) (optional)
  • +///
+static const char*const kEventAddToWishlist = + "add_to_wishlist"; + +/// App Open event. By logging this event when an App becomes active, +/// developers can understand how often users leave and return during the +/// course of a Session. Although Sessions are automatically reported, +/// this event can provide further clarification around the continuous +/// engagement of app-users. +static const char*const kEventAppOpen = "app_open"; + +/// E-Commerce Begin Checkout event. This event signifies that a user has +/// begun the process of checking out. Add this event to a funnel with +/// your @c AnalyticsEventPurchase event to gauge the effectiveness of +/// your checkout process. Note: If you supply the @c +/// AnalyticsParameterValue parameter, you must also supply the @c +/// AnalyticsParameterCurrency parameter so that revenue metrics can be +/// computed accurately. Params: +/// +///
    +///
  • @c AnalyticsParameterCoupon (String) (optional)
  • +///
  • @c AnalyticsParameterCurrency (String) (optional)
  • +///
  • @c AnalyticsParameterItems ([[String: Any]]) (optional)
  • +///
  • @c AnalyticsParameterValue (Double) (optional)
  • +///
+static const char*const kEventBeginCheckout = + "begin_checkout"; + +/// Campaign Detail event. Log this event to supply the referral details +/// of a re-engagement campaign. Note: you must supply at least one of the +/// required parameters AnalyticsParameterSource, AnalyticsParameterMedium +/// or AnalyticsParameterCampaign. Params: +/// +///
    +///
  • @c AnalyticsParameterSource (String)
  • +///
  • @c AnalyticsParameterMedium (String)
  • +///
  • @c AnalyticsParameterCampaign (String)
  • +///
  • @c AnalyticsParameterTerm (String) (optional)
  • +///
  • @c AnalyticsParameterContent (String) (optional)
  • +///
  • @c AnalyticsParameterAdNetworkClickID (String) (optional)
  • +///
  • @c AnalyticsParameterCP1 (String) (optional)
  • +///
  • @c AnalyticsParameterCampaignID (String) (optional)
  • +///
  • @c AnalyticsParameterCreativeFormat (String) (optional)
  • +///
  • @c AnalyticsParameterMarketingTactic (String) (optional)
  • +///
  • @c AnalyticsParameterSourcePlatform (String) (optional)
  • +///
+static const char*const kEventCampaignDetails = + "campaign_details"; + +/// Earn Virtual Currency event. This event tracks the awarding of virtual +/// currency in your app. Log this along with @c +/// AnalyticsEventSpendVirtualCurrency to better understand your virtual +/// economy. Params: +/// +///
    +///
  • @c AnalyticsParameterVirtualCurrencyName (String)
  • +///
  • @c AnalyticsParameterValue (Int or Double)
  • +///
+static const char*const kEventEarnVirtualCurrency + = "earn_virtual_currency"; + +/// Generate Lead event. Log this event when a lead has been generated in +/// the app to understand the efficacy of your install and re-engagement +/// campaigns. Note: If you supply the @c AnalyticsParameterValue +/// parameter, you must also supply the @c AnalyticsParameterCurrency +/// parameter so that revenue metrics can be computed accurately. Params: +/// +///
    +///
  • @c AnalyticsParameterCurrency (String) (optional)
  • +///
  • @c AnalyticsParameterValue (Double) (optional)
  • +///
+static const char*const kEventGenerateLead = + "generate_lead"; + +/// Join Group event. Log this event when a user joins a group such as a +/// guild, team or family. Use this event to analyze how popular certain +/// groups or social features are in your app. Params: +/// +///
    +///
  • @c AnalyticsParameterGroupID (String)
  • +///
+static const char*const kEventJoinGroup = "join_group"; + +/// Level End event. Log this event when the user finishes a level. +/// Params: +/// +///
    +///
  • @c AnalyticsParameterLevelName (String)
  • +///
  • @c AnalyticsParameterSuccess (String)
  • +///
+static const char*const kEventLevelEnd = "level_end"; + +/// Level Start event. Log this event when the user starts a new level. +/// Params: +/// +///
    +///
  • @c AnalyticsParameterLevelName (String)
  • +///
+static const char*const kEventLevelStart = "level_start"; + +/// Level Up event. This event signifies that a player has leveled up in +/// your gaming app. It can help you gauge the level distribution of your +/// userbase and help you identify certain levels that are difficult to +/// pass. Params: +/// +///
    +///
  • @c AnalyticsParameterLevel (Int)
  • +///
  • @c AnalyticsParameterCharacter (String) (optional)
  • +///
+static const char*const kEventLevelUp = "level_up"; + +/// Login event. Apps with a login feature can report this event to +/// signify that a user has logged in. +static const char*const kEventLogin = "login"; + +/// Post Score event. Log this event when the user posts a score in your +/// gaming app. This event can help you understand how users are actually +/// performing in your game and it can help you correlate high scores with +/// certain audiences or behaviors. Params: +/// +///
    +///
  • @c AnalyticsParameterScore (Int)
  • +///
  • @c AnalyticsParameterLevel (Int) (optional)
  • +///
  • @c AnalyticsParameterCharacter (String) (optional)
  • +///
+static const char*const kEventPostScore = "post_score"; + +/// E-Commerce Purchase event. This event signifies that an item(s) was +/// purchased by a user. Note: This is different from the in-app purchase +/// event, which is reported automatically for App Store-based apps. Note: +/// If you supply the @c AnalyticsParameterValue parameter, you must also +/// supply the @c AnalyticsParameterCurrency parameter so that revenue +/// metrics can be computed accurately. Params: +/// +///
    +///
  • @c AnalyticsParameterAffiliation (String) (optional)
  • +///
  • @c AnalyticsParameterCoupon (String) (optional)
  • +///
  • @c AnalyticsParameterCurrency (String) (optional)
  • +///
  • @c AnalyticsParameterEndDate (String) (optional)
  • +///
  • @c AnalyticsParameterItemID (String) (optional)
  • +///
  • @c AnalyticsParameterItems ([[String: Any]]) (optional)
  • +///
  • @c AnalyticsParameterShipping (Double) (optional)
  • +///
  • @c AnalyticsParameterStartDate (String) (optional)
  • +///
  • @c AnalyticsParameterTax (Double) (optional)
  • +///
  • @c AnalyticsParameterTransactionID (String) (optional)
  • +///
  • @c AnalyticsParameterValue (Double) (optional)
  • +///
+static const char*const kEventPurchase = "purchase"; + +/// E-Commerce Refund event. This event signifies that a refund was +/// issued. Note: If you supply the @c AnalyticsParameterValue parameter, +/// you must also supply the @c AnalyticsParameterCurrency parameter so +/// that revenue metrics can be computed accurately. Params: +/// +///
    +///
  • @c AnalyticsParameterAffiliation (String) (optional)
  • +///
  • @c AnalyticsParameterCoupon (String) (optional)
  • +///
  • @c AnalyticsParameterCurrency (String) (optional)
  • +///
  • @c AnalyticsParameterItems ([[String: Any]]) (optional)
  • +///
  • @c AnalyticsParameterShipping (Double) (optional)
  • +///
  • @c AnalyticsParameterTax (Double) (optional)
  • +///
  • @c AnalyticsParameterTransactionID (String) (optional)
  • +///
  • @c AnalyticsParameterValue (Double) (optional)
  • +///
+static const char*const kEventRefund = "refund"; + +/// E-Commerce Remove from Cart event. This event signifies that an +/// item(s) was removed from a cart. Note: If you supply the @c +/// AnalyticsParameterValue parameter, you must also supply the @c +/// AnalyticsParameterCurrency parameter so that revenue metrics can be +/// computed accurately. Params: +/// +///
    +///
  • @c AnalyticsParameterCurrency (String) (optional)
  • +///
  • @c AnalyticsParameterItems ([[String: Any]]) (optional)
  • +///
  • @c AnalyticsParameterValue (Double) (optional)
  • +///
+static const char*const kEventRemoveFromCart = + "remove_from_cart"; + +/// Screen View event. This event signifies a screen view. Use this when a +/// screen transition occurs. This event can be logged irrespective of +/// whether automatic screen tracking is enabled. Params: +/// +///
    +///
  • @c AnalyticsParameterScreenClass (String) (optional)
  • +///
  • @c AnalyticsParameterScreenName (String) (optional)
  • +///
+static const char*const kEventScreenView = "screen_view"; + +/// Search event. Apps that support search features can use this event to +/// contextualize search operations by supplying the appropriate, +/// corresponding parameters. This event can help you identify the most +/// popular content in your app. Params: +/// +///
    +///
  • @c AnalyticsParameterSearchTerm (String)
  • +///
  • @c AnalyticsParameterStartDate (String) (optional)
  • +///
  • @c AnalyticsParameterEndDate (String) (optional)
  • +///
  • @c AnalyticsParameterNumberOfNights (Int) (optional) for hotel bookings
  • +///
  • @c AnalyticsParameterNumberOfRooms (Int) (optional) for hotel bookings
  • +///
  • @c AnalyticsParameterNumberOfPassengers (Int) (optional) for travel bookings
  • +///
  • @c AnalyticsParameterOrigin (String) (optional)
  • +///
  • @c AnalyticsParameterDestination (String) (optional)
  • +///
  • @c AnalyticsParameterTravelClass (String) (optional) for travel bookings
  • +///
+static const char*const kEventSearch = "search"; + +/// Select Content event. This general purpose event signifies that a user +/// has selected some content of a certain type in an app. The content can +/// be any object in your app. This event can help you identify popular +/// content and categories of content in your app. Params: +/// +///
    +///
  • @c AnalyticsParameterContentType (String)
  • +///
  • @c AnalyticsParameterItemID (String)
  • +///
+static const char*const kEventSelectContent = + "select_content"; + +/// Select Item event. This event signifies that an item was selected by a +/// user from a list. Use the appropriate parameters to contextualize the +/// event. Use this event to discover the most popular items selected. +/// Params: +/// +///
    +///
  • @c AnalyticsParameterItems ([[String: Any]]) (optional)
  • +///
  • @c AnalyticsParameterItemListID (String) (optional)
  • +///
  • @c AnalyticsParameterItemListName (String) (optional)
  • +///
+static const char*const kEventSelectItem = "select_item"; + +/// Select promotion event. This event signifies that a user has selected +/// a promotion offer. Use the appropriate parameters to contextualize the +/// event, such as the item(s) for which the promotion applies. Params: +/// +///
    +///
  • @c AnalyticsParameterCreativeName (String) (optional)
  • +///
  • @c AnalyticsParameterCreativeSlot (String) (optional)
  • +///
  • @c AnalyticsParameterItems ([[String: Any]]) (optional)
  • +///
  • @c AnalyticsParameterLocationID (String) (optional)
  • +///
  • @c AnalyticsParameterPromotionID (String) (optional)
  • +///
  • @c AnalyticsParameterPromotionName (String) (optional)
  • +///
+static const char*const kEventSelectPromotion = + "select_promotion"; + +/// Share event. Apps with social features can log the Share event to +/// identify the most viral content. Params: +/// +///
    +///
  • @c AnalyticsParameterContentType (String)
  • +///
  • @c AnalyticsParameterItemID (String)
  • +///
+static const char*const kEventShare = "share"; + +/// Sign Up event. This event indicates that a user has signed up for an +/// account in your app. The parameter signifies the method by which the +/// user signed up. Use this event to understand the different behaviors +/// between logged in and logged out users. Params: +/// +///
    +///
  • @c AnalyticsParameterMethod (String)
  • +///
+static const char*const kEventSignUp = "sign_up"; + +/// Spend Virtual Currency event. This event tracks the sale of virtual +/// goods in your app and can help you identify which virtual goods are +/// the most popular objects of purchase. Params: +/// +///
    +///
  • @c AnalyticsParameterItemName (String)
  • +///
  • @c AnalyticsParameterVirtualCurrencyName (String)
  • +///
  • @c AnalyticsParameterValue (Int or Double)
  • +///
+static const char*const kEventSpendVirtualCurrency + = "spend_virtual_currency"; + +/// Tutorial Begin event. This event signifies the start of the +/// on-boarding process in your app. Use this in a funnel with @c +/// AnalyticsEventTutorialComplete to understand how many users complete +/// this process and move on to the full app experience. +static const char*const kEventTutorialBegin = + "tutorial_begin"; + +/// Tutorial End event. Use this event to signify the user's completion of +/// your app's on-boarding process. Add this to a funnel with @c +/// AnalyticsEventTutorialBegin to gauge the completion rate of your +/// on-boarding process. +static const char*const kEventTutorialComplete = + "tutorial_complete"; + +/// Unlock Achievement event. Log this event when the user has unlocked an +/// achievement in your game. Since achievements generally represent the +/// breadth of a gaming experience, this event can help you understand how +/// many users are experiencing all that your game has to offer. Params: +/// +///
    +///
  • @c AnalyticsParameterAchievementID (String)
  • +///
+static const char*const kEventUnlockAchievement = + "unlock_achievement"; + +/// E-commerce View Cart event. This event signifies that a user has +/// viewed their cart. Use this to analyze your purchase funnel. Note: If +/// you supply the @c AnalyticsParameterValue parameter, you must also +/// supply the @c AnalyticsParameterCurrency parameter so that revenue +/// metrics can be computed accurately. Params: +/// +///
    +///
  • @c AnalyticsParameterCurrency (String) (optional)
  • +///
  • @c AnalyticsParameterItems ([[String: Any]]) (optional)
  • +///
  • @c AnalyticsParameterValue (Double) (optional)
  • +///
+static const char*const kEventViewCart = "view_cart"; + +/// View Item event. This event signifies that a user has viewed an item. +/// Use the appropriate parameters to contextualize the event. Use this +/// event to discover the most popular items viewed in your app. Note: If +/// you supply the @c AnalyticsParameterValue parameter, you must also +/// supply the @c AnalyticsParameterCurrency parameter so that revenue +/// metrics can be computed accurately. Params: +/// +///
    +///
  • @c AnalyticsParameterCurrency (String) (optional)
  • +///
  • @c AnalyticsParameterItems ([[String: Any]]) (optional)
  • +///
  • @c AnalyticsParameterValue (Double) (optional)
  • +///
+static const char*const kEventViewItem = "view_item"; + +/// View Item List event. Log this event when a user sees a list of items +/// or offerings. Params: +/// +///
    +///
  • @c AnalyticsParameterItems ([[String: Any]]) (optional)
  • +///
  • @c AnalyticsParameterItemListID (String) (optional)
  • +///
  • @c AnalyticsParameterItemListName (String) (optional)
  • +///
+static const char*const kEventViewItemList = + "view_item_list"; + +/// View Promotion event. This event signifies that a promotion was shown +/// to a user. Add this event to a funnel with the @c +/// AnalyticsEventAddToCart and @c AnalyticsEventPurchase to gauge your +/// conversion process. Params: +/// +///
    +///
  • @c AnalyticsParameterCreativeName (String) (optional)
  • +///
  • @c AnalyticsParameterCreativeSlot (String) (optional)
  • +///
  • @c AnalyticsParameterItems ([[String: Any]]) (optional)
  • +///
  • @c AnalyticsParameterLocationID (String) (optional)
  • +///
  • @c AnalyticsParameterPromotionID (String) (optional)
  • +///
  • @c AnalyticsParameterPromotionName (String) (optional)
  • +///
+static const char*const kEventViewPromotion = + "view_promotion"; + +/// View Search Results event. Log this event when the user has been +/// presented with the results of a search. Params: +/// +///
    +///
  • @c AnalyticsParameterSearchTerm (String)
  • +///
+static const char*const kEventViewSearchResults = + "view_search_results"; +/// @} + +} // namespace analytics +} // namespace firebase + +#endif // FIREBASE_ANALYTICS_CLIENT_CPP_INCLUDE_FIREBASE_ANALYTICS_EVENT_NAMES_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/analytics/parameter_names.h b/packages/firebase_core/firebase_core/firebase_core/firebase/analytics/parameter_names.h new file mode 100644 index 000000000000..fcc43c22fbc8 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/analytics/parameter_names.h @@ -0,0 +1,755 @@ +// Copyright 2023 Google Inc. All Rights Reserved. + +#ifndef FIREBASE_ANALYTICS_CLIENT_CPP_INCLUDE_FIREBASE_ANALYTICS_PARAMETER_NAMES_H_ +#define FIREBASE_ANALYTICS_CLIENT_CPP_INCLUDE_FIREBASE_ANALYTICS_PARAMETER_NAMES_H_ + +/// @brief Namespace that encompasses all Firebase APIs. +namespace firebase { +/// @brief Firebase Analytics API. +namespace analytics { + + + +/// @defgroup parameter_names Analytics Parameters +/// +/// Predefined event parameter names. +/// +/// Params supply information that contextualize Events. You can associate +/// up to 25 unique Params with each Event type. Some Params are suggested +/// below for certain common Events, but you are not limited to these. You +/// may supply extra Params for suggested Events or custom Params for +/// Custom events. Param names can be up to 40 characters long, may only +/// contain alphanumeric characters and underscores ("_"), and must start +/// with an alphabetic character. Param values can be up to 100 characters +/// long. The "firebase_", "google_", and "ga_" prefixes are reserved and +/// should not be used. +/// @{ + + +/// Game achievement ID (String). +/// @code +/// let params = [ +/// AnalyticsParameterAchievementID : "10_matches_won", +/// // ... +/// ] +/// @endcode +static const char*const kParameterAchievementID = + "achievement_id"; + +/// The ad format (e.g. Banner, Interstitial, Rewarded, Native, Rewarded +/// Interstitial, Instream). (String). +/// @code +/// let params = [ +/// AnalyticsParameterAdFormat : "Banner", +/// // ... +/// ] +/// @endcode +static const char*const kParameterAdFormat = + "ad_format"; + +/// Ad Network Click ID (String). Used for network-specific click IDs +/// which vary in format. +/// @code +/// let params = [ +/// AnalyticsParameterAdNetworParameter(kClickID, "1234567"), +/// // ... +/// ] +/// @endcode +static const char*const kParameterAdNetworkClickID + = "aclid"; + +/// The ad platform (e.g. MoPub, IronSource) (String). +/// @code +/// let params = [ +/// AnalyticsParameterAdPlatform : "MoPub", +/// // ... +/// ] +/// @endcode +static const char*const kParameterAdPlatform = + "ad_platform"; + +/// The ad source (e.g. AdColony) (String). +/// @code +/// let params = [ +/// AnalyticsParameterAdSource : "AdColony", +/// // ... +/// ] +/// @endcode +static const char*const kParameterAdSource = + "ad_source"; + +/// The ad unit name (e.g. Banner_03) (String). +/// @code +/// let params = [ +/// AnalyticsParameterAdUnitName : "Banner_03", +/// // ... +/// ] +/// @endcode +static const char*const kParameterAdUnitName = + "ad_unit_name"; + +/// A product affiliation to designate a supplying company or brick and +/// mortar store location +/// (String). @code +/// let params = [ +/// AnalyticsParameterAffiliation : "Google Store", +/// // ... +/// ] +/// @endcode +static const char*const kParameterAffiliation = + "affiliation"; + +/// Campaign custom parameter (String). Used as a method of capturing +/// custom data in a campaign. Use varies by network. +/// @code +/// let params = [ +/// AnalyticsParameterCP1 : "custom_data", +/// // ... +/// ] +/// @endcode +static const char*const kParameterCP1 = "cp1"; + +/// The individual campaign name, slogan, promo code, etc. Some networks +/// have pre-defined macro to capture campaign information, otherwise can +/// be populated by developer. Highly Recommended (String). +/// @code +/// let params = [ +/// AnalyticsParameterCampaign : "winter_promotion", +/// // ... +/// ] +/// @endcode +static const char*const kParameterCampaign = + "campaign"; + +/// Campaign ID (String). Used for keyword analysis to identify a specific +/// product promotion or strategic campaign. This is a required key for +/// GA4 data import. +/// @code +/// let params = [ +/// AnalyticsParameterCampaignID : "7877652710", +/// // ... +/// ] +/// @endcode +static const char*const kParameterCampaignID = + "campaign_id"; + +/// Character used in game (String). +/// @code +/// let params = [ +/// AnalyticsParameterCharacter : "beat_boss", +/// // ... +/// ] +/// @endcode +static const char*const kParameterCharacter = + "character"; + +/// Campaign content (String). +static const char*const kParameterContent = "content"; + +/// Type of content selected (String). +/// @code +/// let params = [ +/// AnalyticsParameterContentType : "news article", +/// // ... +/// ] +/// @endcode +static const char*const kParameterContentType = + "content_type"; + +/// Coupon code used for a purchase (String). +/// @code +/// let params = [ +/// AnalyticsParameterCoupon : "SUMMER_FUN", +/// // ... +/// ] +/// @endcode +static const char*const kParameterCoupon = "coupon"; + +/// Creative Format (String). Used to identify the high-level +/// classification of the type of ad served by a specific campaign. +/// @code +/// let params = [ +/// AnalyticsParameterCreativeFormat : "display", +/// // ... +/// ] +/// @endcode +static const char*const kParameterCreativeFormat = + "creative_format"; + +/// The name of a creative used in a promotional spot (String). +/// @code +/// let params = [ +/// AnalyticsParameterCreativeName : "Summer Sale", +/// // ... +/// ] +/// @endcode +static const char*const kParameterCreativeName = + "creative_name"; + +/// The name of a creative slot (String). +/// @code +/// let params = [ +/// AnalyticsParameterCreativeSlot : "summer_banner2", +/// // ... +/// ] +/// @endcode +static const char*const kParameterCreativeSlot = + "creative_slot"; + +/// Currency of the purchase or items associated with the event, in +/// 3-letter +/// ISO_4217 format (String). +/// @code +/// let params = [ +/// AnalyticsParameterCurrency : "USD", +/// // ... +/// ] +/// @endcode +static const char*const kParameterCurrency = + "currency"; + +/// Flight or Travel destination (String). +/// @code +/// let params = [ +/// AnalyticsParameterDestination : "Mountain View, CA", +/// // ... +/// ] +/// @endcode +static const char*const kParameterDestination = + "destination"; + +/// Monetary value of discount associated with a purchase (Double). +/// @code +/// let params = [ +/// AnalyticsParameterDiscount : 2.0, +/// AnalyticsParameterCurrency : "USD", // e.g. $2.00 USD +/// // ... +/// ] +/// @endcode +static const char*const kParameterDiscount = + "discount"; + +/// The arrival date, check-out date or rental end date for the item. This +/// should be in YYYY-MM-DD format (String). +/// @code +/// let params = [ +/// AnalyticsParameterEndDate : "2015-09-14", +/// // ... +/// ] +/// @endcode +static const char*const kParameterEndDate = "end_date"; + +/// Indicates that the associated event should either extend the current +/// session or start a new session if no session was active when the event +/// was logged. Specify 1 to extend the current session or to start a new +/// session; any other value will not extend or start a session. +/// @code +/// let params = [ +/// AnalyticsParameterExtendSession : 1, +/// // ... +/// ] +/// @endcode +static const char*const kParameterExtendSession = + "extend_session"; + +/// Flight number for travel events (String). +/// @code +/// let params = [ +/// AnalyticsParameterFlightNumber : "ZZ800", +/// // ... +/// ] +/// @endcode +static const char*const kParameterFlightNumber = + "flight_number"; + +/// Group/clan/guild ID (String). +/// @code +/// let params = [ +/// AnalyticsParameterGroupID : "g1", +/// // ... +/// ] +/// @endcode +static const char*const kParameterGroupID = "group_id"; + +/// The index of the item in a list (Int). +/// @code +/// let params = [ +/// AnalyticsParameterIndex : 5, +/// // ... +/// ] +/// @endcode +static const char*const kParameterIndex = "index"; + +/// Item brand (String). +/// @code +/// let params = [ +/// AnalyticsParameterItemBrand : "Google", +/// // ... +/// ] +/// @endcode +static const char*const kParameterItemBrand = + "item_brand"; + +/// Item category (context-specific) (String). +/// @code +/// let params = [ +/// AnalyticsParameterItemCategory : "pants", +/// // ... +/// ] +/// @endcode +static const char*const kParameterItemCategory = + "item_category"; + +/// Item Category (context-specific) (String). +/// @code +/// let params = [ +/// AnalyticsParameterItemCategory2 : "pants", +/// // ... +/// ] +/// @endcode +static const char*const kParameterItemCategory2 = + "item_category2"; + +/// Item Category (context-specific) (String). +/// @code +/// let params = [ +/// AnalyticsParameterItemCategory3 : "pants", +/// // ... +/// ] +/// @endcode +static const char*const kParameterItemCategory3 = + "item_category3"; + +/// Item Category (context-specific) (String). +/// @code +/// let params = [ +/// AnalyticsParameterItemCategory4 : "pants", +/// // ... +/// ] +/// @endcode +static const char*const kParameterItemCategory4 = + "item_category4"; + +/// Item Category (context-specific) (String). +/// @code +/// let params = [ +/// AnalyticsParameterItemCategory5 : "pants", +/// // ... +/// ] +/// @endcode +static const char*const kParameterItemCategory5 = + "item_category5"; + +/// Item ID (context-specific) (String). +/// @code +/// let params = [ +/// AnalyticsParameterItemID : "SKU_12345", +/// // ... +/// ] +/// @endcode +static const char*const kParameterItemID = "item_id"; + +/// The ID of the list in which the item was presented to the +/// user (String). +/// @code +/// let params = [ +/// AnalyticsParameterItemListID : "ABC123", +/// // ... +/// ] +/// @endcode +static const char*const kParameterItemListID = + "item_list_id"; + +/// The name of the list in which the item was presented to the user +/// (String). +/// @code +/// let params = [ +/// AnalyticsParameterItemListName : "Related products", +/// // ... +/// ] +/// @endcode +static const char*const kParameterItemListName = + "item_list_name"; + +/// Item Name (context-specific) (String). +/// @code +/// let params = [ +/// AnalyticsParameterItemName : "jeggings", +/// // ... +/// ] +/// @endcode +static const char*const kParameterItemName = + "item_name"; + +/// Item variant (String). +/// @code +/// let params = [ +/// AnalyticsParameterItemVariant : "Black", +/// // ... +/// ] +/// @endcode +static const char*const kParameterItemVariant = + "item_variant"; + +/// The list of items involved in the transaction expressed as `[[String: +/// Any]]`. +/// @code +/// let params = [ +/// AnalyticsParameterItems : [ +/// [AnalyticsParameterItemName : "jeggings", AnalyticsParameterItemCategory : "pants"], +/// [AnalyticsParameterItemName : "boots", AnalyticsParameterItemCategory : "shoes"], +/// ], +/// ] +/// @endcode +static const char*const kParameterItems = "items"; + +/// Level in game (Int). +/// @code +/// let params = [ +/// AnalyticsParameterLevel : 42, +/// // ... +/// ] +/// @endcode +static const char*const kParameterLevel = "level"; + +/// The name of a level in a game (String). +/// @code +/// let params = [ +/// AnalyticsParameterLevelName : "room_1", +/// // ... +/// ] +/// @endcode +static const char*const kParameterLevelName = + "level_name"; + +/// Location (String). The Google Place ID +/// that corresponds to the associated event. Alternatively, you can supply your own custom +/// Location ID. +/// @code +/// let params = [ +/// AnalyticsParameterLocation : "ChIJiyj437sx3YAR9kUWC8QkLzQ", +/// // ... +/// ] +/// @endcode +static const char*const kParameterLocation = + "location"; + +/// The location associated with the event. Preferred to be the Google +/// Place ID that corresponds to the +/// associated item but could be overridden to a custom location ID +/// string.(String). +/// @code +/// let params = [ +/// AnalyticsParameterLocationID : "ChIJiyj437sx3YAR9kUWC8QkLzQ", +/// // ... +/// ] +/// @endcode +static const char*const kParameterLocationID = + "location_id"; + +/// Marketing Tactic (String). Used to identify the targeting criteria +/// applied to a specific campaign. +/// @code +/// let params = [ +/// AnalyticsParameterMarParameter(ketingTactic, "Remarketing"), +/// // ... +/// ] +/// @endcode +static const char*const kParameterMarketingTactic + = "marketing_tactic"; + +/// The advertising or marParameter(keting, cpc, banner, email), push. +/// Highly recommended (String). +/// @code +/// let params = [ +/// AnalyticsParameterMedium : "email", +/// // ... +/// ] +/// @endcode +static const char*const kParameterMedium = "medium"; + +/// A particular approach used in an operation; for example, "facebook" or +/// "email" in the context of a sign_up or login event. (String). +/// @code +/// let params = [ +/// AnalyticsParameterMethod : "google", +/// // ... +/// ] +/// @endcode +static const char*const kParameterMethod = "method"; + +/// Number of nights staying at hotel (Int). +/// @code +/// let params = [ +/// AnalyticsParameterNumberOfNights : 3, +/// // ... +/// ] +/// @endcode +static const char*const kParameterNumberOfNights + = "number_of_nights"; + +/// Number of passengers traveling (Int). +/// @code +/// let params = [ +/// AnalyticsParameterNumberOfPassengers : 11, +/// // ... +/// ] +/// @endcode +static const char*const kParameterNumberOfPassengers + = "number_of_passengers"; + +/// Number of rooms for travel events (Int). +/// @code +/// let params = [ +/// AnalyticsParameterNumberOfRooms : 2, +/// // ... +/// ] +/// @endcode +static const char*const kParameterNumberOfRooms = + "number_of_rooms"; + +/// Flight or Travel origin (String). +/// @code +/// let params = [ +/// AnalyticsParameterOrigin : "Mountain View, CA", +/// // ... +/// ] +/// @endcode +static const char*const kParameterOrigin = "origin"; + +/// The chosen method of payment (String). +/// @code +/// let params = [ +/// AnalyticsParameterPaymentType : "Visa", +/// // ... +/// ] +/// @endcode +static const char*const kParameterPaymentType = + "payment_type"; + +/// Purchase price (Double). +/// @code +/// let params = [ +/// AnalyticsParameterPrice : 1.0, +/// AnalyticsParameterCurrency : "USD", // e.g. $1.00 USD +/// // ... +/// ] +/// @endcode +static const char*const kParameterPrice = "price"; + +/// The ID of a product promotion (String). +/// @code +/// let params = [ +/// AnalyticsParameterPromotionID : "ABC123", +/// // ... +/// ] +/// @endcode +static const char*const kParameterPromotionID = + "promotion_id"; + +/// The name of a product promotion (String). +/// @code +/// let params = [ +/// AnalyticsParameterPromotionName : "Summer Sale", +/// // ... +/// ] +/// @endcode +static const char*const kParameterPromotionName = + "promotion_name"; + +/// Purchase quantity (Int). +/// @code +/// let params = [ +/// AnalyticsParameterQuantity : 1, +/// // ... +/// ] +/// @endcode +static const char*const kParameterQuantity = + "quantity"; + +/// Score in game (Int). +/// @code +/// let params = [ +/// AnalyticsParameterScore : 4200, +/// // ... +/// ] +/// @endcode +static const char*const kParameterScore = "score"; + +/// Current screen class, such as the class name of the UIViewController, +/// logged with screen_view event and added to every event (String). +/// @code +/// let params = [ +/// AnalyticsParameterScreenClass : "LoginViewController", +/// // ... +/// ] +/// @endcode +static const char*const kParameterScreenClass = + "screen_class"; + +/// Current screen name, such as the name of the UIViewController, logged +/// with screen_view event and added to every event (String). +/// @code +/// let params = [ +/// AnalyticsParameterScreenName : "LoginView", +/// // ... +/// ] +/// @endcode +static const char*const kParameterScreenName = + "screen_name"; + +/// The search string/keywords used (String). +/// @code +/// let params = [ +/// AnalyticsParameterSearchTerm : "periodic table", +/// // ... +/// ] +/// @endcode +static const char*const kParameterSearchTerm = + "search_term"; + +/// Shipping cost associated with a transaction (Double). +/// @code +/// let params = [ +/// AnalyticsParameterShipping : 5.99, +/// AnalyticsParameterCurrency : "USD", // e.g. $5.99 USD +/// // ... +/// ] +/// @endcode +static const char*const kParameterShipping = + "shipping"; + +/// The shipping tier (e.g. Ground, Air, Next-day) selected for delivery +/// of the purchased item (String). +/// @code +/// let params = [ +/// AnalyticsParameterShippingTier : "Ground", +/// // ... +/// ] +/// @endcode +static const char*const kParameterShippingTier = + "shipping_tier"; + +/// The origin of your traffic, such as an Ad network (for example, +/// google) or partner (urban airship). Identify the advertiser, site, +/// publication, etc. that is sending traffic to your property. Highly +/// recommended (String). +/// @code +/// let params = [ +/// AnalyticsParameterSource : "InMobi", +/// // ... +/// ] +/// @endcode +static const char*const kParameterSource = "source"; + +/// Source Platform (String). Used to identify the platform responsible +/// for directing traffic to a given Analytics property (e.g., a buying +/// platform where budgets, targeting criteria, etc. are set, a platform +/// for managing organic traffic data, etc.). +/// @code +/// let params = [ +/// AnalyticsParameterSourcePlatform : "sa360", +/// // ... +/// ] +/// @endcode +static const char*const kParameterSourcePlatform = + "source_platform"; + +/// The departure date, check-in date or rental start date for the item. +/// This should be in YYYY-MM-DD format (String). +/// @code +/// let params = [ +/// AnalyticsParameterStartDate : "2015-09-14", +/// // ... +/// ] +/// @endcode +static const char*const kParameterStartDate = + "start_date"; + +/// The result of an operation. Specify 1 to indicate success and 0 to +/// indicate failure (Int). +/// @code +/// let params = [ +/// AnalyticsParameterSuccess : 1, +/// // ... +/// ] +/// @endcode +static const char*const kParameterSuccess = "success"; + +/// Tax cost associated with a transaction (Double). +/// @code +/// let params = [ +/// AnalyticsParameterTax : 2.43, +/// AnalyticsParameterCurrency : "USD", // e.g. $2.43 USD +/// // ... +/// ] +/// @endcode +static const char*const kParameterTax = "tax"; + +/// If you're manually tagging keyword campaigns, you should use utm_term +/// to specify the keyword (String). +/// @code +/// let params = [ +/// AnalyticsParameterTerm : "game", +/// // ... +/// ] +/// @endcode +static const char*const kParameterTerm = "term"; + +/// The unique identifier of a transaction (String). +/// @code +/// let params = [ +/// AnalyticsParameterTransactionID : "T12345", +/// // ... +/// ] +/// @endcode +static const char*const kParameterTransactionID = + "transaction_id"; + +/// Travel class (String). +/// @code +/// let params = [ +/// AnalyticsParameterTravelClass : "business", +/// // ... +/// ] +/// @endcode +static const char*const kParameterTravelClass = + "travel_class"; + +/// A context-specific numeric value which is accumulated automatically +/// for each event type. This is a general purpose parameter that is +/// useful for accumulating a key metric that pertains to an event. +/// Examples include revenue, distance, time and points. Value should be +/// specified as Int or Double. Notes: Values for pre-defined +/// currency-related events (such as @c AnalyticsEventAddToCart) should be +/// supplied using Double and must be accompanied by a @c +/// AnalyticsParameterCurrency parameter. The valid range of accumulated +/// values is [-9,223,372,036,854.77, 9,223,372,036,854.77]. Supplying a +/// non-numeric value, omitting the corresponding @c +/// AnalyticsParameterCurrency parameter, or supplying an invalid +/// currency code for conversion events will cause that +/// conversion to be omitted from reporting. +/// @code +/// let params = [ +/// AnalyticsParameterValue : 3.99, +/// AnalyticsParameterCurrency : "USD", // e.g. $3.99 USD +/// // ... +/// ] +/// @endcode +static const char*const kParameterValue = "value"; + +/// Name of virtual currency type (String). +/// @code +/// let params = [ +/// AnalyticsParameterVirtualCurrencyName : "virtual_currency_name", +/// // ... +/// ] +/// @endcode +static const char*const kParameterVirtualCurrencyName + = "virtual_currency_name"; +/// @} + +} // namespace analytics +} // namespace firebase + +#endif // FIREBASE_ANALYTICS_CLIENT_CPP_INCLUDE_FIREBASE_ANALYTICS_PARAMETER_NAMES_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/analytics/user_property_names.h b/packages/firebase_core/firebase_core/firebase_core/firebase/analytics/user_property_names.h new file mode 100644 index 000000000000..155fea86e6f9 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/analytics/user_property_names.h @@ -0,0 +1,50 @@ +// Copyright 2023 Google Inc. All Rights Reserved. + +#ifndef FIREBASE_ANALYTICS_CLIENT_CPP_INCLUDE_FIREBASE_ANALYTICS_USER_PROPERTY_NAMES_H_ +#define FIREBASE_ANALYTICS_CLIENT_CPP_INCLUDE_FIREBASE_ANALYTICS_USER_PROPERTY_NAMES_H_ + +/// @brief Namespace that encompasses all Firebase APIs. +namespace firebase { +/// @brief Firebase Analytics API. +namespace analytics { + + + +/// @defgroup user_property_names Analytics User Properties +/// +/// Predefined user property names. +/// +/// A UserProperty is an attribute that describes the app-user. By +/// supplying UserProperties, you can later analyze different behaviors of +/// various segments of your userbase. You may supply up to 25 unique +/// UserProperties per app, and you can use the name and value of your +/// choosing for each one. UserProperty names can be up to 24 characters +/// long, may only contain alphanumeric characters and underscores ("_"), +/// and must start with an alphabetic character. UserProperty values can +/// be up to 36 characters long. The "firebase_", "google_", and "ga_" +/// prefixes are reserved and should not be used. +/// @{ + + +/// Indicates whether events logged by Google Analytics can be used to +/// personalize ads for the user. Set to "YES" to enable, or "NO" to +/// disable. Default is enabled. See the +/// documentation for +/// more details and information about related settings. +/// +/// @code +/// Analytics.setUserProperty("NO", forName: AnalyticsUserPropertyAllowAdPersonalizationSignals) +/// @endcode +static const char*const kUserPropertyAllowAdPersonalizationSignals + = "allow_personalized_ads"; + +/// The method used to sign in. For example, "google", "facebook" or +/// "twitter". +static const char*const kUserPropertySignUpMethod + = "sign_up_method"; +/// @} + +} // namespace analytics +} // namespace firebase + +#endif // FIREBASE_ANALYTICS_CLIENT_CPP_INCLUDE_FIREBASE_ANALYTICS_USER_PROPERTY_NAMES_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/app.h b/packages/firebase_core/firebase_core/firebase_core/firebase/app.h new file mode 100644 index 000000000000..0501f38ac0c8 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/app.h @@ -0,0 +1,787 @@ +/* + * Copyright 2016 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_APP_SRC_INCLUDE_FIREBASE_APP_H_ +#define FIREBASE_APP_SRC_INCLUDE_FIREBASE_APP_H_ + +#include "firebase/internal/platform.h" + +#if FIREBASE_PLATFORM_ANDROID +#include +#endif // FIREBASE_PLATFORM_ANDROID + +#include +#include +#include + +#if FIREBASE_PLATFORM_IOS || FIREBASE_PLATFORM_TVOS +#ifdef __OBJC__ +@class FIRApp; +#endif // __OBJC__ +#endif // FIREBASE_PLATFORM_IOS + +namespace firebase { + +#ifdef FIREBASE_LINUX_BUILD_CONFIG_STRING +// Check to see if the shared object compiler string matches the input +void CheckCompilerString(const char* input); +#endif // FIREBASE_LINUX_BUILD_CONFIG_STRING + +// Predeclarations. +#ifdef INTERNAL_EXPERIMENTAL +namespace internal { +class FunctionRegistry; +} // namespace internal +#endif // INTERNAL_EXPERIMENTAL + +#ifdef INTERNAL_EXPERIMENTAL +#if FIREBASE_PLATFORM_DESKTOP +namespace heartbeat { +class HeartbeatController; // forward declaration +} // namespace heartbeat +#endif // FIREBASE_PLATFORM_DESKTOP +#endif // INTERNAL_EXPERIMENTAL + +namespace internal { +class AppInternal; +} // namespace internal + +/// @brief Reports whether a Firebase module initialized successfully. +enum InitResult { + /// The given library was successfully initialized. + kInitResultSuccess = 0, + + /// The given library failed to initialize due to a missing dependency. + /// + /// On Android, this typically means that Google Play services is not + /// available and the library requires it. + /// @if cpp_examples + /// Use google_play_services::CheckAvailability() and + /// google_play_services::MakeAvailable() to resolve this issue. + /// @endif + /// + /// @if swig_examples + /// Use FirebaseApp.CheckDependencies() and + /// FirebaseApp.FixDependenciesAsync() to resolve this issue. + /// @endif + /// + /// + /// Also, on Android, this value can be returned if the Java dependencies of a + /// Firebase component are not included in the application, causing + /// initialization to fail. This means that the application's build + /// environment is not configured correctly. To resolve the problem, + /// see the SDK setup documentation for the set of Java dependencies (AARs) + /// required for the component that failed to initialize. + kInitResultFailedMissingDependency +}; + +/// @brief Default name for firebase::App() objects. +extern const char* const kDefaultAppName; + +/// @brief Options that control the creation of a Firebase App. +/// @if cpp_examples +/// @see firebase::App +/// @endif +/// +/// @if swig_examples +/// @see FirebaseApp +/// @endif +/// +class AppOptions { + friend class App; + + public: + /// @brief Create AppOptions. + /// + /// @if cpp_examples + /// To create a firebase::App object, the Firebase application identifier + /// and API key should be set using set_app_id() and set_api_key() + /// respectively. + /// + /// @see firebase::App::Create(). + /// @endif + /// + /// @if swig_examples + /// To create a FirebaseApp object, the Firebase application identifier + /// and API key should be set using AppId and ApiKey respectively. + /// + /// @see FirebaseApp.Create(). + /// @endif + /// + AppOptions() {} + + /// Set the Firebase app ID used to uniquely identify an instance of an app. + /// + /// This is the mobilesdk_app_id in the Android google-services.json config + /// file or GOOGLE_APP_ID in the GoogleService-Info.plist. + /// + /// This only needs to be specified if your application does not include + /// google-services.json or GoogleService-Info.plist in its resources. + void set_app_id(const char* id) { app_id_ = id; } + + /// Retrieves the app ID. + /// + /// @if cpp_examples + /// @see set_app_id(). + /// @endif + /// + /// + /// @xmlonly + /// + /// Gets or sets the App Id. + /// + /// This is the mobilesdk_app_id in the Android google-services.json config + /// file or GOOGLE_APP_ID in the GoogleService-Info.plist. + /// + /// This only needs to be specified if your application does not include + /// google-services.json or GoogleService-Info.plist in its resources. + /// + /// @endxmlonly + /// + const char* app_id() const { return app_id_.c_str(); } + + /// API key used to authenticate requests from your app. + /// + /// For example, "AIzaSyDdVgKwhZl0sTTTLZ7iTmt1r3N2cJLnaDk" used to identify + /// your app to Google servers. + /// + /// This only needs to be specified if your application does not include + /// google-services.json or GoogleService-Info.plist in its resources. + void set_api_key(const char* key) { api_key_ = key; } + + /// Get the API key. + /// + /// @if cpp_examples + /// @see set_api_key(). + /// @endif + /// + /// + /// @xmlonly + /// + /// Gets or sets the API key used to authenticate requests from your app. + /// + /// For example, \"AIzaSyDdVgKwhZl0sTTTLZ7iTmt1r3N2cJLnaDk\" used to identify + /// your app to Google servers. + /// + /// This only needs to be specified if your application does not include + /// google-services.json or GoogleService-Info.plist in its resources. + /// + /// @endxmlonly + /// + const char* api_key() const { return api_key_.c_str(); } + + /// Set the Firebase Cloud Messaging sender ID. + /// + /// For example "012345678901", used to configure Firebase Cloud Messaging. + /// + /// This only needs to be specified if your application does not include + /// google-services.json or GoogleService-Info.plist in its resources. + void set_messaging_sender_id(const char* sender_id) { + fcm_sender_id_ = sender_id; + } + + /// Get the Firebase Cloud Messaging sender ID. + /// + /// @if cpp_examples + /// @see set_messaging_sender_id(). + /// @endif + /// + /// + /// @xmlonly + /// + /// Gets or sets the messaging sender Id. + /// + /// This only needs to be specified if your application does not include + /// google-services.json or GoogleService-Info.plist in its resources. + /// + /// @endxmlonly + /// + const char* messaging_sender_id() const { return fcm_sender_id_.c_str(); } + + /// Set the database root URL, e.g. @"http://abc-xyz-123.firebaseio.com". + void set_database_url(const char* url) { database_url_ = url; } + + /// Get database root URL, e.g. @"http://abc-xyz-123.firebaseio.com". + /// + /// + /// @xmlonly + /// + /// Gets or sets the database root URL, e.g. + /// @\"http://abc-xyz-123.firebaseio.com\". + /// + /// @endxmlonly + /// + const char* database_url() const { return database_url_.c_str(); } + + /// @cond FIREBASE_APP_INTERNAL + + /// Set the tracking ID for Google Analytics, e.g. @"UA-12345678-1". + void set_ga_tracking_id(const char* id) { ga_tracking_id_ = id; } + + /// Get the tracking ID for Google Analytics, + /// + /// @if cpp_examples + /// @see set_ga_tracking_id(). + /// @endif + /// + const char* ga_tracking_id() const { return ga_tracking_id_.c_str(); } + + /// @endcond + + /// Set the Google Cloud Storage bucket name, + /// e.g. @\"abc-xyz-123.storage.firebase.com\". + void set_storage_bucket(const char* bucket) { storage_bucket_ = bucket; } + + /// Get the Google Cloud Storage bucket name, + /// @see set_storage_bucket(). + /// + /// @xmlonly + /// + /// Gets or sets the Google Cloud Storage bucket name, e.g. + /// @\"abc-xyz-123.storage.firebase.com\". + /// + /// @endxmlonly + /// + const char* storage_bucket() const { return storage_bucket_.c_str(); } + + /// Set the Google Cloud project ID. + void set_project_id(const char* project) { project_id_ = project; } + + /// Get the Google Cloud project ID. + /// + /// This is the project_id in the Android google-services.json config + /// file or PROJECT_ID in the GoogleService-Info.plist. + /// + /// @xmlonly + /// + /// Gets the Google Cloud project ID. + /// + /// This is the project_id in the Android google-services.json config + /// file or PROJECT_ID in the GoogleService-Info.plist. + /// + /// @endxmlonly + /// + const char* project_id() const { return project_id_.c_str(); } + +#ifdef INTERNAL_EXPERIMENTAL + /// @brief set the iOS client ID. + /// + /// This is the clientID in the GoogleService-Info.plist. + void set_client_id(const char* client_id) { client_id_ = client_id; } + + /// @brief Get the iOS client ID. + /// + /// This is the client_id in the GoogleService-Info.plist. + const char* client_id() const { return client_id_.c_str(); } +#endif // INTERNAL_EXPERIMENTAL + +#ifdef INTERNAL_EXPERIMENTAL + /// @brief Set the Android or iOS client project name. + /// + /// This is the project_name in the Android google-services.json config + /// file or BUNDLE_ID in the GoogleService-Info.plist. + void set_package_name(const char* package_name) { + package_name_ = package_name; + } + + /// @brief Get the Android or iOS client project name. + /// + /// This is the project_name in the Android google-services.json config + /// file or BUNDLE_ID in the GoogleService-Info.plist. + const char* package_name() const { return package_name_.c_str(); } +#endif // INTERNAL_EXPERIMENTAL + + /// @brief Load options from a config string. + /// + /// @param[in] config A JSON string that contains Firebase configuration i.e. + /// the content of the downloaded google-services.json file. + /// @param[out] options Optional: If provided, load options into it. + /// + /// @returns An instance containing the loaded options if successful. + /// If the options argument to this function is null, this method returns an + /// AppOptions instance allocated from the heap. + static AppOptions* LoadFromJsonConfig(const char* config, + AppOptions* options = nullptr); + +#if INTERNAL_EXPERIMENTAL + /// @brief Determine whether the specified options match this set of options. + /// + /// Fields of this object that are empty are ignored in the comparison. + /// + /// @param[in] options Options to compare with. + bool operator==(const AppOptions& options) const { + return (package_name_.empty() || package_name_ == options.package_name_) && + (api_key_.empty() || api_key_ == options.api_key_) && + (app_id_.empty() || app_id_ == options.app_id_) && + (database_url_.empty() || database_url_ == options.database_url_) && + (ga_tracking_id_.empty() || + ga_tracking_id_ == options.ga_tracking_id_) && + (fcm_sender_id_.empty() || + fcm_sender_id_ == options.fcm_sender_id_) && + (storage_bucket_.empty() || + storage_bucket_ == options.storage_bucket_) && + (project_id_.empty() || project_id_ == options.project_id_); + } +#endif // INTERNAL_EXPERIMENTAL + +#if INTERNAL_EXPERIMENTAL + /// @brief Determine whether the specified options don't match this set of + /// options. + /// + /// Fields of this object that are empty are ignored in the comparison. + /// + /// @param[in] options Options to compare with. + bool operator!=(const AppOptions& options) const { + return !operator==(options); + } +#endif // INTERNAL_EXPERIMENTAL + +#if INTERNAL_EXPERIMENTAL +#if FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) + /// @brief Load default options from the resource file. + /// + /// @param[in] jni_env JNI environment required to allow Firebase services + /// to interact with the Android framework. + /// @param[in] activity JNI reference to the Android activity, required to + /// allow Firebase services to interact with the Android application. + /// @param options Options to populate from a resource file. + /// + /// @return An instance containing the loaded options if successful. + /// If the options argument to this function is null, this method returns an + /// AppOptions instance allocated from the heap.. + static AppOptions* LoadDefault(AppOptions* options, JNIEnv* jni_env, + jobject activity); +#endif // FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) + +#if !FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) + /// @brief Load default options from the resource file. + /// + /// @param options Options to populate from a resource file. + /// + /// @return An instance containing the loaded options if successful. + /// If the options argument to this function is null, this method returns an + /// AppOptions instance allocated from the heap. + static AppOptions* LoadDefault(AppOptions* options); +#endif // !FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) +#endif // INTERNAL_EXPERIMENTAL + +#if INTERNAL_EXPERIMENTAL +#if FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) + /// @brief Attempt to populate required options with default values if not + /// specified. + /// + /// @param[in] jni_env JNI environment required to allow Firebase services + /// to interact with the Android framework. + /// @param[in] activity JNI reference to the Android activity, required to + /// allow Firebase services to interact with the Android application. + /// + /// @return true if successful, false otherwise. + bool PopulateRequiredWithDefaults(JNIEnv* jni_env, jobject activity); +#endif // FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) + +#if !FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) + /// @brief Attempt to populate required options with default values if not + /// specified. + /// + /// @return true if successful, false otherwise. + bool PopulateRequiredWithDefaults(); +#endif // !FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) +#endif // INTERNAL_EXPERIMENTAL + + /// @cond FIREBASE_APP_INTERNAL + private: + /// Application package name (e.g Android package name or iOS bundle ID). + std::string package_name_; + /// API key used to communicate with Google Servers. + std::string api_key_; + /// ID of the app. + std::string app_id_; + /// ClientID of the app. + std::string client_id_; + /// Database root URL. + std::string database_url_; + /// Google analytics tracking ID. + std::string ga_tracking_id_; + /// FCM sender ID. + std::string fcm_sender_id_; + /// Google Cloud Storage bucket name. + std::string storage_bucket_; + /// Google Cloud project ID. + std::string project_id_; + /// @endcond +}; + +/// @brief Firebase application object. +/// +/// @if cpp_examples +/// firebase::App acts as a conduit for communication between all Firebase +/// services used by an application. +/// +/// For example: +/// @code +/// #if defined(__ANDROID__) +/// firebase::App::Create(firebase::AppOptions(), jni_env, activity); +/// #else +/// firebase::App::Create(firebase::AppOptions()); +/// #endif // defined(__ANDROID__) +/// @endcode +/// @endif +/// +/// @if swig_examples +/// FirebaseApp acts as a conduit for communication between all Firebase +/// services used by an application. A default instance is created +/// automatically, based on settings in your Firebase configuration file, +/// and all of the Firebase APIs connect with it automatically. +/// @endif +class App { + public: + ~App(); + +#if !FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) + /// @brief Initializes the default firebase::App with default options. + /// + /// @note This method is specific to non-Android implementations. + /// + /// @return New App instance, the App should not be destroyed for the + /// lifetime of the application. If default options can't be loaded this + /// will return null. + static App* Create(); +#endif // !FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) + +#ifndef SWIG +// +// For Unity, we actually use the simpler, iOS version for both platforms +// +#if FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) + /// @brief Initializes the default firebase::App with default options. + /// + /// @note This method is specific to the Android implementation. + /// + /// @param[in] jni_env JNI environment required to allow Firebase services + /// to interact with the Android framework. + /// @param[in] activity JNI reference to the Android activity, required to + /// allow Firebase services to interact with the Android application. + /// + /// @return New App instance. The App should not be destroyed for the + /// lifetime of the application. If default options can't be loaded this + /// will return null. + static App* Create(JNIEnv* jni_env, jobject activity); +#endif // FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) +#endif // SWIG + +#if !FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) + /// @brief Initializes the default firebase::App with the given options. + /// + /// @note This method is specific to non-Android implementations. + /// + /// Options are copied at initialization time, so changes to the object are + /// ignored. + /// @param[in] options Options that control the creation of the App. + /// + /// @return New App instance, the App should not be destroyed for the + /// lifetime of the application. + static App* Create(const AppOptions& options); +#endif // !FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) + +#ifndef SWIG +// +// For Unity, we actually use the simpler, iOS version for both platforms +// +#if FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) + /// @brief Initializes the default firebase::App with the given options. + /// + /// @note This method is specific to the Android implementation. + /// + /// Options are copied at initialization time, so changes to the object are + /// ignored. + /// @param[in] options Options that control the creation of the App. + /// @param[in] jni_env JNI environment required to allow Firebase services + /// to interact with the Android framework. + /// @param[in] activity JNI reference to the Android activity, required to + /// allow Firebase services to interact with the Android application. + /// + /// @return New App instance. The App should not be destroyed for the + /// lifetime of the application. + static App* Create(const AppOptions& options, JNIEnv* jni_env, + jobject activity); +#endif // FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) +#endif // SWIG + +#if !FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) + /// @brief Initializes a firebase::App with the given options that operates + /// on the named app. + /// + /// @note This method is specific to non-Android implementations. + /// + /// Options are copied at initialization time, so changes to the object are + /// ignored. + /// @param[in] options Options that control the creation of the App. + /// @param[in] name Name of this App instance. This is only required when + /// one application uses multiple App instances. + /// + /// @return New App instance, the App should not be destroyed for the + /// lifetime of the application. + static App* Create(const AppOptions& options, const char* name); +#endif // !FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) + +#ifndef SWIG +// +// For Unity, we actually use the simpler iOS version for both platforms +// +#if FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) + /// @brief Initializes a firebase::App with the given options that operates + /// on the named app. + /// + /// @note This method is specific to the Android implementation. + /// + /// Options are copied at initialization time, so changes to the object are + /// ignored. + /// @param[in] options Options that control the creation of the App. + /// @param[in] name Name of this App instance. This is only required when + /// one application uses multiple App instances. + /// @param[in] jni_env JNI environment required to allow Firebase services + /// to interact with the Android framework. + /// @param[in] activity JNI reference to the Android activity, required to + /// allow Firebase services to interact with the Android application. + /// + /// @return New App instance. The App should not be destroyed for the + /// lifetime of the application. + static App* Create(const AppOptions& options, const char* name, + JNIEnv* jni_env, jobject activity); +#endif // FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) +#endif // SWIG + + /// Get the default App, or nullptr if none has been created. + static App* GetInstance(); + + /// Get the App with the given name, or nullptr if none have been created. + static App* GetInstance(const char* name); + +#ifndef SWIG +// +// Unity doesn't need the JNI from here, it has its method to access JNI. +// +#if FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) + /// Get Java virtual machine, retrieved from the initial JNI environment. + /// @note This method is specific to the Android implementation. + /// + /// @return JNI Java virtual machine object. + JavaVM* java_vm() const; + /// Get JNI environment, needed for performing JNI calls, set on creation. + /// This is not trivial as the correct environment needs to retrieved per + /// thread. + /// @note This method is specific to the Android implementation. + /// + /// @return JNI environment object. + JNIEnv* GetJNIEnv() const; + /// Get a global reference to the Android activity provided to the App on + /// creation. Also serves as the Context needed for Firebase calls. + /// @note This method is specific to the Android implementation. + /// + /// @return Global JNI reference to the Android activity used to create + /// the App. The reference count of the returned object is not increased. + jobject activity() const { return activity_; } +#endif // FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) +#endif // SWIG + + /// Get the name of this App instance. + /// + /// @return The name of this App instance. If a name wasn't provided via + /// Create(), this returns @ref kDefaultAppName. + /// + /// @xmlonly + /// + /// Get the name of this FirebaseApp instance. + /// If a name wasn't provided via Create(), this will match @ref DefaultName. + /// + /// @endxmlonly + /// + const char* name() const { return name_.c_str(); } + + /// Get options the App was created with. + /// + /// @return Options used to create the App. + /// + /// @xmlonly + /// + /// @brief Get the AppOptions the FirebaseApp was created with. + /// @return AppOptions used to create the FirebaseApp. + /// + /// @endxmlonly + /// + const AppOptions& options() const { return options_; } + +#ifdef INTERNAL_EXPERIMENTAL + /// Sets whether automatic data collection is enabled for all products. + /// + /// By default, automatic data collection is enabled. To disable automatic + /// data collection in your mobile app, add to your Android application's + /// manifest: + /// + /// @if NOT_DOXYGEN + /// + /// @else + /// @code + /// <meta-data android:name="firebase_data_collection_default_enabled" + /// android:value="false" /> + /// @endcode + /// @endif + /// + /// or on iOS to your Info.plist: + /// + /// @if NOT_DOXYGEN + /// FirebaseDataCollectionDefaultEnabled + /// + /// @else + /// @code + /// <key>FirebaseDataCollectionDefaultEnabled</key> + /// <false/> + /// @endcode + /// @endif + /// + /// Once your mobile app is set to disable automatic data collection, you can + /// ask users to consent to data collection, and then enable it after their + /// approval by calling this method. + /// + /// This value is persisted across runs of the app so that it can be set once + /// when users have consented to collection. + /// + /// @param enabled Whether or not to enable automatic data collection. + void SetDataCollectionDefaultEnabled(bool enabled); + + /// Gets whether automatic data collection is enabled for all + /// products. Defaults to true unless + /// "firebase_data_collection_default_enabled" is set to false in your + /// Android manifest and FirebaseDataCollectionDefaultEnabled is set to NO + /// in your iOS app's Info.plist. + /// + /// @return Whether or not automatic data collection is enabled for all + /// products. + bool IsDataCollectionDefaultEnabled() const; +#endif // INTERNAL_EXPERIMENTAL +#ifdef SWIG + void SetDataCollectionDefaultEnabled(bool enabled); + bool IsDataCollectionDefaultEnabled() const; +#endif // SWIG + +#ifdef INTERNAL_EXPERIMENTAL + // This is only visible to SWIG and internal users of firebase::App. + /// Get the initialization results of modules that were initialized when + /// creating this app. + /// + /// @return Initialization results of modules indexed by module name. + const std::map& init_results() const { + return init_results_; + } + + // Returns a pointer to the function registry, used by components to expose + // methods to one another without introducing linkage dependencies. + internal::FunctionRegistry* function_registry(); + + /// @brief Register a library which utilizes the Firebase C++ SDK. + /// + /// @param library Name of the library to register as a user of the Firebase + /// C++ SDK. + /// @param version Version of the library being registered. + static void RegisterLibrary(const char* library, const char* version); + + // Internal method to retrieve the combined string of registered libraries. + static const char* GetUserAgent(); + + // On desktop, when App.Create() is invoked without parameters, it looks for a + // file named 'google-services-desktop.json', to load parameters from. + // This function sets the location to search in. + // Note - when setting this, make sure to end the path with the appropriate + // path separator! + static void SetDefaultConfigPath(const char* path); +#endif // INTERNAL_EXPERIMENTAL + +#ifdef INTERNAL_EXPERIMENTAL +#if FIREBASE_PLATFORM_DESKTOP + // These methods are only visible to SWIG and internal users of firebase::App. + + /// Logs a heartbeat using the internal HeartbeatController. + void LogHeartbeat() const; + + /// Get a pointer to the HeartbeatController associated with this app. + std::shared_ptr GetHeartbeatController() + const; +#endif // FIREBASE_PLATFORM_DESKTOP +#endif // INTERNAL_EXPERIMENTAL + +#ifdef INTERNAL_EXPERIMENTAL +#if FIREBASE_PLATFORM_ANDROID + /// Get the platform specific app implementation referenced by this object. + /// + /// @return Global reference to the FirebaseApp. The returned reference + /// most be deleted after use. + jobject GetPlatformApp() const; +#elif FIREBASE_PLATFORM_IOS || FIREBASE_PLATFORM_TVOS +#ifdef __OBJC__ + /// Get the platform specific app implementation referenced by this object. + /// + /// @return Reference to the FIRApp object owned by this app. + FIRApp* GetPlatformApp() const; +#endif // __OBJC__ +#endif // FIREBASE_PLATFORM_ANDROID, FIREBASE_PLATFORM_IOS, + // FIREBASE_PLATFORM_TVOS +#endif // INTERNAL_EXPERIMENTAL + + private: + /// Construct the object. + App() + : +#if FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) + activity_(nullptr), +#endif + internal_(nullptr) { + Initialize(); + +#ifdef FIREBASE_LINUX_BUILD_CONFIG_STRING + CheckCompilerString(FIREBASE_LINUX_BUILD_CONFIG_STRING); +#endif // FIREBASE_LINUX_BUILD_CONFIG_STRING + } + + /// Initialize internal implementation + void Initialize(); + +#ifndef SWIG +// +// Unity doesn't need the JNI from here, it has its method to access JNI. +// +#if FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) + /// Android activity. + /// @note This is specific to Android. + jobject activity_; +#endif // FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) +#endif // SWIG + + /// Name of the App instance. + std::string name_; + /// Options used to create this App instance. + AppOptions options_; + /// Module initialization results. + std::map init_results_; + /// Pointer to other internal data used by this instance. + internal::AppInternal* internal_; + + /// @endcond +}; + +} // namespace firebase + +#endif // FIREBASE_APP_SRC_INCLUDE_FIREBASE_APP_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/auth.h b/packages/firebase_core/firebase_core/firebase_core/firebase/auth.h new file mode 100644 index 000000000000..408c34ea9006 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/auth.h @@ -0,0 +1,939 @@ +/* + * Copyright 2016 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_AUTH_SRC_INCLUDE_FIREBASE_AUTH_H_ +#define FIREBASE_AUTH_SRC_INCLUDE_FIREBASE_AUTH_H_ + +#include + +#include "firebase/app.h" +#include "firebase/auth/user.h" +#include "firebase/future.h" +#include "firebase/internal/common.h" + +#if !defined(DOXYGEN) +#ifndef SWIG +FIREBASE_APP_REGISTER_CALLBACKS_REFERENCE(auth) +#endif // SWIG +#endif // !defined(DOXYGEN) + +namespace firebase { + +/// @brief Firebase Authentication API. +/// +/// Firebase Authentication provides backend services to securely authenticate +/// users. It can authenticate users using passwords and federated identity +/// provider credentials, and it can integrate with a custom auth backend. +namespace auth { + +// Predeclarations. +struct AuthData; +class AuthStateListener; +class IdTokenListener; +class PhoneAuthProvider; +struct AuthCompletionHandle; +class FederatedAuthProvider; +class FederatedOAuthProvider; +struct SignInResult; + +/// @brief Firebase authentication object. +/// +/// +/// @if swig_examples +/// Firebase.Auth.FirebaseAuth is the gateway to the Firebase authentication +/// API. With it, you can reference @ref Firebase.Auth.FirebaseAuth objects to +/// manage user accounts and credentials. +/// +/// Each @ref Firebase.FirebaseApp has up to one Firebase.Auth.FirebaseAuth +/// class. You acquire the Firebase.Auth.FirebaseAuth class through the static +/// function @ref Firebase.Auth.FirebaseAuth.GetAuth. +/// +/// For example: +/// @code{.cs} +/// // Get the Auth class for your App. +/// Firebase.Auth.FirebaseAuth auth = Firebase.Auth.FirebaseAuth.GetAuth(app); +/// +/// // Request anonymous sign-in and wait until asynchronous call completes. +/// auth.SignInAnonymouslyAsync().ContinueWith((authTask) => { +/// // Print sign in results. +/// if (authTask.IsCanceled) { +/// DebugLog("Sign-in canceled."); +/// } else if (authTask.IsFaulted) { +/// DebugLog("Sign-in encountered an error."); +/// DebugLog(authTask.Exception.ToString()); +/// } else if (authTask.IsCompleted) { +/// Firebase.Auth.User user = authTask.Result; +/// DebugLog(String.Format("Signed in as {0} user.", +/// user.Anonymous ? "an anonymous" : "a non-anonymous")); +/// DebugLog("Signing out."); +/// auth.SignOut(); +/// }); +/// @endcode +/// @endif +/// +/// @if cpp_examples +/// +/// firebase::auth::Auth is the gateway to the Firebase authentication API. +/// With it, you can reference @ref firebase::auth::User objects to manage user +/// accounts and credentials. +/// +/// Each @ref firebase::App has up to one firebase::auth::Auth class. You +/// acquire the firebase::auth::Auth class through the static function +/// @ref firebase::auth::Auth::GetAuth. +/// +/// For example: +/// @code{.cpp} +/// +/// // Get the Auth class for your App. +/// firebase::auth::Auth* auth = firebase::auth::Auth::GetAuth(app); +/// +/// // Request anonymous sign-in and wait until asynchronous call completes. +/// firebase::Future sign_in_future = +/// auth->SignInAnonymously(); +/// while(sign_in_future.status() == firebase::kFutureStatusPending) { +/// // when polling, like this, make sure you service your platform's +/// // message loop +/// // see https://github.com/firebase/quickstart-cpp for a sample +/// ProcessEvents(300); +/// std::cout << "Signing in...\n"; +/// } +/// +/// const firebase::auth::AuthError error = +/// static_cast(sign_in_future.error()); +/// if (error != firebase::auth::kAuthErrorNone) { +/// std::cout << "Sign in failed with error '" +/// << sign_in_future.error_message() << "'\n"; +/// } else { +/// firebase::auth::User* user = *sign_in_future.result(); +/// // is_anonymous from Anonymous +/// std::cout << "Signed in as " +/// << (user->is_anonymous() ? "an anonymous" : "a non-anonymous") +/// << " user\n"; +/// } +/// @endcode +/// @endif +class Auth { + public: + /// @brief Results of calls @ref FetchProvidersForEmail. + /// + /// + /// @if swig_examples + /// @see FirebaseAuth.FetchProvidersForEmailAsync(). + /// @endif + /// + struct FetchProvidersResult { + /// The IDPs (identity providers) that can be used for `email`. + /// An array of length `num_providers` of null-terminated strings. + /// + /// The C# doc string is in the SWIG file because nested structs are + /// causing problems b/35780150 + /// + std::vector providers; + }; + + ~Auth(); + + /// Synchronously gets the cached current user, or nullptr if there is none. + /// @note This function may block and wait until the Auth instance finishes + /// loading the saved user's state. This should only happen for a short + /// period of time after the Auth instance is created. + /// + /// @xmlonly + /// + /// Synchronously gets the cached current user, or null if there is none. + /// @note This function may block and wait until the Auth instance finishes + /// loading the saved user's state. This should only happen for a short + /// period of time after the Auth instance is created. + /// + /// @endxmlonly + /// + User* current_user(); + + /// The current user language code. This can be set to the app’s current + /// language by calling set_language_code. The string must be a language code + /// that follows BCP 47. This will return an empty string if the app default + /// language code is being used. + std::string language_code() const; + + /// Sets the user-facing language code for auth operations that can be + /// internationalized, such as FirebaseUser.sendEmailVerification(). This + /// language code should follow the conventions defined by the IETF in BCP 47. + void set_language_code(const char* language_code); + + /// Sets the user-facing language code to be the default app language. This + /// uses a language associated with the device's locale data. On desktop + /// this will set the language code to the Firebase service's default. You + /// may subsequently customize the language code again by invoking + /// set_language_code(). + void UseAppLanguage(); + + // ----- Providers ------------------------------------------------------- + /// Asynchronously requests the IDPs (identity providers) that can be used + /// for the given email address. + /// + /// Useful for an "identifier-first" login flow. + /// + /// @if cpp_examples + /// The following sample code illustrates a possible login screen + /// that allows the user to pick an identity provider. + /// @code{.cpp} + /// // This function is called every frame to display the login screen. + /// // Returns the identity provider name, or "" if none selected. + /// const char* DisplayIdentityProviders(firebase::auth::Auth& auth, + /// const char* email) { + /// // Get results of most recent call to FetchProvidersForEmail(). + /// firebase::Future future = + /// auth.FetchProvidersForEmailLastResult(); + /// const firebase::auth::Auth::FetchProvidersResult* result = + /// future.result(); + /// + /// // Header. + /// ShowTextBox("Sign in %s", email); + /// + /// // Fetch providers from the server if we need to. + /// const bool refetch = + /// future.status() == firebase::kFutureStatusInvalid || + /// (result != nullptr && strcmp(email, result->email.c_str()) != 0); + /// if (refetch) { + /// auth.FetchProvidersForEmail(email); + /// } + /// + /// // Show a waiting icon if we're waiting for the asynchronous call to + /// // complete. + /// if (future.status() != firebase::kFutureStatusComplete) { + /// ShowImage("waiting icon"); + /// return ""; + /// } + /// + /// // Show error code if the call failed. + /// if (future.error() != firebase::auth::kAuthErrorNone) { + /// ShowTextBox("Error fetching providers: %s", future.error_message()); + /// } + /// + /// // Show a button for each provider available to this email. + /// // Return the provider for the button that's pressed. + /// for (size_t i = 0; i < result->providers.size(); ++i) { + /// const bool selected = ShowTextButton(result->providers[i].c_str()); + /// if (selected) return result->providers[i].c_str(); + /// } + /// return ""; + /// } + /// @endcode + /// @endif + Future FetchProvidersForEmail(const char* email); + + /// Get results of the most recent call to @ref FetchProvidersForEmail. + Future FetchProvidersForEmailLastResult() const; + + // ----- Sign In --------------------------------------------------------- + /// Asynchronously logs into Firebase with the given Auth token. + /// + /// An error is returned, if the token is invalid, expired or otherwise + /// not accepted by the server. + Future SignInWithCustomToken(const char* token); + + /// Get results of the most recent call to @ref SignInWithCustomToken. + Future SignInWithCustomTokenLastResult() const; + + /// Convenience method for @ref SignInAndRetrieveDataWithCredential that + /// doesn't return additional identity provider data. + Future SignInWithCredential(const Credential& credential); + + /// Get results of the most recent call to @ref SignInWithCredential. + Future SignInWithCredentialLastResult() const; + + /// Sign-in a user authenticated via a federated auth provider. + /// + /// @param[in] provider Contains information on the provider to authenticate + /// with. + /// + /// @return A Future with the result of the sign-in request. + /// + /// @note: This operation is supported only on iOS, tvOS and Android + /// platforms. On other platforms this method will return a Future with a + /// preset error code: kAuthErrorUnimplemented. + Future SignInWithProvider(FederatedAuthProvider* provider); + + /// Asynchronously logs into Firebase with the given credentials. + /// + /// For example, the credential could wrap a Facebook login access token or + /// a Twitter token/token-secret pair. + /// + /// The SignInResult contains both a reference to the User (which can be null + /// if the sign in failed), and AdditionalUserInfo, which holds details + /// specific to the Identity Provider used to sign in. + /// + /// An error is returned if the token is invalid, expired, or otherwise not + /// accepted by the server. + Future SignInAndRetrieveDataWithCredential( + const Credential& credential); + + /// Get results of the most recent call to + /// @ref SignInAndRetrieveDataWithCredential. + Future SignInAndRetrieveDataWithCredentialLastResult() const; + + /// Asynchronously creates and becomes an anonymous user. + /// If there is already an anonymous user signed in, that user will be + /// returned instead. + /// If there is any other existing user, that user will be signed out. + /// + /// + /// @if swig_examples + /// @code{.cs} + /// bool SignIn(Firebase.Auth.FirebaseAuth auth) { + /// auth.SignInAnonymouslyAsync().ContinueWith((authTask) => { + /// if (authTask.IsCanceled) { + /// DebugLog("Anonymous sign in canceled."); + /// } else if (authTask.IsFaulted) { + /// DebugLog("Anonymous sign in encountered an error."); + /// DebugLog(authTask.Exception.ToString()); + /// } else if (authTask.IsCompleted) { + /// DebugLog("Anonymous sign in successful!"); + /// } + /// }); + /// } + /// @endcode + /// @endif + /// + /// @if cpp_examples + /// The following sample code illustrates the sign-in flow that might be + /// used by a game or some other program with a regular (for example, 30Hz) + /// update loop. + /// + /// The sample calls SignIn() every frame. We don’t maintain our own + /// Futures but instead call SignInAnonymouslyLastResult() to get the Future + /// of our most recent call. + /// + /// @code{.cpp} + /// // Try to ensure that we get logged in. + /// // This function is called every frame. + /// bool SignIn(firebase::auth::Auth& auth) { + /// // Grab the result of the latest sign-in attempt. + /// firebase::Future future = + /// auth.SignInAnonymouslyLastResult(); + /// + /// // If we're in a state where we can try to sign in, do so. + /// if (future.status() == firebase::kFutureStatusInvalid || + /// (future.status() == firebase::kFutureStatusComplete && + /// future.error() != firebase::auth::kAuthErrorNone)) { + /// auth.SignInAnonymously(); + /// } + /// + /// // We're signed in if the most recent result was successful. + /// return future.status() == firebase::kFutureStatusComplete && + /// future.error() == firebase::auth::kAuthErrorNone; + /// } + /// @endcode + /// @endif + Future SignInAnonymously(); + + /// Get results of the most recent call to @ref SignInAnonymously. + Future SignInAnonymouslyLastResult() const; + + /// Signs in using provided email address and password. + /// An error is returned if the password is wrong or otherwise not accepted + /// by the server. + Future SignInWithEmailAndPassword(const char* email, + const char* password); + + /// Get results of the most recent call to @ref SignInWithEmailAndPassword. + Future SignInWithEmailAndPasswordLastResult() const; + + /// Creates, and on success, logs in a user with the given email address + /// and password. + /// + /// An error is returned when account creation is unsuccessful + /// (due to another existing account, invalid password, etc.). + Future CreateUserWithEmailAndPassword(const char* email, + const char* password); + + /// Get results of the most recent call to + /// @ref CreateUserWithEmailAndPassword. + Future CreateUserWithEmailAndPasswordLastResult() const; + + /// Removes any existing authentication credentials from this client. + /// This function always succeeds. + void SignOut(); + + // ----- Password Reset ------------------------------------------------- + /// Initiates a password reset for the given email address. + /// + /// If the email address is not registered, then the returned task has a + /// status of IsFaulted. + /// + /// + /// @if swig_examples + /// @code{.cs} + /// void ResetPassword(string email) { + /// auth.SendPasswordResetEmail(email).ContinueWith((authTask) => { + /// if (authTask.IsCanceled) { + /// DebugLog("Password reset was canceled."); + /// } else if (authTask.IsFaulted) { + /// DebugLog("Password reset encountered an error."); + /// DebugLog(authTask.Exception.ToString()); + /// } else if (authTask.IsCompleted) { + /// DebugLog("Password reset successful!"); + /// } + /// }); + /// } + /// @endcode + /// @endif + /// + /// @if cpp_examples + /// The following sample code illustrating a possible password reset flow. + /// Like in the Anonymous Sign-In example above, the ResetPasswordScreen() + /// function is called once per frame (say 30 times per second). + /// + /// No state is persisted by the caller in this example. The state of the + /// most recent calls are instead accessed through calls to functions like + /// auth.SendPasswordResetEmailLastResult(). + /// @code{.cpp} + /// const char* ImageNameForStatus(const firebase::FutureBase& future) { + /// assert(future.status() != firebase::kFutureStatusInvalid); + /// return future.status() == firebase::kFutureStatusPending + /// ? "waiting icon" + /// : future.error() == firebase::auth::kAuthErrorNone + /// ? "checkmark icon" + /// : "x mark icon"; + /// } + /// + /// // This function is called once per frame. + /// void ResetPasswordScreen(firebase::auth::Auth& auth) { + /// // Gather email address. + /// // ShowInputBox() returns a value when `enter` is pressed. + /// const std::string email = ShowInputBox("Enter e-mail"); + /// if (email != "") { + /// auth.SendPasswordResetEmail(email.c_str()); + /// } + /// + /// // Show checkmark, X-mark, or waiting icon beside the + /// // email input box, to indicate if email has been sent. + /// firebase::Future send_future = + /// auth.SendPasswordResetEmailLastResult(); + /// ShowImage(ImageNameForStatus(send_future)); + /// + /// // Display error message if the e-mail could not be sent. + /// if (send_future.status() == firebase::kFutureStatusComplete && + /// send_future.error() != firebase::auth::kAuthErrorNone) { + /// ShowTextBox(send_future.error_message()); + /// } + /// } + /// @endcode + /// @endif + Future SendPasswordResetEmail(const char* email); + + /// Get results of the most recent call to @ref SendPasswordResetEmail. + Future SendPasswordResetEmailLastResult() const; + +#ifndef SWIG + /// @brief Registers a listener to changes in the authentication state. + /// + /// There can be more than one listener registered at the same time. + /// The listeners are called asynchronously, possibly on a different thread. + /// + /// Authentication state changes are: + /// - Right after the listener has been registered + /// - When a user signs in + /// - When the current user signs out + /// - When the current user changes + /// + /// It is a recommended practice to always listen to sign-out events, as you + /// may want to prompt the user to sign in again and maybe restrict the + /// information or actions they have access to. + /// + /// Use RemoveAuthStateListener to unregister a listener. + /// + /// @note The caller owns `listener` and is responsible for destroying it. + /// When `listener` is destroyed, or when @ref Auth is destroyed, + /// RemoveAuthStateListener is called automatically. + void AddAuthStateListener(AuthStateListener* listener); + + /// @brief Unregisters a listener of authentication changes. + /// + /// Listener must previously been added with AddAuthStateListener. + /// + /// Note that listeners unregister themselves automatically when they + /// are destroyed, and the Auth class unregisters its listeners when the + /// Auth class itself is destroyed, so this function does not normally need + /// to be called explicitly. + void RemoveAuthStateListener(AuthStateListener* listener); + + /// @brief Registers a listener to changes in the ID token state. + /// + /// There can be more than one listener registered at the same time. + /// The listeners are called asynchronously, possibly on a different thread. + /// + /// Authentication state changes are: + /// - Right after the listener has been registered + /// - When a user signs in + /// - When the current user signs out + /// - When the current user changes + /// - When there is a change in the current user's token + /// + /// Use RemoveIdTokenListener to unregister a listener. + /// + /// @note The caller owns `listener` and is responsible for destroying it. + /// When `listener` is destroyed, or when @ref Auth is destroyed, + /// RemoveIdTokenListener is called automatically. + void AddIdTokenListener(IdTokenListener* listener); + + /// @brief Unregisters a listener of ID token changes. + /// + /// Listener must previously been added with AddIdTokenListener. + /// + /// Note that listeners unregister themselves automatically when they + /// are destroyed, and the Auth class unregisters its listeners when the + /// Auth class itself is destroyed, so this function does not normally need + /// to be called explicitly. + void RemoveIdTokenListener(IdTokenListener* listener); +#endif // not SWIG + + /// Gets the App this auth object is connected to. + App& app(); + + /// Returns the Auth object for an App. Creates the Auth if required. + /// + /// To get the Auth object for the default app, use, + /// GetAuth(GetDefaultFirebaseApp()); + /// + /// If the library Auth fails to initialize, init_result_out will be + /// written with the result status (if a pointer is given). + /// + /// @param[in] app The App to use for the Auth object. + /// @param[out] init_result_out Optional: If provided, write the init result + /// here. Will be set to kInitResultSuccess if initialization succeeded, or + /// kInitResultFailedMissingDependency on Android if Google Play services is + /// not available on the current device. + static Auth* GetAuth(App* app, InitResult* init_result_out = nullptr); + + private: + /// @cond FIREBASE_APP_INTERNAL + friend class ::firebase::App; + friend class ::firebase::auth::PhoneAuthProvider; + friend class IdTokenRefreshListener; + friend class IdTokenRefreshThread; + friend class UserDataPersist; + friend class UserDesktopTest; + friend class AuthDesktopTest; + + friend void EnableTokenAutoRefresh(AuthData* authData); + friend void DisableTokenAutoRefresh(AuthData* authData); + friend void ResetTokenRefreshCounter(AuthData* authData); + friend void LogHeartbeat(Auth* auth); + /// @endcond + + // Find Auth instance using App. Return null if the instance does not exist. + static Auth* FindAuth(App* app); + + // Provides access to the auth token for the current user. Returns the + // current user's auth token, or an empty string, if there isn't one. + // Note that this can potentially return an expired token from the cache. + static bool GetAuthTokenForRegistry(App* app, void* /*unused*/, void* out); + + // Provides asynchronous access to the auth token for the current user. Allow + // the caller to force-refresh the token. Even without force-refresh, this + // ensure the future contain a fresh current user's auth token. This function + // returns invalid future if user data is not available. + static bool GetAuthTokenAsyncForRegistry(App* app, void* force_refresh, + void* out_future); + + // Provides access to the current user's uid, equivalent to calling + // this->current_user()->uid(). Returns the current user's uid or an empty + // string, if there isn't one. The out pointer is expected to point to an + // instance of std::string. + static bool GetCurrentUserUidForRegistry(App* app, void* /*unused*/, + void* out); + + // Starts and stops a thread to ensure that the cached auth token is never + // kept long enough for it to expire. Refcounted, so multiple classes can + // register this without causing problems. + static bool StartTokenRefreshThreadForRegistry(App* app, void* /*unused*/, + void* /*unused*/); + static bool StopTokenRefreshThreadForRegistry(App* app, void* /*unused*/, + void* /*unused*/); + + // Adds an indirect auth state listener implemented as a callback and a + // context object. + // + // @param callback a function pointer that takes a single void* argument and + // returns void (i.e. it has type void (*)(void*)). + // @param context a pointer to an arbitrary object that Auth will pass to + // the callback when the auth state changes. + static bool AddAuthStateListenerForRegistry(App* app, void* callback, + void* context); + + // Removes the indirect auth state listener that was added with the same + // arguments. + static bool RemoveAuthStateListenerForRegistry(App* app, void* callback, + void* context); + + // Init and Destroy the platform specific auth data. + void InitPlatformAuth(AuthData* const auth_data); + void DestroyPlatformAuth(AuthData* const auth_data); + + // Call GetAuth() to create an Auth object. + // Constructors and destructors don't make any external calls. + // They just initialize and deinitialize internal variables. + Auth(App* app, void* auth_impl); + + // Delete the internal AuthData object. + void DeleteInternal(); + + // This class uses the pimpl mechanism to avoid exposing platform-dependent + // implementation. + AuthData* auth_data_; +}; + +#ifndef SWIG +/// @brief Listener called when there is a change in the authentication state. +/// +/// Override base class method to handle authentication state changes. +/// Methods are invoked asynchronously and may be invoked on other threads. +class AuthStateListener { + public: + /// @note: Destruction of the listener automatically calls + /// RemoveAuthStateListener() from the Auths this listener is registered with, + /// if those Auths have not yet been destroyed. + virtual ~AuthStateListener(); + + /// Called when the authentication state of `auth` changes. + /// - Right after the listener has been registered + /// - When a user is signed in + /// - When the current user is signed out + /// - When the current user changes + /// + /// @param[in] auth Disambiguates which @ref Auth instance the event + /// corresponds to, in the case where you are using more than one at the same + /// time. + virtual void OnAuthStateChanged(Auth* auth) = 0; + + private: + /// @cond FIREBASE_APP_INTERNAL + friend class Auth; + /// @endcond + + /// The Auths with which this listener has been registered. + std::vector auths_; +}; +#endif // not SWIG + +#ifndef SWIG +/// @brief Listener called when there is a change in the ID token. +/// +/// Override base class method to handle ID token changes. +/// Methods are invoked asynchronously and may be invoked on other threads. +class IdTokenListener { + public: + /// @note: Destruction of the listener automatically calls + /// RemoveIdTokenListener() from the Auths this listener is registered with, + /// if those Auths have not yet been destroyed. + virtual ~IdTokenListener(); + + /// Called when there is a change in the current user's token. + /// - Right after the listener has been registered + /// - When a user signs in + /// - When the current user signs out + /// - When the current user changes + /// - When there is a change in the current user's token + /// + /// @param[in] auth Disambiguates which @ref Auth instance the event + /// corresponds to, in the case where you are using more than one at the same + /// time. + virtual void OnIdTokenChanged(Auth* auth) = 0; + + private: + /// @cond FIREBASE_APP_INTERNAL + friend class Auth; + /// @endcond + + /// The Auths with which this listener has been registered. + std::vector auths_; +}; + +#endif // not SWIG + +/// @brief Used to authenticate with Federated Auth Providers. +/// +/// The federated auth provider implementation may facilitate multiple provider +/// types in the future, with support for OAuth to start. +class FederatedAuthProvider { + public: +#ifdef INTERNAL_EXPERIMENTAL +#ifndef SWIG + /// @brief Contains resulting information of a user authenticated by a + /// Federated Auth Provider. This information will be used by the internal + /// implementation to construct a corresponding User object. + struct AuthenticatedUserData { + /// The unique ID identifies the IdP account. + const char* uid; + + /// [opt] The email of the account. + const char* email; + + /// Whether the sign-in email is verified. + bool is_email_verified; + + /// [opt] The display name for the account. + const char* display_name; + + /// [opt] The username for the account. + const char* user_name; + + /// [opt] The photo Url for the account, if one exists. + const char* photo_url; + + /// The linked provider ID (e.g. "google.com" for the Google provider). + const char* provider_id; + + /// A Firebase Auth ID token for the authenticated user. + const char* access_token; + + /// A Firebase Auth refresh token for the authenticated user. + const char* refresh_token; + + /// [opt] IdP user profile data corresponding to the provided credential. + std::map raw_user_info; + + /// The number of seconds in which the ID token expires. + uint64_t token_expires_in_seconds; + }; + + /// @brief Handlers for client applications to facilitate federated auth + /// requests on non-mobile systems. + template + class Handler { + public: + virtual ~Handler() {} + + /// @brief Application sign-in handler. + /// + /// The application must implement this method to handle federated auth user + /// sign-in requests on non-mobile systems. + /// + /// @param[in] provider_data Contains information on the provider to + /// authenticate with. + /// @param[in] completion_handle Internal data pertaining to this operation + /// which must be passed to SignInComplete once the handler has completed + /// the sign in operation. + /// + /// @see Auth#SignInWithProvider + /// @see SignInComplete + virtual void OnSignIn(const T& provider_data, + AuthCompletionHandle* completion_handle) = 0; + + /// Completion for OnSignIn events. + /// + /// Invoke this method once the corresponding OnSignIn has been fulfilled. + /// This method will trigger the associated Future previously + /// returned from the Auth::SignInWithProvider method. + /// + /// @param[in] completion_handle The handle provided to the application's + /// FederatedAuthProvider::Handler::OnSignIn method. + /// @param[in] user_data The application's resulting Firebase user + /// values following the authorization request. + /// @param[in] auth_error The enumerated status code of the authorization + /// request. + /// @param[in] error_message An optional error message to be set in the + /// Future. + /// + /// @see OnSignIn + /// @see Auth::SignInWithProvider + void SignInComplete(AuthCompletionHandle* completion_handle, + const AuthenticatedUserData& user_data, + AuthError auth_error, const char* error_message); + + /// @brief Application user account link handler. + /// + /// The application must implement this method to handle federated auth user + /// link requests on non-mobile systems. + /// + /// @param[in] provider_data Contains information on the provider to + /// authenticate with. + /// @param[in] completion_handle Internal data pertaining to this operation + /// which must be passed to LinkComplete once the handler has completed the + /// user link operation. + /// + /// @see User#LinkWithProvider + virtual void OnLink(const T& provider_data, + AuthCompletionHandle* completion_handle) = 0; + + /// Completion for non-mobile user authorization handlers. + /// + /// Invoke this method once the OnLine process has been fulfilled. This + /// method will trigger the associated Future previously + /// returned from an invocation of User::LinkWithProvider. + /// + /// @param[in] completion_handle The handle provided to the + /// application's FederatedAuthProvider::Handler::OnLink method. + /// @param[in] user_data The application's resulting Firebase user + /// values following the user link request. + /// @param[in] auth_error The enumerated status code of the user link + /// request. + /// @param[in] error_message An optional error message to be set in the + /// Future. + /// + /// @see OnLink + /// @see User#LinkWithProvider + void LinkComplete(AuthCompletionHandle* completion_handle, + const AuthenticatedUserData& user_data, + AuthError auth_error, const char* error_message); + + /// @brief Application user re-authentication handler. + /// + /// The application must implement this method to handle federated auth user + /// re-authentication requests on non-mobile systems. + /// + /// @param[in] provider_data Contains information on the provider to + /// authenticate with. + /// @param[in] completion_handle Internal data pertaining to this operation + /// which must be passed to ReauthenticateComplete once the handler has + /// completed the reauthentication operation. + /// + /// @see User#ReauthenticateWithProviderComplete + virtual void OnReauthenticate(const T& provider_data, + AuthCompletionHandle* completion_handle) = 0; + + /// Completion for non-mobile user authorization handlers. + /// + /// Invoke this method once the OnReauthenticate process has been + /// fulfilled. This method will trigger the associated Future + /// previously returned from an invocation of + /// User::ReauthenticateWithProvider. + /// + /// @param[in] completion_handle The handle provided to the application's + /// FederatedAuthProvider::Handler::OnReauthenticate method. + /// @param[in] user_data The application's resulting Firebase user + /// values following the user re-authentication request. + /// @param[in] auth_error The enumerated status code of the reauthentication + /// request. + /// @param[in] error_message An optional error message to be set in the + /// Future. + /// + /// @see OnReauthenticate + /// @see User#ReuthenticateWithProvider + void ReauthenticateComplete(AuthCompletionHandle* completion_handle, + const AuthenticatedUserData& user_data, + AuthError auth_error, + const char* error_message); + }; +#endif // not SWIG +#endif // INTERNAL_EXPERIMENTAL + + FederatedAuthProvider() {} + virtual ~FederatedAuthProvider() {} + + private: + friend class ::firebase::auth::Auth; + friend class ::firebase::auth::User; + virtual Future SignIn(AuthData* auth_data) = 0; + virtual Future Link(AuthData* auth_data) = 0; + virtual Future Reauthenticate(AuthData* auth_data) = 0; +}; + +/// @brief Authenticates with Federated OAuth Providers via the +/// firebase::auth::Auth and firebase::auth::User classes. +/// +/// Once configured with a provider id, and with OAuth scope and OAuth custom +/// parameters via an FedeartedOAuthProviderData structure, an object of +/// this class may be used via Auth::SignInWithProvider to sign-in users, or via +/// User::LinkWithProvider and User::ReauthenticateWithProvider for cross +/// account linking and user reauthentication, respectively. +class FederatedOAuthProvider : public FederatedAuthProvider { + public: +#ifdef INTERNAL_EXPERIMENTAL +#ifndef SWIG + /// @brief A FederatedAuthProvider typed specifically for OAuth Authentication + /// handling. + /// + /// To be used on non-mobile environments for custom OAuth implementations and + /// UI flows. + typedef FederatedAuthProvider::Handler + AuthHandler; +#endif // !SWIG +#endif // INTERNAL_EXPERIMENTAL + + /// Constructs an unconfigured provider. + FederatedOAuthProvider(); + + /// Constructs a FederatedOAuthProvider preconfigured with provider data. + /// + /// @param[in] provider_data Contains the federated provider id and OAuth + /// scopes and OAuth custom parameters required for user authentication and + /// user linking. + explicit FederatedOAuthProvider( + const FederatedOAuthProviderData& provider_data); + +#ifdef INTERNAL_EXPERIMENTAL +#ifndef SWIG + /// @brief Constructs a provider with the required information to authenticate + /// using an OAuth Provider. + /// + /// An AuthHandler is required on desktop platforms to facilitate custom + /// implementations of OAuth authentication. The AuthHandler must outlive the + /// instance of this OAuthProvider on desktop systems and is ignored on iOS, + /// tvOS, and Android platforms. + /// + /// @param[in] provider_data Contains information on the provider to + /// authenticate with. + /// @param[in] handler An FederatedOAuthProviderData typed + /// FederatedAuthProvider::Handler which be invoked on non-mobile systems + /// to handle authentication requests. + FederatedOAuthProvider(const FederatedOAuthProviderData& provider_data, + AuthHandler* handler); +#endif // !SWIG +#endif // INTERNAL_EXPERIMENTAL + + ~FederatedOAuthProvider() override; + + /// @brief Configures the provider with OAuth provider information. + /// + /// @param[in] provider_data Contains the federated provider id and OAuth + /// scopes and OAuth custom parameters required for user authentication and + /// user linking. + void SetProviderData(const FederatedOAuthProviderData& provider_data); + +#ifdef INTERNAL_EXPERIMENTAL +#ifndef SWIG + /// @brief Configures the use of an AuthHandler for non-mobile systems. + /// + /// The existence of a handler is required for non-mobile systems, and is + /// ignored on iOS, tvOS and Android platforms. + /// + /// @param[in] handler An FederatedOAuthProviderData typed + /// FederatedAuthProvider::Handler which be invoked on non-mobile systems + /// to handle authentication requests. The handler must outlive the instance + /// of this FederatedOAuthProvider. + void SetAuthHandler(AuthHandler* handler); +#endif // !SWIG +#endif // INTERNAL_EXPERIMENTAL + + private: + friend class ::firebase::auth::Auth; + + Future SignIn(AuthData* auth_data) override; + Future Link(AuthData* auth_data) override; + Future Reauthenticate(AuthData* auth_data) override; + + FederatedOAuthProviderData provider_data_; +#ifdef INTERNAL_EXPERIMENTAL + AuthHandler* handler_; +#endif // INTERNAL_EXPERIMENTAL +}; + +} // namespace auth +} // namespace firebase + +#endif // FIREBASE_AUTH_SRC_INCLUDE_FIREBASE_AUTH_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/auth/credential.h b/packages/firebase_core/firebase_core/firebase_core/firebase/auth/credential.h new file mode 100644 index 000000000000..a179d199b67a --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/auth/credential.h @@ -0,0 +1,633 @@ +/* + * Copyright 2016 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_AUTH_SRC_INCLUDE_FIREBASE_AUTH_CREDENTIAL_H_ +#define FIREBASE_AUTH_SRC_INCLUDE_FIREBASE_AUTH_CREDENTIAL_H_ + +#include + +#include + +#include "firebase/auth/types.h" +#include "firebase/internal/common.h" + +namespace firebase { + +// Predeclarations. +class App; + +/// @cond FIREBASE_APP_INTERNAL +template +class Future; +/// @endcond + +namespace auth { + +// Predeclarations. +class Auth; +class User; + +// Opaque internal types. +struct AuthData; +class ForceResendingTokenData; +struct PhoneAuthProviderData; +struct PhoneListenerData; + +/// @brief Authentication credentials for an authentication provider. +/// +/// An authentication provider is a service that allows you to authenticate +/// a user. Firebase provides email/password authentication, but there are also +/// external authentication providers such as Facebook. +class Credential { +#ifndef SWIG + /// @cond FIREBASE_APP_INTERNAL + friend class EmailAuthProvider; + friend class FacebookAuthProvider; + friend class GameCenterAuthProvider; + friend class GitHubAuthProvider; + friend class GoogleAuthProvider; + friend class JniAuthPhoneListener; + friend class MicrosoftAuthProvider; + friend class OAuthProvider; + friend class PhoneAuthProvider; + friend class PlayGamesAuthProvider; + friend class TwitterAuthProvider; + friend class YahooAuthProvider; + friend class ServiceUpdatedCredentialProvider; + /// @endcond +#endif // !SWIG + + private: + /// Should only be created by `Provider` classes. + /// + /// @see EmailAuthProvider::GetCredential() + /// @see FacebookAuthProvider::GetCredential() + /// @see GoogleAuthProvider::GetCredential() + explicit Credential(void* impl) : impl_(impl), error_code_(kAuthErrorNone) {} + + public: + Credential() : impl_(nullptr), error_code_(kAuthErrorNone) {} + ~Credential(); + + /// Copy constructor. + Credential(const Credential& rhs); + + /// Copy a Credential. + Credential& operator=(const Credential& rhs); + + /// Gets the name of the Identification Provider (IDP) for the credential. + /// + /// + /// @xmlonly + /// + /// Gets the name of the Identification Provider (IDP) for the credential. + /// + /// @endxmlonly + /// + std::string provider() const; + + /// Get whether this credential is valid. A credential can be + /// invalid in an error condition, e.g. empty username/password. + /// + /// @returns True if the credential is valid, false otherwise. + bool is_valid() const; + + protected: + /// @cond FIREBASE_APP_INTERNAL + friend class Auth; + friend class User; + + /// Platform-specific implementation. + /// For example, FIRAuthCredential* on iOS. + void* impl_; + + // If not kAuthErrorNone, then use this error code and string to override + // whatever error we would normally return when trying to sign-in with this + // credential. + AuthError error_code_; + std::string error_message_; + /// @endcond +}; + +/// @brief Use email and password to authenticate. +/// +/// Allows developers to use the email and password credentials as they could +/// other auth providers. For example, this can be used to change passwords, +/// log in, etc. +class EmailAuthProvider { + public: + /// Generate a credential from the given email and password. + /// + /// @param email E-mail to generate the credential from. + /// @param password Password to use for the new credential. + /// + /// @returns New Credential. + static Credential GetCredential(const char* email, const char* password); + + /// The string used to identify this provider. + static const char* const kProviderId; +}; + +/// @brief Use an access token provided by Facebook to authenticate. +class FacebookAuthProvider { + public: + /// Generate a credential from the given Facebook token. + /// + /// @param access_token Facebook token to generate the credential from. + /// + /// @returns New Credential. + static Credential GetCredential(const char* access_token); + + /// The string used to identify this provider. + static const char* const kProviderId; +}; + +/// @brief GameCenter (Apple) auth provider +class GameCenterAuthProvider { + public: + /// Generate a credential from GameCenter for the current user. + /// + /// @return a Future that will be fulfilled with the resulting credential. + static Future GetCredential(); + + /// Get the result of the most recent GetCredential() call. + /// + /// @return an object which can be used to retrieve the Credential. + static Future GetCredentialLastResult(); + + /// Tests to see if the current user is signed in to GameCenter. + /// + /// @return true if the user is signed in, false otherwise. + static bool IsPlayerAuthenticated(); + + /// The string used to identify this provider. + static const char* const kProviderId; +}; + +/// @brief Use an access token provided by GitHub to authenticate. +class GitHubAuthProvider { + public: + /// Generate a credential from the given GitHub token. + /// + /// @param token The GitHub OAuth access token. + /// + /// @returns New Credential. + static Credential GetCredential(const char* token); + + /// The string used to identify this provider. + static const char* const kProviderId; +}; + +/// @brief Use an ID token and access token provided by Google to authenticate. +class GoogleAuthProvider { + public: + /// Generate a credential from the given Google ID token and/or access token. + /// + /// @param id_token Google Sign-In ID token. + /// @param access_token Google Sign-In access token. + /// + /// @returns New Credential. + static Credential GetCredential(const char* id_token, + const char* access_token); + + /// The string used to identify this provider. + static const char* const kProviderId; +}; + +/// @brief Use an access token provided by Microsoft to authenticate. +class MicrosoftAuthProvider { + public: + /// The string used to identify this provider. + static const char* const kProviderId; +}; + +/// @brief OAuth2.0+UserInfo auth provider (OIDC compliant and non-compliant). +class OAuthProvider { + public: + /// Generate a credential for an OAuth2 provider. + /// + /// @param provider_id Name of the OAuth2 provider + /// TODO(jsanmiya) add examples. + /// @param id_token The authentication token (OIDC only). + /// @param access_token TODO(jsanmiya) add explanation (currently missing + /// from Android and iOS implementations). + static Credential GetCredential(const char* provider_id, const char* id_token, + const char* access_token); + + /// Generate a credential for an OAuth2 provider. + /// + /// @param provider_id Name of the OAuth2 provider. + /// @param id_token The authentication token (OIDC only). + /// @param raw_nonce The raw nonce associated with the Auth credential being + /// created. + /// @param access_token The access token associated with the Auth credential + /// to be created, if available. This value may be null. + static Credential GetCredential(const char* provider_id, const char* id_token, + const char* raw_nonce, + const char* access_token); +}; + +/// @brief Use phone number text messages to authenticate. +/// +/// Allows developers to use the phone number and SMS verification codes +/// to authenticate a user on a mobile device. +/// +/// This class is not supported on tvOS and Desktop platforms. +/// +/// The verification flow results in a Credential that can be used to, +/// * Sign in to an existing phone number account/sign up with a new +/// phone number +/// * Link a phone number to a current user. This provider will be added to +/// the user. +/// * Update a phone number on an existing user. +/// * Re-authenticate an existing user. This may be needed when a sensitive +/// operation requires the user to be recently logged in. +/// +/// Possible verification flows: +/// (1) User manually enters verification code. +/// @if cpp_examples +/// - App calls @ref VerifyPhoneNumber. +/// - Web verification page is displayed to user where they may need to +/// solve a CAPTCHA. [iOS only]. +/// - Auth server sends the verification code via SMS to the provided +/// phone number. App receives verification id via Listener::OnCodeSent(). +/// - User receives SMS and enters verification code in app's GUI. +/// - App uses user's verification code to call +/// @ref PhoneAuthProvider::GetCredential. +/// @endif +/// +/// @if swig_examples +/// - App calls @ref VerifyPhoneNumber. +/// - Web verification page is displayed to user where they may need to +/// solve a CAPTCHA. [iOS only]. +/// - Auth server sends the verification code via SMS to the provided +/// phone number. App receives verification id via @ref CodeSent. +/// - User receives SMS and enters verification code in app's GUI. +/// - App uses user's verification code to call +/// @ref PhoneAuthProvider::GetCredential. +/// @endif +/// +/// +/// (2) SMS is automatically retrieved (Android only). +/// - App calls @ref VerifyPhoneNumber with `timeout_ms` > 0. +/// - Auth server sends the verification code via SMS to the provided +/// phone number. +/// - SMS arrives and is automatically retrieved by the operating system. +/// Credential is automatically created and passed to the app via +/// @if cpp_examples +/// Listener::OnVerificationCompleted(). +/// @endif +/// +/// @if swig_examples +/// @ref VerificationCompleted. +/// @endif +/// +/// +/// (3) Phone number is instantly verified (Android only). +/// - App calls @ref VerifyPhoneNumber. +/// - The operating system validates the phone number without having to +/// send an SMS. Credential is automatically created and passed to +/// the app via +/// @if cpp_examples +/// Listener::OnVerificationCompleted(). +/// @endif +/// +/// @if swig_examples +/// @ref VerificationCompleted. +/// @endif +/// +/// +/// @if cpp_examples +/// All three flows can be handled with the example code below. +/// The flow is complete when PhoneVerifier::credential() returns non-NULL. +/// +/// @code{.cpp} +/// class PhoneVerifier : public PhoneAuthProvider::Listener { +/// public: +/// PhoneVerifier(const char* phone_number, +/// PhoneAuthProvider* phone_auth_provider) +/// : display_message_("Sending SMS with verification code"), +/// display_verification_code_input_box_(false), +/// display_resend_sms_button_(false), +/// phone_auth_provider_(phone_auth_provider), +/// phone_number_(phone_number) { +/// SendSms(); +/// } +/// +/// ~PhoneVerifier() override {} +/// +/// void OnVerificationCompleted(Credential credential) override { +/// // Grab `mutex_` for the scope of `lock`. Callbacks can be called on +/// // other threads, so this mutex ensures data access is atomic. +/// MutexLock lock(mutex_); +/// credential_ = credential; +/// } +/// +/// void OnVerificationFailed(const std::string& error) override { +/// MutexLock lock(mutex_); +/// display_message_ = "Verification failed with error: " + error; +/// } +/// +/// void OnCodeSent(const std::string& verification_id, +/// const PhoneAuthProvider::ForceResendingToken& +/// force_resending_token) override { +/// MutexLock lock(mutex_); +/// verification_id_ = verification_id; +/// force_resending_token_ = force_resending_token; +/// +/// display_verification_code_input_box_ = true; +/// display_message_ = "Waiting for SMS"; +/// } +/// +/// void OnCodeAutoRetrievalTimeOut( +/// const std::string& verification_id) override { +/// MutexLock lock(mutex_); +/// display_resend_sms_button_ = true; +/// } +/// +/// // Draw the verification GUI on screen and process input events. +/// void Draw() { +/// MutexLock lock(mutex_); +/// +/// // Draw an informative message describing what's currently happening. +/// ShowTextBox(display_message_.c_str()); +/// +/// // Once the time out expires, display a button to resend the SMS. +/// // If the button is pressed, call VerifyPhoneNumber again using the +/// // force_resending_token_. +/// if (display_resend_sms_button_ && !verification_id_.empty()) { +/// const bool resend_sms = ShowTextButton("Resend SMS"); +/// if (resend_sms) { +/// SendSms(); +/// } +/// } +/// +/// // Once the SMS has been sent, allow the user to enter the SMS +/// // verification code into a text box. When the user has completed +/// // entering it, call GetCredential() to complete the flow. +/// if (display_verification_code_input_box_) { +/// const std::string verification_code = +/// ShowInputBox("Verification code"); +/// if (!verification_code.empty()) { +/// credential_ = phone_auth_provider_->GetCredential( +/// verification_id_.c_str(), verification_code.c_str()); +/// } +/// } +/// } +/// +/// // The phone number verification flow is complete when this returns +/// // non-NULL. +/// Credential* credential() { +/// MutexLock lock(mutex_); +/// return credential_.is_valid() ? &credential_ : nullptr; +/// } +/// +/// private: +/// void SendSms() { +/// static const uint32_t kAutoVerifyTimeOut = 2000; +/// MutexLock lock(mutex_); +/// phone_auth_provider_->VerifyPhoneNumber( +/// phone_number_.c_str(), kAutoVerifyTimeOut, &force_resending_token_, +/// this); +/// display_resend_sms_button_ = false; +/// } +/// +/// // GUI-related variables. +/// std::string display_message_; +/// bool display_verification_code_input_box_; +/// bool display_resend_sms_button_; +/// +/// // Phone flow related variables. +/// PhoneAuthProvider* phone_auth_provider_; +/// std::string phone_number_; +/// std::string verification_id_; +/// PhoneAuthProvider::ForceResendingToken force_resending_token_; +/// Credential credential_; +/// +/// // Callbacks can be called on other threads, so guard them with a mutex. +/// Mutex mutex_; +/// }; +/// @endcode +/// @endif +class PhoneAuthProvider { + public: + /// @brief Token to maintain current phone number verification session. + /// Acquired via @ref Listener::OnCodeSent. Used in @ref VerifyPhoneNumber. + class ForceResendingToken { + public: + /// This token will be invalid until it is assigned a value sent via + /// @ref Listener::OnCodeSent. It can still be passed into + /// @ref VerifyPhoneNumber, but it will be ignored. + ForceResendingToken(); + + /// Make `this` token refer to the same phone session as `rhs`. + ForceResendingToken(const ForceResendingToken& rhs); + + /// Releases internal resources when destructing. + ~ForceResendingToken(); + + /// Make `this` token refer to the same phone session as `rhs`. + ForceResendingToken& operator=(const ForceResendingToken& rhs); + + /// Return true if `rhs` is refers to the same phone number session as + /// `this`. + bool operator==(const ForceResendingToken& rhs) const; + + /// Return true if `rhs` is refers to a different phone number session as + /// `this`. + bool operator!=(const ForceResendingToken& rhs) const; + + private: + friend class JniAuthPhoneListener; + friend class PhoneAuthProvider; + ForceResendingTokenData* data_; + }; + + /// @brief Receive callbacks from @ref VerifyPhoneNumber events. + /// + /// Please see @ref PhoneAuthProvider for a sample implementation. + class Listener { + public: + Listener(); + virtual ~Listener(); + + /// @brief Phone number auto-verification succeeded. + /// + /// Called when, + /// - auto-sms-retrieval has succeeded--flow (2) in @ref PhoneAuthProvider + /// - instant validation has succeeded--flow (3) in @ref PhoneAuthProvider + /// + /// @note This callback is never called on iOS, since iOS does not have + /// auto-validation. It is always called immediately in the stub desktop + /// implementation, however, since it fakes immediate success. + /// + /// @param[in] credential The completed credential from the phone number + /// verification flow. + virtual void OnVerificationCompleted(Credential credential) = 0; + + /// @brief Phone number verification failed with an error. + /// + /// Called when and error occurred doing phone number authentication. + /// For example, + /// - quota exceeded + /// - unknown phone number format + /// + /// @param[in] error A description of the failure. + virtual void OnVerificationFailed(const std::string& error) = 0; + + /// @brief SMS message with verification code sent to phone number. + /// + /// Called immediately after Auth server sends a verification SMS. + /// Once receiving this, you can allow users to manually input the + /// verification code (even if you're also performing auto-verification). + /// For user manual input case, get the SMS verification code from the user + /// and then call @ref GetCredential with the user's code. + /// + /// @param[in] verification_id Pass to @ref GetCredential along with the + /// user-input verification code to complete the phone number verification + /// flow. + /// @param[in] force_resending_token If the user requests that another SMS + /// message be sent, use this when you recall @ref VerifyPhoneNumber. + virtual void OnCodeSent(const std::string& verification_id, + const ForceResendingToken& force_resending_token); + + /// @brief The timeout specified in @ref VerifyPhoneNumber has expired. + /// + /// Called once `auto_verify_time_out_ms` has passed. + /// If using auto SMS retrieval, you can choose to block the UI (do not + /// allow manual input of the verification code) until timeout is hit. + /// + /// @note This callback is called immediately on iOS, since iOS does not + /// have auto-validation. + /// + /// @param[in] verification_id Identify the transaction that has timed out. + virtual void OnCodeAutoRetrievalTimeOut(const std::string& verification_id); + + private: + friend class PhoneAuthProvider; + + /// Back-pointer to the data of the PhoneAuthProvider that + /// @ref VerifyPhoneNumber was called with. Used internally. + PhoneListenerData* data_; + }; + + /// Maximum value of `auto_verify_time_out_ms` in @ref VerifyPhoneNumber. + /// Larger values will be clamped. + /// + /// @deprecated This value is no longer used to clamp + /// `auto_verify_time_out_ms` in VerifyPhoneNumber. The range is + /// determined by the underlying SDK, ex. PhoneAuthOptions.Build + /// in Android SDK + static const uint32_t kMaxTimeoutMs; + + /// Start the phone number authentication operation. + /// + /// @param[in] phone_number The phone number identifier supplied by the user. + /// Its format is normalized on the server, so it can be in any format + /// here. + /// @param[in] auto_verify_time_out_ms The time out for SMS auto retrieval, in + /// miliseconds. Currently SMS auto retrieval is only supported on Android. + /// If 0, do not do SMS auto retrieval. + /// If positive, try to auto-retrieve the SMS verification code. + /// When the time out is exceeded, listener->OnCodeAutoRetrievalTimeOut() + /// is called. + /// @param[in] force_resending_token If NULL, assume this is a new phone + /// number to verify. If not-NULL, bypass the verification session deduping + /// and force resending a new SMS. + /// This token is received in @ref Listener::OnCodeSent. + /// This should only be used when the user presses a Resend SMS button. + /// @param[in,out] listener Class that receives notification whenever an SMS + /// verification event occurs. See sample code at top of class. + void VerifyPhoneNumber(const char* phone_number, + uint32_t auto_verify_time_out_ms, + const ForceResendingToken* force_resending_token, + Listener* listener); + + /// Generate a credential for the given phone number. + /// + /// @param[in] verification_id The id returned when sending the verification + /// code. Sent to the caller via @ref Listener::OnCodeSent. + /// @param[in] verification_code The verification code supplied by the user, + /// most likely by a GUI where the user manually enters the code + /// received in the SMS sent by @ref VerifyPhoneNumber. + /// + /// @returns New Credential. + Credential GetCredential(const char* verification_id, + const char* verification_code); + + /// Return the PhoneAuthProvider for the specified `auth`. + /// + /// @param[in] auth The Auth session for which we want to get a + /// PhoneAuthProvider. + static PhoneAuthProvider& GetInstance(Auth* auth); + + /// The string used to identify this provider. + static const char* const kProviderId; + + private: + friend struct AuthData; + friend class JniAuthPhoneListener; + + // Use @ref GetInstance to access the PhoneAuthProvider. + PhoneAuthProvider(); + + // The PhoneAuthProvider is owned by the Auth class. + ~PhoneAuthProvider(); + + PhoneAuthProviderData* data_; +}; + +/// @brief Use a server auth code provided by Google Play Games to authenticate. +class PlayGamesAuthProvider { + public: + /// Generate a credential from the given Server Auth Code. + /// + /// @param server_auth_code Play Games Sign in Server Auth Code. + /// + /// @return New Credential. + static Credential GetCredential(const char* server_auth_code); + + /// The string used to identify this provider. + static const char* const kProviderId; +}; + +/// @brief Use a token and secret provided by Twitter to authenticate. +class TwitterAuthProvider { + public: + /// Generate a credential from the given Twitter token and password. + /// + /// @param token The Twitter OAuth token. + /// @param secret The Twitter OAuth secret. + /// + /// @return New Credential. + static Credential GetCredential(const char* token, const char* secret); + + /// The string used to identify this provider. + static const char* const kProviderId; +}; + +/// @brief Use an access token provided by Yahoo to authenticate. +class YahooAuthProvider { + public: + /// The string used to identify this provider. + static const char* const kProviderId; +}; + +} // namespace auth +} // namespace firebase + +#endif // FIREBASE_AUTH_SRC_INCLUDE_FIREBASE_AUTH_CREDENTIAL_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/auth/types.h b/packages/firebase_core/firebase_core/firebase_core/firebase/auth/types.h new file mode 100644 index 000000000000..3f141ad3692c --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/auth/types.h @@ -0,0 +1,473 @@ +/* + * Copyright 2016 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_AUTH_SRC_INCLUDE_FIREBASE_AUTH_TYPES_H_ +#define FIREBASE_AUTH_SRC_INCLUDE_FIREBASE_AUTH_TYPES_H_ + +#include +#include +#include + +namespace firebase { +namespace auth { + +/// All possible error codes from asynchronous calls. +/// For error details, +/// @if cpp_examples +/// call Future::ErrorMessage(). +/// @endif +/// +/// @if swig_examples +/// use the FirebaseException.Message property. +/// @endif +/// +enum AuthError { + /// Success. + kAuthErrorNone = 0, + + /// Function will be implemented in a later revision of the API. + kAuthErrorUnimplemented = -1, + + /// This indicates an internal error. + /// Common error code for all API Methods. + kAuthErrorFailure = 1, + + /// Indicates a validation error with the custom token. + /// This error originates from "bring your own auth" methods. + kAuthErrorInvalidCustomToken, + + /// Indicates the service account and the API key belong to different + /// projects. + /// Caused by "Bring your own auth" methods. + kAuthErrorCustomTokenMismatch, + + /// Indicates the IDP token or requestUri is invalid. + /// Caused by "Sign in with credential" methods. + kAuthErrorInvalidCredential, + + /// Indicates the user’s account is disabled on the server. + /// Caused by "Sign in with credential" methods. + kAuthErrorUserDisabled, + + /// Indicates an account already exists with the same email address but using + /// different sign-in credentials. Account linking is required. + /// Caused by "Sign in with credential" methods. + kAuthErrorAccountExistsWithDifferentCredentials, + + /// Indicates the administrator disabled sign in with the specified identity + /// provider. + /// Caused by "Set account info" methods. + kAuthErrorOperationNotAllowed, + + /// Indicates the email used to attempt a sign up is already in use. + /// Caused by "Set account info" methods. + kAuthErrorEmailAlreadyInUse, + + /// Indicates the user has attemped to change email or password more than 5 + /// minutes after signing in, and will need to refresh the credentials. + /// Caused by "Set account info" methods. + kAuthErrorRequiresRecentLogin, + + /// Indicates an attempt to link with a credential that has already been + /// linked with a different Firebase account. + /// Caused by "Set account info" methods. + kAuthErrorCredentialAlreadyInUse, + + /// Indicates an invalid email address. + /// Caused by "Sign in with password" methods. + kAuthErrorInvalidEmail, + + /// Indicates the user attempted sign in with a wrong password. + /// Caused by "Sign in with password" methods. + kAuthErrorWrongPassword, + + /// Indicates that too many requests were made to a server method. + /// Common error code for all API methods. + kAuthErrorTooManyRequests, + + /// Indicates the user account was not found. + /// Send password request email error code. + /// Common error code for all API methods. + kAuthErrorUserNotFound, + + /// Indicates an attempt to link a provider to which the account is already + /// linked. + /// Caused by "Link credential" methods. + kAuthErrorProviderAlreadyLinked, + + /// Indicates an attempt to unlink a provider that is not linked. + /// Caused by "Link credential" methods. + kAuthErrorNoSuchProvider, + + /// Indicates user's saved auth credential is invalid, the user needs to sign + /// in again. + /// Caused by requests with an STS id token. + kAuthErrorInvalidUserToken, + + /// Indicates the saved token has expired. + /// For example, the user may have changed account password on another device. + /// The user needs to sign in again on the device that made this request. + /// Caused by requests with an STS id token. + kAuthErrorUserTokenExpired, + + /// Indicates a network error occurred (such as a timeout, interrupted + /// connection, or unreachable host). These types of errors are often + /// recoverable with a retry. + /// Common error code for all API Methods. + kAuthErrorNetworkRequestFailed, + + /// Indicates an invalid API key was supplied in the request. + /// For Android these should no longer occur (as of 2016 v3). + /// Common error code for all API Methods. + kAuthErrorInvalidApiKey, + + /// Indicates the App is not authorized to use Firebase Authentication with + /// the provided API Key. + /// Common error code for all API Methods. + /// On Android this error should no longer occur (as of 2016 v3). + /// Common error code for all API Methods. + kAuthErrorAppNotAuthorized, + + /// Indicates that an attempt was made to reauthenticate with a user which is + /// not the current user. + kAuthErrorUserMismatch, + + /// Indicates an attempt to set a password that is considered too weak. + kAuthErrorWeakPassword, + + /// Internal api usage error code when there is no signed-in user + /// and getAccessToken is called. + /// + /// @note This error is only reported on Android. + kAuthErrorNoSignedInUser, + + /// This can happen when certain methods on App are performed, when the auth + /// API is not loaded. + /// + /// @note This error is only reported on Android. + kAuthErrorApiNotAvailable, + + /// Indicates the out-of-band authentication code is expired. + kAuthErrorExpiredActionCode, + + /// Indicates the out-of-band authentication code is invalid. + kAuthErrorInvalidActionCode, + + /// Indicates that there are invalid parameters in the payload during a + /// "send password reset email" attempt. + kAuthErrorInvalidMessagePayload, + + /// Indicates that an invalid phone number was provided. + /// This is caused when the user is entering a phone number for verification. + kAuthErrorInvalidPhoneNumber, + + /// Indicates that a phone number was not provided during phone number + /// verification. + /// + /// @note This error is iOS-specific. + kAuthErrorMissingPhoneNumber, + + /// Indicates that the recipient email is invalid. + kAuthErrorInvalidRecipientEmail, + + /// Indicates that the sender email is invalid during a "send password reset + /// email" attempt. + kAuthErrorInvalidSender, + + /// Indicates that an invalid verification code was used in the + /// verifyPhoneNumber request. + kAuthErrorInvalidVerificationCode, + + /// Indicates that an invalid verification ID was used in the + /// verifyPhoneNumber request. + kAuthErrorInvalidVerificationId, + + /// Indicates that the phone auth credential was created with an empty + /// verification code. + kAuthErrorMissingVerificationCode, + + /// Indicates that the phone auth credential was created with an empty + /// verification ID. + kAuthErrorMissingVerificationId, + + /// Indicates that an email address was expected but one was not provided. + kAuthErrorMissingEmail, + + /// Represents the error code for when an application attempts to create an + /// email/password account with an empty/null password field. + /// + /// @note This error is only reported on Android. + kAuthErrorMissingPassword, + + /// Indicates that the project's quota for this operation (SMS messages, + /// sign-ins, account creation) has been exceeded. Try again later. + kAuthErrorQuotaExceeded, + + /// Thrown when one or more of the credentials passed to a method fail to + /// identify and/or authenticate the user subject of that operation. Inspect + /// the error message to find out the specific cause. + /// @note This error is only reported on Android. + kAuthErrorRetryPhoneAuth, + + /// Indicates that the SMS code has expired. + kAuthErrorSessionExpired, + + /// Indicates that the app could not be verified by Firebase during phone + /// number authentication. + /// + /// @note This error is iOS-specific. + kAuthErrorAppNotVerified, + + /// Indicates a general failure during the app verification flow. + /// + /// @note This error is iOS-specific. + kAuthErrorAppVerificationFailed, + + /// Indicates that the reCAPTCHA token is not valid. + /// + /// @note This error is iOS and tvOS-specific. + kAuthErrorCaptchaCheckFailed, + + /// Indicates that an invalid APNS device token was used in the verifyClient + /// request. + /// + /// @note This error is iOS and tvOS-specific. + kAuthErrorInvalidAppCredential, + + /// Indicates that the APNS device token is missing in the verifyClient + /// request. + /// + /// @note This error is iOS and tvOS-specific. + kAuthErrorMissingAppCredential, + + /// Indicates that the clientID used to invoke a web flow is invalid. + /// + /// @note This error is iOS and tvOS-specific. + kAuthErrorInvalidClientId, + + /// Indicates that the domain specified in the continue URI is not valid. + /// + /// @note This error is iOS and tvOS-specific. + kAuthErrorInvalidContinueUri, + + /// Indicates that a continue URI was not provided in a request to the backend + /// which requires one. + kAuthErrorMissingContinueUri, + + /// Indicates an error occurred while attempting to access the keychain. + /// Common error code for all API Methods. + /// + /// @note This error is iOS and tvOS-specific. + kAuthErrorKeychainError, + + /// Indicates that the APNs device token could not be obtained. The app may + /// not have set up remote notification correctly, or may have failed to + /// forward the APNs device token to FIRAuth if app delegate swizzling is + /// disabled. + /// + /// @note This error is iOS and tvOS-specific. + kAuthErrorMissingAppToken, + + /// Indicates that the iOS bundle ID is missing when an iOS App Store ID is + /// provided. + /// + /// @note This error is iOS and tvOS-specific. + kAuthErrorMissingIosBundleId, + + /// Indicates that the app fails to forward remote notification to FIRAuth. + /// + /// @note This error is iOS and tvOS-specific. + kAuthErrorNotificationNotForwarded, + + /// Indicates that the domain specified in the continue URL is not white- + /// listed in the Firebase console. + /// + /// @note This error is iOS and tvOS-specific. + kAuthErrorUnauthorizedDomain, + + /// Indicates that an attempt was made to present a new web context while one + /// was already being presented. + kAuthErrorWebContextAlreadyPresented, + + /// Indicates that the URL presentation was cancelled prematurely by the user. + kAuthErrorWebContextCancelled, + + /// Indicates that Dynamic Links in the Firebase Console is not activated. + kAuthErrorDynamicLinkNotActivated, + + /// Indicates that the operation was cancelled. + kAuthErrorCancelled, + + /// Indicates that the provider id given for the web operation is invalid. + kAuthErrorInvalidProviderId, + + /// Indicates that an internal error occurred during a web operation. + kAuthErrorWebInternalError, + + /// Indicates that 3rd party cookies or data are disabled, or that there was + /// a problem with the browser. + kAuthErrorWebStorateUnsupported, + + /// Indicates that the provided tenant ID does not match the Auth instance's + /// tenant ID. + kAuthErrorTenantIdMismatch, + + /// Indicates that a request was made to the backend with an associated tenant + /// ID for an operation that does not support multi-tenancy. + kAuthErrorUnsupportedTenantOperation, + + /// Indicates that an FDL domain used for an out of band code flow is either + /// not configured or is unauthorized for the current project. + kAuthErrorInvalidLinkDomain, + + /// Indicates that credential related request data is invalid. This can occur + /// when there is a project number mismatch (sessionInfo, spatula header, + /// temporary proof), + /// an incorrect temporary proof phone number, or during game center sign in + /// when the user is + /// already signed into a different game center account. + kAuthErrorRejectedCredential, + + /// Indicates that the phone number provided in the MFA sign in flow to be + /// verified does not correspond to a phone second factor for the user. + kAuthErrorPhoneNumberNotFound, + + /// Indicates that a request was made to the backend with an invalid tenant + /// ID. + kAuthErrorInvalidTenantId, + + /// Indicates that a request was made to the backend without a valid client + /// identifier. + kAuthErrorMissingClientIdentifier, + + /// Indicates that a second factor challenge request was made without proof of + /// a successful first factor sign-in. + kAuthErrorMissingMultiFactorSession, + + /// Indicates that a second factor challenge request was made where a second + /// factor identifier was not provided. + kAuthErrorMissingMultiFactorInfo, + + /// Indicates that a second factor challenge request was made containing an + /// invalid proof of first factor sign-in. + kAuthErrorInvalidMultiFactorSession, + + /// Indicates that the user does not have a second factor matching the + /// provided identifier. + kAuthErrorMultiFactorInfoNotFound, + + /// Indicates that a request was made that is restricted to administrators + /// only. + kAuthErrorAdminRestrictedOperation, + + /// Indicates that the user's email must be verified to perform that request. + kAuthErrorUnverifiedEmail, + + /// Indicates that the user is trying to enroll a second factor that already + /// exists on their account. + kAuthErrorSecondFactorAlreadyEnrolled, + + /// Indicates that the user has reached the maximum number of allowed second + /// factors and is attempting to enroll another one. + kAuthErrorMaximumSecondFactorCountExceeded, + + /// Indicates that a user either attempted to enroll in 2FA with an + /// unsupported first factor or is enrolled and attempts a first factor sign + /// in that is not supported for 2FA users. + kAuthErrorUnsupportedFirstFactor, + + /// Indicates that a second factor users attempted to change their email with + /// updateEmail instead of verifyBeforeUpdateEmail. + kAuthErrorEmailChangeNeedsVerification, + +#ifdef INTERNAL_EXPERIMENTAL + /// Indicates that the provided event handler is null or invalid. + kAuthErrorInvalidEventHandler, + + /// Indicates that the federated provider is busy with a previous + /// authorization request. Try again when the previous authorization request + /// completes. + kAuthErrorFederatedProviderAreadyInUse, + + /// Indicates that one or more fields of the provided AuthenticatedUserData + /// are invalid. + kAuthErrorInvalidAuthenticatedUserData, + + /// Indicates that an error occurred during a Federated Auth UI Flow when the + /// user was prompted to enter their credentials. + kAuthErrorFederatedSignInUserInteractionFailure, + + /// Indicates that a request was made with a missing or invalid nonce. + /// This can happen if the hash of the provided raw nonce did not match the + /// hashed nonce in the OIDC ID token payload. + kAuthErrorMissingOrInvalidNonce, + + /// Indicates that the user did not authorize the application during Generic + /// IDP sign-in. + kAuthErrorUserCancelled, + + /// Indicates that a request was made to an unsupported backend endpoint in + /// passthrough mode. + kAuthErrorUnsupportedPassthroughOperation, + + /// Indicates that a token refresh was requested, but neither a refresh token + /// nor a custom token provider is available. + kAuthErrorTokenRefreshUnavailable, + +#endif // INTERNAL_EXEPERIMENTAL +}; + +/// @brief Contains information required to authenticate with a third party +/// provider. +struct FederatedProviderData { + /// @brief contains the id of the provider to be used during sign-in, link, or + /// reauthentication requests. + std::string provider_id; +}; + +/// @brief Contains information to identify an OAuth povider. +struct FederatedOAuthProviderData : FederatedProviderData { + /// Initailizes an empty provider data structure. + FederatedOAuthProviderData() {} + + /// Initializes the provider data structure with a provider id. + explicit FederatedOAuthProviderData(const std::string& provider) { + this->provider_id = provider; + } + +#ifndef SWIG + /// @brief Initializes the provider data structure with the specified provider + /// id, scopes and custom parameters. + FederatedOAuthProviderData( + const std::string& provider, std::vector scopes, + std::map custom_parameters) { + this->provider_id = provider; + this->scopes = scopes; + this->custom_parameters = custom_parameters; + } +#endif + + /// OAuth parmeters which specify which rights of access are being requested. + std::vector scopes; + + /// OAuth parameters which are provided to the federated provider service. + std::map custom_parameters; +}; + +} // namespace auth +} // namespace firebase + +#endif // FIREBASE_AUTH_SRC_INCLUDE_FIREBASE_AUTH_TYPES_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/auth/user.h b/packages/firebase_core/firebase_core/firebase_core/firebase/auth/user.h new file mode 100644 index 000000000000..ddd1ba890687 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/auth/user.h @@ -0,0 +1,501 @@ +/* + * Copyright 2016 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_AUTH_SRC_INCLUDE_FIREBASE_AUTH_USER_H_ +#define FIREBASE_AUTH_SRC_INCLUDE_FIREBASE_AUTH_USER_H_ + +#include +#include + +#include "firebase/auth/credential.h" +#include "firebase/auth/types.h" +#include "firebase/future.h" +#include "firebase/internal/common.h" +#include "firebase/variant.h" + +namespace firebase { +namespace auth { + +// Predeclarations. +class Auth; +struct AuthData; + +class FederatedAuthProvider; + +/// @brief Interface implemented by each identity provider. +class UserInfoInterface { + public: + virtual ~UserInfoInterface(); + + /// Gets the unique Firebase user ID for the user. + /// + /// @note The user's ID, unique to the Firebase project. + /// Do NOT use this value to authenticate with your backend server, if you + /// have one. + /// @if cpp_examples + /// Use User::GetToken() instead. + /// @endif + /// + /// @if swig_examples + /// Use User.Token instead. + /// @endif + /// @xmlonly + /// + /// Gets the unique Firebase user ID for the user. + /// + /// @note The user's ID, unique to the Firebase project. + /// Do NOT use this value to authenticate with your backend server, if you + /// have one. Use User.Token instead. + /// + /// @endxmlonly + /// + virtual std::string uid() const = 0; + + /// Gets email associated with the user, if any. + /// + /// @xmlonly + /// + /// Gets email associated with the user, if any. + /// + /// @endxmlonly + /// + virtual std::string email() const = 0; + + /// Gets the display name associated with the user, if any. + /// + /// @xmlonly + /// + /// Gets the display name associated with the user, if any. + /// + /// @endxmlonly + /// + virtual std::string display_name() const = 0; + + /// Gets the photo url associated with the user, if any. + /// + /// @xmlonly + /// + /// Gets the photo url associated with the user, if any. + /// + /// @endxmlonly + /// + virtual std::string photo_url() const = 0; + + /// Gets the provider ID for the user (For example, "Facebook"). + /// + /// @xmlonly + /// + /// Gets the provider ID for the user (For example, \"Facebook\"). + /// + /// @endxmlonly + /// + virtual std::string provider_id() const = 0; + + /// Gets the phone number for the user, in E.164 format. + virtual std::string phone_number() const = 0; +}; + +/// @brief Additional user data returned from an identity provider. +struct AdditionalUserInfo { + /// The provider identifier. + std::string provider_id; + + /// The name of the user. + std::string user_name; + + /// Additional identity-provider specific information. + /// Most likely a hierarchical key-value mapping, like a parsed JSON file. + /// Note we use map instead of unordered_map to support older compilers. + std::map profile; + + /// On a nonce-based credential link failure where the user has already linked + /// to the provider, the Firebase auth service may provide an updated + /// Credential. If is_valid returns true on this credential, then it may be + /// passed to a new firebase::auth::Auth::SignInWithCredential request to sign + /// the user in with the provider. + Credential updated_credential; +}; + +/// @brief Metadata corresponding to a Firebase user. +struct UserMetadata { + UserMetadata() : last_sign_in_timestamp(0), creation_timestamp(0) {} + + /// The last sign in UTC timestamp in milliseconds. + /// See https://en.wikipedia.org/wiki/Unix_time for details of UTC. + uint64_t last_sign_in_timestamp; + + /// The Firebase user creation UTC timestamp in milliseconds. + uint64_t creation_timestamp; +}; + +/// @brief Result of operations that can affect authentication state. +struct SignInResult { + SignInResult() : user(NULL) {} + + /// The currently signed-in @ref User, or NULL if there isn't any (i.e. the + /// user is signed out). + User* user; + + /// Identity-provider specific information for the user, if the provider is + /// one of Facebook, GitHub, Google, or Twitter. + AdditionalUserInfo info; + + /// Metadata associated with the Firebase user. + UserMetadata meta; +}; + +/// @brief Firebase user account object. +/// +/// This class allows you to manipulate the profile of a user, link to and +/// unlink from authentication providers, and refresh authentication tokens. +class User : public UserInfoInterface { + public: + /// Parameters to the UpdateUserProfile() function. + /// + /// For fields you don't want to update, pass NULL. + /// For fields you want to reset, pass "". + struct UserProfile { + /// Construct a UserProfile with no display name or photo URL. + UserProfile() : display_name(NULL), photo_url(NULL) {} + + /// User display name. + const char* display_name; + + /// User photo URI. + const char* photo_url; + }; + + ~User(); + + /// The Java Web Token (JWT) that can be used to identify the user to + /// the backend. + /// + /// If a current ID token is still believed to be valid (i.e. it has not yet + /// expired), that token will be returned immediately. + /// A developer may set the optional force_refresh flag to get a new ID token, + /// whether or not the existing token has expired. For example, a developer + /// may use this when they have discovered that the token is invalid for some + /// other reason. + Future GetToken(bool force_refresh); + +#if defined(INTERNAL_EXPERIMENTAL) || defined(SWIG) + /// A "thread safer" version of GetToken. + /// If called by two threads simultaneously, GetToken can return the same + /// pending Future twice. This creates problems if both threads try to set + /// the OnCompletion callback, unaware that there's another copy. + /// GetTokenThreadSafe returns a proxy to the Future if it's still pending, + /// allowing each proxy to have their own callback. + Future GetTokenThreadSafe(bool force_refresh); +#endif // defined(INTERNAL_EXPERIMENTAL) || defined(SWIG) + + /// Get results of the most recent call to @ref GetToken. + Future GetTokenLastResult() const; + + /// Gets the third party profile data associated with this user returned by + /// the authentication server, if any. + /// + /// @xmlonly + /// + /// Gets the third party profile data associated with this user returned by + /// the authentication server, if any. + /// + /// @endxmlonly + /// + const std::vector& provider_data() const; + + /// Sets the email address for the user. + /// + /// May fail if there is already an email/password-based account for the same + /// email address. + Future UpdateEmail(const char* email); + + /// Get results of the most recent call to @ref UpdateEmail. + Future UpdateEmailLastResult() const; + + /// Attempts to change the password for the current user. + /// + /// For an account linked to an Identity Provider (IDP) with no password, + /// this will result in the account becoming an email/password-based account + /// while maintaining the IDP link. May fail if the password is invalid, + /// if there is a conflicting email/password-based account, or if the token + /// has expired. + /// To retrieve fresh tokens, + /// @if cpp_examples + /// call @ref Reauthenticate. + /// @endif + /// + /// @if swig_examples + /// call @ref ReauthenticateAsync. + /// @endif + /// + Future UpdatePassword(const char* password); + + /// Get results of the most recent call to @ref UpdatePassword. + Future UpdatePasswordLastResult() const; + + /// Convenience function for @ref ReauthenticateAndRetrieveData that discards + /// the returned AdditionalUserInfo data. + Future Reauthenticate(const Credential& credential); + + /// Get results of the most recent call to @ref Reauthenticate. + Future ReauthenticateLastResult() const; + + /// Reauthenticate using a credential. + /// + /// @if cpp_examples + /// Some APIs (for example, @ref UpdatePassword, @ref Delete) require that + /// the token used to invoke them be from a recent login attempt. + /// This API takes an existing credential for the user and retrieves fresh + /// tokens, ensuring that the operation can proceed. Developers can call + /// this method prior to calling @ref UpdatePassword() to ensure success. + /// @endif + /// + /// @if swig_examples + /// Some APIs (for example, @ref UpdatePasswordAsync, @ref DeleteAsync) + /// require that the token used to invoke them be from a recent login attempt. + /// This API takes an existing credential for the user and retrieves fresh + /// tokens, ensuring that the operation can proceed. Developers can call + /// this method prior to calling @ref UpdatePasswordAsync() to ensure success. + /// @endif + /// + /// + /// Data from the Identity Provider used to sign-in is returned in the + /// AdditionalUserInfo inside the returned SignInResult. + /// + /// Returns an error if the existing credential is not for this user + /// or if sign-in with that credential failed. + /// @note: The current user may be signed out if this operation fails on + /// Android and desktop platforms. + Future ReauthenticateAndRetrieveData( + const Credential& credential); + + /// Get results of the most recent call to @ref ReauthenticateAndRetrieveData. + Future ReauthenticateAndRetrieveDataLastResult() const; + + /// @brief Re-authenticates the user with a federated auth provider. + /// + /// @param[in] provider Contains information on the auth provider to + /// authenticate with. + /// @return A Future with the result of the re-authentication + /// request. + /// @note: This operation is supported only on iOS, tvOS and Android + /// platforms. On other platforms this method will return a Future with a + /// preset error code: kAuthErrorUnimplemented. + Future ReauthenticateWithProvider( + FederatedAuthProvider* provider) const; + + /// Initiates email verification for the user. + Future SendEmailVerification(); + + /// Get results of the most recent call to @ref SendEmailVerification. + Future SendEmailVerificationLastResult() const; + + /// Updates a subset of user profile information. + Future UpdateUserProfile(const UserProfile& profile); + + /// Get results of the most recent call to @ref UpdateUserProfile. + Future UpdateUserProfileLastResult() const; + + /// Convenience function for @ref ReauthenticateAndRetrieveData that discards + /// the returned @ref AdditionalUserInfo in @ref SignInResult. + Future LinkWithCredential(const Credential& credential); + + /// Get results of the most recent call to @ref LinkWithCredential. + Future LinkWithCredentialLastResult() const; + + /// Links the user with the given 3rd party credentials. + /// + /// For example, a Facebook login access token, a Twitter token/token-secret + /// pair. + /// Status will be an error if the token is invalid, expired, or otherwise + /// not accepted by the server as well as if the given 3rd party + /// user id is already linked with another user account or if the current user + /// is already linked with another id from the same provider. + /// + /// Data from the Identity Provider used to sign-in is returned in the + /// @ref AdditionalUserInfo inside @ref SignInResult. + Future LinkAndRetrieveDataWithCredential( + const Credential& credential); + + /// Get results of the most recent call to + /// @ref LinkAndRetrieveDataWithCredential. + Future LinkAndRetrieveDataWithCredentialLastResult() const; + + /// Links this user with a federated auth provider. + /// + /// @param[in] provider Contains information on the auth provider to link + /// with. + /// @return A Future with the user data result of the link + /// request. + /// + /// @note: This operation is supported only on iOS, tvOS and Android + /// platforms. On other platforms this method will return a Future with a + /// preset error code: kAuthErrorUnimplemented. + Future LinkWithProvider(FederatedAuthProvider* provider) const; + + /// Unlinks the current user from the provider specified. + /// Status will be an error if the user is not linked to the given provider. + Future Unlink(const char* provider); + + /// Get results of the most recent call to @ref Unlink. + Future UnlinkLastResult() const; + + /// Updates the currently linked phone number on the user. + /// This is useful when a user wants to change their phone number. It is a + /// shortcut to calling Unlink(phone_credential.provider().c_str()) and then + /// LinkWithCredential(phone_credential). + /// `credential` must have been created with @ref PhoneAuthProvider. + Future UpdatePhoneNumberCredential(const Credential& credential); + + /// Get results of the most recent call to @ref UpdatePhoneNumberCredential. + Future UpdatePhoneNumberCredentialLastResult() const; + + /// Refreshes the data for this user. + /// + /// For example, the attached providers, email address, display name, etc. + Future Reload(); + + /// Get results of the most recent call to @ref Reload. + Future ReloadLastResult() const; + + /// Deletes the user account. + Future Delete(); + + /// Get results of the most recent call to @ref Delete. + Future DeleteLastResult() const; + + /// Gets the metadata for this user account. + UserMetadata metadata() const; + + /// Returns true if the email address associated with this user has been + /// verified. + /// + /// @xmlonly + /// + /// True if the email address associated with this user has been verified. + /// + /// @endxmlonly + /// + bool is_email_verified() const; + + /// Returns true if user signed in anonymously. + /// + /// @xmlonly + /// + /// True if user signed in anonymously. + /// + /// @endxmlonly + /// + bool is_anonymous() const; + + /// Gets the unique Firebase user ID for the user. + /// + /// @note The user's ID, unique to the Firebase project. + /// Do NOT use this value to authenticate with your backend server, if you + /// have one. + /// @if cpp_examples + /// Use User::GetToken() instead. + /// @endif + /// + /// @if swig_examples + /// Use User.Token instead. + /// @endif + /// @xmlonly + /// + /// Gets the unique Firebase user ID for the user. + /// + /// @note The user's ID, unique to the Firebase project. + /// Do NOT use this value to authenticate with your backend server, if you + /// have one. Use User.Token instead. + /// + /// @endxmlonly + /// + virtual std::string uid() const; + + /// Gets email associated with the user, if any. + /// + /// @xmlonly + /// + /// Gets email associated with the user, if any. + /// + /// @endxmlonly + /// + virtual std::string email() const; + + /// Gets the display name associated with the user, if any. + /// + /// @xmlonly + /// + /// Gets the display name associated with the user, if any. + /// + /// @endxmlonly + /// + virtual std::string display_name() const; + + /// Gets the photo url associated with the user, if any. + /// + /// @xmlonly + /// + /// Gets the photo url associated with the user, if any. + /// + /// @endxmlonly + /// + virtual std::string photo_url() const; + + /// Gets the provider ID for the user (For example, "Facebook"). + /// + /// @xmlonly + /// + /// Gets the provider ID for the user (For example, \"Facebook\"). + /// + /// @endxmlonly + /// + virtual std::string provider_id() const; + + /// Gets the phone number for the user, in E.164 format. + virtual std::string phone_number() const; + + private: + /// @cond FIREBASE_APP_INTERNAL + friend struct AuthData; + // Only exists in AuthData. Access via @ref Auth::CurrentUser(). + explicit User(AuthData* auth_data) : auth_data_(auth_data) {} + + // Disable copy constructor. + User(const User&) = delete; + // Disable copy operator. + User& operator=(const User&) = delete; + /// @endcond + +#if defined(INTERNAL_EXPERIMENTAL) + // Doxygen should not make docs for this function. + /// @cond FIREBASE_APP_INTERNAL + friend class IdTokenRefreshThread; + friend class IdTokenRefreshListener; + friend class Auth; + Future GetTokenInternal(const bool force_refresh, + const int future_identifier); + /// @endcond +#endif // defined(INTERNAL_EXPERIMENTAL) + + // Use the pimpl mechanism to hide data details in the cpp files. + AuthData* auth_data_; +}; + +} // namespace auth +} // namespace firebase + +#endif // FIREBASE_AUTH_SRC_INCLUDE_FIREBASE_AUTH_USER_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/database.h b/packages/firebase_core/firebase_core/firebase_core/firebase/database.h new file mode 100644 index 000000000000..d0dc904c107b --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/database.h @@ -0,0 +1,199 @@ +// Copyright 2016 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_H_ +#define FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_H_ + +#include "firebase/app.h" +#include "firebase/database/common.h" +#include "firebase/database/data_snapshot.h" +#include "firebase/database/database_reference.h" +#include "firebase/database/disconnection.h" +#include "firebase/database/listener.h" +#include "firebase/database/mutable_data.h" +#include "firebase/database/query.h" +#include "firebase/database/transaction.h" +#include "firebase/internal/common.h" +#include "firebase/log.h" + +namespace firebase { + +/// Namespace for the Firebase Realtime Database C++ SDK. +namespace database { + +namespace internal { +class DatabaseInternal; +} // namespace internal + +class DatabaseReference; + +#ifndef SWIG +/// @brief Entry point for the Firebase Realtime Database C++ SDK. +/// +/// To use the SDK, call firebase::database::Database::GetInstance() to obtain +/// an instance of Database, then use GetReference() to obtain references to +/// child paths within the database. From there you can set data via +/// Query::SetValue(), get data via Query::GetValue(), attach listeners, and +/// more. +#endif // SWIG +class Database { + public: + /// @brief Get an instance of Database corresponding to the given App. + /// + /// Firebase Realtime Database uses firebase::App to communicate with Firebase + /// Authentication to authenticate users to the Database server backend. + /// + /// If you call GetInstance() multiple times with the same App, you will get + /// the same instance of Database. + /// + /// @param[in] app Your instance of firebase::App. Firebase Realtime Database + /// will use this to communicate with Firebase Authentication. + /// @param[out] init_result_out Optional: If provided, write the init result + /// here. Will be set to kInitResultSuccess if initialization succeeded, or + /// kInitResultFailedMissingDependency on Android if Google Play services is + /// not available on the current device. + /// + /// @returns An instance of Database corresponding to the given App. + static Database* GetInstance(::firebase::App* app, + InitResult* init_result_out = nullptr); + + /// @brief Gets an instance of FirebaseDatabase for the specified URL. + /// + /// If you call GetInstance() multiple times with the same App and URL, you + /// will get the same instance of Database. + /// + /// @param[in] app Your instance of firebase::App. Firebase Realtime Database + /// will use this to communicate with Firebase Authentication. + /// @param[in] url The URL of your Firebase Realtime Database. This overrides + /// any url specified in the App options. + /// @param[out] init_result_out Optional: If provided, write the init result + /// here. Will be set to kInitResultSuccess if initialization succeeded, or + /// kInitResultFailedMissingDependency on Android if Google Play services is + /// not available on the current device. + /// + /// @returns An instance of Database corresponding to the given App and URL. + static Database* GetInstance(::firebase::App* app, const char* url, + InitResult* init_result_out = nullptr); + + /// @brief Destructor for the Database object. + /// + /// When deleted, this instance will be removed from the cache of Database + /// objects. If you call GetInstance() in the future with the same App, a new + /// Database instance will be created. + ~Database(); + + /// @brief Get the firebase::App that this Database was created with. + /// + /// @returns The firebase::App this Database was created with. + App* app() const; + + /// @brief Get the URL that this Database was created with. + /// + /// @returns The URL this Database was created with, or an empty string if + /// this Database was created with default parameters. This string will remain + /// valid in memory for the lifetime of this Database. + const char* url() const; + + /// @brief Get a DatabaseReference to the root of the database. + /// + /// @returns A DatabaseReference to the root of the database. + DatabaseReference GetReference() const; + /// @brief Get a DatabaseReference for the specified path. + /// + /// @returns A DatabaseReference to the specified path in the database. + /// If you specified an invalid path, the reference's + /// DatabaseReference::IsValid() will return false. + DatabaseReference GetReference(const char* path) const; + /// @brief Get a DatabaseReference for the provided URL, which must belong to + /// the database URL this instance is already connected to. + /// + /// @returns A DatabaseReference to the specified path in the database. + /// If you specified an invalid path, the reference's + /// DatabaseReference::IsValid() will return false. + DatabaseReference GetReferenceFromUrl(const char* url) const; + + /// @brief Shuts down the connection to the Firebase Realtime Database + /// backend until GoOnline() is called. + void GoOffline(); + + /// @brief Resumes the connection to the Firebase Realtime Database backend + /// after a previous GoOffline() call. + void GoOnline(); + + /// @brief Purge all pending writes to the Firebase Realtime Database server. + /// + /// The Firebase Realtime Database client automatically queues writes and + /// sends them to the server at the earliest opportunity, depending on network + /// connectivity. In some cases (e.g. offline usage) there may be a large + /// number of writes waiting to be sent. Calling this method will purge all + /// outstanding writes so they are abandoned. All writes will be purged, + /// including transactions and onDisconnect() writes. The writes will be + /// rolled back locally, perhaps triggering events for affected event + /// listeners, and the client will not (re-)send them to the Firebase backend. + void PurgeOutstandingWrites(); + + /// @brief Sets whether pending write data will persist between application + /// exits. + /// + /// The Firebase Database client will cache synchronized data and keep track + /// of all writes you've initiated while your application is running. It + /// seamlessly handles intermittent network connections and re-sends write + /// operations when the network connection is restored. However by default + /// your write operations and cached data are only stored in-memory and will + /// be lost when your app restarts. By setting this value to `true`, the data + /// will be persisted to on-device (disk) storage and will thus be available + /// again when the app is restarted (even when there is no network + /// connectivity at that time). + /// + /// @note SetPersistenceEnabled should be called before creating any instances + /// of DatabaseReference, and only needs to be called once per application. + /// + /// @param[in] enabled Set this to true to persist write data to on-device + /// (disk) storage, or false to discard pending writes when the app exists. + void set_persistence_enabled(bool enabled); + + /// Set the log verbosity of this Database instance. + /// + /// The log filtering is cumulative with Firebase App. That is, this library's + /// log messages will only be displayed if they are not filtered out by this + /// library's log level setting and by Firebase App's log level setting. + /// + /// @note On Android this can only be set before any operations have been + /// performed with the object. + /// + /// @param[in] log_level Log level, by default this is set to kLogLevelInfo. + void set_log_level(LogLevel log_level); + + /// Get the log verbosity of this Database instance. + /// + /// @return Get the currently configured logging verbosity. + LogLevel log_level() const; + + private: + friend Database* GetDatabaseInstance(::firebase::App* app, const char* url, + InitResult* init_result_out); + Database(::firebase::App* app, internal::DatabaseInternal* internal); + Database(const Database& src); + Database& operator=(const Database& src); + + // Delete the internal_ data. + void DeleteInternal(); + + internal::DatabaseInternal* internal_; +}; + +} // namespace database +} // namespace firebase + +#endif // FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/database/common.h b/packages/firebase_core/firebase_core/firebase_core/firebase/database/common.h new file mode 100644 index 000000000000..298972784631 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/database/common.h @@ -0,0 +1,83 @@ +// Copyright 2016 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_COMMON_H_ +#define FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_COMMON_H_ + +#include "firebase/variant.h" + +namespace firebase { +namespace database { + +/// Error code returned by Firebase Realtime Database C++ functions. +enum Error { + /// The operation was a success, no error occurred. + kErrorNone = 0, + /// The operation had to be aborted due to a network disconnect. + kErrorDisconnected, + /// The supplied auth token has expired. + kErrorExpiredToken, + /// The specified authentication token is invalid. + kErrorInvalidToken, + /// The transaction had too many retries. + kErrorMaxRetries, + /// The operation could not be performed due to a network error. + kErrorNetworkError, + /// The server indicated that this operation failed. + kErrorOperationFailed, + /// The transaction was overridden by a subsequent set. + kErrorOverriddenBySet, + /// This client does not have permission to perform this operation. + kErrorPermissionDenied, + /// The service is unavailable. + kErrorUnavailable, + /// An unknown error occurred. + kErrorUnknownError, + /// The write was canceled locally. + kErrorWriteCanceled, + /// You specified an invalid Variant type for a field. For example, + /// a DatabaseReference's Priority and the keys of a Map must be of + /// scalar type (MutableString, StaticString, Int64, Double). + kErrorInvalidVariantType, + /// An operation that conflicts with this one is already in progress. For + /// example, calling SetValue and SetValueAndPriority on a DatabaseReference + /// is not allowed. + kErrorConflictingOperationInProgress, + /// The transaction was aborted, because the user's DoTransaction function + /// returned kTransactionResultAbort instead of kTransactionResultSuccess. + kErrorTransactionAbortedByUser, +}; + +/// @brief Get the human-readable error message corresponding to an error code. +/// +/// @param[in] error Error code to get the error message for. +/// +/// @returns Statically-allocated string describing the error. +extern const char* GetErrorMessage(Error error); + +/// @brief Get a server-populated value corresponding to the current +/// timestamp. +/// +/// When inserting values into the database, you can use the special value +/// firebase::database::ServerTimestamp() to have the server auto-populate the +/// current timestamp, which is represented as millieconds since the Unix epoch, +/// into the field. +/// +/// @returns A special value that tells the server to use the current timestamp. +const Variant& ServerTimestamp(); + +} // namespace database +} // namespace firebase + +#endif // FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_COMMON_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/database/data_snapshot.h b/packages/firebase_core/firebase_core/firebase_core/firebase/database/data_snapshot.h new file mode 100644 index 000000000000..cb83292a792b --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/database/data_snapshot.h @@ -0,0 +1,205 @@ +// Copyright 2016 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_DATA_SNAPSHOT_H_ +#define FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_DATA_SNAPSHOT_H_ + +#include + +#include + +#include "firebase/internal/common.h" +#include "firebase/variant.h" + +namespace firebase { +namespace database { +namespace internal { +class Callbacks; +class ChildEventRegistration; +class DataSnapshotInternal; +class DatabaseInternal; +class DatabaseInternalTestMatcherTest; +class DatabaseReferenceInternal; +class QueryInternal; +class Repo; +class ValueEventRegistration; +} // namespace internal + +class Database; +class DatabaseReference; + +#ifndef SWIG +/// A DataSnapshot instance contains data from a Firebase Database location. Any +/// time you read Database data, you receive the data as a DataSnapshot. These +/// are efficiently-generated and cannot be changed. To modify data, +/// use DatabaseReference::SetValue() or DatabaseReference::RunTransaction(). +#endif // SWIG +class DataSnapshot { + public: + /// @brief Default constructor. + /// + /// This DataSnapshot contains nothing and is considered invalid (i.e. + /// is_valid() == false). Use this to construct an empty DataSnapshot that you + /// will later populate with data from a database callback. + DataSnapshot() : internal_(nullptr) {} + +#ifdef INTERNAL_EXPERIMENTAL + explicit DataSnapshot(internal::DataSnapshotInternal* internal); +#endif + + /// @brief Copy constructor. DataSnapshots are immutable, so they can be + /// efficiently copied. + /// + /// @param[in] snapshot DataSnapshot to copy. + DataSnapshot(const DataSnapshot& snapshot); + + /// @brief Copy assignment operator. DataSnapshots are immutable, so they can + /// be efficiently copied. + /// + /// @param[in] snapshot DataSnapshot to copy. + /// + /// @returns Reference to the destination DataSnapshot. + DataSnapshot& operator=(const DataSnapshot& snapshot); + +#if defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) + /// @brief Move constructor. DataSnapshots are immutable, so they can be + /// efficiently moved. + /// + /// @param[in] snapshot DataSnapshot to move into this one. + DataSnapshot(DataSnapshot&& snapshot); + + /// @brief Move assignment operator. DataSnapshots are immutable, so they can + /// be efficiently moved. + /// + /// @param[in] snapshot DataSnapshot to move into this one. + /// + /// @returns Reference to this destination DataSnapshot. + DataSnapshot& operator=(DataSnapshot&& snapshot); +#endif // defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) + + /// Destructor. + ~DataSnapshot(); + + /// @brief Returns true if the data is non-empty. + bool exists() const; + + /// @brief Get a DataSnapshot for the location at the specified relative path. + /// + /// @param[in] path Path relative to this snapshot's location. + /// It only needs to be valid during this call. + /// + /// @returns A DataSnapshot corresponding to specified child location. + DataSnapshot Child(const char* path) const; + + /// @brief Get a DataSnapshot for the location at the specified relative path. + /// + /// @param[in] path Path relative to this snapshot's location. + /// + /// @returns A DataSnapshot corresponding to specified child location. + DataSnapshot Child(const std::string& path) const; + + /// @brief Get all the immediate children of this location. + /// + /// @returns The immediate children of this snapshot. + std::vector children() const; + + /// @brief Get the number of children of this location. + /// + /// @returns The number of immediate children of this snapshot. + size_t children_count() const; + + /// @brief Does this DataSnapshot have any children at all? + /// + /// @returns True if the snapshot has any children, false otherwise. + bool has_children() const; + + /// @brief Get the key name of the source location of this snapshot. + /// + /// @note The returned pointer is only guaranteed to be valid while the + /// DataSnapshot is still in memory. + /// + /// @returns Key name of the source location of this snapshot. + const char* key() const; + + /// @brief Get the key name of the source location of this snapshot. + /// + /// @returns Key name of the source location of this snapshot. + std::string key_string() const; + + /// @brief Get the value of the data contained in this snapshot. + /// + /// @returns The value of the data contained in this location. + Variant value() const; + + /// @brief Get the priority of the data contained in this snapshot. + /// + /// @returns The value of this location's Priority relative to its siblings. + Variant priority() const; + + /// @brief Obtain a DatabaseReference to the source location for this + /// snapshot. + /// + /// @returns A DatabaseReference corresponding to same location as + /// this snapshot. + DatabaseReference GetReference() const; + + /// @brief Does this DataSnapshot have data at a particular location? + /// + /// @param[in] path Path relative to this snapshot's location. + /// The pointer only needs to be valid during this call. + /// + /// @returns True if the snapshot has data at the specified location, false if + /// not. + bool HasChild(const char* path) const; + + /// @brief Does this DataSnapshot have data at a particular location? + /// + /// @param[in] path Path relative to this snapshot's location. + /// + /// @returns True if the snapshot has data at the specified location, false if + /// not. + bool HasChild(const std::string& path) const; + + /// @brief Returns true if this snapshot is valid, false if it is not + /// valid. An invalid snapshot could be returned by a transaction where an + /// error has occurred. + /// + /// @returns true if this snapshot is valid, false if this snapshot is + /// invalid. + bool is_valid() const; + + private: + /// @cond FIREBASE_APP_INTERNAL + friend class internal::Callbacks; + friend class internal::ChildEventRegistration; + friend class internal::DataSnapshotInternal; + friend class internal::DatabaseInternal; + friend class internal::DatabaseInternalTestMatcherTest; + friend class internal::DatabaseReferenceInternal; + friend class internal::QueryInternal; + friend class internal::Repo; + friend class internal::ValueEventRegistration; + /// @endcond + +#ifndef INTERNAL_EXPERIMENTAL + explicit DataSnapshot(internal::DataSnapshotInternal* internal); +#endif + + internal::DataSnapshotInternal* internal_; +}; + +} // namespace database +} // namespace firebase + +#endif // FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_DATA_SNAPSHOT_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/database/database_reference.h b/packages/firebase_core/firebase_core/firebase_core/firebase/database/database_reference.h new file mode 100644 index 000000000000..3e746541a1d5 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/database/database_reference.h @@ -0,0 +1,477 @@ +// Copyright 2016 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_DATABASE_REFERENCE_H_ +#define FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_DATABASE_REFERENCE_H_ + +#include +#include + +#include "firebase/database/disconnection.h" +#include "firebase/database/query.h" +#include "firebase/database/transaction.h" +#include "firebase/future.h" +#include "firebase/internal/common.h" +#include "firebase/variant.h" + +namespace firebase { +namespace database { +namespace internal { +class DatabaseInternal; +class DatabaseReferenceInternal; +class Repo; +} // namespace internal + +class DataSnapshot; + +#ifndef SWIG +/// DatabaseReference represents a particular location in your Database and can +/// be used for reading or writing data to that Database location. +/// +/// This class is the starting point for all Database operations. After you've +/// initialized it with a URL, you can use it to read data, write data, and to +/// create new DatabaseReference instances. +#endif // SWIG +class DatabaseReference : public Query { + public: + /// @brief Default constructor. This creates an invalid DatabaseReference. + /// Attempting to perform any operations on this reference will fail unless a + /// valid DatabaseReference has been assigned to it. + DatabaseReference() : Query(), internal_(nullptr) {} + + /// @brief Required virtual destructor. + virtual ~DatabaseReference(); + + /// @brief Copy constructor. It's totally okay (and efficient) to copy + /// DatabaseReference instances, as they simply point to the same location in + /// the database. + /// + /// @param[in] reference DatabaseReference to copy from. + DatabaseReference(const DatabaseReference& reference); + + /// @brief Copy assignment operator. It's totally okay (and efficient) to copy + /// DatabaseReference instances, as they simply point to the same location in + /// the database. + /// + /// @param[in] reference DatabaseReference to copy from. + /// + /// @returns Reference to the destination DatabaseReference. + DatabaseReference& operator=(const DatabaseReference& reference); + +#if defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) + /// @brief Move constructor. Moving is an efficient operation for + /// DatabaseReference instances. + /// + /// @param[in] reference DatabaseReference to move data from. + DatabaseReference(DatabaseReference&& reference); + + /// @brief Move assignment operator. Moving is an efficient operation for + /// DatabaseReference instances. + /// + /// @param[in] reference DatabaseReference to move data from. + /// + /// @returns Reference to the destination DatabaseReference. + DatabaseReference& operator=(DatabaseReference&& reference); +#endif // defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) + + /// @brief Gets the database to which we refer. + /// + /// The pointer will remain valid indefinitely. + /// + /// @returns Firebase Database instance that this DatabaseReference refers to. + Database* database() const; + + /// @brief Gets the string key of this database location. + /// + /// The pointer is only valid while the DatabaseReference remains in memory. + /// + /// @returns String key of this database location, which will remain valid in + /// memory until the DatabaseReference itself goes away. + const char* key() const; + + /// @brief Gets the string key of this database location. + /// + /// @returns String key of this database location. + std::string key_string() const; + + /// @brief Returns true if this reference refers to the root of the database. + /// + /// @returns true if this reference refers to the root of the database, false + /// otherwise. + bool is_root() const; + + /// @brief Returns true if this reference is valid, false if it is not + /// valid. DatabaseReferences constructed with the default constructor + /// are considered invalid. An invalid reference could be returned by + /// Database::GetReference() or Database::GetReferenceFromUrl() if you specify + /// an incorrect location, or calling Query::GetReference() on an invalid + /// query. + /// + /// @returns true if this reference is valid, false if this reference is + /// invalid. + bool is_valid() const override; + + /// @brief Gets the parent of this location, or get this location again if + /// IsRoot(). + /// + /// @returns Parent of this location in the database, unless this location is + /// the root, in which case it returns this same location again. + DatabaseReference GetParent() const; + + /// @brief Gets the root of the database. + /// + /// @returns Root of the database. + DatabaseReference GetRoot() const; + + /// @brief Gets a reference to a location relative to this one. + /// + /// @param[in] path Path relative to this snapshot's location. + /// The pointer only needs to be valid during this call. + /// + /// @returns Child relative to this location. + DatabaseReference Child(const char* path) const; + + /// @brief Gets a reference to a location relative to this one. + /// + /// @param[in] path Path relative to this snapshot's location. + /// + /// @returns Child relative to this location. + DatabaseReference Child(const std::string& path) const; + + /// @brief Automatically generates a child location, create a reference to it, + /// and returns that reference to it. + /// + /// @returns A newly created child, with a unique key. + DatabaseReference PushChild() const; + + /// @brief Removes the value at this location from the database. + /// + /// This is an asynchronous operation which takes time to execute, and uses + /// firebase::Future to return its result. + /// + /// @returns A Future result, which will complete when the operation either + /// succeeds or fails. When the Future is completed, if its Error is + /// kErrorNone, the operation succeeded. + /// + /// @note Only one RemoveValue() should be running on a given database + /// location at the same time. If you need to run multiple operations at once, + /// use RunTransaction(). + Future RemoveValue(); + + /// @brief Gets the result of the most recent call to RemoveValue(); + /// + /// @returns Result of the most recent call to RemoveValue(). + Future RemoveValueLastResult(); + + /// @brief Run a user-supplied callback function (passing in a context), + /// possibly multiple times, to perform an atomic transaction on the database. + /// + /// @see firebase::database::DoTransactionWithContext for more information. + /// + /// @param[in] transaction_function The user-supplied function that will be + /// called, possibly multiple times, to perform the database transaction. + /// @param[in] context User-supplied context that will be passed to the + /// transaction function. + /// @param[in] trigger_local_events If true, events will be triggered for + /// intermediate state changes during the transaction. If false, only the + /// final state will cause events to be triggered. + /// + /// @returns A Future result, which will complete when the transaction either + /// succeeds or fails. When the Future is completed, if its Error is + /// kErrorNone, the operation succeeded and the transaction was committed, and + /// the new value of the data will be returned in the DataSnapshot result. If + /// the Error is kErrorTransactionAbortedByUser, the transaction was aborted + /// because the transaction function returned kTransactionResultAbort, and the + /// old value will be returned in DataSnapshot. Otherwise, if some other error + /// occurred, Error and ErrorMessage will be set and DataSnapshot will be + /// invalid. + /// + /// @note Only one RunTransaction() should be running on a given database + /// location at the same time. + Future RunTransaction( + DoTransactionWithContext transaction_function, void* context, + bool trigger_local_events = true); + +#if defined(FIREBASE_USE_STD_FUNCTION) || defined(DOXYGEN) + /// @brief Run a user-supplied callback, possibly multiple times, to perform + /// an atomic transaction on the database. + /// + /// @see firebase::database::DoTransactionFunction for more information. + /// + /// @param[in] transaction_function The user-supplied function or lambda that + /// will be called, possibly multiple times, to perform the database + /// transaction. + /// @param[in] trigger_local_events If true, events will be triggered for + /// intermediate state changes during the transaction. If false, only the + /// final state will cause events to be triggered. + /// + /// @returns A Future result, which will complete when the transaction either + /// succeeds or fails. When the Future is completed, if its Error is + /// kErrorNone, the operation succeeded and the transaction was committed, and + /// the new value of the data will be returned in the DataSnapshot result. If + /// the Error is kErrorTransactionAbortedByUser, the transaction was aborted + /// because the transaction function returned kTransactionResultAbort, and the + /// old value will be returned in DataSnapshot. Otherwise, if some other error + /// occurred, Error and ErrorMessage will be set and DataSnapshot will be + /// invalid. + /// + /// @note Only one RunTransaction() should be running on a given database + /// location at the same time. + /// + /// @note This version (that accepts an std::function) is not available when + /// using stlport on Android. If you don't wish to use std::function, use the + /// overloaded method that accepts a simple function pointer with a context. + Future RunTransaction( + DoTransactionFunction transaction_function, + bool trigger_local_events = true); +#endif // defined(FIREBASE_USE_STD_FUNCTION) || defined(DOXYGEN) + +#if !defined(FIREBASE_USE_STD_FUNCTION) || defined(DOXYGEN) + /// @brief Run a user-supplied callback function, possibly multiple times, to + /// perform an atomic transaction on the database. + /// + /// @see firebase::database::DoTransaction for more information. + /// + /// @param[in] transaction_function The user-supplied function that will be + /// called, possibly multiple times, to perform the database transaction. + /// @param[in] trigger_local_events If true, events will be triggered for + /// intermediate state changes during the transaction. If false, only the + /// final state will cause events to be triggered. + /// + /// @returns A Future result, which will complete when the transaction either + /// succeeds or fails. When the Future is completed, if its Error is + /// kErrorNone, the operation succeeded and the transaction was committed, and + /// the new value of the data will be returned in the DataSnapshot result. If + /// the Error is kErrorTransactionAbortedByUser, the transaction was aborted + /// because the transaction function returned kTransactionResultAbort, and the + /// old value will be returned in DataSnapshot. Otherwise, if some other error + /// occurred, Error and ErrorMessage will be set and DataSnapshot will be + /// invalid. + /// + /// @note Only one RunTransaction() should be running on a given database + /// location at the same time. + /// + /// @note This version (that accepts a simple function pointer) is only + /// available when using stlport and std::function is not available. + Future RunTransaction(DoTransaction transaction_function, + bool trigger_local_events = true); +#endif // !defined(FIREBASE_USE_STD_FUNCTION) || defined(DOXYGEN) + + /// @brief Get the result of the most recent call to RunTransaction(). + /// + /// @returns Results of the most recent call to RunTransaction(). + Future RunTransactionLastResult(); + + /// @brief Sets the priority of this field, which controls its sort + /// order relative to its siblings. + /// + /// In Firebase, children are sorted in the following order: + /// 1. First, children with no priority. + /// 2. Then, children with numerical priority, sorted numerically in + /// ascending order. + /// 3. Then, remaining children, sorted lexicographically in ascending order + /// of their text priority. + /// + /// Children with the same priority (including no priority) are sorted by + /// key: + /// A. First, children with keys that can be parsed as 32-bit integers, + /// sorted in ascending numerical order of their keys. + /// B. Then, remaining children, sorted in ascending lexicographical order + /// of their keys. + /// + /// This is an asynchronous operation which takes time to execute, and uses + /// firebase::Future to return its result. + /// + /// @param[in] priority Sort priority for this child relative to its siblings. + /// The Variant types accepted are Null, Int64, Double, and String. Other + /// types will return kErrorInvalidVariantType. + /// + /// @returns A Future result, which will complete when the operation either + /// succeeds or fails. When the Future is completed, if its Error is + /// kErrorNone, the operation succeeded. + /// + /// @note Only one SetPriority() should be running on a given database + /// location + /// at the same time. If you need to run multiple operations at once, use + /// RunTransaction(). + Future SetPriority(Variant priority); + + /// @brief Gets the result of the most recent call to SetPriority(). + /// + /// @returns Result of the most recent call to SetPriority(). + Future SetPriorityLastResult(); + + /// @brief Sets the data at this location to the given value. + /// + /// This is an asynchronous operation which takes time to execute, and uses + /// firebase::Future to return its result. + /// + /// @param[in] value The value to set this location to. The Variant's type + /// corresponds to the types accepted by the database JSON: + /// Null: Deletes this location from the database. + /// Int64: Inserts an integer value into this location. + /// Double: Inserts a floating point value into this location. + /// String: Inserts a string into this location. + /// (Accepts both Mutable and Static strings) + /// Vector: Inserts a JSON array into this location. The elements can be any + /// Variant type, including Vector and Map. + /// Map: Inserts a JSON associative array into this location. The keys must + /// be of type String (or Int64/Double which are converted to String). + /// The values can be any Variant type, including Vector and Map. + /// + /// @returns A Future result, which will complete when the operation either + /// succeeds or fails. When the Future is completed, if its Error is + /// kErrorNone, the operation succeeded. + /// + /// @note Only one SetValue() should be running on a given database location + /// at the same time. If you need to run multiple operations at once, use + /// RunTransaction(). + Future SetValue(Variant value); + + /// @brief Gets the result of the most recent call to SetValue(). + /// + /// @returns Result of the most recent call to SetValue(). + Future SetValueLastResult(); + + /// @brief Sets both the data and priority of this location. See SetValue() + /// and SetPriority() for context on the parameters. + /// + /// This is an asynchronous operation which takes time to execute, and uses + /// firebase::Future to return its result. + /// + /// @param[in] value The value to set this location to. See SetValue() for + /// information on the types accepted. + /// @param[in] priority The priority to set this location to. See + /// SetPriority() for information on the types accepted. + /// + /// @returns A Future result, which will complete when the operation either + /// succeeds or fails. When the Future is completed, if its Error is + /// kErrorNone, the operation succeeded. + /// + /// @note Only one SetValueAndPriority() should be running on a given database + /// location at the same time. SetValueAndPriority() can't be used on the same + /// location at the same time as either SetValue() or SetPriority(), and will + /// return kErrorConflictingOperationInProgress if you try. If you need to run + /// multiple operations at once, use RunTransaction(). + Future SetValueAndPriority(Variant value, Variant priority); + + /// @brief Get the result of the most recent call to SetValueAndPriority(). + /// + /// @returns Result of the most recent call to SetValueAndPriority(). + Future SetValueAndPriorityLastResult(); + + /// @brief Updates the specified child keys to the given values. + /// + /// @param[in] values A variant of type Map. The keys are the paths to update + /// and must be of type String (or Int64/Double which are converted to + /// String). The values can be any Variant type. A value of Variant type Null + /// will delete the child. + /// + /// @returns A Future result, which will complete when the operation either + /// succeeds or fails. When the Future is completed, if its Error is + /// kErrorNone, the operation succeeded. + /// + /// @note This method will return kErrorConflictingOperationInProgress if it + /// is run at the same time as SetValue(), SetValueAndPriority(), or + /// RemoveValue() in the same location. + Future UpdateChildren(Variant values); + + /// @brief Updates the specified child keys to the given values. + /// + /// This is an asynchronous operation which takes time to execute, and uses + /// firebase::Future to return its result. + /// + /// @param[in] values The paths to update, and their new child values. A value + /// of type Null will delete that particular child. + /// + /// @returns A Future result, which will complete when the operation either + /// succeeds or fails. When the Future is completed, if its Error is + /// kErrorNone, the operation succeeded. + inline Future UpdateChildren( + const std::map& values) { + return UpdateChildren(Variant(values)); + } + + /// @brief Gets the result of the most recent call to either version of + /// UpdateChildren(). + /// + /// @returns Result of the most recent call to UpdateChildren(). + Future UpdateChildrenLastResult(); + + /// @brief Get the absolute URL of this reference. + /// + /// @returns The absolute URL of the location this reference refers to. + std::string url() const; + + /// @brief Get the disconnect handler, which controls what actions the server + /// will perform to this location's data when this client disconnects. + /// + /// @returns Disconnection handler for this location. You can use this to + /// queue up operations on the server to be performed when the client + /// disconnects. + DisconnectionHandler* OnDisconnect(); + + /// @brief Manually disconnect Firebase Realtime Database from the server, and + /// disable automatic reconnection. This will affect all other instances of + /// DatabaseReference as well. + void GoOffline(); + + /// @brief Manually reestablish connection to the Firebase Realtime Database + /// server and enable automatic reconnection. This will affect all other + /// instances of DatabaseReference as well. + void GoOnline(); + + protected: + /// @cond FIREBASE_APP_INTERNAL + explicit DatabaseReference(internal::DatabaseReferenceInternal* internal); + /// @endcond + + private: + /// @cond FIREBASE_APP_INTERNAL + + // Remove the "Query" cleanup registration (which the base class constructor + // already registered) and replace it with a "DatabaseReference" registration. + // + // This is necessary so that if the instance needs to be cleaned up, the + // correct pointer type will be used to access it. + void SwitchCleanupRegistrationToDatabaseReference(); + + // Remove the "DatabaseReference" cleanup registration and replace it with a + // "Query" one. ~Query() will unregister that one. + void SwitchCleanupRegistrationBackToQuery(); + + friend class DataSnapshot; + friend class Query; + friend class internal::DatabaseInternal; + friend class internal::Repo; + friend bool operator==(const DatabaseReference& lhs, + const DatabaseReference& rhs); + /// @endcond + + internal::DatabaseReferenceInternal* internal_; +}; + +/// @brief Compares two DatabaseReference instances. +/// +/// @param[in] lhs A DatabaseReference. +/// @param[in] rhs A DatabaseReference to compare against. +/// +/// @returns True if the DatabaseReference instances have the same URL. False +/// otherwise. +bool operator==(const DatabaseReference& lhs, const DatabaseReference& rhs); + +} // namespace database +} // namespace firebase + +#endif // FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_DATABASE_REFERENCE_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/database/disconnection.h b/packages/firebase_core/firebase_core/firebase_core/firebase/database/disconnection.h new file mode 100644 index 000000000000..b21fa472e629 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/database/disconnection.h @@ -0,0 +1,156 @@ +// Copyright 2016 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_DISCONNECTION_H_ +#define FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_DISCONNECTION_H_ + +#include "firebase/future.h" +#include "firebase/internal/common.h" +#include "firebase/variant.h" + +namespace firebase { +namespace database { +namespace internal { +class DatabaseReferenceInternal; +class DisconnectionHandlerInternal; +} // namespace internal + +/// Allows you to register server-side actions to occur when the client +/// disconnects. Each method you call (with the exception of Cancel) will queue +/// up an action on the data that will be performed by the server in the event +/// the client disconnects. To reset this queue, call Cancel(). +/// +/// A DisconnectionHandler is associated with a specific location in the +/// database, as they are obtained by calling DatabaseReference::OnDisconnect(). +class DisconnectionHandler { + public: + ~DisconnectionHandler(); + + /// @brief Cancel any Disconnection operations that are queued up by this + /// handler. When the Future returns, if its Error is kErrorNone, the queue + /// has been cleared on the server. + /// + /// @returns A Future result, which will complete when the operation either + /// succeeds or fails. When the Future is completed, if its Error is + /// kErrorNone, the operation succeeded. + Future Cancel(); + /// @brief Get the result of the most recent call to Cancel(). + /// + /// @returns Result of the most recent call to Cancel(). + Future CancelLastResult(); + + /// @brief Remove the value at the current location when the client + /// disconnects. When the Future returns, if its Error is kErrorNone, the + /// RemoveValue operation has been successfully queued up on the server. + /// + /// @returns A Future result, which will complete when the operation either + /// succeeds or fails. When the Future is completed, if its Error is + /// kErrorNone, the operation succeeded. + Future RemoveValue(); + /// @brief Get the result of the most recent call to RemoveValue(). + /// + /// @returns Result of the most recent call to RemoveValue(). + Future RemoveValueLastResult(); + + /// @brief Set the value of the data at the current location when the client + /// disconnects. When the Future returns, if its Error is kErrorNone, the + /// SetValue operation has been successfully queued up on the server. + /// + /// @param[in] value The value to set this location to when the client + /// disconnects. For information on how the Variant types are used, + /// see firebase::database::DatabaseReference::SetValue(). + /// + /// @returns A Future result, which will complete when the operation either + /// succeeds or fails. When the Future is completed, if its Error is + /// kErrorNone, the operation succeeded. + Future SetValue(Variant value); + /// Get the result of the most recent call to SetValue(). + /// + /// @returns Result of the most recent call to SetValue(). + Future SetValueLastResult(); + + /// @brief Set the value and priority of the data at the current location when + /// the client disconnects. When the Future returns, if its Error is + /// kErrorNone, the SetValue operation has been successfully queued up on the + /// server. + /// + /// @param[in] value The value to set this location to when the client + /// disconnects. For information on how the Variant types are used, + /// see firebase::database::DatabaseReference::SetValue(). + /// @param[in] priority The priority to set this location to when the client + /// disconnects. The Variant types accepted are Null, Int64, Double, and + /// String. For information about how priority is used, see + /// firebase::database::DatabaseReference::SetPriority(). + /// + /// @returns A Future result, which will complete when the operation either + /// succeeds or fails. When the Future is completed, if its Error is + /// kErrorNone, the operation succeeded. + Future SetValueAndPriority(Variant value, Variant priority); + /// @brief Get the result of the most recent call to SetValueAndPriority(). + /// + /// @returns Result of the most recent call to SetValueAndPriority(). + Future SetValueAndPriorityLastResult(); + + /// @brief Updates the specified child keys to the given values when the + /// client disconnects. When the Future returns, if its Error is kErrorNone, + /// the UpdateChildren operation has been successfully queued up by the + /// server. + /// + /// @param[in] values A variant of type Map. The keys are the paths to update + /// and must be of type String (or Int64/Double which are converted to + /// String). The values can be any Variant type. A value of Variant type Null + /// will delete the child. + /// + /// @returns A Future result, which will complete when the operation either + /// succeeds or fails. When the Future is completed, if its Error is + /// kErrorNone, the operation succeeded. + Future UpdateChildren(Variant values); + /// @brief Updates the specified child keys to the given values when the + /// client disconnects. When the Future returns, if its Error is kErrorNone, + /// the UpdateChildren operation has been successfully queued up by the + /// server. + /// + /// @param[in] values The paths to update, and their new child values. A value + /// of type Null will delete that particular child. + /// + /// @returns A Future result, which will complete when the operation either + /// succeeds or fails. When the Future is completed, if its Error is + /// kErrorNone, the operation succeeded. + Future UpdateChildren(const std::map& values) { + return UpdateChildren(Variant(values)); + } + /// @brief Gets the result of the most recent call to either version of + /// UpdateChildren(). + /// + /// @returns Result of the most recent call to UpdateChildren(). + Future UpdateChildrenLastResult(); + + private: + /// @cond FIREBASE_APP_INTERNAL + friend class internal::DatabaseReferenceInternal; + friend class internal::DisconnectionHandlerInternal; + /// @endcond + + /// Call DatabaseReference::OnDisconnect() to get an instance of this class. + explicit DisconnectionHandler( + internal::DisconnectionHandlerInternal* internal); + + /// You can only get the DisconnectHandler for a given reference. + internal::DisconnectionHandlerInternal* internal_; +}; + +} // namespace database +} // namespace firebase + +#endif // FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_DISCONNECTION_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/database/listener.h b/packages/firebase_core/firebase_core/firebase_core/firebase/database/listener.h new file mode 100644 index 000000000000..fe13d9299003 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/database/listener.h @@ -0,0 +1,112 @@ +// Copyright 2016 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_LISTENER_H_ +#define FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_LISTENER_H_ + +#include "firebase/database/common.h" + +namespace firebase { +namespace database { + +class DataSnapshot; + +/// Value listener interface. Subclasses of this listener class can be +/// used to receive events about data changes at a location. Attach +/// the listener to a location using +/// DatabaseReference::AddValueListener() or +/// Query::AddValueListener(), and OnValueChanged() will be called +/// once immediately, and again when the value changes. +class ValueListener { + public: + virtual ~ValueListener(); + + /// This method will be called with a snapshot of the data at this + /// location each time that data changes. + /// + /// @param[in] snapshot The current data at the location. + virtual void OnValueChanged(const DataSnapshot& snapshot) = 0; + + /// @brief This method will be triggered in the event that this listener + /// either failed at the server, or is removed as a result of the security and + /// Firebase rules. + /// + /// @param[in] error A code corresponding to the error that occurred. + /// @param[in] error_message A description of the error that occurred. + virtual void OnCancelled(const Error& error, const char* error_message) = 0; +}; + +/// Child listener interface. Subclasses of this listener class can be +/// used to receive events about changes in the child locations of a +/// firebase::database::Query or +/// firebase::database::DatabaseReference. Attach the listener to a +/// location with Query::AddChildListener() or +/// DatabaseReference::AddChildListener() and the appropriate method +/// will be triggered when changes occur. +class ChildListener { + public: + virtual ~ChildListener(); + + /// @brief This method is triggered when a new child is added to the location + /// to which this listener was added. + /// + /// @param[in] snapshot An immutable snapshot of the data at the new data at + /// the child location. + /// @param[in] previous_sibling_key The key name of sibling location ordered + /// before the child. This will be nullptr for the first child node of a + /// location. + virtual void OnChildAdded(const DataSnapshot& snapshot, + const char* previous_sibling_key) = 0; + /// @brief This method is triggered when the data at a child location has + /// changed. + /// + /// @param[in] snapshot An immutable snapshot of the data at the new data at + /// the child location. + /// @param[in] previous_sibling_key The key name of sibling location ordered + /// before the child. This will be nullptr for the first child node of a + /// location. + virtual void OnChildChanged(const DataSnapshot& snapshot, + const char* previous_sibling_key) = 0; + /// @brief This method is triggered when a child location's priority changes. + /// See DatabaseReference::SetPriority() for more information on priorities + /// and + /// ordering data. + /// + /// @param[in] snapshot An immutable snapshot of the data at the new data at + /// the child location. + /// @param[in] previous_sibling_key The key name of sibling location ordered + /// before the child. This will be nullptr for the first child node of a + /// location. + virtual void OnChildMoved(const DataSnapshot& snapshot, + const char* previous_sibling_key) = 0; + /// @brief This method is triggered when a child is removed from the location + /// to which this listener was added. + /// + /// @param[in] snapshot An immutable snapshot of the data at the new data at + /// the child location. + virtual void OnChildRemoved(const DataSnapshot& snapshot) = 0; + + /// @brief This method will be triggered in the event that this listener + /// either failed at the server, or is removed as a result of the security and + /// Firebase rules. + /// + /// @param[in] error A code corresponding to the error that occurred. + /// @param[in] error_message A description of the error that occurred. + virtual void OnCancelled(const Error& error, const char* error_message) = 0; +}; + +} // namespace database +} // namespace firebase + +#endif // FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_LISTENER_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/database/mutable_data.h b/packages/firebase_core/firebase_core/firebase_core/firebase/database/mutable_data.h new file mode 100644 index 000000000000..cedfa159cca6 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/database/mutable_data.h @@ -0,0 +1,165 @@ +// Copyright 2016 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_MUTABLE_DATA_H_ +#define FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_MUTABLE_DATA_H_ + +#include "firebase/internal/common.h" +#include "firebase/variant.h" + +namespace firebase { +namespace database { +namespace internal { +class DatabaseInternal; +class DatabaseReferenceInternal; +class MutableDataInternal; +class Repo; +} // namespace internal + +#ifndef SWIG +/// Instances of this class encapsulate the data and priority at a location. It +/// is used in transactions, and it is intended to be inspected and then updated +/// to the desired data at that location. +#endif // SWIG +class MutableData { + public: +#if defined(FIREBASE_USE_MOVE_OPERATORS) + /// Move constructor + /// Move is more efficient than copy and delete. + MutableData(MutableData&& rhs); + + // MutableData may be moved. + MutableData& operator=(MutableData&& rhs); +#endif // defined(FIREBASE_USE_MOVE_OPERATORS) + + /// Destructor. + ~MutableData(); + + /// @brief Used to obtain a MutableData instance that encapsulates + /// the data and priority at the given relative path. + /// + /// Note that changes made to a child MutableData instance will be visible + /// to the parent and vice versa. + /// + /// @param[in] path Path relative to this snapshot's location. + /// The pointer only needs to be valid during this call. + /// + /// @returns MutableData for the Child relative to this location. The memory + /// will be freed when the Transaction is finished. + MutableData Child(const char* path); + + /// @brief Used to obtain a MutableData instance that encapsulates + /// the data and priority at the given relative path. + /// + /// @param[in] path Path relative to this snapshot's location. + /// + /// @returns MutableData for the Child relative to this location. The memory + /// will be freed when the Transaction is finished. + MutableData Child(const std::string& path); + + /// @brief Get all the immediate children of this location. + /// + /// @returns The immediate children of this location. + std::vector children(); + + /// @brief Get the number of children of this location. + /// + /// @returns The number of immediate children of this location. + size_t children_count(); + + /// @brief Get the key name of the source location of this data. + /// + /// @note The returned pointer is only guaranteed to be valid during the + /// transaction. + /// + /// @returns Key name of the source location of this data. + const char* key() const; + + /// @brief Get the key name of the source location of this data. + /// + /// @returns Key name of the source location of this data. + std::string key_string() const; + + /// @brief Get the value of the data contained at this location. + /// + /// @returns The value of the data contained at this location. + Variant value() const; + + /// @brief Get the priority of the data contained at this snapshot. + /// + /// @returns The value of this location's Priority relative to its siblings. + Variant priority(); + + /// @brief Does this MutableData have data at a particular location? + /// + /// @param[in] path Path relative to this data's location. + /// The pointer only needs to be valid during this call. + /// + /// @returns True if there is data at the specified location, false if not. + bool HasChild(const char* path) const; + + /// @brief Does this MutableData have data at a particular location? + /// + /// @param[in] path Path relative to this data's location. + /// @returns True if there is data at the specified location, false if not. + bool HasChild(const std::string& path) const; + + /// @brief Sets the data at this location to the given value. + /// + /// @param[in] value The value to set this location to. The Variant's type + /// corresponds to the types accepted by the database JSON: + /// Null: Deletes this location from the database. + /// Int64: Inserts an integer value into this location. + /// Double: Inserts a floating point value into this location. + /// String: Inserts a string into this location. + /// (Accepts both Mutable and Static strings) + /// Vector: Inserts a JSON array into this location. The elements can be any + /// Variant type, including Vector and Map. + /// Map: Inserts a JSON associative array into this location. The keys must + /// be of type String (or Int64/Double which are converted to String). + /// The values can be any Variant type, including Vector and Map. + void set_value(const Variant& value); + + /// @brief Sets the priority of this field, which controls its sort + /// order relative to its siblings. + /// + /// @see firebase::database::DatabaseReference::SetPriority() for information + /// on how Priority affects the ordering of a node's children. + /// + /// @param[in] priority Sort priority for this child relative to its siblings. + /// The Variant types accepted are Null, Int64, Double, and String. Other + /// types will return kErrorInvalidVariantType. + void set_priority(const Variant& priority); + + private: + /// @cond FIREBASE_APP_INTERNAL + friend class internal::DatabaseReferenceInternal; + friend class internal::DatabaseInternal; + friend class internal::MutableDataInternal; + friend class internal::Repo; + friend MutableData GetInvalidMutableData(); + /// @endcond + + explicit MutableData(internal::MutableDataInternal* internal); + + MutableData(const MutableData& rhs) = delete; + MutableData& operator=(const MutableData& rhs) = delete; + + internal::MutableDataInternal* internal_; +}; + +} // namespace database +} // namespace firebase + +#endif // FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_MUTABLE_DATA_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/database/query.h b/packages/firebase_core/firebase_core/firebase_core/firebase/database/query.h new file mode 100644 index 000000000000..c60707a7ee65 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/database/query.h @@ -0,0 +1,358 @@ +// Copyright 2016 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_QUERY_H_ +#define FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_QUERY_H_ + +#include + +#include "firebase/database/listener.h" +#include "firebase/future.h" +#include "firebase/internal/common.h" + +namespace firebase { +namespace database { +namespace internal { +class QueryInternal; +} // namespace internal + +class DatabaseReference; + +#ifndef SWIG +/// The Query class is used for reading data. Listeners can be attached, which +/// will be triggered when the data changes. +#endif // SWIG +class Query { + public: + /// Default constructor. This creates an invalid Query. Attempting to perform + /// any operations on this reference will fail unless a valid Query has been + /// assigned to it. + Query() : internal_(nullptr) {} + + /// Copy constructor. Queries can be copied. Copies exist independently of + /// each other. + Query(const Query& query); + + /// Copy assignment operator. Queries can be copied. Copies exist + /// independently of each other. + Query& operator=(const Query& query); + +#if defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) + /// Move constructor. + Query(Query&& query); + /// Move assignment operator. + Query& operator=(Query&& query); +#endif // defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) + + /// @brief Required virtual destructor. + virtual ~Query(); + + /// @brief Gets the value of the query for the given location a single time. + /// + /// This is an asynchronous operation which takes time to execute, and uses + /// firebase::Future to return its result. + /// + /// @returns A Future result, which will complete when the operation either + /// succeeds or fails. On this Future's completion, if its Error is + /// kErrorNone, the operation succeeded, and the DataSnapshot contains the + /// data in this location. + Future GetValue(); + /// @brief Gets the result of the most recent call to GetValue(). + /// + /// @returns Result of the most recent call to GetValue(). + Future GetValueLastResult(); + + /// @brief Adds a listener that will be called immediately and then again any + /// time the data changes. + /// + /// @param[in] listener A ValueListener instance, which must remain in memory + /// until you remove the listener from the Query. + void AddValueListener(ValueListener* listener); + + /// @brief Removes a listener that was previously added with + /// AddValueListener(). + /// + /// @param[in] listener A ValueListener instance to remove from the + /// Query. After it is removed, you can delete it or attach it to a new + /// location. + /// + /// @note You can remove a ValueListener from a different Query than you added + /// it to, as long as the two Query instances are equivalent. + void RemoveValueListener(ValueListener* listener); + + /// @brief Removes all value listeners that were added with + /// AddValueListener(). + /// + /// @note You can remove ValueListeners from a different Query than you added + /// them to, as long as the two Query instances are equivalent. + void RemoveAllValueListeners(); + + /// @brief Adds a listener that will be called any time a child is added, + /// removed, modified, or reordered. + /// + /// @param[in] listener A ChildListener instance, which must remain in memory + /// until you remove the listener from the Query. + void AddChildListener(ChildListener* listener); + + /// @brief Removes a listener that was previously added with + /// AddChildListener(). + /// + /// @param[in] listener A ChildListener instance to remove from the + /// Query. After it is removed, you can delete it or attach it to a new + /// location. + /// + /// @note You can remove a ChildListener from a different Query than you added + /// it to, as long as the two Query instances are equivalent. + void RemoveChildListener(ChildListener* listener); + + /// @brief Removes all child listeners that were added by AddChildListener(). + /// + /// @note You can remove ChildListeners from a different Query than you added + /// them to, as long as the two Query instances are equivalent. + void RemoveAllChildListeners(); + + /// @brief Gets a DatabaseReference corresponding to the given location. + /// + /// @returns A DatabaseReference corresponding to the same location as the + /// Query, but without any of the ordering or filtering parameters. + DatabaseReference GetReference() const; + + /// @brief Sets whether this location's data should be kept in sync even if + /// there are no active Listeners. + /// + /// By calling SetKeepSynchronized(true) on a given database location, the + /// data for that location will automatically be downloaded and kept in sync, + /// even when no listeners are attached for that location. Additionally, while + /// a location is kept synced, it will not be evicted from the persistent disk + /// cache. + /// + /// @param[in] keep_sync If true, set this location to be synchronized. If + /// false, set it to not be synchronized. + void SetKeepSynchronized(bool keep_sync); + + // The OrderBy* functions are used for two purposes: + // 1. Order the data when getting the list of children. + // 2. When filtering the data using the StartAt* and EndAt* functions further + // below, use the specified ordering. + + /// @brief Gets a query in which child nodes are ordered by the values of the + /// specified path. Any previous OrderBy directive will be replaced in the + /// returned Query. + /// + /// @param[in] path Path to a child node. The value of this node will be used + /// for sorting this query. The pointer you pass in need not remain valid + /// after the call completes. + /// + /// @returns A Query in this same location, with the children are sorted by + /// the value of their own child specified here. + Query OrderByChild(const char* path); + /// @brief Gets a query in which child nodes are ordered by the values of the + /// specified path. Any previous OrderBy directive will be replaced in the + /// returned Query. + /// + /// @param[in] path Path to a child node. The value of this node will be used + /// for sorting this query. + /// + /// @returns A Query in this same location, with the children are sorted by + /// the value of their own child specified here. + Query OrderByChild(const std::string& path); + /// @brief Gets a query in which child nodes are ordered by their keys. Any + /// previous OrderBy directive will be replaced in the returned Query. + /// + /// @returns A Query in this same location, with the children are sorted by + /// their key. + Query OrderByKey(); + /// @brief Gets a query in which child nodes are ordered by their priority. + /// Any previous OrderBy directive will be replaced in the returned Query. + /// + /// @returns A Query in this same location, with the children are sorted by + /// their priority. + Query OrderByPriority(); + /// @brief Create a query in which nodes are ordered by their value. + /// + /// @returns A Query in this same location, with the children are sorted by + /// their value. + Query OrderByValue(); + + // The StartAt, EndAt, and EqualTo functions are used to limit which child + // nodes are returned when iterating through the current location. + + /// @brief Get a Query constrained to nodes with the given sort value or + /// higher. + /// + /// This method is used to generate a reference to a limited view of the data + /// at this location. The Query returned will only refer to child nodes with a + /// value greater than or equal to the given value, using the given OrderBy + /// directive (or priority as the default). + /// + /// @param[in] order_value The lowest sort value the Query should include. + /// + /// @returns A Query in this same location, filtering out child nodes that + /// have a lower sort value than the sort value specified. + Query StartAt(Variant order_value); + /// @brief Get a Query constrained to nodes with the given sort value or + /// higher, and the given key or higher. + /// + /// This method is used to generate a reference to a limited view of the data + /// at this location. The Query returned will only refer to child nodes with a + /// value greater than or equal to the given value, using the given OrderBy + /// directive (or priority as default), and additionally only child nodes with + /// a key greater than or equal to the given key. + /// + /// Known issue This currently does not work properly on all platforms. + /// Please use StartAt(Variant order_value) instead. + /// + /// @param[in] order_value The lowest sort value the Query should include. + /// @param[in] child_key The lowest key the Query should include. + /// + /// @returns A Query in this same location, filtering out child nodes that + /// have a lower sort value than the sort value specified, or a lower key than + /// the key specified. + Query StartAt(Variant order_value, const char* child_key); + + /// @brief Get a Query constrained to nodes with the given sort value or + /// lower. + /// + /// This method is used to generate a reference to a limited view of the data + /// at this location. The Query returned will only refer to child nodes with a + /// value less than or equal to the given value, using the given OrderBy + /// directive (or priority as default). + /// + /// @param[in] order_value The highest sort value the Query should refer + /// to. + /// + /// @returns A Query in this same location, filtering out child nodes that + /// have a higher sort value or key than the sort value or key specified. + Query EndAt(Variant order_value); + /// @brief Get a Query constrained to nodes with the given sort value or + /// lower, and the given key or lower. + /// + /// This method is used to generate a reference to a limited view of + /// the data at this location. The Query returned will only refer to child + /// nodes with a value less than or equal to the given value, using the given + /// OrderBy directive (or priority as default), and additionally only child + /// nodes with a key less than or equal to the given key. + /// + /// Known issue This currently does not work properly on all platforms. + /// Please use EndAt(Variant order_value) instead. + /// + /// @param[in] order_value The highest sort value the Query should include. + /// @param[in] child_key The highest key the Query should include. + /// + /// @returns A Query in this same location, filtering out child nodes that + /// have a higher sort value than the sort value specified, or a higher key + /// than the key specified. + Query EndAt(Variant order_value, const char* child_key); + + /// @brief Get a Query constrained to nodes with the exact given sort value. + /// + /// This method is used to create a query constrained to only return child + /// nodes with the given value, using the given OrderBy directive (or priority + /// as default). + /// + /// @param[in] order_value The exact sort value the Query should include. + /// + /// @returns A Query in this same location, filtering out child nodes that + /// have a different sort value than the sort value specified. + Query EqualTo(Variant order_value); + + /// @brief Get a Query constrained to nodes with the exact given sort value, + /// and the exact given key. + /// + /// This method is used to create a query constrained to only return the child + /// node with the given value, using the given OrderBy directive (or priority + /// as default), and the given key. Note that there is at most one such child + /// as child key names are unique. + /// + /// Known issue This currently does not work properly on iOS, tvOS and + /// desktop. Please use EqualTo(Variant order_value) instead. + /// + /// @param[in] order_value The exact sort value the Query should include. + /// @param[in] child_key The exact key the Query should include. + /// + /// @returns A Query in this same location, filtering out child nodes that + /// have a different sort value than the sort value specified, and containing + /// at most one child with the exact key specified. + Query EqualTo(Variant order_value, const char* child_key); + + // The LimitTo* functions are used to limit how many child nodes are returned + // when iterating through the current location. + + /// @brief Gets a Query limited to only the first results. + /// + /// Limits the query to reference only the first N child nodes, using the + /// given OrderBy directive (or priority as default). + /// + /// @param[in] limit Number of children to limit the Query to. + /// + /// @returns A Query in this same location, limited to the specified number of + /// children (taken from the beginning of the sorted list). + Query LimitToFirst(size_t limit); + /// @brief Gets a Query limited to only the last results. + /// + /// @param[in] limit Number of children to limit the Query to. + /// + /// @returns A Query in this same location, limited to the specified number of + /// children (taken from the end of the sorted list). + Query LimitToLast(size_t limit); + + /// @brief Returns true if this query is valid, false if it is not valid. An + /// invalid query could be returned by, say, attempting to OrderBy two + /// different items, or calling OrderByChild() with an empty path, or by + /// constructing a Query with the default constructor. If a Query + /// is invalid, attempting to add more constraints will also result in an + /// invalid Query. + /// + /// @returns true if this query is valid, false if this query is + /// invalid. + virtual bool is_valid() const; + + protected: + /// @cond FIREBASE_APP_INTERNAL + explicit Query(internal::QueryInternal* internal); + void SetInternal(internal::QueryInternal* internal); + void RegisterCleanup(); + void UnregisterCleanup(); + /// @endcond + + private: + /// @cond FIREBASE_APP_INTERNAL + friend bool operator==(const Query& lhs, const Query& rhs); + /// @endcond + + internal::QueryInternal* internal_; +}; + +/// @brief Compares two Query instances. +/// +/// Two Query instances on the same database, in the same location, with the +/// same parameters (OrderBy*, StartAt, EndAt, EqualTo, Limit*) are considered +/// equivalent. +/// +/// Equivalent Queries have a shared pool of ValueListeners and +/// ChildListeners. When listeners are added or removed from one Query +/// instance, it affects all equivalent Query instances. +/// +/// @param[in] lhs The Query to compare against. +/// @param[in] rhs The Query to compare against. +/// +/// @returns True if the Query instances have the same database, the same +/// path, and the same parameters, determined by StartAt(), EndAt(), +/// EqualTo(), and the OrderBy and LimitTo methods. False otherwise. +bool operator==(const Query& lhs, const Query& rhs); + +} // namespace database +} // namespace firebase + +#endif // FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_QUERY_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/database/transaction.h b/packages/firebase_core/firebase_core/firebase_core/firebase/database/transaction.h new file mode 100644 index 000000000000..cb2dd33c59e2 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/database/transaction.h @@ -0,0 +1,102 @@ +// Copyright 2016 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_TRANSACTION_H_ +#define FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_TRANSACTION_H_ + +#include "firebase/database/common.h" +#include "firebase/database/data_snapshot.h" +#include "firebase/database/mutable_data.h" +#include "firebase/internal/common.h" +#include "firebase/variant.h" + +#if defined(FIREBASE_USE_STD_FUNCTION) +#include +#endif // defined(FIREBASE_USE_STD_FUNCTION) + +namespace firebase { +namespace database { + +/// Specifies whether the transaction succeeded or not. +enum TransactionResult { + /// The transaction was successful, the MutableData was updated. + kTransactionResultSuccess, + /// The transaction did not succeed. Any changes to the MutableData + /// will be discarded. + kTransactionResultAbort, +}; + +/// Your own transaction handler, which the Firebase Realtime Database library +/// may call multiple times to apply changes to the data, and should return +/// success or failure depending on whether it succeeds. + +/// @note This version of the callback is no longer supported (unless you are +/// building for Android with stlport). You should use either one of +/// DoTransactionWithContext (a simple function pointer that accepts context +/// data) or DoTransactionFunction (based on std::function). +/// +/// @see DoTransactionWithContext for more information. +typedef TransactionResult (*DoTransaction)(MutableData* data); + +/// Your own transaction handler, which the Firebase Realtime Database library +/// may call multiple times to apply changes to the data, and should return +/// success or failure depending on whether it succeeds. The context you +/// specified to RunTransaction will be passed into this call. +/// +/// This function will be called, _possibly multiple times_, with the current +/// data at this location. The function is responsible for inspecting that data +/// and modifying it as desired, then returning a TransactionResult specifying +/// either that the MutableData was modified to a desired new state, or that the +/// transaction should be aborted. Whenever this function is called, the +/// MutableData passed in must be modified from scratch. +/// +/// Since this function may be called repeatedly for the same transaction, be +/// extremely careful of any side effects that may be triggered by this +/// function. In addition, this function is called from within the Firebase +/// Realtime Database library's run loop, so care is also required when +/// accessing data that may be in use by other threads in your application. +/// +/// Best practices for this function are to ONLY rely on the data passed in. +/// +/// @param[in] data Mutable data, which the callback can edit. +/// @param[in] context Context pointer, passed verbatim to the callback. +/// +/// @returns The callback should return kTransactionResultSuccess if the data +/// was modified, or kTransactionResultAbort if it was unable to modify the +/// data. If the callback returns kTransactionResultAbort, the RunTransaction() +/// call will return the kErrorTransactionAbortedByUser error code. +/// +/// @note If you want a callback to be triggered when the transaction is +/// finished, you can use the Future value returned by the method +/// running the transaction, and call Future::OnCompletion() to register a +/// callback to be called when the transaction either succeeds or fails. +/// +/// @see DoTransaction for more information. +typedef TransactionResult (*DoTransactionWithContext)(MutableData* data, + void* context); + +#if defined(FIREBASE_USE_STD_FUNCTION) || defined(DOXYGEN) +/// Your own transaction handler function or lambda, which the Firebase Realtime +/// Database library may call multiple times to apply changes to the data, and +/// should return success or failure depending on whether it succeeds. +/// +/// @see DoTransactionWithContext for more information. +typedef std::function + DoTransactionFunction; +#endif // defined(FIREBASE_USE_STD_FUNCTION) || defined(DOXYGEN) + +} // namespace database +} // namespace firebase + +#endif // FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_TRANSACTION_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/dynamic_links.h b/packages/firebase_core/firebase_core/firebase_core/firebase/dynamic_links.h new file mode 100644 index 000000000000..7a96de679f62 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/dynamic_links.h @@ -0,0 +1,117 @@ +// Copyright 2017 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef FIREBASE_DYNAMIC_LINKS_SRC_INCLUDE_FIREBASE_DYNAMIC_LINKS_H_ +#define FIREBASE_DYNAMIC_LINKS_SRC_INCLUDE_FIREBASE_DYNAMIC_LINKS_H_ + +#include + +#include "firebase/app.h" +#include "firebase/internal/common.h" + +#if !defined(DOXYGEN) && !defined(SWIG) +FIREBASE_APP_REGISTER_CALLBACKS_REFERENCE(dynamic_links) +#endif // !defined(DOXYGEN) && !defined(SWIG) + +namespace firebase { + +/// @brief Firebase Dynamic Links API. +/// +/// Firebase Dynamic Links is a cross-platform solution for generating and +/// receiving links, whether or not the app is already installed. +namespace dynamic_links { + +#ifndef SWIG +/// @brief Error code used by Futures returned by this API. +enum ErrorCode { + kErrorCodeSuccess = 0, + kErrorCodeFailed, +}; +#endif // SWIG + +/// @brief Enum describing the strength of a dynamic links match. +/// +/// This version is local to dynamic links; there is a similar enum in invites +/// and another internal version in app. +enum LinkMatchStrength { + /// No match has been achieved + kLinkMatchStrengthNoMatch = 0, + + /// The match between the Dynamic Link and device is not perfect. You should + /// not reveal any personal information related to the Dynamic Link. + kLinkMatchStrengthWeakMatch, + + /// The match between the Dynamic Link and this device has a high confidence, + /// but there is a small possibility of error. + kLinkMatchStrengthStrongMatch, + + /// The match between the Dynamic Link and the device is exact. You may + /// safely reveal any personal information related to this Dynamic Link. + kLinkMatchStrengthPerfectMatch +}; + +/// @brief The received Dynamic Link. +struct DynamicLink { + /// The URL that was passed to the app. + std::string url; + /// The match strength of the dynamic link. + LinkMatchStrength match_strength; +}; + +/// @brief Base class used to receive Dynamic Links. +class Listener { + public: + virtual ~Listener(); + + /// Called on the client when a dynamic link arrives. + /// + /// @param[in] dynamic_link The data describing the Dynamic Link. + virtual void OnDynamicLinkReceived(const DynamicLink* dynamic_link) = 0; +}; + +/// @brief Initialize Firebase Dynamic Links. +/// +/// After Initialize is called, the implementation may call functions on the +/// Listener provided at any time. +/// +/// @param[in] app The Firebase App object for this application. +/// @param[in] listener A Listener object that receives Dynamic Links. +/// +/// @return kInitResultSuccess if initialization succeeded, or +/// kInitResultFailedMissingDependency on Android if Google Play services is +/// not available on the current device. +InitResult Initialize(const App& app, Listener* listener); + +/// @brief Terminate Firebase Dynamic Links. +void Terminate(); + +/// @brief Set the listener for receiving Dynamic Links. +/// +/// @param[in] listener A Listener object that receives Dynamic Links. +/// +/// @return Pointer to the previously set listener. +Listener* SetListener(Listener* listener); + +/// Fetch any pending dynamic links. Each pending link will trigger a call to +/// the registered Listener class. +/// +/// This function is implicitly called on initialization. On iOS this is called +/// automatically when the app gains focus, but on Android this needs to be +/// called manually. +void Fetch(); + +} // namespace dynamic_links +} // namespace firebase + +#endif // FIREBASE_DYNAMIC_LINKS_SRC_INCLUDE_FIREBASE_DYNAMIC_LINKS_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/dynamic_links/components.h b/packages/firebase_core/firebase_core/firebase_core/firebase/dynamic_links/components.h new file mode 100644 index 000000000000..7a8e8fa1a44b --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/dynamic_links/components.h @@ -0,0 +1,336 @@ +// Copyright 2017 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef FIREBASE_DYNAMIC_LINKS_SRC_INCLUDE_FIREBASE_DYNAMIC_LINKS_COMPONENTS_H_ +#define FIREBASE_DYNAMIC_LINKS_SRC_INCLUDE_FIREBASE_DYNAMIC_LINKS_COMPONENTS_H_ + +#include +#include +#include + +#include "firebase/future.h" + +namespace firebase { + +namespace dynamic_links { + +/// @brief Google Analytics Parameters. +/// +/// Note that the strings used by the struct are not copied, as so must +/// either be statically allocated, or must persist in memory until the +/// DynamicLinkComponents that uses them goes out of scope. +struct GoogleAnalyticsParameters { + /// Constructs an empty set of Google Analytics parameters. + GoogleAnalyticsParameters() + : source(nullptr), + medium(nullptr), + campaign(nullptr), + term(nullptr), + content(nullptr) {} + + /// The campaign source; used to identify a search engine, newsletter, + /// or other source. + const char* source; + /// The campaign medium; used to identify a medium such as email or + /// cost-per-click (cpc). + const char* medium; + /// The campaign name; The individual campaign name, slogan, promo code, etc. + /// for a product. + const char* campaign; + /// The campaign term; used with paid search to supply the keywords for ads. + const char* term; + /// The campaign content; used for A/B testing and content-targeted ads to + /// differentiate ads or links that point to the same URL. + const char* content; +}; + +/// @brief iOS Parameters. +/// +/// Note that the strings used by the struct are not copied, as so must +/// either be statically allocated, or must persist in memory until the +/// DynamicLinkComponents that uses them goes out of scope. +struct IOSParameters { + /// Constructs a set of IOS parameters with the given bundle id. + /// + /// @param bundle_id_ The parameters ID of the iOS app to use to open the + /// link. + IOSParameters(const char* bundle_id_) + : bundle_id(bundle_id_), + fallback_url(nullptr), + custom_scheme(nullptr), + ipad_fallback_url(nullptr), + ipad_bundle_id(nullptr), + app_store_id(nullptr), + minimum_version(nullptr) {} + + /// Constructs an empty set of IOS parameters. + IOSParameters() + : bundle_id(nullptr), + fallback_url(nullptr), + custom_scheme(nullptr), + ipad_fallback_url(nullptr), + ipad_bundle_id(nullptr), + app_store_id(nullptr), + minimum_version(nullptr) {} + + /// The parameters ID of the iOS app to use to open the link. The app must be + /// connected to your project from the Overview page of the Firebase console. + /// Note this field is required. + const char* bundle_id; + /// The link to open on iOS if the app is not installed. + /// + /// Specify this to do something other than install your app from the + /// App Store when the app isn't installed, such as open the mobile + /// web version of the content, or display a promotional page for your app. + const char* fallback_url; + /// The app's custom URL scheme, if defined to be something other than your + /// app's parameters ID. + const char* custom_scheme; + /// The link to open on iPad if the app is not installed. + /// + /// Overrides fallback_url when on iPad. + const char* ipad_fallback_url; + /// The iPad parameters ID of the app. + const char* ipad_bundle_id; + /// The App Store ID, used to send users to the App Store when the app isn't + /// installed. + const char* app_store_id; + /// The minimum version of your app that can open the link. + const char* minimum_version; +}; + +/// @brief iTunes Connect App Analytics Parameters. +/// +/// Note that the strings used by the struct are not copied, as so must +/// either be statically allocated, or must persist in memory until the +/// DynamicLinkComponents that uses them goes out of scope. +struct ITunesConnectAnalyticsParameters { + /// Constructs an empty set of ITunes Connect Analytics parameters. + ITunesConnectAnalyticsParameters() + : provider_token(nullptr), + affiliate_token(nullptr), + campaign_token(nullptr) {} + + /// The provider token that enables analytics for Dynamic Links from + /// within iTunes Connect. + const char* provider_token; + /// The affiliate token used to create affiliate-coded links. + const char* affiliate_token; + /// The campaign token that developers can add to any link in order to + /// track sales from a specific marketing campaign. + const char* campaign_token; +}; + +/// @brief Android Parameters. +/// +/// Note that the strings used by the struct are not copied, as so must +/// either be statically allocated, or must persist in memory until the +/// DynamicLinkComponents that uses them goes out of scope. +struct AndroidParameters { + /// Constructs a set of Android parameters with the given package name. + /// + /// The package name of the Android app to use to open the link. + AndroidParameters(const char* package_name_) + : package_name(package_name_), + fallback_url(nullptr), + minimum_version(0) {} + + /// Constructs an empty set of Android parameters. + AndroidParameters() + : package_name(nullptr), fallback_url(nullptr), minimum_version(0) {} + + /// The package name of the Android app to use to open the link. The app + /// must be connected to your project from the Overview page of the Firebase + /// console. + /// Note this field is required. + const char* package_name; + /// The link to open when the app isn't installed. + /// + /// Specify this to do something other than install your app from the + /// Play Store when the app isn't installed, such as open the mobile web + /// version of the content, or display a promotional page for your app. + const char* fallback_url; + /// The versionCode of the minimum version of your app that can open the link. + int minimum_version; +}; + +/// @brief Social meta-tag Parameters. +/// +/// Note that the strings used by the struct are not copied, as so must +/// either be statically allocated, or must persist in memory until the +/// DynamicLinkComponents that uses them goes out of scope. +struct SocialMetaTagParameters { + /// Constructs an empty set of Social meta-tag parameters. + SocialMetaTagParameters() + : title(nullptr), description(nullptr), image_url(nullptr) {} + + /// The title to use when the Dynamic Link is shared in a social post. + const char* title; + /// The description to use when the Dynamic Link is shared in a social post. + const char* description; + /// The URL to an image related to this link. + const char* image_url; +}; + +/// @brief The desired path length for shortened Dynamic Link URLs. +enum PathLength { + /// Uses the server-default for the path length. + /// See https://goo.gl/8yDAqC for more information. + kPathLengthDefault = 0, + /// Typical short link for non-sensitive links. + kPathLengthShort, + /// Short link that uses a very long path to make it more difficult to + /// guess. Useful for sensitive links. + kPathLengthUnguessable, +}; + +/// @brief Additional options for Dynamic Link creation. +struct DynamicLinkOptions { + /// Constructs an empty set of Dynamic Link options. + DynamicLinkOptions() : path_length(kPathLengthDefault) {} + + /// The desired path length for shortened Dynamic Link URLs. + PathLength path_length; +}; + +/// @brief The returned value from creating a Dynamic Link. +struct GeneratedDynamicLink { + /// The Dynamic Link value. + std::string url; + /// Information about potential warnings on link creation. + /// + /// Usually presence of warnings means parameter format errors, parameter + /// value errors, or missing parameters. + std::vector warnings; + /// If non-empty, the cause of the Dynamic Link generation failure. + std::string error; +}; + +/// @brief The information needed to generate a Dynamic Link. +/// +/// Note that the strings used by the struct are not copied, as so must +/// either be statically allocated, or must persist in memory until this +/// struct goes out of scope. +struct DynamicLinkComponents { + /// The link your app will open. + /// You can specify any URL your app can handle, such as a link to your + /// app's content, or a URL that initiates some + /// app-specific logic such as crediting the user with a coupon, or + /// displaying a specific welcome screen. This link must be a well-formatted + /// URL, be properly URL-encoded, and use the HTTP or HTTPS scheme. + /// Note, this field is required. + const char* link; + /// The domain (of the form "https://xyz.app.goo.gl") to use for this Dynamic + /// Link. You can find this value in the Dynamic Links section of the Firebase + /// console. + /// + /// If you have set up custom domains on your project, set this to your + /// project's custom domain as listed in the Firebase console. + /// + /// Only https:// links are supported. + /// + /// Note, this field is required. + const char* domain_uri_prefix; + /// The Google Analytics parameters. + GoogleAnalyticsParameters* google_analytics_parameters; + /// The iOS parameters. + IOSParameters* ios_parameters; + /// The iTunes Connect App Analytics parameters. + ITunesConnectAnalyticsParameters* itunes_connect_analytics_parameters; + /// The Android parameters. + AndroidParameters* android_parameters; + /// The social meta-tag parameters. + SocialMetaTagParameters* social_meta_tag_parameters; + + /// Default constructor, initializes all fields to null. + DynamicLinkComponents() + : link(nullptr), + domain_uri_prefix(nullptr), + google_analytics_parameters(nullptr), + ios_parameters(nullptr), + itunes_connect_analytics_parameters(nullptr), + android_parameters(nullptr), + social_meta_tag_parameters(nullptr) {} + + /// Constructor that initializes with the given link and domain. + /// + /// @param link_ The link your app will open. + /// @param domain_uri_prefix_ The domain (of the form + /// "https://xyz.app.goo.gl") to use for this Dynamic Link. You can find this + /// value in the Dynamic Links section of the Firebase console. If you have + /// set up custom domains on your project, set this to your project's custom + /// domain as listed in the Firebase console. Note: If you do not specify + /// "https://" as the URI scheme, it will be added. + DynamicLinkComponents(const char* link_, const char* domain_uri_prefix_) + : link(link_), + domain_uri_prefix(domain_uri_prefix_), + google_analytics_parameters(nullptr), + ios_parameters(nullptr), + itunes_connect_analytics_parameters(nullptr), + android_parameters(nullptr), + social_meta_tag_parameters(nullptr) { + // For backwards compatibility with dynamic_link_domain, if + // domain_uri_prefix doesn't start with "https://", add it. + static const char kHttpsPrefix[] = "https://"; + static const size_t kHttpsPrefixLength = sizeof(kHttpsPrefix) - 1; + if (strncmp(domain_uri_prefix, kHttpsPrefix, kHttpsPrefixLength) != 0) { + domain_uri_prefix_with_scheme = + std::string(kHttpsPrefix) + domain_uri_prefix; + domain_uri_prefix = domain_uri_prefix_with_scheme.c_str(); + } + } + +#ifndef INTERNAL_EXPERIMENTAL + + private: +#endif // INTERNAL_EXPERIMENTAL + std::string domain_uri_prefix_with_scheme; +}; + +/// Creates a long Dynamic Link from the given parameters. +GeneratedDynamicLink GetLongLink(const DynamicLinkComponents& components); + +/// Creates a shortened Dynamic Link from the given parameters. +/// @param components: Settings used to configure the behavior for the link. +Future GetShortLink( + const DynamicLinkComponents& components); + +/// Creates a shortened Dynamic Link from the given parameters. +/// @param components: Settings used to configure the behavior for the link. +/// @param options: Additional options for Dynamic Link shortening, indicating +/// whether or not to produce an unguessable or shortest possible link. +/// No references to the options object will be retained after the call. +Future GetShortLink( + const DynamicLinkComponents& components, const DynamicLinkOptions& options); + +/// Creates a shortened Dynamic Link from a given long Dynamic Link. +/// @param long_dynamic_link A link previously generated from GetLongLink. +Future GetShortLink(const char* long_dynamic_link); + +/// Creates a shortened Dynamic Link from a given long Dynamic Link. +/// @param long_dynamic_link: A link previously generated from GetLongLink. +/// @param options: Additional options for Dynamic Link shortening, indicating +/// whether or not to produce an unguessable or shortest possible link. +/// No references to the options object will be retained after the call. +Future GetShortLink(const char* long_dynamic_link, + const DynamicLinkOptions& options); + +/// Get the (possibly still pending) results of the most recent GetShortUrl +/// call. +Future GetShortLinkLastResult(); + +} // namespace dynamic_links +} // namespace firebase + +#endif // FIREBASE_DYNAMIC_LINKS_SRC_INCLUDE_FIREBASE_DYNAMIC_LINKS_COMPONENTS_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore.h new file mode 100644 index 000000000000..c35de11b4d1a --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore.h @@ -0,0 +1,458 @@ +/* + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_H_ +#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_H_ + +#include +#include + +#include "firebase/internal/common.h" + +#include "firebase/app.h" +#include "firebase/future.h" +#include "firebase/log.h" +// Include *all* the public headers to make sure including just "firestore.h" is +// sufficient for users. +#include "firebase/firestore/collection_reference.h" +#include "firebase/firestore/document_change.h" +#include "firebase/firestore/document_reference.h" +#include "firebase/firestore/document_snapshot.h" +#include "firebase/firestore/field_path.h" +#include "firebase/firestore/field_value.h" +#include "firebase/firestore/firestore_errors.h" +#include "firebase/firestore/geo_point.h" +#include "firebase/firestore/listener_registration.h" +#include "firebase/firestore/load_bundle_task_progress.h" +#include "firebase/firestore/map_field_value.h" +#include "firebase/firestore/metadata_changes.h" +#include "firebase/firestore/query.h" +#include "firebase/firestore/query_snapshot.h" +#include "firebase/firestore/set_options.h" +#include "firebase/firestore/settings.h" +#include "firebase/firestore/snapshot_metadata.h" +#include "firebase/firestore/source.h" +#include "firebase/firestore/timestamp.h" +#include "firebase/firestore/transaction.h" +#include "firebase/firestore/transaction_options.h" +#include "firebase/firestore/write_batch.h" + +namespace firebase { +/** + * @brief Cloud Firestore API. + * + * Cloud Firestore is a flexible, scalable database for mobile, web, and server + * development from Firebase and Google Cloud Platform. + */ +namespace firestore { + +class FirestoreInternal; + +namespace csharp { + +class ApiHeaders; +class TransactionManager; + +} // namespace csharp + +/** + * @brief Entry point for the Firebase Firestore C++ SDK. + * + * To use the SDK, call firebase::firestore::Firestore::GetInstance() to obtain + * an instance of Firestore, then use Collection() or Document() to obtain + * references to child paths within the database. From there, you can set data + * via CollectionReference::Add() and DocumentReference::Set(), or get data via + * CollectionReference::Get() and DocumentReference::Get(), attach listeners, + * and more. + * + * @note Firestore classes are not meant to be subclassed except for use in test + * mocks. Subclassing is not supported in production code and new SDK releases + * may break code that does so. + */ +class Firestore { + public: + /** + * @brief Returns an instance of Firestore corresponding to the given App. + * + * Firebase Firestore uses firebase::App to communicate with Firebase + * Authentication to authenticate users to the Firestore server backend. + * + * If you call GetInstance() multiple times with the same App, you will get + * the same instance of Firestore. + * + * @param[in] app Your instance of firebase::App. Firebase Firestore will use + * this to communicate with Firebase Authentication. + * @param[out] init_result_out If provided, the initialization result will be + * written here. Will be set to firebase::kInitResultSuccess if initialization + * succeeded, or firebase::kInitResultFailedMissingDependency on Android if + * Google Play services is not available on the current device. + * + * @return An instance of Firestore corresponding to the given App. + */ + static Firestore* GetInstance(::firebase::App* app, + InitResult* init_result_out = nullptr); + + /** + * @brief Returns an instance of Firestore corresponding to the default App. + * + * Firebase Firestore uses the default App to communicate with Firebase + * Authentication to authenticate users to the Firestore server backend. + * + * If you call GetInstance() multiple times, you will get the same instance. + * + * @param[out] init_result_out If provided, the initialization result will be + * written here. Will be set to firebase::kInitResultSuccess if initialization + * succeeded, or firebase::kInitResultFailedMissingDependency on Android if + * Google Play services is not available on the current device. + * + * @return An instance of Firestore corresponding to the default App. + */ + static Firestore* GetInstance(InitResult* init_result_out = nullptr); + + /** + * @brief Destructor for the Firestore object. + * + * When deleted, this instance will be removed from the cache of Firestore + * objects. If you call GetInstance() in the future with the same App, a new + * Firestore instance will be created. + */ + virtual ~Firestore(); + + /** + * Deleted copy constructor; Firestore must be created with + * Firestore::GetInstance(). + */ + Firestore(const Firestore& src) = delete; + + /** + * Deleted copy assignment operator; Firestore must be created with + * Firestore::GetInstance(). + */ + Firestore& operator=(const Firestore& src) = delete; + + /** + * @brief Returns the firebase::App that this Firestore was created with. + * + * @return The firebase::App this Firestore was created with. + */ + virtual const App* app() const; + + /** + * @brief Returns the firebase::App that this Firestore was created with. + * + * @return The firebase::App this Firestore was created with. + */ + virtual App* app(); + + /** + * @brief Returns a CollectionReference instance that refers to the + * collection at the specified path within the database. + * + * @param[in] collection_path A slash-separated path to a collection. + * + * @return The CollectionReference instance. + */ + virtual CollectionReference Collection(const char* collection_path) const; + + /** + * @brief Returns a CollectionReference instance that refers to the + * collection at the specified path within the database. + * + * @param[in] collection_path A slash-separated path to a collection. + * + * @return The CollectionReference instance. + */ + virtual CollectionReference Collection( + const std::string& collection_path) const; + + /** + * @brief Returns a DocumentReference instance that refers to the document at + * the specified path within the database. + * + * @param[in] document_path A slash-separated path to a document. + * @return The DocumentReference instance. + */ + virtual DocumentReference Document(const char* document_path) const; + + /** + * @brief Returns a DocumentReference instance that refers to the document at + * the specified path within the database. + * + * @param[in] document_path A slash-separated path to a document. + * + * @return The DocumentReference instance. + */ + virtual DocumentReference Document(const std::string& document_path) const; + + /** + * @brief Returns a Query instance that includes all documents in the + * database that are contained in a collection or subcollection with the + * given collection_id. + * + * @param[in] collection_id Identifies the collections to query over. Every + * collection or subcollection with this ID as the last segment of its path + * will be included. Cannot contain a slash. + * + * @return The Query instance. + */ + virtual Query CollectionGroup(const char* collection_id) const; + + /** + * @brief Returns a Query instance that includes all documents in the + * database that are contained in a collection or subcollection with the + * given collection_id. + * + * @param[in] collection_id Identifies the collections to query over. Every + * collection or subcollection with this ID as the last segment of its path + * will be included. Cannot contain a slash. + * + * @return The Query instance. + */ + virtual Query CollectionGroup(const std::string& collection_id) const; + + /** Returns the settings used by this Firestore object. */ + virtual Settings settings() const; + + /** Sets any custom settings used to configure this Firestore object. */ + virtual void set_settings(Settings settings); + + /** + * Creates a write batch, used for performing multiple writes as a single + * atomic operation. + * + * Unlike transactions, write batches are persisted offline and therefore are + * preferable when you don't need to condition your writes on read data. + * + * @return The created WriteBatch object. + */ + virtual WriteBatch batch() const; + + /** + * Executes the given update and then attempts to commit the changes applied + * within the transaction. If any document read within the transaction has + * changed, the update function will be retried. If it fails to commit after + * 5 attempts, the transaction will fail. + * + * @param update function or lambda to execute within the transaction context. + * The string reference parameter can be used to set the error message. + * + * @return A Future that will be resolved when the transaction finishes. + */ + virtual Future RunTransaction( + std::function update); + + /** + * Executes the given update and then attempts to commit the changes applied + * within the transaction. If any document read within the transaction has + * changed, the update function will be retried. If it fails to commit after + * the `max_attempts` specified in the given `TransactionOptions`, the + * transaction will fail. + * + * @param options The transaction options for controlling execution. + * @param update function or lambda to execute within the transaction context. + * The string reference parameter can be used to set the error message. + * + * @return A Future that will be resolved when the transaction finishes. + */ + virtual Future RunTransaction( + TransactionOptions options, + std::function update); + + /** + * Sets the log verbosity of all Firestore instances. + * + * The default verbosity level is `kLogLevelInfo`. + * + * @param[in] log_level The desired verbosity. + */ + static void set_log_level(LogLevel log_level); + + /** + * Disables network access for this instance. While the network is disabled, + * any snapshot listeners or Get() calls will return results from cache, and + * any write operations will be queued until network usage is re-enabled via a + * call to EnableNetwork(). + * + * If the network was already disabled, calling `DisableNetwork()` again is + * a no-op. + */ + virtual Future DisableNetwork(); + + /** + * Re-enables network usage for this instance after a prior call to + * DisableNetwork(). + * + * If the network is currently enabled, calling `EnableNetwork()` is a no-op. + */ + virtual Future EnableNetwork(); + + /** + * Terminates this `Firestore` instance. + * + * After calling `Terminate()`, only the `ClearPersistence()` method may be + * used. Calling any other methods will result in an error. + * + * To restart after termination, simply create a new instance of `Firestore` + * with `Firestore::GetInstance()`. + * + * `Terminate()` does not cancel any pending writes and any tasks that are + * awaiting a response from the server will not be resolved. The next time you + * start this instance, it will resume attempting to send these writes to the + * server. + * + * Note: under normal circumstances, calling `Terminate()` is not required. + * This method is useful only when you want to force this instance to release + * all of its resources or in combination with `ClearPersistence()` to ensure + * that all local state is destroyed between test runs. + * + * @return A `Future` that is resolved when the instance has been successfully + * terminated. + */ + virtual Future Terminate(); + + /** + * Waits until all currently pending writes for the active user have been + * acknowledged by the backend. + * + * The returned future is resolved immediately without error if there are no + * outstanding writes. Otherwise, the future is resolved when all previously + * issued writes (including those written in a previous app session) have been + * acknowledged by the backend. The future does not wait for writes that were + * added after the method is called. If you wish to wait for additional + * writes, you have to call `WaitForPendingWrites` again. + * + * Any outstanding `WaitForPendingWrites` futures are resolved with an + * error during user change. + */ + virtual Future WaitForPendingWrites(); + + /** + * Clears the persistent storage. This includes pending writes and cached + * documents. + * + * Must be called while the Firestore instance is not started (after the app + * is shut down or when the app is first initialized). On startup, this method + * must be called before other methods (other than `settings()` and + * `set_settings()`). If the Firestore instance is still running, the function + * will complete with an error code of `FailedPrecondition`. + * + * Note: `ClearPersistence()` is primarily intended to help write + * reliable tests that use Firestore. It uses the most efficient mechanism + * possible for dropping existing data but does not attempt to securely + * overwrite or otherwise make cached data unrecoverable. For applications + * that are sensitive to the disclosure of cache data in between user sessions + * we strongly recommend not to enable persistence in the first place. + */ + virtual Future ClearPersistence(); + + /** + * Attaches a listener for a snapshots-in-sync event. Server-generated + * updates and local changes can affect multiple snapshot listeners. + * The snapshots-in-sync event indicates that all listeners affected by + * a given change have fired. + * + * NOTE: The snapshots-in-sync event only indicates that listeners are + * in sync with each other, but does not relate to whether those + * snapshots are in sync with the server. Use `SnapshotMetadata` in the + * individual listeners to determine if a snapshot is from the cache or + * the server. + * + * @param callback A callback to be called every time all snapshot + * listeners are in sync with each other. + * @return A `ListenerRegistration` object that can be used to remove the + * listener. + */ + virtual ListenerRegistration AddSnapshotsInSyncListener( + std::function callback); + + /** + * Loads a Firestore bundle into the local cache. + * + * @param bundle A string containing the bundle to be loaded. + * @return A `Future` that is resolved when the loading is either completed + * or aborted due to an error. + */ + virtual Future LoadBundle(const std::string& bundle); + + /** + * Loads a Firestore bundle into the local cache, with the provided callback + * executed for progress updates. + * + * @param bundle A string containing the bundle to be loaded. + * @param progress_callback A callback that is called with progress + * updates, and completion or error updates. + * @return A `Future` that is resolved when the loading is either completed + * or aborted due to an error. + */ + virtual Future LoadBundle( + const std::string& bundle, + std::function progress_callback); + + /** + * Reads a Firestore `Query` from the local cache, identified by the given + * name. + * + * Named queries are packaged into bundles on the server side (along with the + * resulting documents) and loaded into local cache using `LoadBundle`. Once + * in the local cache, you can use this method to extract a query by name. + * + * If a query cannot be found, the returned future will complete with its + * `error()` set to a non-zero error code. + * + * @param query_name The name of the query to read from saved bundles. + */ + virtual Future NamedQuery(const std::string& query_name); + + protected: + /** + * Default constructor, to be used only for mocking `Firestore`. + */ + Firestore() = default; + + private: + friend class FieldValueInternal; + friend class FirestoreInternal; + friend class Wrapper; + friend struct ConverterImpl; + friend class FirestoreIntegrationTest; + friend class IncludesTest; + template + friend struct CleanupFn; + + friend class csharp::ApiHeaders; + friend class csharp::TransactionManager; + + explicit Firestore(::firebase::App* app); + explicit Firestore(FirestoreInternal* internal); + + static Firestore* CreateFirestore(::firebase::App* app, + FirestoreInternal* internal, + InitResult* init_result_out); + static Firestore* AddFirestoreToCache(Firestore* firestore, + InitResult* init_result_out); + + static void SetClientLanguage(const std::string& language_token); + + // Delete the internal_ data. + void DeleteInternal(); + + mutable FirestoreInternal* internal_ = nullptr; +}; + +} // namespace firestore +} // namespace firebase + +#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/collection_reference.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/collection_reference.h new file mode 100644 index 000000000000..3d9d4de2ee7f --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/collection_reference.h @@ -0,0 +1,183 @@ +/* + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_COLLECTION_REFERENCE_H_ +#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_COLLECTION_REFERENCE_H_ + +#include + +#include "firebase/firestore/map_field_value.h" +#include "firebase/firestore/query.h" + +namespace firebase { + +/// @cond FIREBASE_APP_INTERNAL +template +class Future; +/// @endcond + +namespace firestore { + +class CollectionReferenceInternal; +class DocumentReference; + +/** + * @brief A CollectionReference can be used for adding documents, getting + * document references, and querying for documents (using the methods inherited + * from `Query`). + * + * @note Firestore classes are not meant to be subclassed except for use in test + * mocks. Subclassing is not supported in production code and new SDK releases + * may break code that does so. + */ +class CollectionReference : public Query { + public: + /** + * @brief Creates an invalid CollectionReference that has to be reassigned + * before it can be used. + * + * Calling any member function on an invalid CollectionReference will be + * a no-op. If the function returns a value, it will return a zero, empty, or + * invalid value, depending on the type of the value. + */ + CollectionReference(); + + /** + * @brief Copy constructor. + * + * `CollectionReference` can be efficiently copied because it simply refers to + * a location in the database. + * + * @param[in] other `CollectionReference` to copy from. + */ + CollectionReference(const CollectionReference& other); + + /** + * @brief Move constructor. + * + * Moving is more efficient than copying for a `CollectionReference`. After + * being moved from, a `CollectionReference` is equivalent to its + * default-constructed state. + * + * @param[in] other `CollectionReference` to move data from. + */ + CollectionReference(CollectionReference&& other); + + /** + * @brief Copy assignment operator. + * + * `CollectionReference` can be efficiently copied because it simply refers to + * a location in the database. + * + * @param[in] other `CollectionReference` to copy from. + * + * @return Reference to the destination `CollectionReference`. + */ + CollectionReference& operator=(const CollectionReference& other); + + /** + * @brief Move assignment operator. + * + * Moving is more efficient than copying for a `CollectionReference`. After + * being moved from, a `CollectionReference` is equivalent to its + * default-constructed state. + * + * @param[in] other `CollectionReference` to move data from. + * + * @return Reference to the destination `CollectionReference`. + */ + CollectionReference& operator=(CollectionReference&& other); + + /** + * @brief Gets the ID of the referenced collection. + * + * @return The ID as a std::string. + */ + virtual const std::string& id() const; + + /** + * @brief Returns the path of this collection (relative to the root of the + * database) as a slash-separated string. + * + * @return The path as a std::string. + */ + virtual std::string path() const; + + /** + * @brief Gets a DocumentReference to the document that contains this + * collection. + * + * @return The DocumentReference that contains this collection if this is a + * subcollection. If this is a root collection, returns an invalid + * DocumentReference (`DocumentReference::is_valid()` will return false). + */ + virtual DocumentReference Parent() const; + + /** + * @brief Returns a DocumentReference that points to a new document with an + * auto-generated ID within this collection. + * + * @return A DocumentReference pointing to the new document. + */ + virtual DocumentReference Document() const; + + /** + * @brief Gets a DocumentReference instance that refers to the document at the + * specified path within this collection. + * + * @param[in] document_path A slash-separated relative path to a document. + * The pointer only needs to be valid during this call. + * + * @return The DocumentReference instance. + */ + virtual DocumentReference Document(const char* document_path) const; + + /** + * @brief Gets a DocumentReference instance that refers to the document at the + * specified path within this collection. + * + * @param[in] document_path A slash-separated relative path to a document. + * + * @return The DocumentReference instance. + */ + virtual DocumentReference Document(const std::string& document_path) const; + + /** + * @brief Adds a new document to this collection with the specified data, + * assigning it a document ID automatically. + * + * @param data A map containing the data for the new document. + * + * @return A Future that will be resolved with the DocumentReference of the + * newly created document. + */ + virtual Future Add(const MapFieldValue& data); + + private: + friend class DocumentReference; + friend class DocumentReferenceInternal; + friend class FirestoreInternal; + friend struct ConverterImpl; + + explicit CollectionReference(CollectionReferenceInternal* internal); + + CollectionReferenceInternal* internal() const; +}; + +} // namespace firestore +} // namespace firebase + +#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_COLLECTION_REFERENCE_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/document_change.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/document_change.h new file mode 100644 index 000000000000..fbef011d290f --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/document_change.h @@ -0,0 +1,203 @@ +/* + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_DOCUMENT_CHANGE_H_ +#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_DOCUMENT_CHANGE_H_ + +#include + +namespace firebase { +namespace firestore { + +class DocumentChangeInternal; +class DocumentSnapshot; + +/** + * @brief A DocumentChange represents a change to the documents matching + * a query. + * + * DocumentChange contains the document affected and the type of change that + * occurred (added, modified, or removed). + * + * @note Firestore classes are not meant to be subclassed except for use in test + * mocks. Subclassing is not supported in production code and new SDK releases + * may break code that does so. + */ +class DocumentChange { + public: + /** + * An enumeration of snapshot diff types. + */ + enum class Type { + /** + * Indicates a new document was added to the set of documents matching the + * query. + */ + kAdded, + + /** + * Indicates a document within the query was modified. + */ + kModified, + + /** + * Indicates a document within the query was removed (either deleted or no + * longer matches the query). + */ + kRemoved, + }; + + /** + * The sentinel index used as a return value to indicate no matches. + */ +#if defined(ANDROID) + // Older NDK (r16b) fails to define this properly. Fix this when support for + // the older NDK is removed. + static const std::size_t npos; +#else + static constexpr std::size_t npos = static_cast(-1); +#endif // defined(ANDROID) + + /** + * @brief Creates an invalid DocumentChange that has to be reassigned before + * it can be used. + * + * Calling any member function on an invalid DocumentChange will be a no-op. + * If the function returns a value, it will return a zero, empty, or invalid + * value, depending on the type of the value. + */ + DocumentChange(); + + /** + * @brief Copy constructor. + * + * `DocumentChange` is immutable and can be efficiently copied (no deep copy + * is performed). + * + * @param[in] other `DocumentChange` to copy from. + */ + DocumentChange(const DocumentChange& other); + + /** + * @brief Move constructor. + * + * Moving is more efficient than copying for a `DocumentChange`. After being + * moved from, a `DocumentChange` is equivalent to its default-constructed + * state. + * + * @param[in] other `DocumentChange` to move data from. + */ + DocumentChange(DocumentChange&& other); + + virtual ~DocumentChange(); + + /** + * @brief Copy assignment operator. + * + * `DocumentChange` is immutable and can be efficiently copied (no deep copy + * is performed). + * + * @param[in] other `DocumentChange` to copy from. + * + * @return Reference to the destination `DocumentChange`. + */ + DocumentChange& operator=(const DocumentChange& other); + + /** + * @brief Move assignment operator. + * + * Moving is more efficient than copying for a `DocumentChange`. After being + * moved from, a `DocumentChange` is equivalent to its default-constructed + * state. + * + * @param[in] other `DocumentChange` to move data from. + * + * @return Reference to the destination `DocumentChange`. + */ + DocumentChange& operator=(DocumentChange&& other); + + /** + * Returns the type of change that occurred (added, modified, or removed). + */ + virtual Type type() const; + + /** + * @brief The document affected by this change. + * + * Returns the newly added or modified document if this DocumentChange is for + * an updated document. Returns the deleted document if this document change + * represents a removal. + */ + virtual DocumentSnapshot document() const; + + /** + * The index of the changed document in the result set immediately prior to + * this DocumentChange (that is, supposing that all prior DocumentChange + * objects have been applied). Returns DocumentChange::npos for 'added' + * events. + */ + virtual std::size_t old_index() const; + + /** + * The index of the changed document in the result set immediately after this + * DocumentChange (that is, supposing that all prior DocumentChange objects + * and the current DocumentChange object have been applied). Returns + * DocumentChange::npos for 'removed' events. + */ + virtual std::size_t new_index() const; + + /** + * @brief Returns true if this `DocumentChange` is valid, false if it is + * not valid. An invalid `DocumentChange` could be the result of: + * - Creating a `DocumentChange` using the default constructor. + * - Moving from the `DocumentChange`. + * - Deleting your Firestore instance, which will invalidate all the + * `DocumentChange` instances associated with it. + * + * @return true if this `DocumentChange` is valid, false if this + * `DocumentChange` is invalid. + */ + bool is_valid() const { return internal_ != nullptr; } + + private: + std::size_t Hash() const; + + friend bool operator==(const DocumentChange& lhs, const DocumentChange& rhs); + friend std::size_t DocumentChangeHash(const DocumentChange& change); + + friend class FirestoreInternal; + friend class Wrapper; + friend struct ConverterImpl; + template + friend struct CleanupFn; + + explicit DocumentChange(DocumentChangeInternal* internal); + + mutable DocumentChangeInternal* internal_ = nullptr; +}; + +/** Checks `lhs` and `rhs` for equality. */ +bool operator==(const DocumentChange& lhs, const DocumentChange& rhs); + +/** Checks `lhs` and `rhs` for inequality. */ +inline bool operator!=(const DocumentChange& lhs, const DocumentChange& rhs) { + return !(lhs == rhs); +} + +} // namespace firestore +} // namespace firebase + +#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_DOCUMENT_CHANGE_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/document_reference.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/document_reference.h new file mode 100644 index 000000000000..d0f82cf42d73 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/document_reference.h @@ -0,0 +1,351 @@ +/* + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_DOCUMENT_REFERENCE_H_ +#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_DOCUMENT_REFERENCE_H_ + +#include +#include +#include + +#include "firebase/internal/common.h" + +#include "firebase/firestore/firestore_errors.h" +#include "firebase/firestore/map_field_value.h" +#include "firebase/firestore/metadata_changes.h" +#include "firebase/firestore/set_options.h" +#include "firebase/firestore/source.h" + +namespace firebase { + +/// @cond FIREBASE_APP_INTERNAL +template +class Future; +/// @endcond + +namespace firestore { + +class CollectionReference; +class DocumentReferenceInternal; +class DocumentSnapshot; +template +class EventListener; +class Firestore; +class ListenerRegistration; + +/** + * @brief A DocumentReference refers to a document location in a Firestore + * database and can be used to write, read, or listen to the location. + * + * There may or may not exist a document at the referenced location. + * A DocumentReference can also be used to create a CollectionReference to + * a subcollection. + * + * Create a DocumentReference via `Firestore::Document(const std::string& + * path)`. + * + * @note Firestore classes are not meant to be subclassed except for use in test + * mocks. Subclassing is not supported in production code and new SDK releases + * may break code that does so. + */ +class DocumentReference { + public: + /** + * @brief Creates an invalid DocumentReference that has to be reassigned + * before it can be used. + * + * Calling any member function on an invalid DocumentReference will be + * a no-op. If the function returns a value, it will return a zero, empty, or + * invalid value, depending on the type of the value. + */ + DocumentReference(); + + /** + * @brief Copy constructor. + * + * `DocumentReference` can be efficiently copied because it simply refers to + * a location in the database. + * + * @param[in] other `DocumentReference` to copy from. + */ + DocumentReference(const DocumentReference& other); + + /** + * @brief Move constructor. + * + * Moving is more efficient than copying for a `DocumentReference`. After + * being moved from, a `DocumentReference` is equivalent to its + * default-constructed state. + * + * @param[in] other `DocumentReference` to move data from. + */ + DocumentReference(DocumentReference&& other); + + virtual ~DocumentReference(); + + /** + * @brief Copy assignment operator. + * + * `DocumentReference` can be efficiently copied because it simply refers to + * a location in the database. + * + * @param[in] other `DocumentReference` to copy from. + * + * @return Reference to the destination `DocumentReference`. + */ + DocumentReference& operator=(const DocumentReference& other); + + /** + * @brief Move assignment operator. + * + * Moving is more efficient than copying for a `DocumentReference`. After + * being moved from, a `DocumentReference` is equivalent to its + * default-constructed state. + * + * @param[in] other `DocumentReference` to move data from. + * + * @return Reference to the destination `DocumentReference`. + */ + DocumentReference& operator=(DocumentReference&& other); + + /** + * @brief Returns the Firestore instance associated with this document + * reference. + * + * The pointer will remain valid indefinitely. + * + * @return Firebase Firestore instance that this DocumentReference refers to. + */ + virtual const Firestore* firestore() const; + + /** + * @brief Returns the Firestore instance associated with this document + * reference. + * + * The pointer will remain valid indefinitely. + * + * @return Firebase Firestore instance that this DocumentReference refers to. + */ + virtual Firestore* firestore(); + + /** + * @brief Returns the string ID of this document location. + * + * @return String ID of this document location. + */ + virtual const std::string& id() const; + + /** + * @brief Returns the path of this document (relative to the root of the + * database) as a slash-separated string. + * + * @return String path of this document location. + */ + virtual std::string path() const; + + /** + * @brief Returns a CollectionReference to the collection that contains this + * document. + */ + virtual CollectionReference Parent() const; + + /** + * @brief Returns a CollectionReference instance that refers to the + * subcollection at the specified path relative to this document. + * + * @param[in] collection_path A slash-separated relative path to a + * subcollection. The pointer only needs to be valid during this call. + * + * @return The CollectionReference instance. + */ + virtual CollectionReference Collection(const char* collection_path) const; + + /** + * @brief Returns a CollectionReference instance that refers to the + * subcollection at the specified path relative to this document. + * + * @param[in] collection_path A slash-separated relative path to a + * subcollection. + * + * @return The CollectionReference instance. + */ + virtual CollectionReference Collection( + const std::string& collection_path) const; + + /** + * @brief Reads the document referenced by this DocumentReference. + * + * By default, Get() attempts to provide up-to-date data when possible by + * waiting for data from the server, but it may return cached data or fail if + * you are offline and the server cannot be reached. This behavior can be + * altered via the Source parameter. + * + * @param[in] source A value to configure the get behavior (optional). + * + * @return A Future that will be resolved with the contents of the Document at + * this DocumentReference. + */ + virtual Future Get(Source source = Source::kDefault) const; + + /** + * @brief Writes to the document referred to by this DocumentReference. + * + * If the document does not yet exist, it will be created. If you pass + * SetOptions, the provided data can be merged into an existing document. + * + * @param[in] data A map of the fields and values to write to the document. + * @param[in] options An object to configure the Set() behavior (optional). + * + * @return A Future that will be resolved when the write finishes. + */ + virtual Future Set(const MapFieldValue& data, + const SetOptions& options = SetOptions()); + + /** + * @brief Updates fields in the document referred to by this + * DocumentReference. + * + * If no document exists yet, the update will fail. + * + * @param[in] data A map of field / value pairs to update. Fields can contain + * dots to reference nested fields within the document. + * + * @return A Future that will be resolved when the client is online and the + * commit has completed against the server. The future will not resolve when + * the device is offline, though local changes will be visible immediately. + */ + virtual Future Update(const MapFieldValue& data); + + /** + * @brief Updates fields in the document referred to by this + * DocumentReference. + * + * If no document exists yet, the update will fail. + * + * @param[in] data A map from FieldPath to FieldValue to update. + * + * @return A Future that will be resolved when the client is online and the + * commit has completed against the server. The future will not resolve when + * the device is offline, though local changes will be visible immediately. + */ + virtual Future Update(const MapFieldPathValue& data); + + /** + * @brief Removes the document referred to by this DocumentReference. + * + * @return A Future that will be resolved when the delete completes. + */ + virtual Future Delete(); + + /** + * @brief Starts listening to the document referenced by this + * DocumentReference. + * + * @param[in] callback The std::function to call. When this function is + * called, snapshot value is valid if and only if error is Error::kErrorOk. + * The std::string is an error message; the value may be empty if an error + * message is not available. + * + * @return A registration object that can be used to remove the listener. + */ + virtual ListenerRegistration AddSnapshotListener( + std::function + callback); + + /** + * @brief Starts listening to the document referenced by this + * DocumentReference. + * + * @param[in] metadata_changes Indicates whether metadata-only changes (that + * is, only DocumentSnapshot::metadata() changed) should trigger snapshot + * events. + * @param[in] callback The std::function to call. When this function is + * called, snapshot value is valid if and only if error is Error::kErrorOk. + * The std::string is an error message; the value may be empty if an error + * message is not available. + * + * @return A registration object that can be used to remove the listener. + */ + virtual ListenerRegistration AddSnapshotListener( + MetadataChanges metadata_changes, + std::function + callback); + + /** + * @brief Returns true if this `DocumentReference` is valid, false if it is + * not valid. An invalid `DocumentReference` could be the result of: + * - Creating a `DocumentReference` using the default constructor. + * - Moving from the `DocumentReference`. + * - Calling `CollectionReference::Parent()` on a `CollectionReference` that + * is not a subcollection. + * - Deleting your Firestore instance, which will invalidate all the + * `DocumentReference` instances associated with it. + * + * @return true if this `DocumentReference` is valid, false if this + * `DocumentReference` is invalid. + */ + bool is_valid() const { return internal_ != nullptr; } + + /** + * Returns a string representation of this `DocumentReference` for + * logging/debugging purposes. + * + * @note the exact string representation is unspecified and subject to + * change; don't rely on the format of the string. + */ + std::string ToString() const; + + /** + * Outputs the string representation of this `DocumentReference` to the given + * stream. + * + * @see `ToString()` for comments on the representation format. + */ + friend std::ostream& operator<<(std::ostream& out, + const DocumentReference& reference); + + private: + friend bool operator==(const DocumentReference& lhs, + const DocumentReference& rhs); + + friend class CollectionReferenceInternal; + friend class DocumentSnapshotInternal; + friend class FieldValueInternal; + friend class FirestoreInternal; + friend class TransactionInternal; + friend class WriteBatchInternal; + friend struct ConverterImpl; + template + friend struct CleanupFn; + + explicit DocumentReference(DocumentReferenceInternal* internal); + + mutable DocumentReferenceInternal* internal_ = nullptr; +}; + +/** Checks `lhs` and `rhs` for equality. */ +bool operator==(const DocumentReference& lhs, const DocumentReference& rhs); + +/** Checks `lhs` and `rhs` for inequality. */ +inline bool operator!=(const DocumentReference& lhs, + const DocumentReference& rhs) { + return !(lhs == rhs); +} + +} // namespace firestore +} // namespace firebase + +#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_DOCUMENT_REFERENCE_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/document_snapshot.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/document_snapshot.h new file mode 100644 index 000000000000..7617eb5d1412 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/document_snapshot.h @@ -0,0 +1,297 @@ +/* + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_DOCUMENT_SNAPSHOT_H_ +#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_DOCUMENT_SNAPSHOT_H_ + +#include +#include + +#include "firebase/firestore/map_field_value.h" +#include "firebase/firestore/snapshot_metadata.h" + +namespace firebase { +namespace firestore { + +class DocumentReference; +class DocumentSnapshotInternal; +class FieldPath; +class FieldValue; +class Firestore; + +/** + * @brief A DocumentSnapshot contains data read from a document in your + * Firestore database. + * + * The data can be extracted with the GetData() method, or by using + * Get() to access a specific field. For a DocumentSnapshot that points to + * a non-existing document, any data access will cause a failed assertion. You + * can use the exists() method to explicitly verify a document's existence. + * + * @note Firestore classes are not meant to be subclassed except for use in test + * mocks. Subclassing is not supported in production code and new SDK releases + * may break code that does so. + */ +class DocumentSnapshot { + public: + /** + * Controls the return value for server timestamps that have not yet been set + * to their final value. + */ + enum class ServerTimestampBehavior { + /** + * Return Null for server timestamps that have not yet been set to their + * final value. + */ + kNone = 0, + + /** + * Return local estimates for server timestamps that have not yet been set + * to their final value. This estimate will likely differ from the final + * value and may cause these pending values to change once the server result + * becomes available. + */ + kEstimate, + + /** + * Return the previous value for server timestamps that have not yet been + * set to their final value. + */ + kPrevious, + + /** The default behavior, which is equivalent to specifying kNone. */ + // + // Note, SWIG renaming mechanism doesn't properly handle initializing an + // enum constant with another enum constant (e.g., in expression `kFoo = + // kBar` only `kFoo` will be renamed, leaving `kBar` as is, leading to + // compilation errors). + // + kDefault = 0, + }; + + /** + * @brief Creates an invalid DocumentSnapshot that has to be reassigned before + * it can be used. + * + * Calling any member function on an invalid DocumentSnapshot will be a no-op. + * If the function returns a value, it will return a zero, empty, or invalid + * value, depending on the type of the value. + */ + DocumentSnapshot(); + + /** + * @brief Copy constructor. + * + * `DocumentSnapshot` is immutable and can be efficiently copied (no deep copy + * is performed). + * + * @param[in] other `DocumentSnapshot` to copy from. + */ + DocumentSnapshot(const DocumentSnapshot& other); + + /** + * @brief Move constructor. + * + * Moving is more efficient than copying for a `DocumentSnapshot`. After being + * moved from, a `DocumentSnapshot` is equivalent to its default-constructed + * state. + * + * @param[in] other `DocumentSnapshot` to move data from. + */ + DocumentSnapshot(DocumentSnapshot&& other); + + virtual ~DocumentSnapshot(); + + /** + * @brief Copy assignment operator. + * + * `DocumentSnapshot` is immutable and can be efficiently copied (no deep copy + * is performed). + * + * @param[in] other `DocumentSnapshot` to copy from. + * + * @return Reference to the destination `DocumentSnapshot`. + */ + DocumentSnapshot& operator=(const DocumentSnapshot& other); + + /** + * @brief Move assignment operator. + * + * Moving is more efficient than copying for a `DocumentSnapshot`. After being + * moved from, a `DocumentSnapshot` is equivalent to its default-constructed + * state. + * + * @param[in] other `DocumentSnapshot` to move data from. + * + * @return Reference to the destination `DocumentSnapshot`. + */ + DocumentSnapshot& operator=(DocumentSnapshot&& other); + + /** + * @brief Returns the string ID of the document for which this + * DocumentSnapshot contains data. + * + * @return String ID of this document location. + */ + virtual const std::string& id() const; + + /** + * @brief Returns the document location for which this DocumentSnapshot + * contains data. + * + * @return DocumentReference of this document location. + */ + virtual DocumentReference reference() const; + + /** + * @brief Returns the metadata about this snapshot concerning its source and + * if it has local modifications. + * + * @return SnapshotMetadata about this snapshot. + */ + virtual SnapshotMetadata metadata() const; + + /** + * @brief Explicitly verify a document's existence. + * + * @return True if the document exists in this snapshot. + */ + virtual bool exists() const; + + /** + * @brief Retrieves all fields in the document as a map of FieldValues. + * + * @param stb Configures how server timestamps that have not yet + * been set to their final value are returned from the snapshot (optional). + * + * @return A map containing all fields in the document, or an empty map if the + * document doesn't exist. + */ + virtual MapFieldValue GetData( + ServerTimestampBehavior stb = ServerTimestampBehavior::kDefault) const; + + /** + * @brief Retrieves a specific field from the document. + * + * @param field String ID of the field to retrieve. The pointer only needs to + * be valid during this call. + * @param stb Configures how server timestamps that have not yet been set to + * their final value are returned from the snapshot (optional). + * + * @return The value contained in the field. If the field does not exist in + * the document, then a `FieldValue` instance with `is_valid() == false` will + * be returned. + */ + virtual FieldValue Get( + const char* field, + ServerTimestampBehavior stb = ServerTimestampBehavior::kDefault) const; + + /** + * @brief Retrieves a specific field from the document. + * + * @param field String ID of the field to retrieve. + * @param stb Configures how server timestamps that have not yet been set to + * their final value are returned from the snapshot (optional). + * + * @return The value contained in the field. If the field does not exist in + * the document, then a `FieldValue` instance with `is_valid() == false` will + * be returned. + */ + virtual FieldValue Get( + const std::string& field, + ServerTimestampBehavior stb = ServerTimestampBehavior::kDefault) const; + + /** + * @brief Retrieves a specific field from the document. + * + * @param field Path of the field to retrieve. + * @param stb Configures how server timestamps that have not yet been set to + * their final value are returned from the snapshot (optional). + * + * @return The value contained in the field. If the field does not exist in + * the document, then a `FieldValue` instance with `is_valid() == false` will + * be returned. + */ + virtual FieldValue Get( + const FieldPath& field, + ServerTimestampBehavior stb = ServerTimestampBehavior::kDefault) const; + + /** + * @brief Returns true if this `DocumentSnapshot` is valid, false if it is + * not valid. An invalid `DocumentSnapshot` could be the result of: + * - Creating a `DocumentSnapshot` with the default constructor. + * - Moving from the `DocumentSnapshot`. + * - Deleting your Firestore instance, which will invalidate all the + * `DocumentSnapshot` instances associated with it. + * + * @return true if this `DocumentSnapshot` is valid, false if this + * `DocumentSnapshot` is invalid. + */ + bool is_valid() const { return internal_ != nullptr; } + + /** + * Returns a string representation of this `DocumentSnapshot` for + * logging/debugging purposes. + * + * @note the exact string representation is unspecified and subject to + * change; don't rely on the format of the string. + */ + std::string ToString() const; + + /** + * Outputs the string representation of this `DocumentSnapshot` to the given + * stream. + * + * @see `ToString()` for comments on the representation format. + */ + friend std::ostream& operator<<(std::ostream& out, + const DocumentSnapshot& document); + + private: + std::size_t Hash() const; + + friend bool operator==(const DocumentSnapshot& lhs, + const DocumentSnapshot& rhs); + friend std::size_t DocumentSnapshotHash(const DocumentSnapshot& snapshot); + + friend class DocumentChangeInternal; + friend class EventListenerInternal; + friend class FirestoreInternal; + friend class QueryInternal; + friend class TransactionInternal; + friend class Wrapper; + friend struct ConverterImpl; + template + friend struct CleanupFn; + + explicit DocumentSnapshot(DocumentSnapshotInternal* internal); + + mutable DocumentSnapshotInternal* internal_ = nullptr; +}; + +/** Checks `lhs` and `rhs` for equality. */ +bool operator==(const DocumentSnapshot& lhs, const DocumentSnapshot& rhs); + +/** Checks `lhs` and `rhs` for inequality. */ +inline bool operator!=(const DocumentSnapshot& lhs, + const DocumentSnapshot& rhs) { + return !(lhs == rhs); +} + +} // namespace firestore +} // namespace firebase + +#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_DOCUMENT_SNAPSHOT_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/field_path.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/field_path.h new file mode 100644 index 000000000000..d09dec641140 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/field_path.h @@ -0,0 +1,205 @@ +/* + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_FIELD_PATH_H_ +#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_FIELD_PATH_H_ + +#include +#include +#include +#include + +namespace firebase { +namespace firestore { + +#if !defined(__ANDROID__) + +namespace model { +class FieldPath; +} // namespace model + +#else + +class FieldPathPortable; + +#endif // !defined(__ANDROID__) + +/** + * @brief A FieldPath refers to a field in a document. + * + * The path may consist of a single field name (referring to a top level field + * in the document) or a list of field names (referring to a nested field in the + * document). + */ +class FieldPath final { + public: + /** + * @brief Creates an invalid FieldPath that has to be reassigned before it can + * be used. + * + * Calling any member function on an invalid FieldPath will be a no-op. If the + * function returns a value, it will return a zero, empty, or invalid value, + * depending on the type of the value. + */ + FieldPath(); + + /** + * Creates a FieldPath from the provided field names. If more than one field + * name is provided, the path will point to a nested field in a document. + * + * @param field_names A list of field names. + */ + FieldPath(std::initializer_list field_names); + + /** + * Creates a FieldPath from the provided field names. If more than one field + * name is provided, the path will point to a nested field in a document. + * + * @param field_names A vector of field names. + */ + FieldPath(const std::vector& field_names); + + /** + * @brief Copy constructor. + * + * This performs a deep copy, creating an independent instance. + * + * @param[in] other `FieldPath` to copy from. + */ + FieldPath(const FieldPath& other); + + /** + * @brief Move constructor. + * + * Moving is more efficient than copying for `FieldPath`. After being moved + * from, `FieldPath` is in a valid but unspecified state. + * + * @param[in] other `FieldPath` to move data from. + */ + FieldPath(FieldPath&& other) noexcept; + + ~FieldPath(); + + /** + * @brief Copy assignment operator. + * + * This performs a deep copy, creating an independent instance. + * + * @param[in] other `FieldPath` to copy from. + * + * @return Reference to the destination `FieldPath`. + */ + FieldPath& operator=(const FieldPath& other); + + /** + * @brief Move assignment operator. + * + * Moving is more efficient than copying for `FieldPath`. After being moved + * from, `FieldPath` is in a valid but unspecified state. + * + * @param[in] other `FieldPath` to move data from. + * + * @return Reference to the destination `FieldPath`. + */ + FieldPath& operator=(FieldPath&& other) noexcept; + + /** + * A special sentinel FieldPath to refer to the ID of a document. It can be + * used in queries to sort or filter by the document ID. + */ + static FieldPath DocumentId(); + + /** + * @brief Returns true if this `FieldPath` is valid, false if it is not valid. + * An invalid `FieldPath` could be the result of: + * - Creating a `FieldPath` using the default constructor. + * - Moving from the `FieldPath`. + * + * @return true if this `FieldPath` is valid, false if this `FieldPath` is + * invalid. + */ + bool is_valid() const { return internal_ != nullptr; } + + /** + * Returns a string representation of this `FieldPath` for + * logging/debugging purposes. + * + * @note the exact string representation is unspecified and subject to + * change; don't rely on the format of the string. + */ + std::string ToString() const; + + /** + * Outputs the string representation of this `FieldPath` to the given + * stream. + * + * @see `ToString()` for comments on the representation format. + */ + friend std::ostream& operator<<(std::ostream& out, const FieldPath& path); + + private: + // The type of the internal object that implements the public interface. +#if !defined(SWIG) +#if !defined(__ANDROID__) + using FieldPathInternal = ::firebase::firestore::model::FieldPath; +#else + using FieldPathInternal = ::firebase::firestore::FieldPathPortable; +#endif // !defined(__ANDROID__) +#endif // !defined(SWIG) + + friend bool operator==(const FieldPath& lhs, const FieldPath& rhs); + friend bool operator!=(const FieldPath& lhs, const FieldPath& rhs); + friend struct std::hash; + + friend class DocumentSnapshot; // For access to `FromDotSeparatedString` + friend class Query; + friend class QueryInternal; + friend class SetOptions; // For access to `FromDotSeparatedString` + friend class FieldPathConverter; + friend struct ConverterImpl; + + explicit FieldPath(FieldPathInternal* internal); + + static FieldPathInternal* InternalFromSegments( + std::vector field_names); + + static FieldPath FromDotSeparatedString(const std::string& path); + + FieldPathInternal* internal_ = nullptr; +}; + +} // namespace firestore +} // namespace firebase + +#if !defined(SWIG) +namespace std { +/** + * A convenient specialization of std::hash for FieldPath. + */ +template <> +struct hash { + /** + * Calculates the hash of the argument. + * + * Note: specialization of `std::hash` is provided for convenience only. The + * implementation is subject to change. + */ + size_t operator()(const firebase::firestore::FieldPath& field_path) const; +}; +} // namespace std +#endif // !defined(SWIG) + +#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_FIELD_PATH_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/field_value.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/field_value.h new file mode 100644 index 000000000000..e66814104ed7 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/field_value.h @@ -0,0 +1,436 @@ +/* + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_FIELD_VALUE_H_ +#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_FIELD_VALUE_H_ + +#include +#include +#include +#include +#include + +#include "firebase/firestore/map_field_value.h" +#include "firebase/internal/type_traits.h" + +namespace firebase { + +class Timestamp; + +namespace firestore { + +class DocumentReference; +class FieldValueInternal; +class GeoPoint; + +/** + * @brief A field value represents variant datatypes as stored by Firestore. + * + * FieldValue can be used when reading a particular field with + * DocumentSnapshot::Get() or fields with DocumentSnapshot::GetData(). When + * writing document fields with DocumentReference::Set() or + * DocumentReference::Update(), it can also represent sentinel values in + * addition to real data values. + * + * For a non-sentinel instance, you can check whether it is of a particular type + * with is_foo() and get the value with foo_value(), where foo can be one of + * null, boolean, integer, double, timestamp, string, blob, reference, + * geo_point, array or map. If the instance is not of type foo, the call to + * foo_value() will fail (and cause a crash). + */ +class FieldValue final { + // Helper aliases for `Increment` member functions. + // Qualifying `is_integer` is to prevent ambiguity with the + // `FieldValue::is_integer` member function. + // Note: normally, `enable_if::type` would be included in the alias, but such + // a declaration breaks SWIG (presumably, SWIG cannot handle `typename` within + // an alias template). + template + using EnableIfIntegral = enable_if<::firebase::is_integer::value, int>; + template + using EnableIfFloatingPoint = enable_if::value, int>; + + public: + /** + * The enumeration of all valid runtime types of FieldValue. + */ + enum class Type { + kNull, + kBoolean, + kInteger, + kDouble, + kTimestamp, + kString, + kBlob, + kReference, + kGeoPoint, + kArray, + kMap, + // Below are sentinel types. Sentinel types can be passed to Firestore + // methods as arguments, but are never returned from Firestore. + kDelete, + kServerTimestamp, + kArrayUnion, + kArrayRemove, + kIncrementInteger, + kIncrementDouble, + }; + + /** + * @brief Creates an invalid FieldValue that has to be reassigned before it + * can be used. + * + * Calling any member function on an invalid FieldValue will be a no-op. If + * the function returns a value, it will return a zero, empty, or invalid + * value, depending on the type of the value. + */ + FieldValue(); + + /** + * @brief Copy constructor. + * + * `FieldValue` is immutable and can be efficiently copied (no deep copy is + * performed). + * + * @param[in] other `FieldValue` to copy from. + */ + FieldValue(const FieldValue& other); + + /** + * @brief Move constructor. + * + * Moving is more efficient than copying for a `FieldValue`. After being moved + * from, a `FieldValue` is equivalent to its default-constructed state. + * + * @param[in] other `FieldValue` to move data from. + */ + FieldValue(FieldValue&& other) noexcept; + + ~FieldValue(); + + /** + * @brief Copy assignment operator. + * + * `FieldValue` is immutable and can be efficiently copied (no deep copy is + * performed). + * + * @param[in] other `FieldValue` to copy from. + * + * @return Reference to the destination `FieldValue`. + */ + FieldValue& operator=(const FieldValue& other); + + /** + * @brief Move assignment operator. + * + * Moving is more efficient than copying for a `FieldValue`. After being moved + * from, a `FieldValue` is equivalent to its default-constructed state. + * + * @param[in] other `FieldValue` to move data from. + * + * @return Reference to the destination `FieldValue`. + */ + FieldValue& operator=(FieldValue&& other) noexcept; + + /** + * @brief Constructs a FieldValue containing the given boolean value. + */ + static FieldValue Boolean(bool value); + + /** + * @brief Constructs a FieldValue containing the given 64-bit integer value. + */ + static FieldValue Integer(int64_t value); + + /** + * @brief Constructs a FieldValue containing the given double-precision + * floating point value. + */ + static FieldValue Double(double value); + + /** + * @brief Constructs a FieldValue containing the given Timestamp value. + */ + static FieldValue Timestamp(Timestamp value); + + /** + * @brief Constructs a FieldValue containing the given std::string value. + */ + static FieldValue String(std::string value); + + /** + * @brief Constructs a FieldValue containing the given blob value of given + * size. `value` is copied into the returned FieldValue. + */ + static FieldValue Blob(const uint8_t* value, size_t size); + + /** + * @brief Constructs a FieldValue containing the given reference value. + */ + static FieldValue Reference(DocumentReference value); + + /** + * @brief Constructs a FieldValue containing the given GeoPoint value. + */ + static FieldValue GeoPoint(GeoPoint value); + + /** + * @brief Constructs a FieldValue containing the given FieldValue vector + * value. + */ + static FieldValue Array(std::vector value); + + /** + * @brief Constructs a FieldValue containing the given FieldValue map value. + */ + static FieldValue Map(MapFieldValue value); + + /** @brief Gets the current type contained in this FieldValue. */ + Type type() const; + + /** @brief Gets whether this FieldValue is currently null. */ + bool is_null() const { return type() == Type::kNull; } + + /** @brief Gets whether this FieldValue contains a boolean value. */ + bool is_boolean() const { return type() == Type::kBoolean; } + + /** @brief Gets whether this FieldValue contains an integer value. */ + bool is_integer() const { return type() == Type::kInteger; } + + /** @brief Gets whether this FieldValue contains a double value. */ + bool is_double() const { return type() == Type::kDouble; } + + /** @brief Gets whether this FieldValue contains a timestamp. */ + bool is_timestamp() const { return type() == Type::kTimestamp; } + + /** @brief Gets whether this FieldValue contains a string. */ + bool is_string() const { return type() == Type::kString; } + + /** @brief Gets whether this FieldValue contains a blob. */ + bool is_blob() const { return type() == Type::kBlob; } + + /** + * @brief Gets whether this FieldValue contains a reference to a document in + * the same Firestore. + */ + bool is_reference() const { return type() == Type::kReference; } + + /** @brief Gets whether this FieldValue contains a GeoPoint. */ + bool is_geo_point() const { return type() == Type::kGeoPoint; } + + /** @brief Gets whether this FieldValue contains an array of FieldValues. */ + bool is_array() const { return type() == Type::kArray; } + + /** @brief Gets whether this FieldValue contains a map of std::string to + * FieldValue. */ + bool is_map() const { return type() == Type::kMap; } + + /** @brief Gets the boolean value contained in this FieldValue. */ + bool boolean_value() const; + + /** @brief Gets the integer value contained in this FieldValue. */ + int64_t integer_value() const; + + /** @brief Gets the double value contained in this FieldValue. */ + double double_value() const; + + /** @brief Gets the timestamp value contained in this FieldValue. */ + class Timestamp timestamp_value() const; + + /** @brief Gets the string value contained in this FieldValue. */ + std::string string_value() const; + + /** @brief Gets the blob value contained in this FieldValue. */ + const uint8_t* blob_value() const; + + /** @brief Gets the blob size contained in this FieldValue. */ + size_t blob_size() const; + + /** @brief Gets the DocumentReference contained in this FieldValue. */ + DocumentReference reference_value() const; + + /** @brief Gets the GeoPoint value contained in this FieldValue. */ + class GeoPoint geo_point_value() const; + + /** @brief Gets the vector of FieldValues contained in this FieldValue. */ + std::vector array_value() const; + + /** + * @brief Gets the map of string to FieldValue contained in this FieldValue. + */ + MapFieldValue map_value() const; + + /** + * @brief Returns `true` if this `FieldValue` is valid, `false` if it is not + * valid. An invalid `FieldValue` could be the result of: + * - Creating a `FieldValue` using the default constructor. + * - Moving from the `FieldValue`. + * - Calling `DocumentSnapshot::Get(field)` for a field that does not exist + * in the document. + * + * @return `true` if this `FieldValue` is valid, `false` if this `FieldValue` + * is invalid. + */ + bool is_valid() const { return internal_ != nullptr; } + + /** @brief Constructs a null. */ + static FieldValue Null(); + + /** + * @brief Returns a sentinel for use with Update() to mark a field for + * deletion. + */ + static FieldValue Delete(); + + /** + * Returns a sentinel that can be used with Set() or Update() to include + * a server-generated timestamp in the written data. + */ + static FieldValue ServerTimestamp(); + + /** + * Returns a special value that can be used with Set() or Update() that tells + * the server to union the given elements with any array value that already + * exists on the server. Each specified element that doesn't already exist in + * the array will be added to the end. If the field being modified is not + * already an array, it will be overwritten with an array containing exactly + * the specified elements. + * + * @param elements The elements to union into the array. + * @return The FieldValue sentinel for use in a call to Set() or Update(). + */ + static FieldValue ArrayUnion(std::vector elements); + + /** + * Returns a special value that can be used with Set() or Update() that tells + * the server to remove the given elements from any array value that already + * exists on the server. All instances of each element specified will be + * removed from the array. If the field being modified is not already an + * array, it will be overwritten with an empty array. + * + * @param elements The elements to remove from the array. + * @return The FieldValue sentinel for use in a call to Set() or Update(). + */ + static FieldValue ArrayRemove(std::vector elements); + + /** + * Returns a special value that can be used with `Set()` or `Update()` that + * tells the server to increment the field's current value by the given + * integer value. + * + * If the current field value is an integer, possible integer overflows are + * resolved to `LONG_MAX` or `LONG_MIN`. If the current field value is a + * double, both values will be interpreted as doubles and the arithmetic will + * follow IEEE 754 semantics. + * + * If field is not an integer or a double, or if the field does not yet exist, + * the transformation will set the field to the given value. + * + * @param by_value The integer value to increment by. Should be an integer + * type not larger than `int64_t`. + * @return The FieldValue sentinel for use in a call to `Set()` or `Update().` + */ + template ::type = 0> + static FieldValue Increment(T by_value) { + // Note: Doxygen will run into trouble if this function's definition is + // moved outside the class body. + static_assert( + (std::numeric_limits::max)() <= + (std::numeric_limits::max)(), + "The integer type you provided is larger than can fit in an int64_t. " + "If you are sure the value will not be truncated, please explicitly " + "cast to int64_t before passing it to FieldValue::Increment()."); + return IntegerIncrement(static_cast(by_value)); + } + + /** + * Returns a special value that can be used with `Set()` or `Update()` that + * tells the server to increment the field's current value by the given + * floating point value. + * + * If the current field value is an integer, possible integer overflows are + * resolved to `LONG_MAX` or `LONG_MIN`. If the current field value is a + * double, both values will be interpreted as doubles and the arithmetic will + * follow IEEE 754 semantics. + * + * If field is not an integer or a double, or if the field does not yet exist, + * the transformation will set the field to the given value. + * + * @param by_value The double value to increment by. Should be a floating + * point type no larger than `double`. + * @return The FieldValue sentinel for use in a call to `Set()` or `Update().` + */ + template ::type = 0> + static FieldValue Increment(T by_value) { + // Note: Doxygen will run into trouble if this function's definition is + // moved outside the class body. + static_assert( + (std::numeric_limits::max)() <= (std::numeric_limits::max)(), + "The floating point type you provided is larger than can fit in a " + "double. If you are sure the value will not be truncated, please " + "explicitly cast to double before passing it to " + "FieldValue::Increment()."); + return DoubleIncrement(static_cast(by_value)); + } + + /** + * Returns a string representation of this `FieldValue` for logging/debugging + * purposes. + * + * @note the exact string representation is unspecified and subject to + * change; don't rely on the format of the string. + */ + std::string ToString() const; + + /** + * Outputs the string representation of this `FieldValue` to the given stream. + * + * @see `ToString()` for comments on the representation format. + */ + friend std::ostream& operator<<(std::ostream& out, const FieldValue& value); + + private: + friend class DocumentReferenceInternal; + friend class DocumentSnapshotInternal; + friend class FieldValueInternal; + friend class FirestoreInternal; + friend class QueryInternal; + friend class TransactionInternal; + friend class Wrapper; + friend class WriteBatchInternal; + friend struct ConverterImpl; + friend bool operator==(const FieldValue& lhs, const FieldValue& rhs); + + explicit FieldValue(FieldValueInternal* internal); + + static FieldValue IntegerIncrement(int64_t by_value); + static FieldValue DoubleIncrement(double by_value); + + FieldValueInternal* internal_ = nullptr; +}; + +/** Checks `lhs` and `rhs` for equality. */ +bool operator==(const FieldValue& lhs, const FieldValue& rhs); + +/** Checks `lhs` and `rhs` for inequality. */ +inline bool operator!=(const FieldValue& lhs, const FieldValue& rhs) { + return !(lhs == rhs); +} + +} // namespace firestore +} // namespace firebase + +#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_FIELD_VALUE_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/firestore_errors.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/firestore_errors.h new file mode 100644 index 000000000000..6af214a08df1 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/firestore_errors.h @@ -0,0 +1,116 @@ +/* + * Copyright 2018 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIRESTORE_CORE_INCLUDE_FIREBASE_FIRESTORE_FIRESTORE_ERRORS_H_ +#define FIRESTORE_CORE_INCLUDE_FIREBASE_FIRESTORE_FIRESTORE_ERRORS_H_ + +namespace firebase { +namespace firestore { + +/** + * Error codes used by Cloud Firestore. + * + * The codes are in sync across Firestore SDKs on various platforms. + */ +enum Error { + /** The operation completed successfully. */ + // Note: NSError objects will never have a code with this value. + kErrorOk = 0, + + kErrorNone = 0, + + /** The operation was cancelled (typically by the caller). */ + kErrorCancelled = 1, + + /** Unknown error or an error from a different error domain. */ + kErrorUnknown = 2, + + /** + * Client specified an invalid argument. Note that this differs from + * FailedPrecondition. InvalidArgument indicates arguments that are + * problematic regardless of the state of the system (e.g., an invalid field + * name). + */ + kErrorInvalidArgument = 3, + + /** + * Deadline expired before operation could complete. For operations that + * change the state of the system, this error may be returned even if the + * operation has completed successfully. For example, a successful response + * from a server could have been delayed long enough for the deadline to + * expire. + */ + kErrorDeadlineExceeded = 4, + + /** Some requested document was not found. */ + kErrorNotFound = 5, + + /** Some document that we attempted to create already exists. */ + kErrorAlreadyExists = 6, + + /** The caller does not have permission to execute the specified operation. */ + kErrorPermissionDenied = 7, + + /** + * Some resource has been exhausted, perhaps a per-user quota, or perhaps the + * entire file system is out of space. + */ + kErrorResourceExhausted = 8, + + /** + * Operation was rejected because the system is not in a state required for + * the operation's execution. + */ + kErrorFailedPrecondition = 9, + + /** + * The operation was aborted, typically due to a concurrency issue like + * transaction aborts, etc. + */ + kErrorAborted = 10, + + /** Operation was attempted past the valid range. */ + kErrorOutOfRange = 11, + + /** Operation is not implemented or not supported/enabled. */ + kErrorUnimplemented = 12, + + /** + * Internal errors. Means some invariants expected by underlying system has + * been broken. If you see one of these errors, something is very broken. + */ + kErrorInternal = 13, + + /** + * The service is currently unavailable. This is a most likely a transient + * condition and may be corrected by retrying with a backoff. + */ + kErrorUnavailable = 14, + + /** Unrecoverable data loss or corruption. */ + kErrorDataLoss = 15, + + /** + * The request does not have valid authentication credentials for the + * operation. + */ + kErrorUnauthenticated = 16 +}; + +} // namespace firestore +} // namespace firebase + +#endif // FIRESTORE_CORE_INCLUDE_FIREBASE_FIRESTORE_FIRESTORE_ERRORS_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/firestore_version.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/firestore_version.h new file mode 100644 index 000000000000..627ead9e3ae7 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/firestore_version.h @@ -0,0 +1,29 @@ +/* + * Copyright 2018 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIRESTORE_CORE_INCLUDE_FIREBASE_FIRESTORE_FIRESTORE_VERSION_H_ +#define FIRESTORE_CORE_INCLUDE_FIREBASE_FIRESTORE_FIRESTORE_VERSION_H_ + +namespace firebase { +namespace firestore { + +/** Version string for the Firebase Firestore SDK. */ +extern const char* const kFirestoreVersionString; + +} // namespace firestore +} // namespace firebase + +#endif // FIRESTORE_CORE_INCLUDE_FIREBASE_FIRESTORE_FIRESTORE_VERSION_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/geo_point.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/geo_point.h new file mode 100644 index 000000000000..ac56e74a4515 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/geo_point.h @@ -0,0 +1,120 @@ +/* + * Copyright 2018 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIRESTORE_CORE_INCLUDE_FIREBASE_FIRESTORE_GEO_POINT_H_ +#define FIRESTORE_CORE_INCLUDE_FIREBASE_FIRESTORE_GEO_POINT_H_ + +#include +#include + +namespace firebase { +namespace firestore { + +/** + * An immutable object representing a geographical point in Firestore. The point + * is represented as a latitude/longitude pair. + * + * Latitude values are in the range of [-90, 90]. + * Longitude values are in the range of [-180, 180]. + */ +class GeoPoint { + public: + /** Creates a `GeoPoint` with both latitude and longitude set to 0. */ + GeoPoint() = default; + + /** + * Creates a `GeoPoint` from the provided latitude and longitude values. + * + * @param latitude The latitude as number of degrees between -90 and 90. + * @param longitude The longitude as number of degrees between -180 and 180. + */ + GeoPoint(double latitude, double longitude); + + /** Copy constructor, `GeoPoint` is trivially copyable. */ + GeoPoint(const GeoPoint& other) = default; + + /** Move constructor, equivalent to copying. */ + GeoPoint(GeoPoint&& other) = default; + + /** Copy assignment operator, `GeoPoint` is trivially copyable. */ + GeoPoint& operator=(const GeoPoint& other) = default; + + /** Move assignment operator, equivalent to copying. */ + GeoPoint& operator=(GeoPoint&& other) = default; + + /** Returns the latitude value of this `GeoPoint`. */ + double latitude() const { + return latitude_; + } + + /** Returns the latitude value of this `GeoPoint`. */ + double longitude() const { + return longitude_; + } + + /** + * Returns a string representation of this `GeoPoint` for logging/debugging + * purposes. + * + * @note: the exact string representation is unspecified and subject to + * change; don't rely on the format of the string. + */ + std::string ToString() const; + + /** + * Outputs the string representation of this `GeoPoint` to the given stream. + * + * @see `ToString()` for comments on the representation format. + */ + friend std::ostream& operator<<(std::ostream& out, const GeoPoint& geo_point); + + private: + double latitude_ = 0.0; + double longitude_ = 0.0; +}; + +/** Checks whether `lhs` and `rhs` are in ascending order. */ +bool operator<(const GeoPoint& lhs, const GeoPoint& rhs); + +/** Checks whether `lhs` and `rhs` are in descending order. */ +inline bool operator>(const GeoPoint& lhs, const GeoPoint& rhs) { + return rhs < lhs; +} + +/** Checks whether `lhs` and `rhs` are in non-ascending order. */ +inline bool operator>=(const GeoPoint& lhs, const GeoPoint& rhs) { + return !(lhs < rhs); +} + +/** Checks whether `lhs` and `rhs` are in non-descending order. */ +inline bool operator<=(const GeoPoint& lhs, const GeoPoint& rhs) { + return !(lhs > rhs); +} + +/** Checks `lhs` and `rhs` for inequality. */ +inline bool operator!=(const GeoPoint& lhs, const GeoPoint& rhs) { + return lhs < rhs || lhs > rhs; +} + +/** Checks `lhs` and `rhs` for equality. */ +inline bool operator==(const GeoPoint& lhs, const GeoPoint& rhs) { + return !(lhs != rhs); +} + +} // namespace firestore +} // namespace firebase + +#endif // FIRESTORE_CORE_INCLUDE_FIREBASE_FIRESTORE_GEO_POINT_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/listener_registration.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/listener_registration.h new file mode 100644 index 000000000000..20487943347f --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/listener_registration.h @@ -0,0 +1,130 @@ +/* + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_LISTENER_REGISTRATION_H_ +#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_LISTENER_REGISTRATION_H_ + +namespace firebase { +namespace firestore { + +class FirestoreInternal; +class ListenerRegistrationInternal; + +/** Represents a listener that can be removed by calling Remove(). */ +class ListenerRegistration { + public: + /** + * @brief Creates an invalid ListenerRegistration that has to be reassigned + * before it can be used. + * + * Calling Remove() on an invalid ListenerRegistration is a no-op. + */ + ListenerRegistration(); + + /** + * @brief Copy constructor. + * + * `ListenerRegistration` can be efficiently copied because it simply refers + * to the same underlying listener. If there is more than one copy of + * a `ListenerRegistration`, after calling `Remove` on one of them, the + * listener is removed, and calling `Remove` on any other copies will be + * a no-op. + * + * @param[in] other `ListenerRegistration` to copy from. + */ + ListenerRegistration(const ListenerRegistration& other); + + /** + * @brief Move constructor. + * + * Moving is more efficient than copying for a `ListenerRegistration`. After + * being moved from, a `ListenerRegistration` is equivalent to its + * default-constructed state. + * + * @param[in] other `ListenerRegistration` to move data from. + */ + ListenerRegistration(ListenerRegistration&& other); + + virtual ~ListenerRegistration(); + + /** + * @brief Copy assignment operator. + * + * `ListenerRegistration` can be efficiently copied because it simply refers + * to the same underlying listener. If there is more than one copy of + * a `ListenerRegistration`, after calling `Remove` on one of them, the + * listener is removed, and calling `Remove` on any other copies will be + * a no-op. + * + * @param[in] other `ListenerRegistration` to copy from. + * + * @return Reference to the destination `ListenerRegistration`. + */ + ListenerRegistration& operator=(const ListenerRegistration& other); + + /** + * @brief Move assignment operator. + * + * Moving is more efficient than copying for a `ListenerRegistration`. After + * being moved from, a `ListenerRegistration` is equivalent to its + * default-constructed state. + * + * @param[in] other `ListenerRegistration` to move data from. + * + * @return Reference to the destination `ListenerRegistration`. + */ + ListenerRegistration& operator=(ListenerRegistration&& other); + + /** + * Removes the listener being tracked by this ListenerRegistration. After the + * initial call, subsequent calls have no effect. + */ + virtual void Remove(); + + /** + * @brief Returns true if this `ListenerRegistration` is valid, false if it is + * not valid. An invalid `ListenerRegistration` could be the result of: + * - Creating a `ListenerRegistration` using the default constructor. + * - Moving from the `ListenerRegistration`. + * - Deleting your Firestore instance, which will invalidate all the + * `ListenerRegistration` instances associated with it. + * + * @return true if this `ListenerRegistration` is valid, false if this + * `ListenerRegistration` is invalid. + */ + bool is_valid() const { return internal_ != nullptr; } + + private: + friend class DocumentReferenceInternal; + friend class FirestoreInternal; + friend class ListenerRegistrationInternal; + friend class QueryInternal; + friend struct ConverterImpl; + template + friend struct CleanupFn; + + explicit ListenerRegistration(ListenerRegistrationInternal* internal); + + void Cleanup(); + + FirestoreInternal* firestore_ = nullptr; + mutable ListenerRegistrationInternal* internal_ = nullptr; +}; + +} // namespace firestore +} // namespace firebase + +#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_LISTENER_REGISTRATION_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/load_bundle_task_progress.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/load_bundle_task_progress.h new file mode 100644 index 000000000000..be9b235f1205 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/load_bundle_task_progress.h @@ -0,0 +1,101 @@ +/* + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_LOAD_BUNDLE_TASK_PROGRESS_H_ +#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_LOAD_BUNDLE_TASK_PROGRESS_H_ + +#include + +namespace firebase { +namespace firestore { + +class LoadBundleTaskProgressInternal; + +/** Represents a progress update or the final state from loading bundles. */ +class LoadBundleTaskProgress { + public: + /** + * Represents the state of bundle loading tasks. + * + * Both `kSuccess` and `kError` are final states: the task will abort + * or complete and there will be no more updates after they are reported. + */ + enum class State { kError, kInProgress, kSuccess }; + + LoadBundleTaskProgress() = default; + /** Construct a LoadBundleTaskProgress with specific state. **/ + LoadBundleTaskProgress(int32_t documents_loaded, + int32_t total_documents, + int64_t bytes_loaded, + int64_t total_bytes, + State state); + + /** Returns how many documents have been loaded. */ + int32_t documents_loaded() const { return documents_loaded_; } + + /** + * Returns the total number of documents in the bundle. Returns 0 if the + * bundle failed to parse. + */ + int32_t total_documents() const { return total_documents_; } + + /** Returns how many bytes have been loaded. */ + int64_t bytes_loaded() const { return bytes_loaded_; } + + /** + * Returns the total number of bytes in the bundle. Returns 0 if the bundle + * failed to parse. + */ + int64_t total_bytes() const { return total_bytes_; } + + /** Returns the current state of the loading progress. */ + State state() const { return state_; } + + private: + friend class EventListenerInternal; + friend class LoadBundleTaskProgressInternal; + friend struct ConverterImpl; + +#if defined(__ANDROID__) + explicit LoadBundleTaskProgress(LoadBundleTaskProgressInternal* internal); +#endif // defined(__ANDROID__) + + int32_t documents_loaded_ = 0; + int32_t total_documents_ = 0; + int64_t bytes_loaded_ = 0; + int64_t total_bytes_ = 0; + State state_ = State::kInProgress; +}; + +/** LoadBundleTaskProgress == comparison operator. **/ +inline bool operator==(const LoadBundleTaskProgress& lhs, + const LoadBundleTaskProgress& rhs) { + return lhs.state() == rhs.state() && + lhs.bytes_loaded() == rhs.bytes_loaded() && + lhs.documents_loaded() == rhs.documents_loaded() && + lhs.total_bytes() == rhs.total_bytes() && + lhs.total_documents() == rhs.total_documents(); +} + +/** LoadBundleTaskProgress != comparison operator. **/ +inline bool operator!=(const LoadBundleTaskProgress& lhs, + const LoadBundleTaskProgress& rhs) { + return !(lhs == rhs); +} + +} // namespace firestore +} // namespace firebase + +#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_LOAD_BUNDLE_TASK_PROGRESS_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/map_field_value.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/map_field_value.h new file mode 100644 index 000000000000..8c67c05a1088 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/map_field_value.h @@ -0,0 +1,37 @@ +/* + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_MAP_FIELD_VALUE_H_ +#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_MAP_FIELD_VALUE_H_ + +#include +#include + +namespace firebase { +namespace firestore { + +class FieldPath; +class FieldValue; + +/** @brief A map of `FieldValue`s indexed by stringified field paths. */ +using MapFieldValue = std::unordered_map; +/** @brief A map of `FieldValue`s indexed by field paths. */ +using MapFieldPathValue = std::unordered_map; + +} // namespace firestore +} // namespace firebase + +#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_MAP_FIELD_VALUE_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/metadata_changes.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/metadata_changes.h new file mode 100644 index 000000000000..13f9abe48427 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/metadata_changes.h @@ -0,0 +1,41 @@ +/* + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_METADATA_CHANGES_H_ +#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_METADATA_CHANGES_H_ + +namespace firebase { +namespace firestore { + +/** + * Indicates whether metadata-only changes (that is, + * DocumentSnapshot::metadata() or QuerySnapshot::metadata() changed) should + * trigger snapshot events. + */ +enum class MetadataChanges { + /** Snapshot events will not be triggered by metadata-only changes. */ + kExclude, + + /** + * Snapshot events will be triggered by any changes, including metadata-only + * changes. + */ + kInclude, +}; + +} // namespace firestore +} // namespace firebase +#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_METADATA_CHANGES_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/query.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/query.h new file mode 100644 index 000000000000..d2e73400cee6 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/query.h @@ -0,0 +1,683 @@ +/* + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_QUERY_H_ +#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_QUERY_H_ + +#include +#include +#include +#include +#include + +#include "firebase/internal/common.h" + +#include "firebase/firestore/firestore_errors.h" +#include "firebase/firestore/metadata_changes.h" +#include "firebase/firestore/source.h" + +namespace firebase { +/// @cond FIREBASE_APP_INTERNAL +template +class Future; +/// @endcond + +namespace firestore { + +class DocumentSnapshot; +template +class EventListener; +class FieldPath; +class FieldValue; +class ListenerRegistration; +class Firestore; +class QueryInternal; +class QuerySnapshot; + +/** + * @brief A Query which you can read or listen to. + * + * You can also construct refined Query objects by adding filters and ordering. + * + * You cannot construct a valid Query directly; use CollectionReference + * methods that return a Query instead. + * + * @note Firestore classes are not meant to be subclassed except for use in test + * mocks. Subclassing is not supported in production code and new SDK releases + * may break code that does so. + */ +class Query { + public: + /** + * An enum for the direction of a sort. + */ + enum class Direction { + kAscending, + kDescending, + }; + + /** + * @brief Creates an invalid Query that has to be reassigned before it can be + * used. + * + * Calling any member function on an invalid Query will be a no-op. If the + * function returns a value, it will return a zero, empty, or invalid value, + * depending on the type of the value. + */ + Query(); + + /** + * @brief Copy constructor. + * + * `Query` is immutable and can be efficiently copied (no deep copy is + * performed). + * + * @param[in] other `Query` to copy from. + */ + Query(const Query& other); + + /** + * @brief Move constructor. + * + * Moving is more efficient than copying for a `Query`. After being moved + * from, a `Query` is equivalent to its default-constructed state. + * + * @param[in] other `Query` to move data from. + */ + Query(Query&& other); + + virtual ~Query(); + + /** + * @brief Copy assignment operator. + * + * `Query` is immutable and can be efficiently copied (no deep copy is + * performed). + * + * @param[in] other `Query` to copy from. + * + * @return Reference to the destination `Query`. + */ + Query& operator=(const Query& other); + + /** + * @brief Move assignment operator. + * + * Moving is more efficient than copying for a `Query`. After being moved + * from, a `Query` is equivalent to its default-constructed state. + * + * @param[in] other `Query` to move data from. + * + * @return Reference to the destination `Query`. + */ + Query& operator=(Query&& other); + + /** + * @brief Returns the Firestore instance associated with this query. + * + * The pointer will remain valid indefinitely. + * + * @return Firebase Firestore instance that this Query refers to. + */ + virtual const Firestore* firestore() const; + + /** + * @brief Returns the Firestore instance associated with this query. + * + * The pointer will remain valid indefinitely. + * + * @return Firebase Firestore instance that this Query refers to. + */ + virtual Firestore* firestore(); + + /** + * @brief Creates and returns a new Query with the additional filter that + * documents must contain the specified field and the value should be equal to + * the specified value. + * + * @param[in] field The name of the field to compare. + * @param[in] value The value for comparison. + * + * @return The created Query. + */ + virtual Query WhereEqualTo(const std::string& field, + const FieldValue& value) const; + + /** + * @brief Creates and returns a new Query with the additional filter that + * documents must contain the specified field and the value should be equal to + * the specified value. + * + * @param[in] field The path of the field to compare. + * @param[in] value The value for comparison. + * + * @return The created Query. + */ + virtual Query WhereEqualTo(const FieldPath& field, + const FieldValue& value) const; + + /** + * @brief Creates and returns a new Query with the additional filter that + * documents must contain the specified field and the value does not equal the + * specified value. + * + * A Query can have only one `WhereNotEqualTo()` filter, and it cannot be + * combined with `WhereNotIn()`. + * + * @param[in] field The name of the field to compare. + * @param[in] value The value for comparison. + * + * @return The created Query. + */ + virtual Query WhereNotEqualTo(const std::string& field, + const FieldValue& value) const; + + /** + * @brief Creates and returns a new Query with the additional filter that + * documents must contain the specified field and the value does not equal the + * specified value. + * + * A Query can have only one `WhereNotEqualTo()` filter, and it cannot be + * combined with `WhereNotIn()`. + * + * @param[in] field The path of the field to compare. + * @param[in] value The value for comparison. + * + * @return The created Query. + */ + virtual Query WhereNotEqualTo(const FieldPath& field, + const FieldValue& value) const; + + /** + * @brief Creates and returns a new Query with the additional filter that + * documents must contain the specified field and the value should be less + * than the specified value. + * + * @param[in] field The name of the field to compare. + * @param[in] value The value for comparison. + * + * @return The created Query. + */ + virtual Query WhereLessThan(const std::string& field, + const FieldValue& value) const; + + /** + * @brief Creates and returns a new Query with the additional filter that + * documents must contain the specified field and the value should be less + * than the specified value. + * + * @param[in] field The path of the field to compare. + * @param[in] value The value for comparison. + * + * @return The created Query. + */ + virtual Query WhereLessThan(const FieldPath& field, + const FieldValue& value) const; + + /** + * @brief Creates and returns a new Query with the additional filter that + * documents must contain the specified field and the value should be less + * than or equal to the specified value. + * + * @param[in] field The name of the field to compare. + * @param[in] value The value for comparison. + * + * @return The created Query. + */ + virtual Query WhereLessThanOrEqualTo(const std::string& field, + const FieldValue& value) const; + + /** + * @brief Creates and returns a new Query with the additional filter that + * documents must contain the specified field and the value should be less + * than or equal to the specified value. + * + * @param[in] field The path of the field to compare. + * @param[in] value The value for comparison. + * + * @return The created Query. + */ + virtual Query WhereLessThanOrEqualTo(const FieldPath& field, + const FieldValue& value) const; + + /** + * @brief Creates and returns a new Query with the additional filter that + * documents must contain the specified field and the value should be greater + * than the specified value. + * + * @param[in] field The name of the field to compare. + * @param[in] value The value for comparison. + * + * @return The created Query. + */ + virtual Query WhereGreaterThan(const std::string& field, + const FieldValue& value) const; + + /** + * @brief Creates and returns a new Query with the additional filter that + * documents must contain the specified field and the value should be greater + * than the specified value. + * + * @param[in] field The path of the field to compare. + * @param[in] value The value for comparison. + * + * @return The created Query. + */ + virtual Query WhereGreaterThan(const FieldPath& field, + const FieldValue& value) const; + + /** + * @brief Creates and returns a new Query with the additional filter that + * documents must contain the specified field and the value should be greater + * than or equal to the specified value. + * + * @param[in] field The name of the field to compare. + * @param[in] value The value for comparison. + * + * @return The created Query. + */ + virtual Query WhereGreaterThanOrEqualTo(const std::string& field, + const FieldValue& value) const; + + /** + * @brief Creates and returns a new Query with the additional filter that + * documents must contain the specified field and the value should be greater + * than or equal to the specified value. + * + * @param[in] field The path of the field to compare. + * @param[in] value The value for comparison. + * + * @return The created Query. + */ + virtual Query WhereGreaterThanOrEqualTo(const FieldPath& field, + const FieldValue& value) const; + + /** + * @brief Creates and returns a new Query with the additional filter that + * documents must contain the specified field, the value must be an array, and + * that the array must contain the provided value. + * + * A Query can have only one `WhereArrayContains()` filter and it cannot be + * combined with `WhereArrayContainsAny()` or `WhereIn()`. + * + * @param[in] field The name of the field containing an array to search. + * @param[in] value The value that must be contained in the array. + * + * @return The created Query. + */ + virtual Query WhereArrayContains(const std::string& field, + const FieldValue& value) const; + + /** + * @brief Creates and returns a new Query with the additional filter that + * documents must contain the specified field, the value must be an array, and + * that the array must contain the provided value. + * + * A Query can have only one `WhereArrayContains()` filter and it cannot be + * combined with `WhereArrayContainsAny()` or `WhereIn()`. + * + * @param[in] field The path of the field containing an array to search. + * @param[in] value The value that must be contained in the array. + * + * @return The created Query. + */ + virtual Query WhereArrayContains(const FieldPath& field, + const FieldValue& value) const; + + /** + * @brief Creates and returns a new Query with the additional filter that + * documents must contain the specified field, the value must be an array, and + * that the array must contain at least one value from the provided list. + * + * A Query can have only one `WhereArrayContainsAny()` filter and it cannot be + * combined with `WhereArrayContains()` or `WhereIn()`. + * + * @param[in] field The name of the field containing an array to search. + * @param[in] values The list that contains the values to match. + * + * @return The created Query. + */ + virtual Query WhereArrayContainsAny( + const std::string& field, const std::vector& values) const; + + /** + * @brief Creates and returns a new Query with the additional filter that + * documents must contain the specified field, the value must be an array, and + * that the array must contain at least one value from the provided list. + * + * A Query can have only one `WhereArrayContainsAny()` filter and it cannot be + * combined with` WhereArrayContains()` or `WhereIn()`. + * + * @param[in] field The path of the field containing an array to search. + * @param[in] values The list that contains the values to match. + * + * @return The created Query. + */ + virtual Query WhereArrayContainsAny( + const FieldPath& field, const std::vector& values) const; + + /** + * @brief Creates and returns a new Query with the additional filter that + * documents must contain the specified field and the value must equal one of + * the values from the provided list. + * + * A Query can have only one `WhereIn()` filter and it cannot be + * combined with `WhereArrayContainsAny()`. + * + * @param[in] field The name of the field containing an array to search. + * @param[in] values The list that contains the values to match. + * + * @return The created Query. + */ + virtual Query WhereIn(const std::string& field, + const std::vector& values) const; + + /** + * @brief Creates and returns a new Query with the additional filter that + * documents must contain the specified field and the value must equal one of + * the values from the provided list. + * + * A Query can have only one `WhereIn()` filter and it cannot be + * combined with `WhereArrayContainsAny()`. + * + * @param[in] field The path of the field containing an array to search. + * @param[in] values The list that contains the values to match. + * + * @return The created Query. + */ + virtual Query WhereIn(const FieldPath& field, + const std::vector& values) const; + + /** + * @brief Creates and returns a new Query with the additional filter that + * documents must contain the specified field and the value must not equal any + * of the values from the provided list. + * + * One special case is that `WhereNotIn` cannot match `FieldValue::Null()` + * values. To query for documents where a field exists and is + * `FieldValue::Null()`, use `WhereNotEqualTo`, which can handle this special + * case. + * + * A `Query` can have only one `WhereNotIn()` filter, and it cannot be + * combined with `WhereArrayContains()`, `WhereArrayContainsAny()`, + * `WhereIn()`, or `WhereNotEqualTo()`. + * + * @param[in] field The name of the field containing an array to search. + * @param[in] values The list that contains the values to match. + * + * @return The created Query. + */ + virtual Query WhereNotIn(const std::string& field, + const std::vector& values) const; + + /** + * @brief Creates and returns a new Query with the additional filter that + * documents must contain the specified field and the value must not equal any + * of the values from the provided list. + * + * One special case is that `WhereNotIn` cannot match `FieldValue::Null()` + * values. To query for documents where a field exists and is + * `FieldValue::Null()`, use `WhereNotEqualTo`, which can handle this special + * case. + * + * A `Query` can have only one `WhereNotIn()` filter, and it cannot be + * combined with `WhereArrayContains()`, `WhereArrayContainsAny()`, + * `WhereIn()`, or `WhereNotEqualTo()`. + * + * @param[in] field The path of the field containing an array to search. + * @param[in] values The list that contains the values to match. + * + * @return The created Query. + */ + virtual Query WhereNotIn(const FieldPath& field, + const std::vector& values) const; + + /** + * @brief Creates and returns a new Query that's additionally sorted by the + * specified field. + * + * @param[in] field The field to sort by. + * @param[in] direction The direction to sort (optional). If not specified, + * order will be ascending. + * + * @return The created Query. + */ + virtual Query OrderBy(const std::string& field, + Direction direction = Direction::kAscending) const; + + /** + * @brief Creates and returns a new Query that's additionally sorted by the + * specified field. + * + * @param[in] field The field to sort by. + * @param[in] direction The direction to sort (optional). If not specified, + * order will be ascending. + * + * @return The created Query. + */ + virtual Query OrderBy(const FieldPath& field, + Direction direction = Direction::kAscending) const; + + /** + * @brief Creates and returns a new Query that only returns the first matching + * documents up to the specified number. + * + * @param[in] limit A non-negative integer to specify the maximum number of + * items to return. + * + * @return The created Query. + */ + virtual Query Limit(int32_t limit) const; + + /** + * @brief Creates and returns a new Query that only returns the last matching + * documents up to the specified number. + * + * @param[in] limit A non-negative integer to specify the maximum number of + * items to return. + * + * @return The created Query. + */ + virtual Query LimitToLast(int32_t limit) const; + + /** + * @brief Creates and returns a new Query that starts at the provided document + * (inclusive). The starting position is relative to the order of the query. + * The document must contain all of the fields provided in the order by of + * this query. + * + * @param[in] snapshot The snapshot of the document to start at. + * + * @return The created Query. + */ + virtual Query StartAt(const DocumentSnapshot& snapshot) const; + + /** + * @brief Creates and returns a new Query that starts at the provided fields + * relative to the order of the query. The order of the field values must + * match the order of the order by clauses of the query. + * + * @param[in] values The field values to start this query at, in order of the + * query's order by. + * + * @return The created Query. + */ + virtual Query StartAt(const std::vector& values) const; + + /** + * @brief Creates and returns a new Query that starts after the provided + * document (inclusive). The starting position is relative to the order of the + * query. The document must contain all of the fields provided in the order by + * of this query. + * + * @param[in] snapshot The snapshot of the document to start after. + * + * @return The created Query. + */ + virtual Query StartAfter(const DocumentSnapshot& snapshot) const; + + /** + * @brief Creates and returns a new Query that starts after the provided + * fields relative to the order of the query. The order of the field values + * must match the order of the order by clauses of the query. + * + * @param[in] values The field values to start this query after, in order of + * the query's order by. + * + * @return The created Query. + */ + virtual Query StartAfter(const std::vector& values) const; + + /** + * @brief Creates and returns a new Query that ends before the provided + * document (inclusive). The end position is relative to the order of the + * query. The document must contain all of the fields provided in the order by + * of this query. + * + * @param[in] snapshot The snapshot of the document to end before. + * + * @return The created Query. + */ + virtual Query EndBefore(const DocumentSnapshot& snapshot) const; + + /** + * @brief Creates and returns a new Query that ends before the provided fields + * relative to the order of the query. The order of the field values must + * match the order of the order by clauses of the query. + * + * @param[in] values The field values to end this query before, in order of + * the query's order by. + * + * @return The created Query. + */ + virtual Query EndBefore(const std::vector& values) const; + + /** + * @brief Creates and returns a new Query that ends at the provided document + * (inclusive). The end position is relative to the order of the query. The + * document must contain all of the fields provided in the order by of this + * query. + * + * @param[in] snapshot The snapshot of the document to end at. + * + * @return The created Query. + */ + virtual Query EndAt(const DocumentSnapshot& snapshot) const; + + /** + * @brief Creates and returns a new Query that ends at the provided fields + * relative to the order of the query. The order of the field values must + * match the order of the order by clauses of the query. + * + * @param[in] values The field values to end this query at, in order of the + * query's order by. + * + * @return The created Query. + */ + virtual Query EndAt(const std::vector& values) const; + + /** + * @brief Executes the query and returns the results as a QuerySnapshot. + * + * By default, Get() attempts to provide up-to-date data when possible by + * waiting for data from the server, but it may return cached data or fail if + * you are offline and the server cannot be reached. This behavior can be + * altered via the Source parameter. + * + * @param[in] source A value to configure the get behavior (optional). + * + * @return A Future that will be resolved with the results of the Query. + */ + virtual Future Get(Source source = Source::kDefault) const; + + /** + * @brief Starts listening to the QuerySnapshot events referenced by this + * query. + * + * @param[in] callback The std::function to call. When this function is + * called, snapshot value is valid if and only if error is Error::kErrorOk. + * The std::string is an error message; the value may be empty if an error + * message is not available. + * + * @return A registration object that can be used to remove the listener. + */ + virtual ListenerRegistration AddSnapshotListener( + std::function + callback); + + /** + * @brief Starts listening to the QuerySnapshot events referenced by this + * query. + * + * @param[in] metadata_changes Indicates whether metadata-only changes (that + * is, only DocumentSnapshot::metadata() changed) should trigger snapshot + * events. + * @param[in] callback The std::function to call. When this function is + * called, snapshot value is valid if and only if error is Error::kErrorOk. + * The std::string is an error message; the value may be empty if an error + * message is not available. + * + * @return A registration object that can be used to remove the listener. + */ + virtual ListenerRegistration AddSnapshotListener( + MetadataChanges metadata_changes, + std::function + callback); + + /** + * @brief Returns true if this `Query` is valid, false if it is not valid. An + * invalid `Query` could be the result of: + * - Creating a `Query` using the default constructor. + * - Moving from the `Query`. + * - Deleting your Firestore instance, which will invalidate all the `Query` + * instances associated with it. + * + * @return true if this `Query` is valid, false if this `Query` is invalid. + */ + bool is_valid() const { return internal_ != nullptr; } + + private: + size_t Hash() const; + + friend bool operator==(const Query& lhs, const Query& rhs); + friend size_t QueryHash(const Query& query); + + friend class FirestoreInternal; + friend class QueryInternal; + friend class QuerySnapshotInternal; + friend struct ConverterImpl; + template + friend struct CleanupFn; + // For access to the constructor and to `internal_`. + friend class CollectionReference; + + explicit Query(QueryInternal* internal); + + mutable QueryInternal* internal_ = nullptr; +}; + +/** Checks `lhs` and `rhs` for equality. */ +bool operator==(const Query& lhs, const Query& rhs); + +/** Checks `lhs` and `rhs` for inequality. */ +inline bool operator!=(const Query& lhs, const Query& rhs) { + return !(lhs == rhs); +} + +} // namespace firestore +} // namespace firebase + +#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_QUERY_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/query_snapshot.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/query_snapshot.h new file mode 100644 index 000000000000..2dcf7aaf5239 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/query_snapshot.h @@ -0,0 +1,194 @@ +/* + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_QUERY_SNAPSHOT_H_ +#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_QUERY_SNAPSHOT_H_ + +#include +#include + +#include "firebase/firestore/metadata_changes.h" +#include "firebase/firestore/snapshot_metadata.h" + +namespace firebase { +namespace firestore { + +class DocumentChange; +class DocumentSnapshot; +class Query; +class QuerySnapshotInternal; + +/** + * @brief A QuerySnapshot contains zero or more DocumentSnapshot objects. + * + * QuerySnapshot can be iterated using a range-based for loop, and its size can + * be inspected with empty() and size(). + * + * @note Firestore classes are not meant to be subclassed except for use in test + * mocks. Subclassing is not supported in production code and new SDK releases + * may break code that does so. + */ +class QuerySnapshot { + public: + /** + * @brief Creates an invalid QuerySnapshot that has to be reassigned before it + * can be used. + * + * Calling any member function on an invalid QuerySnapshot will be a no-op. If + * the function returns a value, it will return a zero, empty, or invalid + * value, depending on the type of the value. + */ + QuerySnapshot(); + + /** + * @brief Copy constructor. + * + * `QuerySnapshot` is immutable and can be efficiently copied (no deep copy is + * performed). + * + * @param[in] other `QuerySnapshot` to copy from. + */ + QuerySnapshot(const QuerySnapshot& other); + + /** + * @brief Move constructor. + * + * Moving is more efficient than copying for a `QuerySnapshot`. After being + * moved from, a `QuerySnapshot` is equivalent to its default-constructed + * state. + * + * @param[in] other `QuerySnapshot` to move data from. + */ + QuerySnapshot(QuerySnapshot&& other); + + virtual ~QuerySnapshot(); + + /** + * @brief Copy assignment operator. + * + * `QuerySnapshot` is immutable and can be efficiently copied (no deep copy is + * performed). + * + * @param[in] other `QuerySnapshot` to copy from. + * + * @return Reference to the destination `QuerySnapshot`. + */ + QuerySnapshot& operator=(const QuerySnapshot& other); + + /** + * @brief Move assignment operator. + * + * Moving is more efficient than copying for a `QuerySnapshot`. After being + * moved from, a `QuerySnapshot` is equivalent to its default-constructed + * state. + * + * @param[in] other `QuerySnapshot` to move data from. + * + * @return Reference to the destination `QuerySnapshot`. + */ + QuerySnapshot& operator=(QuerySnapshot&& other); + + /** + * @brief The query from which you got this QuerySnapshot. + */ + virtual Query query() const; + + /** + * @brief Metadata about this snapshot, concerning its source and if it has + * local modifications. + * + * @return The metadata for this document snapshot. + */ + virtual SnapshotMetadata metadata() const; + + /** + * @brief The list of documents that changed since the last snapshot. + * + * If it's the first snapshot, all documents will be in the list as added + * changes. Documents with changes only to their metadata will not be + * included. + * + * @param[in] metadata_changes Indicates whether metadata-only changes (that + * is, only QuerySnapshot::metadata() changed) should be included. + * + * @return The list of document changes since the last snapshot. + */ + virtual std::vector DocumentChanges( + MetadataChanges metadata_changes = MetadataChanges::kExclude) const; + + /** + * @brief The list of documents in this QuerySnapshot in order of the query. + * + * @return The list of documents. + */ + virtual std::vector documents() const; + + /** + * @brief Checks the emptiness of the QuerySnapshot. + * + * @return True if there are no documents in the QuerySnapshot. + */ + bool empty() const { return size() == 0; } + + /** + * @brief Checks the size of the QuerySnapshot. + * + * @return The number of documents in the QuerySnapshot. + */ + virtual std::size_t size() const; + + /** + * @brief Returns true if this `QuerySnapshot` is valid, false if it is not + * valid. An invalid `QuerySnapshot` could be the result of: + * - Creating a `QuerySnapshot` using the default constructor. + * - Moving from the `QuerySnapshot`. + * - Deleting your Firestore instance, which will invalidate all the + * `QuerySnapshot` instances associated with it. + * + * @return true if this `QuerySnapshot` is valid, false if this + * `QuerySnapshot` is invalid. + */ + bool is_valid() const { return internal_ != nullptr; } + + private: + std::size_t Hash() const; + + friend bool operator==(const QuerySnapshot& lhs, const QuerySnapshot& rhs); + friend std::size_t QuerySnapshotHash(const QuerySnapshot& snapshot); + + friend class EventListenerInternal; + friend class FirestoreInternal; + friend struct ConverterImpl; + template + friend struct CleanupFn; + + explicit QuerySnapshot(QuerySnapshotInternal* internal); + + mutable QuerySnapshotInternal* internal_ = nullptr; +}; + +/** Checks `lhs` and `rhs` for equality. */ +bool operator==(const QuerySnapshot& lhs, const QuerySnapshot& rhs); + +/** Checks `lhs` and `rhs` for inequality. */ +inline bool operator!=(const QuerySnapshot& lhs, const QuerySnapshot& rhs) { + return !(lhs == rhs); +} + +} // namespace firestore +} // namespace firebase + +#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_QUERY_SNAPSHOT_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/set_options.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/set_options.h new file mode 100644 index 000000000000..bf21b07a0c45 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/set_options.h @@ -0,0 +1,161 @@ +/* + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_SET_OPTIONS_H_ +#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_SET_OPTIONS_H_ + +#include +#include +#include + +#include "firebase/firestore/field_path.h" + +namespace firebase { +namespace firestore { + +/** + * @brief An options object that configures the behavior of Set() calls. + * + * By providing the SetOptions objects returned by Merge(), the Set() methods in + * DocumentReference, WriteBatch and Transaction can be configured to perform + * granular merges instead of overwriting the target documents in their + * entirety. + */ +class SetOptions final { + public: + /** The enumeration of all types of SetOptions. */ + enum class Type { + /** Overwrites the whole document. */ + kOverwrite, + + /** + * Replaces the values specified in the call parameter while leaves omitted + * fields untouched. + */ + kMergeAll, + + /** + * Replaces the values of the fields explicitly specified in the call + * parameter. + */ + kMergeSpecific, + }; + + /** + * Creates SetOptions with overwrite semantics. + */ + SetOptions() = default; + + /** + * @brief Copy constructor. + * + * This performs a deep copy, creating an independent instance. + * + * @param[in] other `SetOptions` to copy from. + */ + SetOptions(const SetOptions& other) = default; + + /** + * @brief Move constructor. + * + * Moving is more efficient than copying for `SetOptions`. After being moved + * from, `SetOptions` is in a valid but unspecified state. + * + * @param[in] other `SetOptions` to move data from. + */ + SetOptions(SetOptions&& other) = default; + + ~SetOptions(); + + /** + * @brief Copy assignment operator. + * + * This performs a deep copy, creating an independent instance. + * + * @param[in] other `SetOptions` to copy from. + * + * @return Reference to the destination `SetOptions`. + */ + SetOptions& operator=(const SetOptions& other) = default; + + /** + * @brief Move assignment operator. + * + * Moving is more efficient than copying for `SetOptions`. After being moved + * from, `SetOptions` is in a valid but unspecified state. + * + * @param[in] other `SetOptions` to move data from. + * + * @return Reference to the destination `SetOptions`. + */ + SetOptions& operator=(SetOptions&& other) = default; + + /** + * Returns an instance that can be used to change the behavior of Set() calls + * to only replace the values specified in its data argument. Fields omitted + * from the Set() call will remain untouched. + */ + static SetOptions Merge(); + + /** + * Returns an instance that can be used to change the behavior of Set() calls + * to only replace the given fields. Any field that is not specified in + * `fields` is ignored and remains untouched. + * + * It is an error to pass a SetOptions object to a Set() call that is missing + * a value for any of the fields specified here. + * + * @param fields The list of fields to merge. Fields can contain dots to + * reference nested fields within the document. + */ + static SetOptions MergeFields(const std::vector& fields); + + /** + * Returns an instance that can be used to change the behavior of Set() calls + * to only replace the given fields. Any field that is not specified in + * `fields` is ignored and remains untouched. + * + * It is an error to pass a SetOptions object to a Set() call that is missing + * a value for any of the fields specified here in its to data argument. + * + * @param fields The list of fields to merge. + */ + static SetOptions MergeFieldPaths(const std::vector& fields); + + private: + friend bool operator==(const SetOptions& lhs, const SetOptions& rhs); + friend class SetOptionsInternal; + + SetOptions(Type type, std::unordered_set fields); + + Type type_ = Type::kOverwrite; + std::unordered_set fields_; +}; + +/** Checks `lhs` and `rhs` for equality. */ +inline bool operator==(const SetOptions& lhs, const SetOptions& rhs) { + return lhs.type_ == rhs.type_ && lhs.fields_ == rhs.fields_; +} + +/** Checks `lhs` and `rhs` for inequality. */ +inline bool operator!=(const SetOptions& lhs, const SetOptions& rhs) { + return !(lhs == rhs); +} + +} // namespace firestore +} // namespace firebase + +#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_SET_OPTIONS_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/settings.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/settings.h new file mode 100644 index 000000000000..8169d9f594e8 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/settings.h @@ -0,0 +1,247 @@ +/* + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_SETTINGS_H_ +#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_SETTINGS_H_ + +#if defined(__OBJC__) +#include +#endif + +#include +#include +#include +#include + +namespace firebase { +namespace firestore { + +#if !defined(__ANDROID__) +// +// This declaration is guarded by a preprocessor macro because it causes +// problems with name lookup on Android. Android implementation of the public +// API extensively uses function calls of the form `util::Foo` which are +// expected to resolve to `::firebase::util::Foo`. As soon as namespace +// `::firebase::firestore::util` becomes visible, it shadows `::firebase::util` +// (within `::firebase::firestore`), so now all those calls fail to compile +// because they are interpreted as referring to +// `::firebase::firestore::util::Foo`, which doesn't exist. Changing existing +// code is impractical because such usages are numerous. +// +namespace util { +class Executor; +} +#endif + +class FirestoreInternal; + +/** Settings used to configure a Firestore instance. */ +class Settings final { + public: + /** + * Constant to use with `set_cache_size_bytes` to disable garbage collection. + */ + static constexpr int64_t kCacheSizeUnlimited = -1; + + /** + * @brief Creates the default settings. + */ + Settings(); + + /** + * @brief Copy constructor. + * + * This performs a deep copy, creating an independent instance. + * + * @param[in] other `Settings` to copy from. + */ + Settings(const Settings& other) = default; + + /** + * @brief Move constructor. + * + * Moving is more efficient than copying for `Settings`. After being moved + * from, `Settings` is in a valid but unspecified state. + * + * @param[in] other `Settings` to move data from. + */ + Settings(Settings&& other) = default; + + /** + * @brief Copy assignment operator. + * + * This performs a deep copy, creating an independent instance. + * + * @param[in] other `Settings` to copy from. + * + * @return Reference to the destination `Settings`. + */ + Settings& operator=(const Settings& other) = default; + + /** + * @brief Move assignment operator. + * + * Moving is more efficient than copying for `Settings`. After being moved + * from, `Settings` is in a valid but unspecified state. + * + * @param[in] other `Settings` to move data from. + * + * @return Reference to the destination `Settings`. + */ + Settings& operator=(Settings&& other) = default; + + /** + * Gets the host of the Firestore backend to connect to. + */ + const std::string& host() const { return host_; } + + /** + * Returns whether to use SSL when communicating. + */ + bool is_ssl_enabled() const { return ssl_enabled_; } + + /** + * Returns whether to enable local persistent storage. + */ + bool is_persistence_enabled() const { return persistence_enabled_; } + + /** Returns cache size for on-disk data. */ + int64_t cache_size_bytes() const { return cache_size_bytes_; } + + /** + * Sets the host of the Firestore backend. The default is + * "firestore.googleapis.com". + * + * @param host The host string. + */ + void set_host(std::string host); + + /** + * Enables or disables SSL for communication. + * + * @param enabled Set true to enable SSL for communication. + */ + void set_ssl_enabled(bool enabled); + + /** + * Enables or disables local persistent storage. + * + * @param enabled Set true to enable local persistent storage. + */ + void set_persistence_enabled(bool enabled); + + /** + * Sets an approximate cache size threshold for the on-disk data. If the cache + * grows beyond this size, Cloud Firestore will start removing data that + * hasn't been recently used. The size is not a guarantee that the cache will + * stay below that size, only that if the cache exceeds the given size, + * cleanup will be attempted. + * + * By default, collection is enabled with a cache size of 100 MB. The minimum + * value is 1 MB. + */ + void set_cache_size_bytes(int64_t value); + +#if defined(__OBJC__) || defined(DOXYGEN) + /** + * Returns a dispatch queue that Firestore will use to execute callbacks. + * + * The returned dispatch queue is used for all completion handlers and event + * handlers. + * + * If no dispatch queue is explictly set by calling `set_dispatch_queue()` + * then a dedicated "callback queue" will be used; namely, the main thread + * will not be used for callbacks unless expliclty set to do so by a call to + * `set_dispatch_queue()`. + * + * @note This method is only available when `__OBJC__` is defined, such as + * when compiling for iOS or tvOS. + * + * @see `set_dispatch_queue(dispatch_queue_t)` for information on how to + * explicitly set the dispatch queue to use. + */ + dispatch_queue_t dispatch_queue() const; + + /** + * Sets the dispatch queue that Firestore will use to execute callbacks. + * + * The specified dispatch queue will be used for all completion handlers and + * event handlers. + * + * @param queue The dispatch queue to use. + * + * @note This method is only available when `__OBJC__` is defined, such as + * when compiling for iOS or tvOS. + * + * @see `dispatch_queue()` for the "get" counterpart to this method. + */ + void set_dispatch_queue(dispatch_queue_t queue); +#endif // defined(__OBJC__) || defined(DOXYGEN) + + /** + * Returns a string representation of these `Settings` for + * logging/debugging purposes. + * + * @note the exact string representation is unspecified and subject to + * change; don't rely on the format of the string. + */ + std::string ToString() const; + + /** + * Outputs the string representation of these `Settings` to the given + * stream. + * + * @see `ToString()` for comments on the representation format. + */ + friend std::ostream& operator<<(std::ostream& out, const Settings& settings); + + private: + static constexpr int64_t kDefaultCacheSizeBytes = 100 * 1024 * 1024; + + std::string host_; + bool ssl_enabled_ = true; + bool persistence_enabled_ = true; + int64_t cache_size_bytes_ = kDefaultCacheSizeBytes; + + // + // TODO(varconst): fix Android problems and make these declarations + // unconditional. + // +#if !defined(__ANDROID__) + friend class FirestoreInternal; + std::unique_ptr CreateExecutor() const; + + std::shared_ptr executor_; +#endif +}; + +/** Checks `lhs` and `rhs` for equality. */ +inline bool operator==(const Settings& lhs, const Settings& rhs) { + return lhs.host() == rhs.host() && + lhs.is_ssl_enabled() == rhs.is_ssl_enabled() && + lhs.is_persistence_enabled() == rhs.is_persistence_enabled() && + lhs.cache_size_bytes() == rhs.cache_size_bytes(); +} + +/** Checks `lhs` and `rhs` for inequality. */ +inline bool operator!=(const Settings& lhs, const Settings& rhs) { + return !(lhs == rhs); +} + +} // namespace firestore +} // namespace firebase + +#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_SETTINGS_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/snapshot_metadata.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/snapshot_metadata.h new file mode 100644 index 000000000000..ce7f3f2b8607 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/snapshot_metadata.h @@ -0,0 +1,159 @@ +/* + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_SNAPSHOT_METADATA_H_ +#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_SNAPSHOT_METADATA_H_ + +#include +#include + +namespace firebase { +namespace firestore { + +/** Metadata about a snapshot, describing the state of the snapshot. */ +class SnapshotMetadata final { + public: + /** + * Constructs a SnapshotMetadata that has all of its boolean members set to + * false. + */ + SnapshotMetadata() = default; + + /** + * Constructs a SnapshotMetadata by providing boolean parameters that describe + * the state of the snapshot. + * + * @param has_pending_writes Whether there is any pending write on the + * snapshot. + * @param is_from_cache Whether the snapshot is from cache instead of backend. + */ + SnapshotMetadata(bool has_pending_writes, bool is_from_cache) + : has_pending_writes_(has_pending_writes), + is_from_cache_(is_from_cache) {} + + /** + * @brief Copy constructor. + * + * This performs a deep copy, creating an independent instance. + * + * @note This class is currently trivially copyable, but it is not guaranteed + * to stay that way, and code relying on this might be broken by a future + * release. + * + * @param[in] other `SnapshotMetadata` to copy from. + */ + SnapshotMetadata(const SnapshotMetadata& other) = default; + + /** + * @brief Move constructor, equivalent to copying. + * + * After being moved from, `SnapshotMetadata` is in a valid but unspecified + * state. + * + * @param[in] other `SnapshotMetadata` to move data from. + */ + SnapshotMetadata(SnapshotMetadata&& other) = default; + + /** + * @brief Copy assignment operator. + * + * This performs a deep copy, creating an independent instance. + * + * @note This class is currently trivially copyable, but it is not guaranteed + * to stay that way, and code relying on this might be broken by a future + * release. + * + * @param[in] other `SnapshotMetadata` to copy from. + * + * @return Reference to the destination `SnapshotMetadata`. + */ + SnapshotMetadata& operator=(const SnapshotMetadata& other) = default; + + /** + * @brief Move assignment operator, equivalent to copying. + * + * After being moved from, `SnapshotMetadata` is in a valid but unspecified + * state. + * + * @param[in] other `SnapshotMetadata` to move data from. + * + * @return Reference to the destination `SnapshotMetadata`. + */ + SnapshotMetadata& operator=(SnapshotMetadata&& other) = default; + + /** + * Returns whether the snapshot contains the result of local writes. + * + * @return true if the snapshot contains the result of local writes (for + * example, Set() or Update() calls) that have not yet been committed to the + * backend. If your listener has opted into metadata updates (via + * MetadataChanges::kInclude) you will receive another snapshot with + * has_pending_writes() equal to false once the writes have been committed to + * the backend. + */ + bool has_pending_writes() const { return has_pending_writes_; } + + /** + * Returns whether the snapshot was created from cached data. + * + * @return true if the snapshot was created from cached data rather than + * guaranteed up-to-date server data. If your listener has opted into metadata + * updates (via MetadataChanges::kInclude) you will receive another snapshot + * with is_from_cache() equal to false once the client has received up-to-date + * data from the backend. + */ + bool is_from_cache() const { return is_from_cache_; } + + /** + * Returns a string representation of this `SnapshotMetadata` for + * logging/debugging purposes. + * + * @note the exact string representation is unspecified and subject to + * change; don't rely on the format of the string. + */ + std::string ToString() const; + + /** + * Outputs the string representation of this `SnapshotMetadata` to the given + * stream. + * + * @see `ToString()` for comments on the representation format. + */ + friend std::ostream& operator<<(std::ostream& out, + const SnapshotMetadata& metadata); + + private: + bool has_pending_writes_ = false; + bool is_from_cache_ = false; +}; + +/** Checks `lhs` and `rhs` for equality. */ +inline bool operator==(const SnapshotMetadata& lhs, + const SnapshotMetadata& rhs) { + return lhs.has_pending_writes() == rhs.has_pending_writes() && + lhs.is_from_cache() == rhs.is_from_cache(); +} + +/** Checks `lhs` and `rhs` for inequality. */ +inline bool operator!=(const SnapshotMetadata& lhs, + const SnapshotMetadata& rhs) { + return !(lhs == rhs); +} + +} // namespace firestore +} // namespace firebase + +#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_SNAPSHOT_METADATA_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/source.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/source.h new file mode 100644 index 000000000000..743106d9e578 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/source.h @@ -0,0 +1,59 @@ +/* + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_SOURCE_H_ +#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_SOURCE_H_ + +namespace firebase { +namespace firestore { + +/** + * @brief Configures the behavior of DocumentReference::Get() and Query::Get(). + * + * By providing a Source value, these methods can be configured to fetch results + * only from the server, only from the local cache, or attempt to fetch results + * from the server and fall back to the cache (which is the default). + */ +enum class Source { + /** + * Causes Firestore to try to retrieve an up-to-date (server-retrieved) + * snapshot, but fall back to returning cached data if the server can't be + * reached. + */ + kDefault, + + /** + * Causes Firestore to avoid the cache, generating an error if the server + * cannot be reached. Note that the cache will still be updated if the server + * request succeeds. Also note that latency-compensation still takes effect, + * so any pending write operations will be visible in the returned data + * (merged into the server-provided data). + */ + kServer, + + /** + * Causes Firestore to immediately return a value from the cache, ignoring the + * server completely (implying that the returned value may be stale with + * respect to the value on the server). If there is no data in the cache to + * satisfy the DocumentReference::Get() call will return an error and + * Query::Get() will return an empty QuerySnapshot with no documents. + */ + kCache, +}; + +} // namespace firestore +} // namespace firebase +#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_SOURCE_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/timestamp.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/timestamp.h new file mode 100644 index 000000000000..e806bb87c136 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/timestamp.h @@ -0,0 +1,252 @@ +/* + * Copyright 2018 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIRESTORE_CORE_INCLUDE_FIREBASE_FIRESTORE_TIMESTAMP_H_ +#define FIRESTORE_CORE_INCLUDE_FIREBASE_FIRESTORE_TIMESTAMP_H_ + +#include +#include +#include +#include + +#if !defined(_STLPORT_VERSION) +#include // NOLINT(build/c++11) +#endif // !defined(_STLPORT_VERSION) + +namespace firebase { + +/** + * A Timestamp represents a point in time independent of any time zone or + * calendar, represented as seconds and fractions of seconds at nanosecond + * resolution in UTC Epoch time. It is encoded using the Proleptic Gregorian + * Calendar which extends the Gregorian calendar backwards to year one. It is + * encoded assuming all minutes are 60 seconds long, i.e. leap seconds are + * "smeared" so that no leap second table is needed for interpretation. Range is + * from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.999999999Z. + * + * @see + * https://github.com/google/protobuf/blob/master/src/google/protobuf/timestamp.proto + */ +class Timestamp { + public: + /** + * Creates a new timestamp representing the epoch (with seconds and + * nanoseconds set to 0). + */ + Timestamp() = default; + + /** + * Creates a new timestamp. + * + * @param seconds The number of seconds of UTC time since Unix epoch + * 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to + * 9999-12-31T23:59:59Z inclusive; otherwise, assertion failure will be + * triggered. + * @param nanoseconds The non-negative fractions of a second at nanosecond + * resolution. Negative second values with fractions must still have + * non-negative nanoseconds values that count forward in time. Must be + * from 0 to 999,999,999 inclusive; otherwise, assertion failure will be + * triggered. + */ + Timestamp(int64_t seconds, int32_t nanoseconds); + + /** Copy constructor, `Timestamp` is trivially copyable. */ + Timestamp(const Timestamp& other) = default; + + /** Move constructor, equivalent to copying. */ + Timestamp(Timestamp&& other) = default; + + /** Copy assignment operator, `Timestamp` is trivially copyable. */ + Timestamp& operator=(const Timestamp& other) = default; + + /** Move assignment operator, equivalent to copying. */ + Timestamp& operator=(Timestamp&& other) = default; + + /** + * Creates a new timestamp with the current date. + * + * The precision is up to nanoseconds, depending on the system clock. + * + * @return a new timestamp representing the current date. + */ + static Timestamp Now(); + + /** + * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z. + */ + int64_t seconds() const { + return seconds_; + } + + /** + * The non-negative fractions of a second at nanosecond resolution. Negative + * second values with fractions still have non-negative nanoseconds values + * that count forward in time. + */ + int32_t nanoseconds() const { + return nanoseconds_; + } + + /** + * Converts `time_t` to a `Timestamp`. + * + * @param seconds_since_unix_epoch + * @parblock + * The number of seconds of UTC time since Unix epoch + * 1970-01-01T00:00:00Z. Can be negative to represent dates before the + * epoch. Must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z + * inclusive; otherwise, assertion failure will be triggered. + * + * Note that while the epoch of `time_t` is unspecified, it's usually Unix + * epoch. If this assumption is broken, this function will produce + * incorrect results. + * @endparblock + * + * @return a new timestamp with the given number of seconds and zero + * nanoseconds. + */ + static Timestamp FromTimeT(time_t seconds_since_unix_epoch); + +#if !defined(_STLPORT_VERSION) + /** + * Converts `std::chrono::time_point` to a `Timestamp`. + * + * @param time_point + * @parblock + * The time point with system clock's epoch, which is + * presumed to be Unix epoch 1970-01-01T00:00:00Z. Can be negative to + * represent dates before the epoch. Must be from 0001-01-01T00:00:00Z to + * 9999-12-31T23:59:59Z inclusive; otherwise, assertion failure will be + * triggered. + * + * Note that while the epoch of `std::chrono::system_clock` is + * unspecified, it's usually Unix epoch. If this assumption is broken, + * this constructor will produce incorrect results. + * @endparblock + */ + static Timestamp FromTimePoint( + std::chrono::time_point time_point); + + /** + * Converts this `Timestamp` to a `time_point`. + * + * Important: if overflow would occur, the returned value will be the maximum + * or minimum value that `Duration` can hold. Note in particular that `long + * long` is insufficient to hold the full range of `Timestamp` values with + * nanosecond precision (which is why `Duration` defaults to `microseconds`). + */ + template + std::chrono::time_point ToTimePoint() const; +#endif // !defined(_STLPORT_VERSION) + + /** + * Returns a string representation of this `Timestamp` for logging/debugging + * purposes. + * + * @note: the exact string representation is unspecified and subject to + * change; don't rely on the format of the string. + */ + std::string ToString() const; + + /** + * Outputs the string representation of this `Timestamp` to the given stream. + * + * @see `ToString()` for comments on the representation format. + */ + friend std::ostream& operator<<(std::ostream& out, + const Timestamp& timestamp); + + private: + // Checks that the number of seconds is within the supported date range, and + // that nanoseconds satisfy 0 <= ns <= 1second. + void ValidateBounds() const; + + int64_t seconds_ = 0; + int32_t nanoseconds_ = 0; +}; + +/** Checks whether `lhs` and `rhs` are in ascending order. */ +inline bool operator<(const Timestamp& lhs, const Timestamp& rhs) { + return lhs.seconds() < rhs.seconds() || + (lhs.seconds() == rhs.seconds() && + lhs.nanoseconds() < rhs.nanoseconds()); +} + +/** Checks whether `lhs` and `rhs` are in descending order. */ +inline bool operator>(const Timestamp& lhs, const Timestamp& rhs) { + return rhs < lhs; +} + +/** Checks whether `lhs` and `rhs` are in non-ascending order. */ +inline bool operator>=(const Timestamp& lhs, const Timestamp& rhs) { + return !(lhs < rhs); +} + +/** Checks whether `lhs` and `rhs` are in non-descending order. */ +inline bool operator<=(const Timestamp& lhs, const Timestamp& rhs) { + return !(lhs > rhs); +} + +/** Checks `lhs` and `rhs` for inequality. */ +inline bool operator!=(const Timestamp& lhs, const Timestamp& rhs) { + return lhs < rhs || lhs > rhs; +} + +/** Checks `lhs` and `rhs` for equality. */ +inline bool operator==(const Timestamp& lhs, const Timestamp& rhs) { + return !(lhs != rhs); +} + +#if !defined(_STLPORT_VERSION) + +// Make sure the header compiles even when included after `` without +// `NOMINMAX` defined. `push/pop_macro` pragmas are supported by Visual Studio +// as well as Clang and GCC. +#pragma push_macro("min") +#pragma push_macro("max") +#undef min +#undef max + +template +std::chrono::time_point Timestamp::ToTimePoint() const { + namespace chr = std::chrono; + using TimePoint = chr::time_point; + + // Saturate on overflow + const auto max_seconds = chr::duration_cast(Duration::max()); + if (seconds_ > 0 && max_seconds.count() <= seconds_) { + return TimePoint{Duration::max()}; + } + const auto min_seconds = chr::duration_cast(Duration::min()); + if (seconds_ < 0 && min_seconds.count() >= seconds_) { + return TimePoint{Duration::min()}; + } + + const auto seconds = chr::duration_cast(chr::seconds(seconds_)); + const auto nanoseconds = + chr::duration_cast(chr::nanoseconds(nanoseconds_)); + return TimePoint{seconds + nanoseconds}; +} + +#pragma pop_macro("max") +#pragma pop_macro("min") + +#endif // !defined(_STLPORT_VERSION) + +} // namespace firebase + +#endif // FIRESTORE_CORE_INCLUDE_FIREBASE_FIRESTORE_TIMESTAMP_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/transaction.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/transaction.h new file mode 100644 index 000000000000..af78e0a2fb70 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/transaction.h @@ -0,0 +1,143 @@ +/* + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_TRANSACTION_H_ +#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_TRANSACTION_H_ + +#include + +#include "firebase/firestore/firestore_errors.h" +#include "firebase/firestore/map_field_value.h" +#include "firebase/firestore/set_options.h" + +namespace firebase { +namespace firestore { + +class DocumentReference; +class DocumentSnapshot; +class TransactionInternal; + +/** + * @brief Transaction provides methods to read and write data within + * a transaction. + * + * You cannot create a `Transaction` directly; use `Firestore::RunTransaction()` + * function instead. + * + * @note Firestore classes are not meant to be subclassed except for use in test + * mocks. Subclassing is not supported in production code and new SDK releases + * may break code that does so. + */ +class Transaction { + public: + /** Destructor. */ + virtual ~Transaction(); + + /** + * @brief Deleted copy constructor. + * + * A `Transaction` object is only valid for the duration of the callback you + * pass to `Firestore::RunTransaction()` and cannot be copied. + */ + Transaction(const Transaction& other) = delete; + + /** + * @brief Deleted copy assignment operator. + * + * A `Transaction` object is only valid for the duration of the callback you + * pass to `Firestore::RunTransaction()` and cannot be copied. + */ + Transaction& operator=(const Transaction& other) = delete; + + /** + * @brief Writes to the document referred to by the provided reference. + * + * If the document does not yet exist, it will be created. If you pass + * SetOptions, the provided data can be merged into an existing document. + * + * @param[in] document The DocumentReference to overwrite. + * @param[in] data A map of the fields and values to write to the document. + * @param[in] options An object to configure the Set() behavior (optional). + */ + virtual void Set(const DocumentReference& document, + const MapFieldValue& data, + const SetOptions& options = SetOptions()); + + /** + * Updates fields in the document referred to by the provided reference. If no + * document exists yet, the update will fail. + * + * @param[in] document The DocumentReference to update. + * @param[in] data A map of field / value pairs to update. Fields can contain + * dots to reference nested fields within the document. + */ + virtual void Update(const DocumentReference& document, + const MapFieldValue& data); + + /** + * Updates fields in the document referred to by the provided reference. If no + * document exists yet, the update will fail. + * + * @param[in] document The DocumentReference to update. + * @param[in] data A map from FieldPath to FieldValue to update. + */ + virtual void Update(const DocumentReference& document, + const MapFieldPathValue& data); + + /** + * Deletes the document referred to by the provided reference. + * + * @param[in] document The DocumentReference to delete. + */ + virtual void Delete(const DocumentReference& document); + + /** + * Reads the document referred by the provided reference. + * + * @param[in] document The DocumentReference to read. + * @param[out] error_code An out parameter to capture an error, if one + * occurred. + * @param[out] error_message An out parameter to capture error message, if + * any. + * @return The contents of the document at this DocumentReference or invalid + * DocumentSnapshot if there is any error. + */ + virtual DocumentSnapshot Get(const DocumentReference& document, + Error* error_code, + std::string* error_message); + + protected: + /** + * Default constructor, to be used only for mocking a `Transaction`. + */ + Transaction() = default; + + private: + friend class FirestoreInternal; + friend class TransactionInternal; + friend struct ConverterImpl; + template + friend struct CleanupFn; + + explicit Transaction(TransactionInternal* internal); + + mutable TransactionInternal* internal_ = nullptr; +}; + +} // namespace firestore +} // namespace firebase + +#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_TRANSACTION_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/transaction_options.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/transaction_options.h new file mode 100644 index 000000000000..9433578879b3 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/transaction_options.h @@ -0,0 +1,137 @@ +/* + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_TRANSACTION_OPTIONS_H_ +#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_TRANSACTION_OPTIONS_H_ + +#include +#include +#include + +namespace firebase { +namespace firestore { + +/** + * Options to customize transaction behavior for `Firestore.runTransaction()`. + */ +class TransactionOptions final { + public: + /** + * @brief Creates the default `TransactionOptions`. + */ + TransactionOptions() = default; + + /** + * @brief Copy constructor. + * + * This performs a deep copy, creating an independent instance. + * + * @param[in] other `TransactionOptions` to copy from. + */ + TransactionOptions(const TransactionOptions& other) = default; + + /** + * @brief Move constructor. + * + * Moving is not any more efficient than copying for `TransactionOptions` + * because this class is trivially copyable; however, future additions to this + * class may make it not trivially copyable, at which point moving would be + * more efficient than copying. After being moved from, `TransactionOptions` + * is in a valid but unspecified state. + * + * @param[in] other `TransactionOptions` to move data from. + */ + TransactionOptions(TransactionOptions&& other) = default; + + /** + * @brief Copy assignment operator. + * + * This performs a deep copy, creating an independent instance. + * + * @param[in] other `TransactionOptions` to copy from. + * + * @return Reference to the destination `TransactionOptions`. + */ + TransactionOptions& operator=(const TransactionOptions& other) = default; + + /** + * @brief Move assignment operator. + * + * Moving is not any more efficient than copying for `TransactionOptions` + * because this class is trivially copyable; however, future additions to this + * class may make it not trivially copyable, at which point moving would be + * more efficient than copying. After being moved from, `TransactionOptions` + * is in a valid but unspecified state. + * + * @param[in] other `TransactionOptions` to move data from. + * + * @return Reference to the destination `TransactionOptions`. + */ + TransactionOptions& operator=(TransactionOptions&& other) = default; + + /** + * @brief Gets the maximum number of attempts to commit, after which the + * transaction fails. + * + * The default value is 5. + */ + int32_t max_attempts() const { return max_attempts_; } + + /** + * @brief Sets the maximum number of attempts to commit, after which the + * transaction fails. + * + * The default value is 5. + * + * @param[in] max_attempts The maximum number of attempts; must be greater + * than zero. + */ + void set_max_attempts(int32_t max_attempts); + + /** + * Returns a string representation of this `TransactionOptions` object for + * logging/debugging purposes. + * + * @note the exact string representation is unspecified and subject to + * change; don't rely on the format of the string. + */ + std::string ToString() const; + + /** + * Outputs the string representation of this `TransactionOptions` object to + * the given stream. + * + * @see `ToString()` for comments on the representation format. + */ + friend std::ostream& operator<<(std::ostream&, const TransactionOptions&); + + private: + int32_t max_attempts_ = 5; +}; + +/** Compares two `TransactionOptions` objects for equality. */ +bool operator==(const TransactionOptions&, const TransactionOptions&); + +/** Compares two `TransactionOptions` objects for inequality. */ +inline bool operator!=(const TransactionOptions& lhs, + const TransactionOptions& rhs) { + return !(lhs == rhs); +} + +} // namespace firestore +} // namespace firebase + +#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_TRANSACTION_OPTIONS_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/write_batch.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/write_batch.h new file mode 100644 index 000000000000..1e92cd693516 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/write_batch.h @@ -0,0 +1,188 @@ +/* + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_WRITE_BATCH_H_ +#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_WRITE_BATCH_H_ + +#include "firebase/firestore/map_field_value.h" +#include "firebase/firestore/set_options.h" + +namespace firebase { + +/// @cond FIREBASE_APP_INTERNAL +template +class Future; +/// @endcond + +namespace firestore { + +class DocumentReference; +class WriteBatchInternal; + +/** + * @brief A write batch is used to perform multiple writes as a single atomic + * unit. + * + * A WriteBatch object provides methods for adding writes to the write batch. + * None of the writes will be committed (or visible locally) until Commit() is + * called. + * + * Unlike transactions, write batches are persisted offline and therefore are + * preferable when you don't need to condition your writes on read data. + * + * @note Firestore classes are not meant to be subclassed except for use in test + * mocks. Subclassing is not supported in production code and new SDK releases + * may break code that does so. + */ +class WriteBatch { + public: + /** + * @brief Creates an invalid WriteBatch that has to be reassigned before it + * can be used. + * + * Calling any member function on an invalid WriteBatch will be a no-op. If + * the function returns a value, it will return a zero, empty, or invalid + * value, depending on the type of the value. + */ + WriteBatch(); + + /** + * @brief Copy constructor. + * + * This performs a deep copy, creating an independent instance. + * + * @param[in] other `WriteBatch` to copy from. + */ + WriteBatch(const WriteBatch& other); + + /** + * @brief Move constructor. + * + * Moving is more efficient than copying for a `WriteBatch`. After being moved + * from, a `WriteBatch` is equivalent to its default-constructed state. + * + * @param[in] other `WriteBatch` to move data from. + */ + WriteBatch(WriteBatch&& other); + + virtual ~WriteBatch(); + + /** + * @brief Copy assignment operator. + * + * This performs a deep copy, creating an independent instance. + * + * @param[in] other `WriteBatch` to copy from. + * + * @return Reference to the destination `WriteBatch`. + */ + WriteBatch& operator=(const WriteBatch& other); + + /** + * @brief Move assignment operator. + * + * Moving is more efficient than copying for a `WriteBatch`. After being moved + * from, a `WriteBatch` is equivalent to its default-constructed state. + * + * @param[in] other `WriteBatch` to move data from. + * + * @return Reference to the destination `WriteBatch`. + */ + WriteBatch& operator=(WriteBatch&& other); + + /** + * @brief Writes to the document referred to by the provided reference. + * + * If the document does not yet exist, it will be created. If you pass + * SetOptions, the provided data can be merged into an existing document. + * + * @param document The DocumentReference to write to. + * @param data A map of the fields and values to write to the document. + * @param[in] options An object to configure the Set() behavior (optional). + * + * @return This WriteBatch instance. Used for chaining method calls. + */ + virtual WriteBatch& Set(const DocumentReference& document, + const MapFieldValue& data, + const SetOptions& options = SetOptions()); + + /** + * Updates fields in the document referred to by the provided reference. If no + * document exists yet, the update will fail. + * + * @param document The DocumentReference to update. + * @param data A map of field / value pairs to update. Fields can contain dots + * to reference nested fields within the document. + * @return This WriteBatch instance. Used for chaining method calls. + */ + virtual WriteBatch& Update(const DocumentReference& document, + const MapFieldValue& data); + + /** + * Updates fields in the document referred to by the provided reference. If no + * document exists yet, the update will fail. + * + * @param document The DocumentReference to update. + * @param data A map from FieldPath to FieldValue to update. + * @return This WriteBatch instance. Used for chaining method calls. + */ + virtual WriteBatch& Update(const DocumentReference& document, + const MapFieldPathValue& data); + + /** + * Deletes the document referred to by the provided reference. + * + * @param document The DocumentReference to delete. + * @return This WriteBatch instance. Used for chaining method calls. + */ + virtual WriteBatch& Delete(const DocumentReference& document); + + /** + * Commits all of the writes in this write batch as a single atomic unit. + * + * @return A Future that will be resolved when the write finishes. + */ + virtual Future Commit(); + + /** + * @brief Returns true if this `WriteBatch` is valid, false if it is not + * valid. An invalid `WriteBatch` could be the result of: + * - Creating a `WriteBatch` using the default constructor. + * - Moving from the `WriteBatch`. + * - Deleting your Firestore instance, which will invalidate all the + * `WriteBatch` instances associated with it. + * + * @return true if this `WriteBatch` is valid, false if this `WriteBatch` is + * invalid. + */ + bool is_valid() const { return internal_ != nullptr; } + + private: + friend class FirestoreInternal; + friend class WriteBatchInternal; + friend struct ConverterImpl; + template + friend struct CleanupFn; + + explicit WriteBatch(WriteBatchInternal* internal); + + mutable WriteBatchInternal* internal_ = nullptr; +}; + +} // namespace firestore +} // namespace firebase + +#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_WRITE_BATCH_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/functions.h b/packages/firebase_core/firebase_core/firebase_core/firebase/functions.h new file mode 100644 index 000000000000..500a05cc7ae9 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/functions.h @@ -0,0 +1,115 @@ +// Copyright 2017 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef FIREBASE_FUNCTIONS_SRC_INCLUDE_FIREBASE_FUNCTIONS_H_ +#define FIREBASE_FUNCTIONS_SRC_INCLUDE_FIREBASE_FUNCTIONS_H_ + +#include + +#include "firebase/app.h" +#include "firebase/functions/callable_reference.h" +#include "firebase/functions/callable_result.h" +#include "firebase/functions/common.h" + +namespace firebase { + +/// Namespace for the Firebase C++ SDK for Cloud Functions. +namespace functions { + +/// @cond FIREBASE_APP_INTERNAL +namespace internal { +class FunctionsInternal; +} // namespace internal +/// @endcond + +class FunctionsReference; + +#ifndef SWIG +/// @brief Entry point for the Firebase C++ SDK for Cloud Functions. +/// +/// To use the SDK, call firebase::functions::Functions::GetInstance() to +/// obtain an instance of Functions, then use GetHttpsCallable() to obtain +/// references to callable functions. From there you can call them with +/// CallableReference::Call(). +#endif // SWIG +class Functions { + public: + /// @brief Destructor. You may delete an instance of Functions when + /// you are finished using it, to shut down the Functions library. + ~Functions(); + + /// @brief Get an instance of Functions corresponding to the given App. + /// + /// Cloud Functions uses firebase::App to communicate with Firebase + /// Authentication to authenticate users to the server backend. + /// + /// @param[in] app An instance of firebase::App. Cloud Functions will use + /// this to communicate with Firebase Authentication. + /// @param[out] init_result_out Optional: If provided, write the init result + /// here. Will be set to kInitResultSuccess if initialization succeeded, or + /// kInitResultFailedMissingDependency on Android if Google Play services is + /// not available on the current device. + /// + /// @returns An instance of Functions corresponding to the given App. + static Functions* GetInstance(::firebase::App* app, + InitResult* init_result_out = nullptr); + + /// @brief Get an instance of Functions corresponding to the given App. + /// + /// Cloud Functions uses firebase::App to communicate with Firebase + /// Authentication to authenticate users to the server backend. + /// + /// @param[in] app An instance of firebase::App. Cloud Functions will use + /// this to communicate with Firebase Authentication. + /// @param[in] region The region to call functions in. + /// @param[out] init_result_out Optional: If provided, write the init result + /// here. Will be set to kInitResultSuccess if initialization succeeded, or + /// kInitResultFailedMissingDependency on Android if Google Play services is + /// not available on the current device. + /// + /// @returns An instance of Functions corresponding to the given App. + static Functions* GetInstance(::firebase::App* app, const char* region, + InitResult* init_result_out = nullptr); + + /// @brief Get the firebase::App that this Functions was created with. + /// + /// @returns The firebase::App this Functions was created with. + ::firebase::App* app(); + + /// @brief Get a FunctionsReference for the specified path. + HttpsCallableReference GetHttpsCallable(const char* name) const; + + /// @brief Get a FunctionsReference for the specified URL. + HttpsCallableReference GetHttpsCallableFromURL(const char* url) const; + + /// @brief Sets an origin for a Cloud Functions emulator to use. + void UseFunctionsEmulator(const char* origin); + + private: + /// @cond FIREBASE_APP_INTERNAL + Functions(::firebase::App* app, const char* region); + Functions(const Functions& src); + Functions& operator=(const Functions& src); + + // Delete the internal_ data. + void DeleteInternal(); + + internal::FunctionsInternal* internal_; + /// @endcond +}; + +} // namespace functions +} // namespace firebase + +#endif // FIREBASE_FUNCTIONS_SRC_INCLUDE_FIREBASE_FUNCTIONS_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/functions/callable_reference.h b/packages/firebase_core/firebase_core/firebase_core/firebase/functions/callable_reference.h new file mode 100644 index 000000000000..9641c23564df --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/functions/callable_reference.h @@ -0,0 +1,124 @@ +// Copyright 2017 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef FIREBASE_FUNCTIONS_SRC_INCLUDE_FIREBASE_FUNCTIONS_CALLABLE_REFERENCE_H_ +#define FIREBASE_FUNCTIONS_SRC_INCLUDE_FIREBASE_FUNCTIONS_CALLABLE_REFERENCE_H_ + +#include +#include + +#include "firebase/future.h" +#include "firebase/internal/common.h" + +namespace firebase { +class Variant; + +namespace functions { +class Functions; +class HttpsCallableResult; + +/// @cond FIREBASE_APP_INTERNAL +namespace internal { +class HttpsCallableReferenceInternal; +} // namespace internal +/// @endcond + +#ifndef SWIG +/// Represents a reference to a Cloud Functions object. +/// Developers can call HTTPS Callable Functions. +#endif // SWIG +class HttpsCallableReference { + public: + /// @brief Default constructor. This creates an invalid + /// HttpsCallableReference. Attempting to perform any operations on this + /// reference will fail unless a valid HttpsCallableReference has been + /// assigned to it. + HttpsCallableReference() : internal_(nullptr) {} + + ~HttpsCallableReference(); + + /// @brief Copy constructor. It's totally okay (and efficient) to copy + /// HttpsCallableReference instances, as they simply point to the same + /// location. + /// + /// @param[in] reference HttpsCallableReference to copy from. + HttpsCallableReference(const HttpsCallableReference& reference); + + /// @brief Copy assignment operator. It's totally okay (and efficient) to copy + /// HttpsCallableReference instances, as they simply point to the same + /// location. + /// + /// @param[in] reference HttpsCallableReference to copy from. + /// + /// @returns Reference to the destination HttpsCallableReference. + HttpsCallableReference& operator=(const HttpsCallableReference& reference); + +#if defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) + /// @brief Move constructor. Moving is an efficient operation for + /// HttpsCallableReference instances. + /// + /// @param[in] other HttpsCallableReference to move data from. + HttpsCallableReference(HttpsCallableReference&& other); + + /// @brief Move assignment operator. Moving is an efficient operation for + /// HttpsCallableReference instances. + /// + /// @param[in] other HttpsCallableReference to move data from. + /// + /// @returns Reference to the destination HttpsCallableReference. + HttpsCallableReference& operator=(HttpsCallableReference&& other); +#endif // defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) + + /// @brief Gets the firebase::functions::Functions instance to which we refer. + /// + /// The pointer will remain valid indefinitely. + /// + /// @returns The firebase::functions::Functions instance that this + /// HttpsCallableReference refers to. + Functions* functions(); + + /// @brief Calls the function. + /// + /// @returns The result of the call; + Future Call(); + + /// @brief Calls the function. + /// + /// @param[in] data The params to pass to the function. + /// @returns The result of the call; + Future Call(const Variant& data); + + /// @brief Returns true if this HttpsCallableReference is valid, false if it + /// is not valid. An invalid HttpsCallableReference indicates that the + /// reference is uninitialized (created with the default constructor) or that + /// there was an error retrieving the reference. + /// + /// @returns true if this HttpsCallableReference is valid, false if this + /// HttpsCallableReference is invalid. + bool is_valid() const; + + private: + /// @cond FIREBASE_APP_INTERNAL + friend class Functions; + + HttpsCallableReference(internal::HttpsCallableReferenceInternal* internal); + + internal::HttpsCallableReferenceInternal* internal_; + /// @endcond +}; + +} // namespace functions +} // namespace firebase + +#endif // FIREBASE_FUNCTIONS_SRC_INCLUDE_FIREBASE_FUNCTIONS_CALLABLE_REFERENCE_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/functions/callable_result.h b/packages/firebase_core/firebase_core/firebase_core/firebase/functions/callable_result.h new file mode 100644 index 000000000000..5186377ae828 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/functions/callable_result.h @@ -0,0 +1,96 @@ +// Copyright 2018 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef FIREBASE_FUNCTIONS_SRC_INCLUDE_FIREBASE_FUNCTIONS_CALLABLE_RESULT_H_ +#define FIREBASE_FUNCTIONS_SRC_INCLUDE_FIREBASE_FUNCTIONS_CALLABLE_RESULT_H_ + +#include "firebase/functions/common.h" +#include "firebase/variant.h" + +namespace firebase { +namespace functions { + +/// @cond FIREBASE_APP_INTERNAL +namespace internal { +class HttpsCallableReferenceInternal; +} +/// @endcond + +/// An HttpsCallableResult contains the result of calling an HttpsCallable. +class HttpsCallableResult { + public: + /// @brief Creates an HttpsCallableResult with null data. + HttpsCallableResult() {} + + ~HttpsCallableResult() {} + + /// @brief Copy constructor. Copying is as efficient as copying a Variant. + /// + /// @param[in] other HttpsCallableResult to copy data from. + HttpsCallableResult(const HttpsCallableResult& other) : data_(other.data_) {} + + /// @brief Assignment operator. Copying is as efficient as copying a Variant. + /// + /// @param[in] other HttpsCallableResult to copy data from. + /// + /// @returns Reference to the destination HttpsCallableResult. + HttpsCallableResult& operator=(const HttpsCallableResult& other) { + data_ = other.data_; + return *this; + } + +#if defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) + /// @brief Move constructor. Moving is an efficient operation for + /// HttpsCallableResult instances. + /// + /// @param[in] other HttpsCallableResult to move data from. + HttpsCallableResult(HttpsCallableResult&& other) { + data_ = std::move(other.data_); + } + + /// @brief Move assignment operator. Moving is an efficient operation for + /// HttpsCallableResult instances. + /// + /// @param[in] other HttpsCallableResult to move data from. + /// + /// @returns Reference to the destination HttpsCallableResult. + HttpsCallableResult& operator=(HttpsCallableResult&& other) { + data_ = std::move(other.data_); + return *this; + } + +#endif // defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) + + /// @brief Returns the data that is the result of a Call. + /// + /// @returns The variant containing the data. + const Variant& data() const { return data_; } + + private: + /// @cond FIREBASE_APP_INTERNAL + // Only functions are allowed to construct results. + friend class ::firebase::functions::internal::HttpsCallableReferenceInternal; + HttpsCallableResult(const Variant& data) : data_(data) {} +#if defined(FIREBASE_USE_MOVE_OPERATORS) + HttpsCallableResult(Variant&& data) : data_(std::move(data)) {} +#endif // defined(FIREBASE_USE_MOVE_OPERATORS) + + Variant data_; + /// @endcond +}; + +} // namespace functions +} // namespace firebase + +#endif // FIREBASE_FUNCTIONS_SRC_INCLUDE_FIREBASE_FUNCTIONS_CALLABLE_RESULT_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/functions/common.h b/packages/firebase_core/firebase_core/firebase_core/firebase/functions/common.h new file mode 100644 index 000000000000..143dc8257618 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/functions/common.h @@ -0,0 +1,202 @@ +// Copyright 2017 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef FIREBASE_FUNCTIONS_SRC_INCLUDE_FIREBASE_FUNCTIONS_COMMON_H_ +#define FIREBASE_FUNCTIONS_SRC_INCLUDE_FIREBASE_FUNCTIONS_COMMON_H_ + +#include "firebase/variant.h" + +namespace firebase { +namespace functions { + +/// Error code returned by Cloud Functions C++ functions. +/// Standard gRPC error codes, as defined in: +/// https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto +enum Error { +#ifdef INTERNAL_EXPERIMENTAL +// LINT.IfChange +#endif // INTERNAL_EXPERIMENTAL + + // Not an error; returned on success + // + // HTTP Mapping: 200 OK + kErrorNone = 0, + + // The operation was cancelled, typically by the caller. + // + // HTTP Mapping: 499 Client Closed Request + kErrorCancelled = 1, + + // Unknown error. For example, this error may be returned when + // a `Status` value received from another address space belongs to + // an error space that is not known in this address space. Also + // errors raised by APIs that do not return enough error information + // may be converted to this error. + // + // HTTP Mapping: 500 Internal Server Error + kErrorUnknown = 2, + + // The client specified an invalid argument. Note that this differs + // from `FAILED_PRECONDITION`. `INVALID_ARGUMENT` indicates arguments + // that are problematic regardless of the state of the system + // (e.g., a malformed file name). + // + // HTTP Mapping: 400 Bad Request + kErrorInvalidArgument = 3, + + // The deadline expired before the operation could complete. For operations + // that change the state of the system, this error may be returned + // even if the operation has completed successfully. For example, a + // successful response from a server could have been delayed long + // enough for the deadline to expire. + // + // HTTP Mapping: 504 Gateway Timeout + kErrorDeadlineExceeded = 4, + + // Some requested entity (e.g., file or directory) was not found. + // + // Note to server developers: if a request is denied for an entire class + // of users, such as gradual feature rollout or undocumented whitelist, + // `NOT_FOUND` may be used. If a request is denied for some users within + // a class of users, such as user-based access control, `PERMISSION_DENIED` + // must be used. + // + // HTTP Mapping: 404 Not Found + kErrorNotFound = 5, + + // The entity that a client attempted to create (e.g., file or directory) + // already exists. + // + // HTTP Mapping: 409 Conflict + kErrorAlreadyExists = 6, + + // The caller does not have permission to execute the specified + // operation. `PERMISSION_DENIED` must not be used for rejections + // caused by exhausting some resource (use `RESOURCE_EXHAUSTED` + // instead for those errors). `PERMISSION_DENIED` must not be + // used if the caller can not be identified (use `UNAUTHENTICATED` + // instead for those errors). This error code does not imply the + // request is valid or the requested entity exists or satisfies + // other pre-conditions. + // + // HTTP Mapping: 403 Forbidden + kErrorPermissionDenied = 7, + + // The request does not have valid authentication credentials for the + // operation. + // + // HTTP Mapping: 401 Unauthorized + kErrorUnauthenticated = 16, + + // Some resource has been exhausted, perhaps a per-user quota, or + // perhaps the entire file system is out of space. + // + // HTTP Mapping: 429 Too Many Requests + kErrorResourceExhausted = 8, + + // The operation was rejected because the system is not in a state + // required for the operation's execution. For example, the directory + // to be deleted is non-empty, an rmdir operation is applied to + // a non-directory, etc. + // + // Service implementors can use the following guidelines to decide + // between `FAILED_PRECONDITION`, `ABORTED`, and `UNAVAILABLE`: + // (a) Use `UNAVAILABLE` if the client can retry just the failing call. + // (b) Use `ABORTED` if the client should retry at a higher level + // (e.g., when a client-specified test-and-set fails, indicating the + // client should restart a read-modify-write sequence). + // (c) Use `FAILED_PRECONDITION` if the client should not retry until + // the system state has been explicitly fixed. E.g., if an "rmdir" + // fails because the directory is non-empty, `FAILED_PRECONDITION` + // should be returned since the client should not retry unless + // the files are deleted from the directory. + // + // HTTP Mapping: 400 Bad Request + kErrorFailedPrecondition = 9, + + // The operation was aborted, typically due to a concurrency issue such as + // a sequencer check failure or transaction abort. + // + // See the guidelines above for deciding between `FAILED_PRECONDITION`, + // `ABORTED`, and `UNAVAILABLE`. + // + // HTTP Mapping: 409 Conflict + kErrorAborted = 10, + + // The operation was attempted past the valid range. E.g., seeking or + // reading past end-of-file. + // + // Unlike `INVALID_ARGUMENT`, this error indicates a problem that may + // be fixed if the system state changes. For example, a 32-bit file + // system will generate `INVALID_ARGUMENT` if asked to read at an + // offset that is not in the range [0,2^32-1], but it will generate + // `OUT_OF_RANGE` if asked to read from an offset past the current + // file size. + // + // There is a fair bit of overlap between `FAILED_PRECONDITION` and + // `OUT_OF_RANGE`. We recommend using `OUT_OF_RANGE` (the more specific + // error) when it applies so that callers who are iterating through + // a space can easily look for an `OUT_OF_RANGE` error to detect when + // they are done. + // + // HTTP Mapping: 400 Bad Request + kErrorOutOfRange = 11, + + // The operation is not implemented or is not supported/enabled in this + // service. + // + // HTTP Mapping: 501 Not Implemented + kErrorUnimplemented = 12, + + // Internal errors. This means that some invariants expected by the + // underlying system have been broken. This error code is reserved + // for serious errors. + // + // HTTP Mapping: 500 Internal Server Error + kErrorInternal = 13, + + // The service is currently unavailable. This is most likely a + // transient condition, which can be corrected by retrying with + // a backoff. + // + // See the guidelines above for deciding between `FAILED_PRECONDITION`, + // `ABORTED`, and `UNAVAILABLE`. + // + // HTTP Mapping: 503 Service Unavailable + kErrorUnavailable = 14, + + // Unrecoverable data loss or corruption. + // + // HTTP Mapping: 500 Internal Server Error + kErrorDataLoss = 15, + +}; + +#ifdef INTERNAL_EXPERIMENTAL +/// @cond FIREBASE_APP_INTERNAL +namespace internal { + +// Get the human-readable error message corresponding to an error code. +// +// Returns a statically-allocated string describing the error code you pass in. +const char* GetErrorMessage(Error error); + +} // namespace internal +/// @endcond +#endif // INTERNAL_EXPERIMENTAL + +} // namespace functions +} // namespace firebase + +#endif // FIREBASE_FUNCTIONS_SRC_INCLUDE_FIREBASE_FUNCTIONS_COMMON_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/future.h b/packages/firebase_core/firebase_core/firebase_core/firebase/future.h new file mode 100644 index 000000000000..0d09fc079a32 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/future.h @@ -0,0 +1,533 @@ +/* + * Copyright 2016 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_APP_SRC_INCLUDE_FIREBASE_FUTURE_H_ +#define FIREBASE_APP_SRC_INCLUDE_FIREBASE_FUTURE_H_ + +#include +#include + +#include + +#include "firebase/internal/common.h" +#include "firebase/internal/mutex.h" + +#ifdef FIREBASE_USE_STD_FUNCTION +#include +#endif + +namespace firebase { + +// Predeclarations. +/// @cond FIREBASE_APP_INTERNAL +namespace detail { +class FutureApiInterface; +class CompletionCallbackHandle; +} // namespace detail +/// @endcond + +/// Asynchronous call status. +enum FutureStatus { + /// Results are ready. + kFutureStatusComplete, + + /// Result is still being processed. + kFutureStatusPending, + + /// No result is pending. + /// FutureBase::Release() or move operator was called. + kFutureStatusInvalid +}; + +/// Handle that the API uses to identify an asynchronous call. +/// The exact interpretation of the handle is up to the API. +typedef uintptr_t FutureHandleId; + +/// Class that provides more context to FutureHandleId, which allows the +/// underlying API to track handles, perform reference counting, etc. +class FutureHandle { + public: + /// @cond FIREBASE_APP_INTERNAL + FutureHandle(); + explicit FutureHandle(FutureHandleId id) : FutureHandle(id, nullptr) {} + FutureHandle(FutureHandleId id, detail::FutureApiInterface* api); + ~FutureHandle(); + + // Copy constructor and assignment operator. + FutureHandle(const FutureHandle& rhs); + FutureHandle& operator=(const FutureHandle& rhs); + +#if defined(FIREBASE_USE_MOVE_OPERATORS) + // Move constructor and assignment operator. + FutureHandle(FutureHandle&& rhs) noexcept; + FutureHandle& operator=(FutureHandle&& rhs) noexcept; +#endif // defined(FIREBASE_USE_MOVE_OPERATORS) + + // Comparison operators. + bool operator!=(const FutureHandle& rhs) const { return !(*this == rhs); } + bool operator==(const FutureHandle& rhs) const { + // Only compare IDs, since the API is irrelevant (comparison will only occur + // within the context of a single API anyway). + return id() == rhs.id(); + } + + FutureHandleId id() const { return id_; } + detail::FutureApiInterface* api() const { return api_; } + + // Detach from the FutureApi. This handle will no longer increment the + // Future's reference count. This is mainly used for testing, so that you can + // still look up the Future based on its handle's ID without affecting the + // reference count yourself. + void Detach(); + + // Called by CleanupNotifier when the API is being deleted. At this point we + // can ignore all of the reference counts since all Future data is about to be + // deleted anyway. + void Cleanup() { api_ = nullptr; } + + private: + FutureHandleId id_; + detail::FutureApiInterface* api_; + /// @endcond +}; + +/// @brief Type-independent return type of asynchronous calls. +/// +/// @see Future for code samples. +/// +/// @cond FIREBASE_APP_INTERNAL +/// Notes: +/// - Futures have pointers back to the API, but the API does not maintain +/// pointers to its Futures. Therefore, all Futures must be destroyed +/// *before* the API is destroyed. +/// - Futures can be moved or copied. Call results are reference counted, +/// and are destroyed when they are no longer referenced by any Futures. +/// - The actual `Status`, `Error`, and `Result` values are kept inside the +/// API. This makes synchronization and data management easier. +/// +/// WARNING: This class should remain POD (plain old data). It should not have +/// virtual methods. Nor should the derived Future class add any +/// data. Internally, we static_cast FutureBase to Future, +/// so the underlying data should remain the same. +/// @endcond +class FutureBase { + public: + /// Function pointer for a completion callback. When we call this, we will + /// send the completed future, along with the user data that you specified + /// when you set up the callback. + typedef void (*CompletionCallback)(const FutureBase& result_data, + void* user_data); + +#if defined(INTERNAL_EXPERIMENTAL) + /// Handle, representing a completion callback, that can be passed to + /// RemoveOnCompletion. + using CompletionCallbackHandle = detail::CompletionCallbackHandle; +#endif + + /// Construct an untyped future. + FutureBase(); + + /// @cond FIREBASE_APP_INTERNAL + + /// Construct an untyped future using the specified API and handle. + /// + /// @param api API class used to provide the future implementation. + /// @param handle Handle to the future. + FutureBase(detail::FutureApiInterface* api, const FutureHandle& handle); + + /// @endcond + + ~FutureBase(); + + /// Copy constructor and operator. + /// Increment the reference count when creating a copy of the future. + FutureBase(const FutureBase& rhs); + + /// Copy an untyped future. + FutureBase& operator=(const FutureBase& rhs); + +#if defined(FIREBASE_USE_MOVE_OPERATORS) + /// Move constructor and operator. + /// Move is more efficient than copy and delete because we don't touch the + /// reference counting in the API. + FutureBase(FutureBase&& rhs) noexcept; + + /// Copy an untyped future. + FutureBase& operator=(FutureBase&& rhs) noexcept; +#endif // defined(FIREBASE_USE_MOVE_OPERATORS) + + /// Explicitly release the internal resources for a future. + /// Future will become invalid. + void Release(); + + /// Completion status of the asynchronous call. + FutureStatus status() const; + + /// When status() is firebase::kFutureStatusComplete, returns the API-defined + /// error code. Otherwise, return value is undefined. + int error() const; + + /// When status() is firebase::kFutureStatusComplete, returns the API-defined + /// error message, as human-readable text, or an empty string if the API does + /// not provide a human readable description of the error. + /// + /// @note The returned pointer is only valid for the lifetime of the Future + /// or its copies. + const char* error_message() const; + + /// Result of the asynchronous call, or nullptr if the result is still + /// pending. Cast is required since GetFutureResult() returns void*. + const void* result_void() const; + +#if defined(INTERNAL_EXPERIMENTAL) + /// Special timeout value indicating an infinite timeout. + /// + /// Passing this value to FutureBase::Wait() or Future::Await() will cause + /// those methods to wait until the future is complete. + /// + /// @Warning It is inadvisable to use this from code that could be called + /// from an event loop. + static const int kWaitTimeoutInfinite; + + /// Block (i.e. suspend the current thread) until either the future is + /// completed or the specified timeout period (in milliseconds) has elapsed. + /// If `timeout_milliseconds` is `kWaitTimeoutInfinite`, then the timeout + /// period is treated as being infinite, i.e. this will block until the + /// future is completed. + /// + /// @return True if the future completed, or + /// false if the timeout period elapsed before the future completed. + bool Wait(int timeout_milliseconds) const; +#endif // defined(INTERNAL_EXPERIMENTAL) + + /// Register a single callback that will be called at most once, when the + /// future is completed. + /// + /// If you call any OnCompletion() method more than once on the same future, + /// only the most recent callback you registered with OnCompletion() will be + /// called. +#if defined(INTERNAL_EXPERIMENTAL) + /// However completions registered with AddCompletion() will still be + /// called even if there is a subsequent call to OnCompletion(). + /// + /// When the future completes, first the most recent callback registered with + /// OnCompletion(), if any, will be called; then all callbacks registered with + /// AddCompletion() will be called, in the order that they were registered. +#endif + /// + /// When your callback is called, the user_data that you supplied here will be + /// passed back as the second parameter. + /// + /// @param[in] callback Function pointer to your callback. + /// @param[in] user_data Optional user data. We will pass this back to your + /// callback. + void OnCompletion(CompletionCallback callback, void* user_data) const; + +#if defined(FIREBASE_USE_STD_FUNCTION) || defined(DOXYGEN) + /// Register a single callback that will be called at most once, when the + /// future is completed. + /// + /// If you call any OnCompletion() method more than once on the same future, + /// only the most recent callback you registered with OnCompletion() will be + /// called. +#if defined(INTERNAL_EXPERIMENTAL) + /// However completions registered with AddCompletion() will still be + /// called even if there is a subsequent call to OnCompletion(). + /// + /// When the future completes, first the most recent callback registered with + /// OnCompletion(), if any, will be called; then all callbacks registered with + /// AddCompletion() will be called, in the order that they were registered. +#endif + /// + /// @param[in] callback Function or lambda to call. + /// + /// @note This method is not available when using STLPort on Android, as + /// `std::function` is not supported on STLPort. + void OnCompletion(std::function callback) const; +#endif // defined(FIREBASE_USE_STD_FUNCTION) || defined(DOXYGEN) + +#if defined(INTERNAL_EXPERIMENTAL) + /// Like OnCompletion, but allows adding multiple callbacks. + /// + /// If you call AddCompletion() more than once, all of the completions that + /// you register will be called, when the future is completed. However, any + /// callbacks which were subsequently removed by calling RemoveOnCompletion + /// will not be called. + /// + /// When the future completes, first the most recent callback registered with + /// OnCompletion(), if any, will be called; then all callbacks registered with + /// AddCompletion() will be called, in the order that they were registered. + /// + /// @param[in] callback Function pointer to your callback. + /// @param[in] user_data Optional user data. We will pass this back to your + /// callback. + /// @return A handle that can be passed to RemoveOnCompletion. + CompletionCallbackHandle AddOnCompletion(CompletionCallback callback, + void* user_data) const; + +#if defined(FIREBASE_USE_STD_FUNCTION) || defined(DOXYGEN) + /// Like OnCompletion, but allows adding multiple callbacks. + /// + /// If you call AddCompletion() more than once, all of the completions that + /// you register will be called, when the future is completed. However, any + /// callbacks which were subsequently removed by calling RemoveOnCompletion + /// will not be called. + /// + /// When the future completes, first the most recent callback registered with + /// OnCompletion(), if any, will be called; then all callbacks registered with + /// AddCompletion() will be called, in the order that they were registered. + /// + /// @param[in] callback Function or lambda to call. + /// @return A handle that can be passed to RemoveOnCompletion. + /// + /// @note This method is not available when using STLPort on Android, as + /// `std::function` is not supported on STLPort. + CompletionCallbackHandle AddOnCompletion( + std::function callback) const; + +#endif // defined(FIREBASE_USE_STD_FUNCTION) || defined(DOXYGEN) + + /// Unregisters a callback that was previously registered with + /// AddOnCompletion. + /// + /// @param[in] completion_handle The return value of a previous call to + /// AddOnCompletion. + void RemoveOnCompletion(CompletionCallbackHandle completion_handle) const; +#endif // defined(INTERNAL_EXPERIMENTAL) + + /// Returns true if the two Futures reference the same result. + bool operator==(const FutureBase& rhs) const { + MutexLock lock(mutex_); + return api_ == rhs.api_ && handle_ == rhs.handle_; + } + + /// Returns true if the two Futures reference different results. + bool operator!=(const FutureBase& rhs) const { return !operator==(rhs); } + +#if defined(INTERNAL_EXPERIMENTAL) + /// Returns the API-specific handle. Should only be called by the API. + FutureHandle GetHandle() const { + MutexLock lock(mutex_); + return handle_; + } +#endif // defined(INTERNAL_EXPERIMENTAL) + + protected: + /// @cond FIREBASE_APP_INTERNAL + + mutable Mutex mutex_; + + /// Backpointer to the issuing API class. + /// Set to nullptr when Future is invalidated. + detail::FutureApiInterface* api_; + + /// API-specified handle type. + FutureHandle handle_; + + /// @endcond +}; + +/// @brief Type-specific version of FutureBase. +/// +/// The Firebase C++ SDK uses this class to return results from asynchronous +/// operations. All Firebase C++ functions and method calls that operate +/// asynchronously return a Future, and provide a "LastResult" function to +/// retrieve the most recent Future result. +/// +/// @code +/// // You can retrieve the Future from the function call directly, like this: +/// Future< SampleResultType > future = firebase::SampleAsyncOperation(); +/// +/// // Or you can retrieve it later, like this: +/// firebase::SampleAsyncOperation(); +/// // [...] +/// Future< SampleResultType > future = +/// firebase::SampleAsyncOperationLastResult(); +/// @endcode +/// +/// When you have a Future from an asynchronous operation, it will eventually +/// complete. Once it is complete, you can check for errors (a nonzero error() +/// means an error occurred) and get the result data if no error occurred by +/// calling result(). +/// +/// There are two ways to find out that a Future has completed. You can poll +/// its status(), or set an OnCompletion() callback: +/// +/// @code +/// // Check whether the status is kFutureStatusComplete. +/// if (future.status() == firebase::kFutureStatusComplete) { +/// if (future.error() == 0) { +/// DoSomethingWithResultData(future.result()); +/// } +/// else { +/// LogMessage("Error %d: %s", future.error(), future.error_message()); +/// } +/// } +/// +/// // Or, set an OnCompletion callback, which accepts a C++11 lambda or +/// // function pointer. You can pass your own user data to the callback. In +/// // most cases, the callback will be running in a different thread, so take +/// // care to make sure your code is thread-safe. +/// future.OnCompletion([](const Future< SampleResultType >& completed_future, +/// void* user_data) { +/// // We are probably in a different thread right now. +/// if (completed_future.error() == 0) { +/// DoSomethingWithResultData(completed_future.result()); +/// } +/// else { +/// LogMessage("Error %d: %s", +/// completed_future.error(), +/// completed_future.error_message()); +/// } +/// }, user_data); +/// @endcode +/// +/// @tparam ResultType The type of this Future's result. +// +// WARNING: This class should not have virtual methods or data members. +// See the warning in FutureBase for further details. +template +class Future : public FutureBase { + public: + /// Function pointer for a completion callback. When we call this, we will + /// send the completed future, along with the user data that you specified + /// when you set up the callback. + typedef void (*TypedCompletionCallback)(const Future& result_data, + void* user_data); + + /// Construct a future. + Future() {} + + /// @cond FIREBASE_APP_INTERNAL + + /// Construct a future using the specified API and handle. + /// + /// @param api API class used to provide the future implementation. + /// @param handle Handle to the future. + Future(detail::FutureApiInterface* api, const FutureHandle& handle) + : FutureBase(api, handle) {} + + /// @endcond + + /// Result of the asynchronous call, or nullptr if the result is still + /// pending. Allows the API to provide a type-specific interface. + /// + const ResultType* result() const { + return static_cast(result_void()); + } + +#if defined(INTERNAL_EXPERIMENTAL) + /// Waits (blocks) until either the future is completed, or the specified + /// timeout period (in milliseconds) has elapsed, then returns the result of + /// the asynchronous call. + /// + /// This is a convenience method that calls Wait() and then returns result(). + /// + /// If `timeout_milliseconds` is `kWaitTimeoutInfinite`, then the timeout + /// period is treated as being infinite, i.e. this will block until the + /// future is completed. + const ResultType* Await(int timeout_milliseconds) const { + Wait(timeout_milliseconds); + return result(); + } +#endif // defined(INTERNAL_EXPERIMENTAL) + + /// Register a single callback that will be called at most once, when the + /// future is completed. + /// + /// If you call any OnCompletion() method more than once on the same future, + /// only the most recent callback you registered will be called. + /// + /// When your callback is called, the user_data that you supplied here will be + /// passed back as the second parameter. + /// + /// @param[in] callback Function pointer to your callback. + /// @param[in] user_data Optional user data. We will pass this back to your + /// callback. + /// + /// @note This is the same callback as FutureBase::OnCompletion(), so you + /// can't expect to set both and have both run; again, only the most recently + /// registered one will run. + inline void OnCompletion(TypedCompletionCallback callback, + void* user_data) const; + +#if defined(FIREBASE_USE_STD_FUNCTION) || defined(DOXYGEN) + /// Register a single callback that will be called at most once, when the + /// future is completed. + /// + /// If you call any OnCompletion() method more than once on the same future, + /// only the most recent callback you registered will be called. + /// + /// @param[in] callback Function or lambda to call. + /// + /// @note This method is not available when using STLPort on Android, as + /// `std::function` is not supported on STLPort. + /// + /// @note This is the same callback as FutureBase::OnCompletion(), so you + /// can't expect to set both and have both run; again, only the most recently + /// registered one will run. + inline void OnCompletion( + std::function&)> callback) const; +#endif // defined(FIREBASE_USE_STD_FUNCTION) || defined(DOXYGEN) + +#if defined(INTERNAL_EXPERIMENTAL) + /// Like OnCompletion, but allows adding multiple callbacks. + /// + /// If you call AddCompletion() more than once, all of the completions that + /// you register will be called, when the future is completed. However, any + /// callbacks which were subsequently removed by calling RemoveOnCompletion + /// will not be called. + /// + /// When the future completes, first the most recent callback registered with + /// OnCompletion(), if any, will be called; then all callbacks registered with + /// AddCompletion() will be called, in the order that they were registered. + /// + /// @param[in] callback Function pointer to your callback. + /// @param[in] user_data Optional user data. We will pass this back to your + /// callback. + /// @return A handle that can be passed to RemoveOnCompletion. + inline CompletionCallbackHandle AddOnCompletion( + TypedCompletionCallback callback, void* user_data) const; + +#if defined(FIREBASE_USE_STD_FUNCTION) || defined(DOXYGEN) + /// Like OnCompletion, but allows adding multiple callbacks. + /// + /// If you call AddCompletion() more than once, all of the completions that + /// you register will be called, when the future is completed. However, any + /// callbacks which were subsequently removed by calling RemoveOnCompletion + /// will not be called. + /// + /// When the future completes, first the most recent callback registered with + /// OnCompletion(), if any, will be called; then all callbacks registered with + /// AddCompletion() will be called, in the order that they were registered. + /// + /// @param[in] callback Function or lambda to call. + /// @return A handle that can be passed to RemoveOnCompletion. + /// + /// @note This method is not available when using STLPort on Android, as + /// `std::function` is not supported on STLPort. + inline CompletionCallbackHandle AddOnCompletion( + std::function&)> callback) const; +#endif // defined(FIREBASE_USE_STD_FUNCTION) || defined(DOXYGEN) +#endif // defined(INTERNAL_EXPERIMENTAL) +}; + +} // namespace firebase + +// Include the inline implementation. +#include "firebase/internal/future_impl.h" + +#endif // FIREBASE_APP_SRC_INCLUDE_FIREBASE_FUTURE_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/gma.h b/packages/firebase_core/firebase_core/firebase_core/firebase/gma.h new file mode 100644 index 000000000000..b7da2cf569b9 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/gma.h @@ -0,0 +1,207 @@ +/* + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_GMA_SRC_INCLUDE_FIREBASE_GMA_H_ +#define FIREBASE_GMA_SRC_INCLUDE_FIREBASE_GMA_H_ + +#include "firebase/internal/platform.h" + +#if FIREBASE_PLATFORM_ANDROID +#include +#endif // FIREBASE_PLATFORM_ANDROID + +#include + +#include "firebase/app.h" +#include "firebase/gma/ad_view.h" +#include "firebase/gma/interstitial_ad.h" +#include "firebase/gma/rewarded_ad.h" +#include "firebase/gma/types.h" +#include "firebase/internal/common.h" + +#if !defined(DOXYGEN) && !defined(SWIG) +FIREBASE_APP_REGISTER_CALLBACKS_REFERENCE(gma) +#endif // !defined(DOXYGEN) && !defined(SWIG) + +namespace firebase { +// In the GMA docs, link to firebase::Future in the Firebase C++ docs. +#if defined(DOXYGEN_ADMOB) +/// @brief The Google Mobile Ads C++ SDK uses this class to return results from +/// asynchronous operations. All C++ functions and method calls that operate +/// asynchronously return a %Future, and provide a "LastResult" +/// function to retrieve the most recent %Future result. +/// +/// The Google Mobile Ads C++ SDK uses this class from the Firebase C++ SDK to +/// return results from asynchronous operations. For more information, see the +/// Firebase +/// C++ SDK documentation. +template +class Future { + // Empty class (used for documentation only). +}; +#endif // defined(DOXYGEN_ADMOB) + +/// @brief API for Google Mobile Ads with Firebase. +/// +/// The GMA API allows you to load and display mobile ads using the Google +/// Mobile Ads SDK. Each ad format has its own header file. +namespace gma { + +/// Initializes Google Mobile Ads (GMA) via Firebase. +/// +/// @param[in] app The Firebase app for which to initialize mobile ads. +/// +/// @param[out] init_result_out Optional: If provided, write the basic init +/// result here. kInitResultSuccess if initialization succeeded, or +/// kInitResultFailedMissingDependency on Android if Google Play services is not +/// available on the current device and the Google Mobile Ads SDK requires +/// Google Play services (for example, when using 'play-services-ads-lite'). +/// Note that this does not include the adapter initialization status, which is +/// returned in the Future. +/// +/// @return If init_result_out is kInitResultSuccess, this Future will contain +/// the initialization status of each adapter once initialization is complete. +/// Otherwise, the returned Future will have kFutureStatusInvalid. +Future Initialize( + const ::firebase::App& app, InitResult* init_result_out = nullptr); + +#if FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) +/// Initializes Google Mobile Ads (GMA) without Firebase for Android. +/// +/// The arguments to @ref Initialize are platform-specific so the caller must do +/// something like this: +/// @code +/// #if defined(__ANDROID__) +/// firebase::gma::Initialize(jni_env, activity); +/// #else +/// firebase::gma::Initialize(); +/// #endif +/// @endcode +/// +/// @param[in] jni_env JNIEnv pointer. +/// @param[in] activity Activity used to start the application. +/// @param[out] init_result_out Optional: If provided, write the basic init +/// result here. kInitResultSuccess if initialization succeeded, or +/// kInitResultFailedMissingDependency on Android if Google Play services is not +/// available on the current device and the Google Mobile Ads SDK requires +/// Google Play services (for example, when using 'play-services-ads-lite'). +/// Note that this does not include the adapter initialization status, which is +/// returned in the Future. +/// +/// @return If init_result_out is kInitResultSuccess, this Future will contain +/// the initialization status of each adapter once initialization is complete. +/// Otherwise, the returned Future will have kFutureStatusInvalid. +Future Initialize( + JNIEnv* jni_env, jobject activity, InitResult* init_result_out = nullptr); + +#endif // defined(__ANDROID__) || defined(DOXYGEN) +#if !FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) +/// Initializes Google Mobile Ads (GMA) without Firebase for iOS. +/// +/// @param[out] init_result_out Optional: If provided, write the basic init +/// result here. kInitResultSuccess if initialization succeeded, or +/// kInitResultFailedMissingDependency on Android if Google Play services is not +/// available on the current device and the Google Mobile Ads SDK requires +/// Google Play services (for example, when using 'play-services-ads-lite'). +/// Note that this does not include the adapter initialization status, which is +/// returned in the Future. +/// +/// @return If init_result_out is kInitResultSuccess, this Future +/// will contain the initialization status of each adapter once initialization +/// is complete. Otherwise, the returned Future will have +/// kFutureStatusInvalid. +Future Initialize( + InitResult* init_result_out = nullptr); +#endif // !defined(__ANDROID__) || defined(DOXYGEN) + +/// Get the Future returned by a previous call to +/// @ref firebase::gma::Initialize(). +Future InitializeLastResult(); + +/// Get the current adapter initialization status. You can poll this method to +/// check which adapters have been initialized. +AdapterInitializationStatus GetInitializationStatus(); + +/// Disables automated SDK crash reporting on iOS. If not called, the SDK +/// records the original exception handler if available and registers a new +/// exception handler. The new exception handler only reports SDK related +/// exceptions and calls the recorded original exception handler. +/// +/// This method has no effect on Android. +void DisableSDKCrashReporting(); + +/// Disables mediation adapter initialization on iOS during initialization of +/// the GMA SDK. Calling this method may negatively impact your ad +/// performance and should only be called if you will not use GMA SDK +/// controlled mediation during this app session. This method must be called +/// before initializing the GMA SDK or loading ads and has no effect once the +/// SDK has been initialized. +/// +/// This method has no effect on Android. +void DisableMediationInitialization(); + +/// Sets the global @ref RequestConfiguration that will be used for +/// every @ref AdRequest during the app's session. +/// +/// @param[in] request_configuration The request configuration that should be +/// applied to all ad requests. +void SetRequestConfiguration(const RequestConfiguration& request_configuration); + +/// Gets the global RequestConfiguration. +/// +/// @return the currently active @ref RequestConfiguration that's being +/// used for every ad request. +/// @note: on iOS, the +/// @ref RequestConfiguration::tag_for_child_directed_treatment and +/// @ref RequestConfiguration::tag_for_under_age_of_consent fields will be set +/// to RequestConfiguration.kChildDirectedTreatmentUnspecified, and +/// RequestConfiguration.kUnderAgeOfConsentUnspecified, respectfully. +RequestConfiguration GetRequestConfiguration(); + +/// Opens the ad inspector UI. +/// +/// @param[in] parent The platform-specific UI element that will host the +/// ad inspector. For iOS this should be the window's +/// UIViewController. For Android this is the +/// Activity Context which the GMA SDK is running in. +/// @param[in] listener The listener will be invoked when the user closes +/// the ad inspector UI. @ref firebase::gma::Initialize(). must be called +/// prior to this function. +void OpenAdInspector(AdParent parent, AdInspectorClosedListener* listener); + +/// Controls whether the Google Mobile Ads SDK Same App Key is enabled. +/// +/// This function must be invoked after GMA has been initialized. The value set +/// persists across app sessions. The key is enabled by default. +/// +/// This operation is supported on iOS only. This is a no-op on Android +/// systems. +/// +/// @param[in] is_enabled whether the Google Mobile Ads SDK Same App Key is +/// enabled. +void SetIsSameAppKeyEnabled(bool is_enabled); + +/// @brief Terminate GMA. +/// +/// Frees resources associated with GMA that were allocated during +/// @ref firebase::gma::Initialize(). +void Terminate(); + +} // namespace gma +} // namespace firebase + +#endif // FIREBASE_GMA_SRC_INCLUDE_FIREBASE_GMA_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/gma/ad_view.h b/packages/firebase_core/firebase_core/firebase_core/firebase/gma/ad_view.h new file mode 100644 index 000000000000..16916a21665f --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/gma/ad_view.h @@ -0,0 +1,267 @@ +/* + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_GMA_SRC_INCLUDE_FIREBASE_GMA_AD_VIEW_H_ +#define FIREBASE_GMA_SRC_INCLUDE_FIREBASE_GMA_AD_VIEW_H_ + +#include "firebase/future.h" +#include "firebase/gma/types.h" +#include "firebase/internal/common.h" + +namespace firebase { +namespace gma { + +namespace internal { +// Forward declaration for platform-specific data, implemented in each library. +class AdViewInternal; +} // namespace internal + +class AdViewBoundingBoxListener; +struct BoundingBox; + +/// @brief Loads and displays Google Mobile Ads AdView ads. +/// +/// Each AdView object corresponds to a single GMA ad placement of a specified +/// size. There are methods to load an ad, move it, show it and hide it, and +/// retrieve the bounds of the ad onscreen. +/// +/// AdView objects provide information about their current state through +/// Futures. Methods like @ref Initialize, @ref LoadAd, and @ref Hide each have +/// a corresponding @ref Future from which the result of the last call can be +/// determined. The two variants of @ref SetPosition share a single result +/// @ref Future, since they're essentially the same action. +/// +/// For example, you could initialize, load, and show an AdView while +/// checking the result of the previous action at each step as follows: +/// +/// @code +/// namespace gma = ::firebase::gma; +/// gma::AdView* ad_view = new gma::AdView(); +/// ad_view->Initialize(ad_parent, "YOUR_AD_UNIT_ID", desired_ad_size) +/// @endcode +/// +/// Then, later: +/// +/// @code +/// if (ad_view->InitializeLastResult().status() == +/// ::firebase::kFutureStatusComplete && +/// ad_view->InitializeLastResult().error() == +/// firebase::gma::kAdErrorCodeNone) { +/// ad_view->LoadAd(your_ad_request); +/// } +/// @endcode +class AdView { + public: + /// The possible screen positions for a @ref AdView, configured via + /// @ref SetPosition. + enum Position { + /// The position isn't one of the predefined screen locations. + kPositionUndefined = -1, + /// Top of the screen, horizontally centered. + kPositionTop = 0, + /// Bottom of the screen, horizontally centered. + kPositionBottom, + /// Top-left corner of the screen. + kPositionTopLeft, + /// Top-right corner of the screen. + kPositionTopRight, + /// Bottom-left corner of the screen. + kPositionBottomLeft, + /// Bottom-right corner of the screen. + kPositionBottomRight, + }; + + /// Creates an uninitialized @ref AdView object. + /// @ref Initialize must be called before the object is used. + AdView(); + + ~AdView(); + + /// Initializes the @ref AdView object. + /// @param[in] parent The platform-specific UI element that will host the ad. + /// @param[in] ad_unit_id The ad unit ID to use when requesting ads. + /// @param[in] size The desired ad size for the ad. + Future Initialize(AdParent parent, const char* ad_unit_id, + const AdSize& size); + + /// Returns a @ref Future that has the status of the last call to + /// @ref Initialize. + Future InitializeLastResult() const; + + /// Begins an asynchronous request for an ad. If successful, the ad will + /// automatically be displayed in the AdView. + /// @param[in] request An AdRequest struct with information about the request + /// to be made (such as targeting info). + Future LoadAd(const AdRequest& request); + + /// Returns a @ref Future containing the status of the last call to + /// @ref LoadAd. + Future LoadAdLastResult() const; + + /// Retrieves the @ref AdView's current onscreen size and location. + /// + /// @return The current size and location. Values are in pixels, and location + /// coordinates originate from the top-left corner of the screen. + BoundingBox bounding_box() const; + + /// Sets an AdListener for this ad view. + /// + /// @param[in] listener An AdListener object which will be invoked + /// when lifecycle events occur on this AdView. + void SetAdListener(AdListener* listener); + + /// Sets a listener to be invoked when the Ad's bounding box + /// changes size or location. + /// + /// @param[in] listener A AdViewBoundingBoxListener object which will be + /// invoked when the ad changes size, shape, or position. + void SetBoundingBoxListener(AdViewBoundingBoxListener* listener); + + /// Sets a listener to be invoked when this ad is estimated to have earned + /// money. + /// + /// @param[in] listener A PaidEventListener object to be invoked when a + /// paid event occurs on the ad. + void SetPaidEventListener(PaidEventListener* listener); + + /// Moves the @ref AdView so that its top-left corner is located at + /// (x, y). Coordinates are in pixels from the top-left corner of the screen. + /// + /// When built for Android, the library will not display an ad on top of or + /// beneath an Activity's status bar. If a call to SetPostion + /// would result in an overlap, the @ref AdView is placed just below the + /// status bar, so no overlap occurs. + /// @param[in] x The desired horizontal coordinate. + /// @param[in] y The desired vertical coordinate. + /// + /// @return a @ref Future which will be completed when this move operation + /// completes. + Future SetPosition(int x, int y); + + /// Moves the @ref AdView so that it's located at the given predefined + /// position. + /// + /// @param[in] position The predefined position to which to move the + /// @ref AdView. + /// + /// @return a @ref Future which will be completed when this move operation + /// completes. + Future SetPosition(Position position); + + /// Returns a @ref Future containing the status of the last call to either + /// version of @ref SetPosition. + Future SetPositionLastResult() const; + + /// Hides the AdView. + Future Hide(); + + /// Returns a @ref Future containing the status of the last call to + /// @ref Hide. + Future HideLastResult() const; + + /// Shows the @ref AdView. + Future Show(); + + /// Returns a @ref Future containing the status of the last call to + /// @ref Show. + Future ShowLastResult() const; + + /// Pauses the @ref AdView. Should be called whenever the C++ engine + /// pauses or the application loses focus. + Future Pause(); + + /// Returns a @ref Future containing the status of the last call to + /// @ref Pause. + Future PauseLastResult() const; + + /// Resumes the @ref AdView after pausing. + Future Resume(); + + /// Returns a @ref Future containing the status of the last call to + /// @ref Resume. + Future ResumeLastResult() const; + + /// Cleans up and deallocates any resources used by the @ref AdView. + /// You must call this asynchronous operation before this object's destructor + /// is invoked or risk leaking device resources. + Future Destroy(); + + /// Returns a @ref Future containing the status of the last call to + /// @ref Destroy. + Future DestroyLastResult() const; + + /// Returns the AdSize of the AdView. + /// + /// @return An @ref AdSize object representing the size of the ad. If this + /// view has not been initialized then the AdSize will be 0,0. + AdSize ad_size() const; + + protected: + /// Pointer to a listener for AdListener events. + AdListener* ad_listener_; + + /// Pointer to a listener for BoundingBox events. + AdViewBoundingBoxListener* ad_view_bounding_box_listener_; + + /// Pointer to a listener for paid events. + PaidEventListener* paid_event_listener_; + + private: + // An internal, platform-specific implementation object that this class uses + // to interact with the Google Mobile Ads SDKs for iOS and Android. + internal::AdViewInternal* internal_; +}; + +/// A listener class that developers can extend and pass to an @ref AdView +/// object's @ref AdView::SetBoundingBoxListener method to be notified of +/// changes to the size of the Ad's bounding box. +class AdViewBoundingBoxListener { + public: + virtual ~AdViewBoundingBoxListener(); + + /// This method is called when the @ref AdView object's bounding box + /// changes. + /// + /// @param[in] ad_view The view whose bounding box changed. + /// @param[in] box The new bounding box. + virtual void OnBoundingBoxChanged(AdView* ad_view, BoundingBox box) = 0; +}; + +/// @brief The screen location and dimensions of an AdView once it has been +/// initialized. +struct BoundingBox { + /// Default constructor which initializes all member variables to 0. + BoundingBox() + : height(0), width(0), x(0), y(0), position(AdView::kPositionUndefined) {} + + /// Height of the ad in pixels. + int height; + /// Width of the ad in pixels. + int width; + /// Horizontal position of the ad in pixels from the left. + int x; + /// Vertical position of the ad in pixels from the top. + int y; + + /// The position of the AdView if one has been set as the target position, or + /// kPositionUndefined otherwise. + AdView::Position position; +}; + +} // namespace gma +} // namespace firebase + +#endif // FIREBASE_GMA_SRC_INCLUDE_FIREBASE_GMA_AD_VIEW_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/gma/interstitial_ad.h b/packages/firebase_core/firebase_core/firebase_core/firebase/gma/interstitial_ad.h new file mode 100644 index 000000000000..4680537178c8 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/gma/interstitial_ad.h @@ -0,0 +1,128 @@ +/* + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_GMA_SRC_INCLUDE_FIREBASE_GMA_INTERSTITIAL_AD_H_ +#define FIREBASE_GMA_SRC_INCLUDE_FIREBASE_GMA_INTERSTITIAL_AD_H_ + +#include "firebase/future.h" +#include "firebase/gma/types.h" +#include "firebase/internal/common.h" + +namespace firebase { +namespace gma { + +namespace internal { +// Forward declaration for platform-specific data, implemented in each library. +class InterstitialAdInternal; +} // namespace internal + +/// @brief Loads and displays Google Mobile Ads interstitial ads. +/// +/// @ref InterstitialAd is a single-use object that can load and show a +/// single GMA interstitial ad. +/// +/// InterstitialAd objects provide information about their current state +/// through Futures. @ref Initialize, @ref LoadAd, and @ref Show each have a +/// corresponding @ref Future from which you can determine result of the +/// previous call. +/// +/// Here's how one might initialize, load, and show an interstitial ad while +/// checking against the result of the previous action at each step: +/// +/// @code +/// namespace gma = ::firebase::gma; +/// gma::InterstitialAd* interstitial = new gma::InterstitialAd(); +/// interstitial->Initialize(ad_parent); +/// @endcode +/// +/// Then, later: +/// +/// @code +/// if (interstitial->InitializeLastResult().status() == +/// ::firebase::kFutureStatusComplete && +/// interstitial->InitializeLastResult().error() == +/// firebase::gma::kAdErrorCodeNone) { +/// interstitial->LoadAd( "YOUR_AD_UNIT_ID", my_ad_request); +/// } +/// @endcode +/// +/// And after that: +/// +/// @code +/// if (interstitial->LoadAdLastResult().status() == +/// ::firebase::kFutureStatusComplete && +/// interstitial->LoadAdLastResult().error() == +/// firebase::gma::kAdErrorCodeNone)) { +/// interstitial->Show(); +/// } +/// @endcode +class InterstitialAd { + public: + /// Creates an uninitialized @ref InterstitialAd object. + /// @ref Initialize must be called before the object is used. + InterstitialAd(); + + ~InterstitialAd(); + + /// Initialize the @ref InterstitialAd object. + /// @param[in] parent The platform-specific UI element that will host the ad. + Future Initialize(AdParent parent); + + /// Returns a @ref Future containing the status of the last call to + /// @ref Initialize. + Future InitializeLastResult() const; + + /// Begins an asynchronous request for an ad. + /// + /// @param[in] ad_unit_id The ad unit ID to use in loading the ad. + /// @param[in] request An AdRequest struct with information about the request + /// to be made (such as targeting info). + Future LoadAd(const char* ad_unit_id, const AdRequest& request); + + /// Returns a @ref Future containing the status of the last call to + /// @ref LoadAd. + Future LoadAdLastResult() const; + + /// Shows the @ref InterstitialAd. This should not be called unless an ad has + /// already been loaded. + Future Show(); + + /// Returns a @ref Future containing the status of the last call to + /// @ref Show. + Future ShowLastResult() const; + + /// Sets the @ref FullScreenContentListener for this @ref InterstitialAd. + /// + /// @param[in] listener A valid @ref FullScreenContentListener to receive + /// callbacks. + void SetFullScreenContentListener(FullScreenContentListener* listener); + + /// Registers a callback to be invoked when this ad is estimated to have + /// earned money + /// + /// @param[in] listener A valid @ref PaidEventListener to receive callbacks. + void SetPaidEventListener(PaidEventListener* listener); + + private: + // An internal, platform-specific implementation object that this class uses + // to interact with the Google Mobile Ads SDKs for iOS and Android. + internal::InterstitialAdInternal* internal_; +}; + +} // namespace gma +} // namespace firebase + +#endif // FIREBASE_GMA_SRC_INCLUDE_FIREBASE_GMA_INTERSTITIAL_AD_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/gma/rewarded_ad.h b/packages/firebase_core/firebase_core/firebase_core/firebase/gma/rewarded_ad.h new file mode 100644 index 000000000000..a3c5431486d4 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/gma/rewarded_ad.h @@ -0,0 +1,152 @@ +/* + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_GMA_SRC_INCLUDE_FIREBASE_GMA_REWARDED_AD_H_ +#define FIREBASE_GMA_SRC_INCLUDE_FIREBASE_GMA_REWARDED_AD_H_ + +#include + +#include "firebase/future.h" +#include "firebase/gma/types.h" +#include "firebase/internal/common.h" + +namespace firebase { +namespace gma { + +namespace internal { +// Forward declaration for platform-specific data, implemented in each library. +class RewardedAdInternal; +} // namespace internal + +/// @brief Loads and displays Google Mobile Ads rewarded ads. +/// +/// @ref RewardedAd is a single-use object that can load and show a +/// single GMA rewarded ad. +/// +/// RewardedAd objects provide information about their current state +/// through Futures. @ref Initialize, @ref LoadAd, and @ref Show each have a +/// corresponding @ref Future from which you can determine result of the +/// previous call. +/// +/// Here's how one might initialize, load, and show an rewarded ad while +/// checking against the result of the previous action at each step: +/// +/// @code +/// namespace gma = ::firebase::gma; +/// gma::RewardedAd* rewarded = new gma::RewardedAd(); +/// rewarded->Initialize(ad_parent); +/// @endcode +/// +/// Then, later: +/// +/// @code +/// if (rewarded->InitializeLastResult().status() == +/// ::firebase::kFutureStatusComplete && +/// rewarded->InitializeLastResult().error() == +/// firebase::gma::kAdErrorCodeNone) { +/// rewarded->LoadAd( "YOUR_AD_UNIT_ID", my_ad_request); +/// } +/// @endcode +/// +/// And after that: +/// +/// @code +/// if (rewarded->LoadAdLastResult().status() == +/// ::firebase::kFutureStatusComplete && +/// rewarded->LoadAdLastResult().error() == +/// firebase::gma::kAdErrorCodeNone)) { +/// rewarded->Show(&my_user_earned_reward_listener); +/// } +/// @endcode +class RewardedAd { + public: + /// Options for RewardedAd server-side verification callbacks. Set options on + /// a RewardedAd object using the @ref SetServerSideVerificationOptions + /// method. + struct ServerSideVerificationOptions { + /// Custom data to be included in server-side verification callbacks. + std::string custom_data; + + /// User id to be used in server-to-server reward callbacks. + std::string user_id; + }; + + /// Creates an uninitialized @ref RewardedAd object. + /// @ref Initialize must be called before the object is used. + RewardedAd(); + + ~RewardedAd(); + + /// Initialize the @ref RewardedAd object. + /// @param[in] parent The platform-specific UI element that will host the ad. + Future Initialize(AdParent parent); + + /// Returns a @ref Future containing the status of the last call to + /// @ref Initialize. + Future InitializeLastResult() const; + + /// Begins an asynchronous request for an ad. + /// + /// @param[in] ad_unit_id The ad unit ID to use in loading the ad. + /// @param[in] request An AdRequest struct with information about the request + /// to be made (such as targeting info). + Future LoadAd(const char* ad_unit_id, const AdRequest& request); + + /// Returns a @ref Future containing the status of the last call to + /// @ref LoadAd. + Future LoadAdLastResult() const; + + /// Shows the @ref RewardedAd. This should not be called unless an ad has + /// already been loaded. + /// + /// @param[in] listener The @ref UserEarnedRewardListener to be notified when + /// user earns a reward. + Future Show(UserEarnedRewardListener* listener); + + /// Returns a @ref Future containing the status of the last call to + /// @ref Show. + Future ShowLastResult() const; + + /// Sets the @ref FullScreenContentListener for this @ref RewardedAd. + /// + /// @param[in] listener A valid @ref FullScreenContentListener to receive + /// callbacks. + void SetFullScreenContentListener(FullScreenContentListener* listener); + + /// Registers a callback to be invoked when this ad is estimated to have + /// earned money + /// + /// @param[in] listener A valid @ref PaidEventListener to receive callbacks. + void SetPaidEventListener(PaidEventListener* listener); + + /// Sets the server side verification options. + /// + /// @param[in] serverSideVerificationOptions A @ref + /// ServerSideVerificationOptions object containing custom data and a user + /// Id. + void SetServerSideVerificationOptions( + const ServerSideVerificationOptions& serverSideVerificationOptions); + + private: + // An internal, platform-specific implementation object that this class uses + // to interact with the Google Mobile Ads SDKs for iOS and Android. + internal::RewardedAdInternal* internal_; +}; + +} // namespace gma +} // namespace firebase + +#endif // FIREBASE_GMA_SRC_INCLUDE_FIREBASE_GMA_REWARDED_AD_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/gma/types.h b/packages/firebase_core/firebase_core/firebase_core/firebase/gma/types.h new file mode 100644 index 000000000000..292ee4138a68 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/gma/types.h @@ -0,0 +1,939 @@ +/* + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_GMA_SRC_INCLUDE_FIREBASE_GMA_TYPES_H_ +#define FIREBASE_GMA_SRC_INCLUDE_FIREBASE_GMA_TYPES_H_ + +#include +#include +#include +#include +#include + +#include "firebase/future.h" +#include "firebase/internal/platform.h" + +#if FIREBASE_PLATFORM_ANDROID +#include +#elif FIREBASE_PLATFORM_IOS || FIREBASE_PLATFORM_TVOS +extern "C" { +#include +} // extern "C" +#endif // FIREBASE_PLATFORM_ANDROID, FIREBASE_PLATFORM_IOS, + // FIREBASE_PLATFORM_TVOS + +namespace firebase { +namespace gma { + +struct AdErrorInternal; +struct AdapterResponseInfoInternal; +struct BoundingBox; +struct ResponseInfoInternal; + +class AdapterResponseInfo; +class AdViewBoundingBoxListener; +class GmaInternal; +class AdView; +class InterstitialAd; +class PaidEventListener; +class ResponseInfo; + +namespace internal { +class AdViewInternal; +} + +/// This is a platform specific datatype that is required to create +/// a Google Mobile Ads ad. +/// +/// The following defines the datatype on each platform: +///
    +///
  • Android: A `jobject` which references an Android Activity.
  • +///
  • iOS: An `id` which references an iOS UIView.
  • +///
+#if FIREBASE_PLATFORM_ANDROID +/// An Android Activity from Java. +typedef jobject AdParent; +#elif FIREBASE_PLATFORM_IOS || FIREBASE_PLATFORM_TVOS +/// A pointer to an iOS UIView. +typedef id AdParent; +#else +/// A void pointer for stub classes. +typedef void* AdParent; +#endif // FIREBASE_PLATFORM_ANDROID, FIREBASE_PLATFORM_IOS, + // FIREBASE_PLATFORM_TVOS + +/// Error codes returned by Future::error(). +enum AdErrorCode { + /// Call completed successfully. + kAdErrorCodeNone, + /// The ad has not been fully initialized. + kAdErrorCodeUninitialized, + /// The ad is already initialized (repeat call). + kAdErrorCodeAlreadyInitialized, + /// A call has failed because an ad is currently loading. + kAdErrorCodeLoadInProgress, + /// A call to load an ad has failed due to an internal SDK error. + kAdErrorCodeInternalError, + /// A call to load an ad has failed due to an invalid request. + kAdErrorCodeInvalidRequest, + /// A call to load an ad has failed due to a network error. + kAdErrorCodeNetworkError, + /// A call to load an ad has failed because no ad was available to serve. + kAdErrorCodeNoFill, + /// An attempt has been made to show an ad on an Android Activity that has + /// no window token (such as one that's not done initializing). + kAdErrorCodeNoWindowToken, + /// An attempt to load an Ad Network extras class for an ad request has + /// failed. + kAdErrorCodeAdNetworkClassLoadError, + /// The ad server experienced a failure processing the request. + kAdErrorCodeServerError, + /// The current device’s OS is below the minimum required version. + kAdErrorCodeOSVersionTooLow, + /// The request was unable to be loaded before being timed out. + kAdErrorCodeTimeout, + /// Will not send request because the interstitial object has already been + /// used. + kAdErrorCodeInterstitialAlreadyUsed, + /// The mediation response was invalid. + kAdErrorCodeMediationDataError, + /// Error finding or creating a mediation ad network adapter. + kAdErrorCodeMediationAdapterError, + /// Attempting to pass an invalid ad size to an adapter. + kAdErrorCodeMediationInvalidAdSize, + /// Invalid argument error. + kAdErrorCodeInvalidArgument, + /// Received invalid response. + kAdErrorCodeReceivedInvalidResponse, + /// Will not send a request because the rewarded ad object has already been + /// used. + kAdErrorCodeRewardedAdAlreadyUsed, + /// A mediation ad network adapter received an ad request, but did not fill. + /// The adapter’s error is included as an underlyingError. + kAdErrorCodeMediationNoFill, + /// Will not send request because the ad object has already been used. + kAdErrorCodeAdAlreadyUsed, + /// Will not send request because the application identifier is missing. + kAdErrorCodeApplicationIdentifierMissing, + /// Android Ad String is invalid. + kAdErrorCodeInvalidAdString, + /// The ad can not be shown when app is not in the foreground. + kAdErrorCodeAppNotInForeground, + /// A mediation adapter failed to show the ad. + kAdErrorCodeMediationShowError, + /// The ad is not ready to be shown. + kAdErrorCodeAdNotReady, + /// Ad is too large for the scene. + kAdErrorCodeAdTooLarge, + /// Attempted to present ad from a non-main thread. This is an internal + /// error which should be reported to support if encountered. + kAdErrorCodeNotMainThread, + /// A debug operation failed because the device is not in test mode. + kAdErrorCodeNotInTestMode, + /// An attempt to load the Ad Inspector failed. + kAdErrorCodeInspectorFailedToLoad, + /// The request to show the Ad Inspector failed because it's already open. + kAdErrorCodeInsepctorAlreadyOpen, + /// Fallback error for any unidentified cases. + kAdErrorCodeUnknown, +}; + +/// A listener for receiving notifications during the lifecycle of a BannerAd. +class AdListener { + public: + virtual ~AdListener(); + + /// Called when a click is recorded for an ad. + virtual void OnAdClicked() {} + + /// Called when the user is about to return to the application after clicking + /// on an ad. + virtual void OnAdClosed() {} + + /// Called when an impression is recorded for an ad. + virtual void OnAdImpression() {} + + /// Called when an ad opens an overlay that covers the screen. + virtual void OnAdOpened() {} +}; + +/// Information about why an ad operation failed. +class AdError { + public: + /// Default Constructor. + AdError(); + + /// Copy Constructor. + AdError(const AdError& ad_error); + + /// Destructor. + virtual ~AdError(); + + /// Assignment operator. + AdError& operator=(const AdError& obj); + + /// Retrieves an AdError which represents the cause of this error. + /// + /// @return a pointer to an adError which represents the cause of this + /// AdError. If there was no cause then nullptr is returned. + std::unique_ptr GetCause() const; + + /// Gets the error's code. + AdErrorCode code() const; + + /// Gets the domain of the error. + const std::string& domain() const; + + /// Gets the message describing the error. + const std::string& message() const; + + /// Gets the ResponseInfo if an error occurred during a loadAd operation. + /// The ResponseInfo will have empty fields if this AdError does not + /// represent an error stemming from a load ad operation. + const ResponseInfo& response_info() const; + + /// Returns a log friendly string version of this object. + virtual const std::string& ToString() const; + + /// A domain string which represents an undefined error domain. + /// + /// The GMA SDK returns this domain for domain() method invocations when + /// converting error information from legacy mediation adapter callbacks. + static const char* const kUndefinedDomain; + + private: + friend class AdapterResponseInfo; + friend class GmaInternal; + friend class AdView; + friend class InterstitialAd; + + /// Constructor used when building results in Ad event callbacks. + explicit AdError(const AdErrorInternal& ad_error_internal); + + // Collection of response from adapters if this Result is due to a loadAd + // operation. + ResponseInfo* response_info_; + + // An internal, platform-specific implementation object that this class uses + // to interact with the Google Mobile Ads SDKs for iOS and Android. + AdErrorInternal* internal_; +}; + +/// Information about an ad response. +class ResponseInfo { + public: + /// Constructor creates an uninitialized ResponseInfo. + ResponseInfo(); + + /// Gets the AdapterResponseInfo objects for the ad response. + /// + /// @return a vector of AdapterResponseInfo objects containing metadata for + /// each adapter included in the ad response. + const std::vector& adapter_responses() const { + return adapter_responses_; + } + + /// A class name that identifies the ad network that returned the ad. + /// Returns an empty string if the ad failed to load. + const std::string& mediation_adapter_class_name() const { + return mediation_adapter_class_name_; + } + + /// Gets the response ID string for the loaded ad. Returns an empty + /// string if the ad fails to load. + const std::string& response_id() const { return response_id_; } + + /// Gets a log friendly string version of this object. + const std::string& ToString() const { return to_string_; } + + private: + friend class AdError; + friend class GmaInternal; + + explicit ResponseInfo(const ResponseInfoInternal& internal); + + std::vector adapter_responses_; + std::string mediation_adapter_class_name_; + std::string response_id_; + std::string to_string_; +}; + +/// Information about the result of an ad operation. +class AdResult { + public: + /// Default Constructor. + AdResult(); + + /// Constructor. + explicit AdResult(const AdError& ad_error); + + /// Destructor. + virtual ~AdResult(); + + /// Returns true if the operation was successful. + bool is_successful() const; + + /// An object representing an error which occurred during an ad operation. + /// If the @ref AdResult::is_successful() returned true, then the + /// @ref AdError object returned via this method will contain no contextual + /// information. + const AdError& ad_error() const; + + /// For debugging and logging purposes, successfully loaded ads provide a + /// ResponseInfo object which contains information about the adapter which + /// loaded the ad. If the ad failed to load then the object returned from + /// this method will have default values. Information about the error + /// should be retrieved via @ref AdResult::ad_error() instead. + const ResponseInfo& response_info() const; + + private: + friend class GmaInternal; + + /// Constructor invoked upon successful ad load. This contains response + /// information from the adapter which loaded the ad. + explicit AdResult(const ResponseInfo& response_info); + + /// Denotes if the @ref AdResult represents a success or an error. + bool is_successful_; + + /// Information about the error. Will be a default-constructed @ref AdError + /// if this result represents a success. + AdError ad_error_; + + /// Information from the adapter which loaded the ad. + ResponseInfo response_info_; +}; + +/// A snapshot of a mediation adapter's initialization status. +class AdapterStatus { + public: + AdapterStatus() : is_initialized_(false), latency_(0) {} + + /// Detailed description of the status. + /// + /// This method should only be used for informational purposes, such as + /// logging. Use @ref is_initialized to make logical decisions regarding an + /// adapter's status. + const std::string& description() const { return description_; } + + /// Returns the adapter's initialization state. + bool is_initialized() const { return is_initialized_; } + + /// The adapter's initialization latency in milliseconds. + /// 0 if initialization has not yet ended. + int latency() const { return latency_; } + +#if !defined(DOXYGEN) + // Equality operator for testing. + bool operator==(const AdapterStatus& rhs) const { + return (description() == rhs.description() && + is_initialized() == rhs.is_initialized() && + latency() == rhs.latency()); + } +#endif // !defined(DOXYGEN) + + private: + friend class GmaInternal; + std::string description_; + bool is_initialized_; + int latency_; +}; + +/// An immutable snapshot of the GMA SDK’s initialization status, categorized +/// by mediation adapter. +class AdapterInitializationStatus { + public: + /// Initialization status of each known ad network, keyed by its adapter's + /// class name. + std::map GetAdapterStatusMap() const { + return adapter_status_map_; + } +#if !defined(DOXYGEN) + // Equality operator for testing. + bool operator==(const AdapterInitializationStatus& rhs) const { + return (GetAdapterStatusMap() == rhs.GetAdapterStatusMap()); + } +#endif // !defined(DOXYGEN) + + private: + friend class GmaInternal; + std::map adapter_status_map_; +}; + +/// Listener to be invoked when the Ad Inspector has been closed. +class AdInspectorClosedListener { + public: + virtual ~AdInspectorClosedListener(); + + /// Called when the user clicked the ad. The AdResult contains the status of + /// the operation, including details of the error if one occurred. + virtual void OnAdInspectorClosed(const AdResult& ad_result) = 0; +}; + +/// @brief Response information for an individual ad network contained within +/// a @ref ResponseInfo object. +class AdapterResponseInfo { + public: + /// Destructor + ~AdapterResponseInfo(); + + /// @brief Information about the result including whether an error + /// occurred, and any contextual information about that error. + /// + /// @return the error that occurred while rendering the ad. If no error + /// occurred then the AdResult's successful method will return true. + AdResult ad_result() const { return ad_result_; } + + /// Returns a string representation of a class name that identifies the ad + /// network adapter. + const std::string& adapter_class_name() const { return adapter_class_name_; } + + /// Amount of time the ad network spent loading an ad. + /// + /// @return number of milliseconds the network spent loading an ad. This value + /// is 0 if the network did not make a load attempt. + int64_t latency_in_millis() const { return latency_; } + + /// A log friendly string version of this object. + const std::string& ToString() const { return to_string_; } + + private: + friend class ResponseInfo; + + /// Constructs an Adapter Response Info Object. + explicit AdapterResponseInfo(const AdapterResponseInfoInternal& internal); + + AdResult ad_result_; + std::string adapter_class_name_; + int64_t latency_; + std::string to_string_; +}; + +/// The size of a banner ad. +class AdSize { + public: + /// Denotes the orientation of the AdSize. + enum Orientation { + /// AdSize should reflect the current orientation of the device. + kOrientationCurrent = 0, + + /// AdSize will be adaptively formatted in Landscape mode. + kOrientationLandscape, + + /// AdSize will be adaptively formatted in Portrait mode. + kOrientationPortrait + }; + + /// Denotes the type size object that the @ref AdSize represents. + enum Type { + /// The standard AdSize type of a set height and width. + kTypeStandard = 0, + + /// An adaptive size anchored to a portion of the screen. + kTypeAnchoredAdaptive, + + /// An adaptive size intended to be embedded in scrollable content. + kTypeInlineAdaptive, + }; + + /// Mobile Marketing Association (MMA) banner ad size (320x50 + /// density-independent pixels). + static const AdSize kBanner; + + /// Interactive Advertising Bureau (IAB) full banner ad size + /// (468x60 density-independent pixels). + static const AdSize kFullBanner; + + /// Taller version of kBanner. Typically 320x100. + static const AdSize kLargeBanner; + + /// Interactive Advertising Bureau (IAB) leaderboard ad size + /// (728x90 density-independent pixels). + static const AdSize kLeaderboard; + + /// Interactive Advertising Bureau (IAB) medium rectangle ad size + /// (300x250 density-independent pixels). + static const AdSize kMediumRectangle; + + /// Creates a new AdSize. + /// + /// @param[in] width The width of the ad in density-independent pixels. + /// @param[in] height The height of the ad in density-independent pixels. + AdSize(uint32_t width, uint32_t height); + + /// @brief Creates an AdSize with the given width and a Google-optimized + /// height to create a banner ad in landscape mode. + /// + /// @param[in] width The width of the ad in density-independent pixels. + /// + /// @return an AdSize with the given width and a Google-optimized height + /// to create a banner ad. The size returned will have an aspect ratio + /// similar to BANNER, suitable for anchoring near the top or bottom of + /// your app. The exact size of the ad returned can be retrieved by calling + /// @ref AdView::ad_size once the ad has been loaded. + static AdSize GetLandscapeAnchoredAdaptiveBannerAdSize(uint32_t width); + + /// @brief Creates an AdSize with the given width and a Google-optimized + /// height to create a banner ad in portrait mode. + /// + /// @param[in] width The width of the ad in density-independent pixels. + /// + /// @return an AdSize with the given width and a Google-optimized height + /// to create a banner ad. The size returned will have an aspect ratio + /// similar to BANNER, suitable for anchoring near the top or bottom + /// of your app. The exact size of the ad returned can be retrieved by + /// calling @ref AdView::ad_size once the ad has been loaded. + static AdSize GetPortraitAnchoredAdaptiveBannerAdSize(uint32_t width); + + /// @brief Creates an AdSize with the given width and a Google-optimized + /// height to create a banner ad given the current orientation. + /// + /// @param[in] width The width of the ad in density-independent pixels. + /// + /// @return an AdSize with the given width and a Google-optimized height + /// to create a banner ad. The size returned will have an aspect ratio + /// similar to AdSize, suitable for anchoring near the top or bottom of + /// your app. The exact size of the ad returned can be retrieved by calling + /// @ref AdView::ad_size once the ad has been loaded. + static AdSize GetCurrentOrientationAnchoredAdaptiveBannerAdSize( + uint32_t width); + + /// @brief This ad size is most suitable for banner ads given a maximum + /// height. + /// + /// This AdSize allows Google servers to choose an optimal ad size with + /// a height less than or equal to the max height given in + /// + /// @param[in] width The width of the ad in density-independent pixels. + /// @param[in] max_height The maximum height that a loaded ad will have. Must + /// be + /// at least 32 dp, but a maxHeight of 50 dp or higher is recommended. + /// + /// @return an AdSize with the given width and a height that is always 0. + /// The exact size of the ad returned can be retrieved by calling + /// @ref AdView::ad_size once the ad has been loaded. + static AdSize GetInlineAdaptiveBannerAdSize(int width, int max_height); + + /// @brief Creates an AdSize with the given width and the device’s + /// landscape height. + /// + /// This ad size allows Google servers to choose an optimal ad size with + /// a height less than or equal to the height of the screen in landscape + /// orientation. + /// + /// @param[in] width The width of the ad in density-independent pixels. + /// + /// @return an AdSize with the given width and a height that is always 0. + /// The exact size of the ad returned can be retrieved by calling + /// @ref AdView::ad_size once the ad has been loaded. + static AdSize GetLandscapeInlineAdaptiveBannerAdSize(int width); + + /// @brief Creates an AdSize with the given width and the device’s + /// portrait height. + /// + /// This ad size allows Google servers to choose an optimal ad size with + /// a height less than or equal to the height of the screen in portrait + /// orientation. + /// + /// @param[in] width The width of the ad in density-independent pixels. + /// + /// @return an AdSize with the given width and a height that is always 0. + /// The exact size of the ad returned can be retrieved by calling + /// @ref AdView::ad_size once the ad has been loaded. + static AdSize GetPortraitInlineAdaptiveBannerAdSize(int width); + + /// @brief A convenience method to return an inline adaptive banner ad size + /// given the current interface orientation. + /// + /// This AdSize allows Google servers to choose an optimal ad size with a + /// height less than or equal to the height of the screen in the requested + /// orientation. + /// + /// @param[in] width The width of the ad in density-independent pixels. + /// + /// @return an AdSize with the given width and a height that is always 0. + /// The exact size of the ad returned can be retrieved by calling + /// @ref AdView::ad_size once the ad has been loaded. + static AdSize GetCurrentOrientationInlineAdaptiveBannerAdSize(int width); + + /// Comparison operator. + /// + /// @return true if `rhs` refers to the same AdSize as `this`. + bool operator==(const AdSize& rhs) const; + + /// Comparison operator. + /// + /// @returns true if `rhs` refers to a different AdSize as `this`. + bool operator!=(const AdSize& rhs) const; + + /// The width of the region represented by this AdSize. Value is in + /// density-independent pixels. + uint32_t width() const { return width_; } + + /// The height of the region represented by this AdSize. Value is in + /// density-independent pixels. + uint32_t height() const { return height_; } + + /// The AdSize orientation. + Orientation orientation() const { return orientation_; } + + /// The AdSize type, either standard size or adaptive. + Type type() const { return type_; } + + private: + friend class firebase::gma::internal::AdViewInternal; + + /// Returns an Anchor Adpative AdSize Object given a width and orientation. + static AdSize GetAnchoredAdaptiveBannerAdSize(uint32_t width, + Orientation orientation); + + /// Returns true if the AdSize parameter is equivalient to this AdSize object. + bool is_equal(const AdSize& ad_size) const; + + /// Denotes the orientation for anchored adaptive AdSize objects. + Orientation orientation_; + + /// Advertisement width in platform-indepenent pixels. + uint32_t width_; + + /// Advertisement width in platform-indepenent pixels. + uint32_t height_; + + /// The type of AdSize (standard or adaptive) + Type type_; +}; + +/// Contains targeting information used to fetch an ad. +class AdRequest { + public: + /// Creates an @ref AdRequest with no custom configuration. + AdRequest(); + + /// Creates an @ref AdRequest with the optional content URL. + /// + /// When requesting an ad, apps may pass the URL of the content they are + /// serving. This enables keyword targeting to match the ad with the content. + /// + /// The URL is ignored if null or the number of characters exceeds 512. + /// + /// @param[in] content_url the url of the content being viewed. + explicit AdRequest(const char* content_url); + + ~AdRequest(); + + /// The content URL targeting information. + /// + /// @return the content URL for the @ref AdRequest. The string will be empty + /// if no content URL has been configured. + const std::string& content_url() const { return content_url_; } + + /// A Map of adapter class names to their collection of extra parameters, as + /// configured via @ref add_extra. + const std::map >& extras() + const { + return extras_; + } + + /// Keywords which will help GMA to provide targeted ads, as added by + /// @ref add_keyword. + const std::unordered_set& keywords() const { return keywords_; } + + /// Returns the set of neighboring content URLs or an empty set if no URLs + /// were set via @ref add_neighboring_content_urls(). + const std::unordered_set& neighboring_content_urls() const { + return neighboring_content_urls_; + } + + /// Add a network extra for the associated ad mediation adapter. + /// + /// Appends an extra to the corresponding list of extras for the ad mediation + /// adapter. Each ad mediation adapter can have multiple extra strings. + /// + /// @param[in] adapter_class_name the class name of the ad mediation adapter + /// for which to add the extra. + /// @param[in] extra_key a key which will be passed to the corresponding ad + /// mediation adapter. + /// @param[in] extra_value the value associated with extra_key. + void add_extra(const char* adapter_class_name, const char* extra_key, + const char* extra_value); + + /// Adds a keyword for targeting purposes. + /// + /// Multiple keywords may be added via repeated invocations of this method. + /// + /// @param[in] keyword a string that GMA will use to aid in targeting ads. + void add_keyword(const char* keyword); + + /// When requesting an ad, apps may pass the URL of the content they are + /// serving. This enables keyword targeting to match the ad with the content. + /// + /// The URL is ignored if null or the number of characters exceeds 512. + /// + /// @param[in] content_url the url of the content being viewed. + void set_content_url(const char* content_url); + + /// Adds to the list of URLs which represent web content near an ad. + /// + /// Promotes brand safety and allows displayed ads to have an app level + /// rating (MA, T, PG, etc) that is more appropriate to neighboring content. + /// + /// Subsequent invocations append to the existing list. + /// + /// @param[in] neighboring_content_urls neighboring content URLs to be + /// attached to the existing neighboring content URLs. + void add_neighboring_content_urls( + const std::vector& neighboring_content_urls); + + private: + std::string content_url_; + std::map > extras_; + std::unordered_set keywords_; + std::unordered_set neighboring_content_urls_; +}; + +/// Describes a reward credited to a user for interacting with a RewardedAd. +class AdReward { + public: + /// Creates an @ref AdReward. + AdReward(const std::string& type, int64_t amount) + : type_(type), amount_(amount) {} + + /// Returns the reward amount. + int64_t amount() const { return amount_; } + + /// Returns the type of the reward. + const std::string& type() const { return type_; } + + private: + const int64_t amount_; + const std::string type_; +}; + +/// The monetary value earned from an ad. +class AdValue { + public: + /// Allowed constants for @ref precision_type(). + enum PrecisionType { + /// An ad value with unknown precision. + kdValuePrecisionUnknown = 0, + /// An ad value estimated from aggregated data. + kAdValuePrecisionEstimated, + /// A publisher-provided ad value, such as manual CPMs in a mediation group. + kAdValuePrecisionPublisherProvided = 2, + /// The precise value paid for this ad. + kAdValuePrecisionPrecise = 3 + }; + + /// Constructor + AdValue(const char* currency_code, PrecisionType precision_type, + int64_t value_micros) + : currency_code_(currency_code), + precision_type_(precision_type), + value_micros_(value_micros) {} + + /// The value's ISO 4217 currency code. + const std::string& currency_code() const { return currency_code_; } + + /// The precision of the reported ad value. + PrecisionType precision_type() const { return precision_type_; } + + /// The ad's value in micro-units, where 1,000,000 micro-units equal one + /// unit of the currency. + int64_t value_micros() const { return value_micros_; } + + private: + const std::string currency_code_; + const PrecisionType precision_type_; + const int64_t value_micros_; +}; + +/// @brief Listener to be invoked when ads show and dismiss full screen content, +/// such as a fullscreen ad experience or an in-app browser. +class FullScreenContentListener { + public: + virtual ~FullScreenContentListener(); + + /// Called when the user clicked the ad. + virtual void OnAdClicked() {} + + /// Called when the ad dismissed full screen content. + virtual void OnAdDismissedFullScreenContent() {} + + /// Called when the ad failed to show full screen content. + /// + /// @param[in] ad_error An object containing detailed information + /// about the error. + virtual void OnAdFailedToShowFullScreenContent(const AdError& ad_error) {} + + /// Called when an impression is recorded for an ad. + virtual void OnAdImpression() {} + + /// Called when the ad showed the full screen content. + virtual void OnAdShowedFullScreenContent() {} +}; + +/// Listener to be invoked when ads have been estimated to earn money. +class PaidEventListener { + public: + virtual ~PaidEventListener(); + + /// Called when an ad is estimated to have earned money. + virtual void OnPaidEvent(const AdValue& value) {} +}; + +/// @brief Global configuration that will be used for every @ref AdRequest. +/// Set the configuration via @ref SetRequestConfiguration. +struct RequestConfiguration { + /// A maximum ad content rating, which may be configured via + /// @ref max_ad_content_rating. + enum MaxAdContentRating { + /// No content rating has been specified. + kMaxAdContentRatingUnspecified = -1, + + /// Content suitable for general audiences, including families. + kMaxAdContentRatingG, + + /// Content suitable only for mature audiences. + kMaxAdContentRatingMA, + + /// Content suitable for most audiences with parental guidance. + kMaxAdContentRatingPG, + + /// Content suitable for teen and older audiences. + kMaxAdContentRatingT + }; + + /// Specify whether you would like your app to be treated as child-directed + /// for purposes of the Children’s Online Privacy Protection Act (COPPA). + /// Values defined here may be configured via + /// @ref tag_for_child_directed_treatment. + enum TagForChildDirectedTreatment { + /// Indicates that ad requests will include no indication of how you would + /// like your app treated with respect to COPPA. + kChildDirectedTreatmentUnspecified = -1, + + /// Indicates that your app should not be treated as child-directed for + /// purposes of the Children’s Online Privacy Protection Act (COPPA). + kChildDirectedTreatmentFalse, + + /// Indicates that your app should be treated as child-directed for purposes + /// of the Children’s Online Privacy Protection Act (COPPA). + kChildDirectedTreatmentTrue + }; + + /// Configuration values to mark your app to receive treatment for users in + /// the European Economic Area (EEA) under the age of consent. Values defined + /// here should be configured via @ref tag_for_under_age_of_consent. + enum TagForUnderAgeOfConsent { + /// Indicates that the publisher has not specified whether the ad request + /// should receive treatment for users in the European Economic Area (EEA) + /// under the age of consent. + kUnderAgeOfConsentUnspecified = -1, + + /// Indicates the publisher specified that the ad request should not receive + /// treatment for users in the European Economic Area (EEA) under the age of + /// consent. + kUnderAgeOfConsentFalse, + + /// Indicates the publisher specified that the ad request should receive + /// treatment for users in the European Economic Area (EEA) under the age of + /// consent. + kUnderAgeOfConsentTrue + }; + + /// Sets a maximum ad content rating. GMA ads returned for your app will + /// have a content rating at or below that level. + MaxAdContentRating max_ad_content_rating; + + /// @brief Allows you to specify whether you would like your app + /// to be treated as child-directed for purposes of the Children’s Online + /// Privacy Protection Act (COPPA) - + /// http://business.ftc.gov/privacy-and-security/childrens-privacy. + /// + /// If you set this value to + /// RequestConfiguration.kChildDirectedTreatmentTrue, you will indicate + /// that your app should be treated as child-directed for purposes of the + /// Children’s Online Privacy Protection Act (COPPA). + /// + /// If you set this value to + /// RequestConfiguration.kChildDirectedTreatmentFalse, you will indicate + /// that your app should not be treated as child-directed for purposes of the + /// Children’s Online Privacy Protection Act (COPPA). + /// + /// If you do not set this value, or set this value to + /// RequestConfiguration.kChildDirectedTreatmentUnspecified, ad requests will + /// include no indication of how you would like your app treated with respect + /// to COPPA. + /// + /// By setting this value, you certify that this notification is accurate and + /// you are authorized to act on behalf of the owner of the app. You + /// understand that abuse of this setting may result in termination of your + /// Google account. + /// + /// @note: it may take some time for this designation to be fully implemented + /// in applicable Google services. + /// + TagForChildDirectedTreatment tag_for_child_directed_treatment; + + /// This value allows you to mark your app to receive treatment for users in + /// the European Economic Area (EEA) under the age of consent. This feature is + /// designed to help facilitate compliance with the General Data Protection + /// Regulation (GDPR). Note that you may have other legal obligations under + /// GDPR. Please review the European Union's guidance and consult with your + /// own legal counsel. Please remember that Google's tools are designed to + /// facilitate compliance and do not relieve any particular publisher of its + /// obligations under the law. + /// + /// When using this feature, a Tag For Users under the Age of Consent in + /// Europe (TFUA) parameter will be included in all ad requests. This + /// parameter disables personalized advertising, including remarketing, for + /// that specific ad request. It also disables requests to third-party ad + /// vendors, such as ad measurement pixels and third-party ad servers. + /// + /// If you set this value to RequestConfiguration.kUnderAgeOfConsentTrue, you + /// will indicate that you want your app to be handled in a manner suitable + /// for users under the age of consent. + /// + /// If you set this value to RequestConfiguration.kUnderAgeOfConsentFalse, + /// you will indicate that you don't want your app to be handled in a manner + /// suitable for users under the age of consent. + /// + /// If you do not set this value, or set this value to + /// kUnderAgeOfConsentUnspecified, your app will include no indication of how + /// you would like your app to be handled in a manner suitable for users under + /// the age of consent. + TagForUnderAgeOfConsent tag_for_under_age_of_consent; + + /// Sets a list of test device IDs corresponding to test devices which will + /// always request test ads. + std::vector test_device_ids; +}; + +/// Listener to be invoked when the user earned a reward. +class UserEarnedRewardListener { + public: + virtual ~UserEarnedRewardListener(); + /// Called when the user earned a reward. The app is responsible for + /// crediting the user with the reward. + /// + /// @param[in] reward the @ref AdReward that should be granted to the user. + virtual void OnUserEarnedReward(const AdReward& reward) {} +}; + +} // namespace gma +} // namespace firebase + +#endif // FIREBASE_GMA_SRC_INCLUDE_FIREBASE_GMA_TYPES_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/installations.h b/packages/firebase_core/firebase_core/firebase_core/firebase/installations.h new file mode 100644 index 000000000000..c9774bc37e73 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/installations.h @@ -0,0 +1,123 @@ +// Copyright 2020 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef FIREBASE_INSTALLATIONS_SRC_INCLUDE_FIREBASE_INSTALLATIONS_H_ +#define FIREBASE_INSTALLATIONS_SRC_INCLUDE_FIREBASE_INSTALLATIONS_H_ + +#include +#include + +#include "firebase/app.h" +#include "firebase/future.h" +#include "firebase/internal/common.h" + +/// @brief Namespace that encompasses all Firebase APIs. +namespace firebase { + +namespace installations { + +/// Installations error codes. +enum Error { + kErrorNone = 0, + /// An unknown error occurred. + kErrorUnknown, + /// Installations service cannot be accessed. + kErrorNoAccess, + /// Some of the parameters of the request were invalid. + kErrorInvalidConfiguration, +}; + +namespace internal { +// Implementation specific data for an Installation. +class InstallationsInternal; +} // namespace internal + +/// @brief Installations provides a unique identifier for each app instance and +/// a mechanism to authenticate and authorize actions (for example, sending an +/// FCM message). +/// +/// Provides a unique identifier for a Firebase installation. +/// Provides an auth token for a Firebase installation. +/// Provides a API to perform data deletion for a Firebase +/// installation. +class Installations { + public: + ~Installations(); + + /// @brief Get the App this object is connected to. + /// + /// @return App this object is connected to. + App* app() const { return app_; } + + /// @brief Returns the Installations object for an App creating the + /// Installations if required. + /// + /// @param[in] app The App to create an Installations object from. + /// + /// @return Installations object if successful, nullptr otherwise. + static Installations* GetInstance(App* app); + + /// @brief Returns a stable identifier that uniquely identifies the app + /// installation. + /// + /// @return Unique identifier for the app installation. + Future GetId(); + + /// @brief Get the results of the most recent call to @ref GetId. + Future GetIdLastResult(); + + /// @brief Call to delete this Firebase app installation from the Firebase + /// backend. + Future Delete(); + + /// @brief Get the results of the most recent call to @ref Delete. + Future DeleteLastResult(); + + /// @brief Returns a token that authorizes an Entity to perform an action on + /// behalf of the application identified by installations. + /// + /// This is similar to an OAuth2 token except it applies to the + /// application instance instead of a user. + /// + /// For example, to get a token that can be used to send messages to an + /// application via Firebase Cloud Messaging, set entity to the + /// sender ID, and set scope to "FCM". + /// + /// @param forceRefresh If set true, will always return a new token. + /// + /// @return Returns a valid authentication token for the Firebase + /// installation. + Future GetToken(bool forceRefresh); + + /// @brief Get the results of the most recent call to @ref GetToken. + Future GetTokenLastResult(); + + private: + explicit Installations(App* app); + + static Installations* FindInstallations(App* app); + // Installations internal initialize. + bool InitInternal(); + // Clean up Installations instance. + void DeleteInternal(); + + App* app_; + internal::InstallationsInternal* installations_internal_; +}; + +} // namespace installations + +} // namespace firebase + +#endif // FIREBASE_INSTALLATIONS_SRC_INCLUDE_FIREBASE_INSTALLATIONS_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/internal/common.h b/packages/firebase_core/firebase_core/firebase_core/firebase/internal/common.h new file mode 100644 index 000000000000..2e2878a0bd97 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/internal/common.h @@ -0,0 +1,128 @@ +/* + * Copyright 2016 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_APP_SRC_INCLUDE_FIREBASE_INTERNAL_COMMON_H_ +#define FIREBASE_APP_SRC_INCLUDE_FIREBASE_INTERNAL_COMMON_H_ + +// This file contains definitions that configure the SDK. + +// Include a STL header file, othewise _STLPORT_VERSION won't be set. +#include + +// Move operators use rvalue references, which are a C++11 extension. +// Also, Visual Studio 2010 and later actually support move operators despite +// reporting __cplusplus to be 199711L, so explicitly check for that. +// Also, stlport doesn't implement std::move(). +#if (__cplusplus >= 201103L || _MSC_VER >= 1600) && !defined(_STLPORT_VERSION) +#define FIREBASE_USE_MOVE_OPERATORS +#endif + +// stlport doesn't implement std::function. +#if !defined(_STLPORT_VERSION) +#define FIREBASE_USE_STD_FUNCTION +#endif // !defined(_STLPORT_VERSION) + +// stlport doesn't implement std::aligned_storage. +#if defined(_STLPORT_VERSION) +#include + +namespace firebase { +template +struct AlignedStorage { + struct type { + alignas(Alignment) unsigned char data[Length]; + }; +}; +} // namespace firebase +#define FIREBASE_ALIGNED_STORAGE ::firebase::AlignedStorage +#else +#include +#define FIREBASE_ALIGNED_STORAGE std::aligned_storage +#endif // defined(_STLPORT_VERSION) + +// Visual Studio 2013 does not support snprintf, so use streams instead. +#if !(defined(_MSC_VER) && _MSC_VER <= 1800) +#define FIREBASE_USE_SNPRINTF +#endif // !(defined(_MSC_VER) && _MSC_VER <= 1800) + +#if !(defined(_MSC_VER) && _MSC_VER <= 1800) +#define FIREBASE_USE_EXPLICIT_DEFAULT_METHODS +#endif // !(defined(_MSC_VER) && _MSC_VER <= 1800) + +#if !defined(DOXYGEN) && !defined(SWIG) +#if !defined(_WIN32) && !defined(__CYGWIN__) +// Prevent GCC & Clang from stripping a symbol. +#define FIREBASE_APP_KEEP_SYMBOL __attribute__((used)) +#else +// MSVC needs to reference a symbol directly in the application for it to be +// kept in the final executable. In this case, the end user's application +// must include the appropriate Firebase header (e.g firebase/analytics.h) to +// initialize the module. +#define FIREBASE_APP_KEEP_SYMBOL +#endif // !defined(_WIN32) && !defined(__CYGWIN__) + +// Module initializer's name. +// +// This can be used to explicitly include a module initializer in an application +// to prevent the object from being stripped by the linker. The symbol is +// located in the "firebase" namespace so can be referenced using: +// +// ::firebase::FIREBASE_APP_REGISTER_CALLBACKS_REFERENCE_NAME(name) +// +// Where "name" is the module name, for example "analytics". +#define FIREBASE_APP_REGISTER_CALLBACKS_INITIALIZER_NAME(module_name) \ + g_##module_name##_initializer + +// Declare a module initializer variable as a global. +#define FIREBASE_APP_REGISTER_CALLBACKS_INITIALIZER_VARIABLE(module_name) \ + namespace firebase { \ + extern void* FIREBASE_APP_REGISTER_CALLBACKS_INITIALIZER_NAME(module_name); \ + } /* namespace firebase */ + +// Generates code which references a module initializer. +// For example, FIREBASE_APP_REGISTER_REFERENCE(analytics) will register the +// module initializer for the analytics module. +#define FIREBASE_APP_REGISTER_CALLBACKS_REFERENCE(module_name) \ + FIREBASE_APP_REGISTER_CALLBACKS_INITIALIZER_VARIABLE(module_name) \ + namespace firebase { \ + static void* module_name##_ref FIREBASE_APP_KEEP_SYMBOL = \ + &FIREBASE_APP_REGISTER_CALLBACKS_INITIALIZER_NAME(module_name); \ + } /* namespace firebase */ +#endif // !defined(DOXYGEN) && !defined(SWIG) + +#if defined(SWIG) || defined(DOXYGEN) +// SWIG needs to ignore the FIREBASE_DEPRECATED tag. +#define FIREBASE_DEPRECATED +#endif // defined(SWIG) || defined(DOXYGEN) + +#ifndef FIREBASE_DEPRECATED +#ifdef __GNUC__ +#define FIREBASE_DEPRECATED __attribute__((deprecated)) +#elif defined(_MSC_VER) +#define FIREBASE_DEPRECATED __declspec(deprecated) +#else +// We don't know how to mark functions as "deprecated" with this compiler. +#define FIREBASE_DEPRECATED +#endif +#endif // FIREBASE_DEPRECATED + +// Calculates the number of elements in an array. +#define FIREBASE_ARRAYSIZE(x) (sizeof(x) / sizeof((x)[0])) + +// Guaranteed compile time strlen. +#define FIREBASE_STRLEN(s) (FIREBASE_ARRAYSIZE(s) - sizeof((s)[0])) + +#endif // FIREBASE_APP_SRC_INCLUDE_FIREBASE_INTERNAL_COMMON_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/internal/future_impl.h b/packages/firebase_core/firebase_core/firebase_core/firebase/internal/future_impl.h new file mode 100644 index 000000000000..59e7771d010b --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/internal/future_impl.h @@ -0,0 +1,359 @@ +/* + * Copyright 2016 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_APP_SRC_INCLUDE_FIREBASE_INTERNAL_FUTURE_IMPL_H_ +#define FIREBASE_APP_SRC_INCLUDE_FIREBASE_INTERNAL_FUTURE_IMPL_H_ + +/// @cond FIREBASE_APP_INTERNAL + +// You shouldn't include future_impl.h directly, since its just the inline +// implementation of the functions in future.h. Include future.h instead. +#include "firebase/future.h" + +#if defined(FIREBASE_USE_MOVE_OPERATORS) +#include +#endif // defined(FIREBASE_USE_MOVE_OPERATORS) + +namespace firebase { + +class ReferenceCountedFutureImpl; + +namespace detail { + +class CompletionCallbackHandle; + +/// Pure-virtual interface that APIs must implement to use Futures. +class FutureApiInterface { + public: + // typedef void FutureCallbackFn(const FutureBase* future); + virtual ~FutureApiInterface(); + + /// Increment the reference count on handle's asynchronous call. + /// Called when the Future is copied. + virtual void ReferenceFuture(const FutureHandle& handle) = 0; + + /// Decrement the reference count on handle's asynchronous call. + /// Called when the Future is destroyed or moved. + /// If the reference count drops to zero, the asynchronous call can be + /// forgotten. + virtual void ReleaseFuture(const FutureHandle& handle) = 0; + + /// Return the status of the asynchronous call. + virtual FutureStatus GetFutureStatus(const FutureHandle& handle) const = 0; + + /// Return the API-specific error. + /// Valid when GetFutureStatus() is kFutureStatusComplete, and undefined + /// otherwise. + virtual int GetFutureError(const FutureHandle& handle) const = 0; + + /// Return the API-specific error, in human-readable form, or "" if no message + /// has been provided. + /// Valid when GetFutureStatus() is kFutureStatusComplete, and undefined + /// otherwise. + virtual const char* GetFutureErrorMessage( + const FutureHandle& handle) const = 0; + + /// Return a pointer to the completed asynchronous result, or NULL if + /// result is still pending. + /// After an asynchronous call is marked complete, the API should not + /// modify the result (especially on a callback thread), since the threads + /// owning the Future can reference the result memory via this function. + virtual const void* GetFutureResult(const FutureHandle& handle) const = 0; + + /// Register a callback that will be called when this future's status is set + /// to Complete. If clear_existing_callbacks is true, then the new callback + /// will replace any existing callbacks, otherwise it will be added to the + /// list of callbacks. + /// + /// The future's result data will be passed back when the callback is + /// called, along with the user_data supplied here. + /// + /// After the callback has been called, if `user_data_delete_fn_ptr` is + /// non-null, then `(*user_data_delete_fn_ptr)(user_data)` will be called. + virtual CompletionCallbackHandle AddCompletionCallback( + const FutureHandle& handle, FutureBase::CompletionCallback callback, + void* user_data, void (*user_data_delete_fn)(void*), + bool clear_existing_callbacks) = 0; + + /// Unregister a callback that was previously registered with + /// `AddCompletionCallback`. + virtual void RemoveCompletionCallback( + const FutureHandle& handle, CompletionCallbackHandle callback_handle) = 0; + +#if defined(FIREBASE_USE_STD_FUNCTION) + /// Register a callback that will be called when this future's status is set + /// to Complete. + /// + /// If `clear_existing_callbacks` is true, then the new callback + /// will replace any existing callbacks, otherwise it will be added to the + /// list of callbacks. + /// + /// The future's result data will be passed back when the callback is + /// called. + /// + /// @return A handle that can be passed to `FutureBase::RemoveCompletion`. + virtual CompletionCallbackHandle AddCompletionCallbackLambda( + const FutureHandle& handle, + std::function callback, + bool clear_existing_callbacks) = 0; +#endif // defined(FIREBASE_USE_STD_FUNCTION) + + /// Register this Future instance to be cleaned up. + virtual void RegisterFutureForCleanup(FutureBase* future) = 0; + + /// Unregister this Future instance from the cleanup list. + virtual void UnregisterFutureForCleanup(FutureBase* future) = 0; +}; + +inline void RegisterForCleanup(FutureApiInterface* api, FutureBase* future) { + if (api != NULL) { // NOLINT + api->RegisterFutureForCleanup(future); + } +} + +inline void UnregisterForCleanup(FutureApiInterface* api, FutureBase* future) { + if (api != NULL) { // NOLINT + api->UnregisterFutureForCleanup(future); + } +} + +class CompletionCallbackHandle { + public: + // Construct a null CompletionCallbackHandle. + CompletionCallbackHandle() + : callback_(nullptr), + user_data_(nullptr), + user_data_delete_fn_(nullptr) {} + + private: + friend class ::firebase::FutureBase; + friend class ::firebase::ReferenceCountedFutureImpl; + CompletionCallbackHandle(FutureBase::CompletionCallback callback, + void* user_data, void (*user_data_delete_fn)(void*)) + : callback_(callback), + user_data_(user_data), + user_data_delete_fn_(user_data_delete_fn) {} + + FutureBase::CompletionCallback callback_; + void* user_data_; + void (*user_data_delete_fn_)(void*); +}; + +} // namespace detail + +template +void Future::OnCompletion(TypedCompletionCallback callback, + void* user_data) const { + FutureBase::OnCompletion(reinterpret_cast(callback), + user_data); +} + +#if defined(FIREBASE_USE_STD_FUNCTION) +template +inline void Future::OnCompletion( + std::function&)> callback) const { + FutureBase::OnCompletion( + *reinterpret_cast*>(&callback)); +} +#endif // defined(FIREBASE_USE_STD_FUNCTION) + +#if defined(INTERNAL_EXPERIMENTAL) +template +FutureBase::CompletionCallbackHandle Future::AddOnCompletion( + TypedCompletionCallback callback, void* user_data) const { + return FutureBase::AddOnCompletion( + reinterpret_cast(callback), user_data); +} + +#if defined(FIREBASE_USE_STD_FUNCTION) +template +inline FutureBase::CompletionCallbackHandle Future::AddOnCompletion( + std::function&)> callback) const { + return FutureBase::AddOnCompletion( + *reinterpret_cast*>(&callback)); +} +#endif // defined(FIREBASE_USE_STD_FUNCTION) + +#endif // defined(INTERNAL_EXPERIMENTAL) + +inline FutureBase::FutureBase() + : mutex_(Mutex::Mode::kModeNonRecursive), + api_(NULL), + handle_(0) {} // NOLINT + +inline FutureBase::FutureBase(detail::FutureApiInterface* api, + const FutureHandle& handle) + : mutex_(Mutex::Mode::kModeNonRecursive), api_(api), handle_(handle) { + api_->ReferenceFuture(handle_); + // Once the FutureBase has reference, we don't need extra handle reference. + handle_.Detach(); + detail::RegisterForCleanup(api_, this); +} + +inline FutureBase::~FutureBase() { Release(); } + +inline FutureBase::FutureBase(const FutureBase& rhs) + : mutex_(Mutex::Mode::kModeNonRecursive), + api_(NULL) // NOLINT +{ // NOLINT + *this = rhs; +} + +inline FutureBase& FutureBase::operator=(const FutureBase& rhs) { + Release(); + + detail::FutureApiInterface* new_api; + FutureHandle new_handle; + { + MutexLock lock(rhs.mutex_); + new_api = rhs.api_; + new_handle = rhs.handle_; + } + + { + MutexLock lock(mutex_); + api_ = new_api; + handle_ = new_handle; + + if (api_ != NULL) { // NOLINT + api_->ReferenceFuture(handle_); + } + detail::RegisterForCleanup(api_, this); + } + + return *this; +} + +#if defined(FIREBASE_USE_MOVE_OPERATORS) +inline FutureBase::FutureBase(FutureBase&& rhs) noexcept + : mutex_(Mutex::Mode::kModeNonRecursive), + api_(NULL) // NOLINT +{ + *this = std::move(rhs); +} + +inline FutureBase& FutureBase::operator=(FutureBase&& rhs) noexcept { + Release(); + + detail::FutureApiInterface* new_api; + FutureHandle new_handle; + { + MutexLock lock(rhs.mutex_); + detail::UnregisterForCleanup(rhs.api_, &rhs); + new_api = rhs.api_; + new_handle = rhs.handle_; + rhs.api_ = NULL; // NOLINT + } + + MutexLock lock(mutex_); + api_ = new_api; + handle_ = new_handle; + detail::RegisterForCleanup(api_, this); + return *this; +} +#endif // defined(FIREBASE_USE_MOVE_OPERATORS) + +inline void FutureBase::Release() { + MutexLock lock(mutex_); + if (api_ != NULL) { // NOLINT + detail::UnregisterForCleanup(api_, this); + api_->ReleaseFuture(handle_); + api_ = NULL; // NOLINT + } +} + +inline FutureStatus FutureBase::status() const { + MutexLock lock(mutex_); + return api_ == NULL ? // NOLINT + kFutureStatusInvalid + : api_->GetFutureStatus(handle_); +} + +inline int FutureBase::error() const { + MutexLock lock(mutex_); + return api_ == NULL ? -1 : api_->GetFutureError(handle_); // NOLINT +} + +inline const char* FutureBase::error_message() const { + MutexLock lock(mutex_); + return api_ == NULL ? NULL : api_->GetFutureErrorMessage(handle_); // NOLINT +} + +inline const void* FutureBase::result_void() const { + MutexLock lock(mutex_); + return api_ == NULL ? NULL : api_->GetFutureResult(handle_); // NOLINT +} + +inline void FutureBase::OnCompletion(CompletionCallback callback, + void* user_data) const { + MutexLock lock(mutex_); + if (api_ != NULL) { // NOLINT + api_->AddCompletionCallback(handle_, callback, user_data, nullptr, + /*clear_existing_callbacks=*/true); + } +} + +#if defined(INTERNAL_EXPERIMENTAL) +inline FutureBase::CompletionCallbackHandle FutureBase::AddOnCompletion( + CompletionCallback callback, void* user_data) const { + MutexLock lock(mutex_); + if (api_ != NULL) { // NOLINT + return api_->AddCompletionCallback(handle_, callback, user_data, nullptr, + /*clear_existing_callbacks=*/false); + } + return CompletionCallbackHandle(); +} + +inline void FutureBase::RemoveOnCompletion( + CompletionCallbackHandle completion_handle) const { + MutexLock lock(mutex_); + if (api_ != NULL) { // NOLINT + api_->RemoveCompletionCallback(handle_, completion_handle); + } +} +#endif // defined(INTERNAL_EXPERIMENTAL) + +#if defined(FIREBASE_USE_STD_FUNCTION) +inline void FutureBase::OnCompletion( + std::function callback) const { + MutexLock lock(mutex_); + if (api_ != NULL) { // NOLINT + api_->AddCompletionCallbackLambda(handle_, callback, + /*clear_existing_callbacks=*/true); + } +} + +#if defined(INTERNAL_EXPERIMENTAL) +inline FutureBase::CompletionCallbackHandle FutureBase::AddOnCompletion( + std::function callback) const { + MutexLock lock(mutex_); + if (api_ != NULL) { // NOLINT + return api_->AddCompletionCallbackLambda( + handle_, callback, + /*clear_existing_callbacks=*/false); + } + return CompletionCallbackHandle(); +} +#endif // defined(INTERNAL__EXPERIMENTAL) + +#endif // defined(FIREBASE_USE_STD_FUNCTION) + +// NOLINTNEXTLINE - allow namespace overridden +} // namespace firebase + +/// @endcond + +#endif // FIREBASE_APP_SRC_INCLUDE_FIREBASE_INTERNAL_FUTURE_IMPL_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/internal/mutex.h b/packages/firebase_core/firebase_core/firebase_core/firebase/internal/mutex.h new file mode 100644 index 000000000000..86f6a45d1b38 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/internal/mutex.h @@ -0,0 +1,100 @@ +/* + * Copyright 2016 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_APP_SRC_INCLUDE_FIREBASE_INTERNAL_MUTEX_H_ +#define FIREBASE_APP_SRC_INCLUDE_FIREBASE_INTERNAL_MUTEX_H_ + +#include "firebase/internal/platform.h" + +#if FIREBASE_PLATFORM_WINDOWS +#include +#else +#include +#endif // FIREBASE_PLATFORM_WINDOWS + +namespace firebase { + +#if !defined(DOXYGEN) + +/// @brief A simple synchronization lock. Only one thread at a time can Acquire. +class Mutex { + public: + // Bitfield that describes the mutex configuration. + enum Mode { + kModeNonRecursive = (0 << 0), + kModeRecursive = (1 << 0), + }; + + Mutex() : Mutex(kModeRecursive) {} + + explicit Mutex(Mode mode); + + ~Mutex(); + + // Acquires the lock for this mutex, blocking until it is available. + void Acquire(); + + // Releases the lock for this mutex acquired by a previous `Acquire()` call. + void Release(); + +// Returns the implementation-defined native mutex handle. +// Used by firebase::Thread implementation. +#if FIREBASE_PLATFORM_WINDOWS + HANDLE* native_handle() { return &synchronization_object_; } +#else + pthread_mutex_t* native_handle() { return &mutex_; } +#endif // FIREBASE_PLATFORM_WINDOWS + + private: + Mutex(const Mutex&) = delete; + Mutex& operator=(const Mutex&) = delete; + +#if FIREBASE_PLATFORM_WINDOWS + HANDLE synchronization_object_; + Mode mode_; +#else + pthread_mutex_t mutex_; +#endif // FIREBASE_PLATFORM_WINDOWS +}; + +/// @brief Acquire and hold a /ref Mutex, while in scope. +/// +/// Example usage: +/// \code{.cpp} +/// Mutex syncronization_mutex; +/// void MyFunctionThatRequiresSynchronization() { +/// MutexLock lock(syncronization_mutex); +/// // ... logic ... +/// } +/// \endcode +class MutexLock { + public: + explicit MutexLock(Mutex& mutex) : mutex_(&mutex) { mutex_->Acquire(); } + ~MutexLock() { mutex_->Release(); } + + private: + // Copy is disallowed. + MutexLock(const MutexLock& rhs); // NOLINT + MutexLock& operator=(const MutexLock& rhs); + + Mutex* mutex_; +}; + +#endif // !defined(DOXYGEN) + +} // namespace firebase + +#endif // FIREBASE_APP_SRC_INCLUDE_FIREBASE_INTERNAL_MUTEX_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/internal/platform.h b/packages/firebase_core/firebase_core/firebase_core/firebase/internal/platform.h new file mode 100644 index 000000000000..17d64e32d022 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/internal/platform.h @@ -0,0 +1,110 @@ +/* + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_APP_SRC_INCLUDE_FIREBASE_INTERNAL_PLATFORM_H_ +#define FIREBASE_APP_SRC_INCLUDE_FIREBASE_INTERNAL_PLATFORM_H_ + +// This header serts exactly one of these FIREBASE_PLATFORM macros to 1, and the +// rest to 0: +// +// FIREBASE_PLATFORM_ANDROID +// FIREBASE_PLATFORM_IOS +// FIREBASE_PLATFORM_TVOS +// FIREBASE_PLATFORM_OSX +// FIREBASE_PLATFORM_WINDOWS +// FIREBASE_PLATFORM_LINUX +// FIREBASE_PLATFORM_UNKNOWN +// +// You can use e.g. #if FIREBASE_PLATFORM_OSX to conditionally compile code +// after including this header. +// +// It also defines some convenience macros: +// FIREBASE_PLATFORM_DESKTOP (1 on OSX, WINDOWS, and LINUX, 0 otherwise) +// FIREBASE_PLATFORM_MOBILE (1 on IOS and ANDROID, 0 otherwise) + +#define FIREBASE_PLATFORM_ANDROID 0 +#define FIREBASE_PLATFORM_IOS 0 +#define FIREBASE_PLATFORM_TVOS 0 +#define FIREBASE_PLATFORM_OSX 0 +#define FIREBASE_PLATFORM_WINDOWS 0 +#define FIREBASE_PLATFORM_LINUX 0 +#define FIREBASE_PLATFORM_UNKNOWN 0 + +#ifdef __APPLE__ +#include "TargetConditionals.h" +#endif // __APPLE__ + +#if defined(__ANDROID__) +#undef FIREBASE_PLATFORM_ANDROID +#define FIREBASE_PLATFORM_ANDROID 1 +#elif defined(TARGET_OS_IOS) && TARGET_OS_IOS +#undef FIREBASE_PLATFORM_IOS +#define FIREBASE_PLATFORM_IOS 1 +#elif defined(TARGET_OS_TV) && TARGET_OS_TV +#undef FIREBASE_PLATFORM_TVOS +#define FIREBASE_PLATFORM_TVOS 1 +#elif defined(TARGET_OS_OSX) && TARGET_OS_OSX +#undef FIREBASE_PLATFORM_OSX +#define FIREBASE_PLATFORM_OSX 1 +#elif defined(_WIN32) +#undef FIREBASE_PLATFORM_WINDOWS +#define FIREBASE_PLATFORM_WINDOWS 1 +#elif defined(__linux__) +#undef FIREBASE_PLATFORM_LINUX +#define FIREBASE_PLATFORM_LINUX 1 +#else +#undef FIREBASE_PLATFORM_UNKNOWN +#define FIREBASE_PLATFORM_UNKNOWN 1 +#endif + +#if FIREBASE_PLATFORM_LINUX + +// Include std library header to get version defines +#include + +#if defined(__clang__) +#define FIREBASE_COMPILER_CLANG 1 +#elif defined(__GNUC__) +#define FIREBASE_COMPILER_GCC 1 +#endif + +#if defined(_LIBCPP_VERSION) +#define FIREBASE_STANDARD_LIBCPP 1 +#elif defined(__GLIBCXX__) +#define FIREBASE_STANDARD_LIBSTDCPP 1 +#endif + +#if (FIREBASE_COMPILER_CLANG && FIREBASE_STANDARD_LIBCPP) +#define FIREBASE_LINUX_BUILD_CONFIG_STRING "clang_libstdcpp" +#elif (FIREBASE_COMPILER_CLANG && FIREBASE_STANDARD_LIBSTDCPP) +#define FIREBASE_LINUX_BUILD_CONFIG_STRING "clang_libcpp" +#elif (FIREBASE_COMPILER_GCC && FIREBASE_STANDARD_LIBCPP) +#define FIREBASE_LINUX_BUILD_CONFIG_STRING "gcc_libstdcpp" +#elif (FIREBASE_COMPILER_GCC && FIREBASE_STANDARD_LIBSTDCPP) +#define FIREBASE_LINUX_BUILD_CONFIG_STRING "gcc_libcpp" +#else +#error "Unsupported compiler or standard library" +#endif + +#endif // FIREBASE_PLATFORM_LINUX + +#define FIREBASE_PLATFORM_MOBILE \ + (FIREBASE_PLATFORM_IOS || FIREBASE_PLATFORM_ANDROID) +#define FIREBASE_PLATFORM_DESKTOP \ + (FIREBASE_PLATFORM_LINUX || FIREBASE_PLATFORM_WINDOWS || \ + FIREBASE_PLATFORM_OSX) + +#endif // FIREBASE_APP_SRC_INCLUDE_FIREBASE_INTERNAL_PLATFORM_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/internal/type_traits.h b/packages/firebase_core/firebase_core/firebase_core/firebase/internal/type_traits.h new file mode 100644 index 000000000000..7c465ea27c1e --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/internal/type_traits.h @@ -0,0 +1,134 @@ +/* + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_APP_SRC_INCLUDE_FIREBASE_INTERNAL_TYPE_TRAITS_H_ +#define FIREBASE_APP_SRC_INCLUDE_FIREBASE_INTERNAL_TYPE_TRAITS_H_ + +#include +#include + +// Doxygen breaks trying to parse this file, and since it is internal logic, +// it doesn't need to be included in the generated documentation. +#ifndef DOXYGEN + +namespace firebase { + +template +struct remove_reference { + typedef T type; +}; + +template +struct remove_reference { + typedef T type; +}; + +template +struct remove_reference { + typedef T type; +}; + +template +struct is_array { + static constexpr bool value = false; +}; + +template +struct is_array { + static constexpr bool value = true; +}; + +template +struct is_array { + static constexpr bool value = true; +}; + +template +struct is_lvalue_reference { + static constexpr bool value = false; +}; + +template +struct is_lvalue_reference { + static constexpr bool value = true; +}; + +// STLPort does include header, but its contents are in `std::tr1` +// namespace. To work around this, use aliases. +// TODO(varconst): all of the reimplementations of traits above can be replaced +// with appropriate aliases. +// TODO(varconst): the traits in this file would be more conformant if they +// inherited from `std::integral_constant`. +#ifdef STLPORT +#define FIREBASE_TYPE_TRAITS_NS std::tr1 +#else +#define FIREBASE_TYPE_TRAITS_NS std +#endif + +template +using decay = FIREBASE_TYPE_TRAITS_NS::decay; + +template +using decay_t = typename decay::type; + +template +using enable_if = FIREBASE_TYPE_TRAITS_NS::enable_if; + +template +using is_floating_point = FIREBASE_TYPE_TRAITS_NS::is_floating_point; + +template +using is_integral = FIREBASE_TYPE_TRAITS_NS::is_integral; + +template +using is_same = FIREBASE_TYPE_TRAITS_NS::is_same; + +template +using integral_constant = FIREBASE_TYPE_TRAITS_NS::integral_constant; + +using true_type = FIREBASE_TYPE_TRAITS_NS::true_type; +using false_type = FIREBASE_TYPE_TRAITS_NS::false_type; + +#undef FIREBASE_TYPE_TRAITS_NS + +// `is_char::value` is true iff `T` is a character type (including `wchar_t` +// and C++11 fixed-width character types). +template +struct is_char { + static constexpr bool value = +#if __cplusplus >= 202002L + is_same::value || +#endif +#if __cplusplus >= 201103L + is_same::value || is_same::value || +#endif + is_same::value || is_same::value || + is_same::value || is_same::value; +}; + +// A subset of `std::is_integral`: excludes `bool` and character types. +template +struct is_integer { + static constexpr bool value = + is_integral::value && !is_same::value && !is_char::value; +}; + +// NOLINTNEXTLINE - allow namespace overridden +} // namespace firebase + +#endif // DOXYGEN + +#endif // FIREBASE_APP_SRC_INCLUDE_FIREBASE_INTERNAL_TYPE_TRAITS_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/log.h b/packages/firebase_core/firebase_core/firebase_core/firebase/log.h new file mode 100644 index 000000000000..3d36ce37dcb3 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/log.h @@ -0,0 +1,54 @@ +/* + * Copyright 2016 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_APP_SRC_INCLUDE_FIREBASE_LOG_H_ +#define FIREBASE_APP_SRC_INCLUDE_FIREBASE_LOG_H_ + +/// @brief Namespace that encompasses all Firebase APIs. +namespace firebase { + +/// @brief Levels used when logging messages. +enum LogLevel { + /// Verbose Log Level + kLogLevelVerbose = 0, + /// Debug Log Level + kLogLevelDebug, + /// Info Log Level + kLogLevelInfo, + /// Warning Log Level + kLogLevelWarning, + /// Error Log Level + kLogLevelError, + /// Assert Log Level + kLogLevelAssert, +}; + +/// @brief Sets the logging verbosity. +/// All log messages at or above the specific log level. +/// +/// @param[in] level Log level to display, by default this is set to +/// kLogLevelInfo. +void SetLogLevel(LogLevel level); + +/// @brief Gets the logging verbosity. +/// +/// @return Get the currently configured logging verbosity. +LogLevel GetLogLevel(); + +// NOLINTNEXTLINE - allow namespace overridden +} // namespace firebase + +#endif // FIREBASE_APP_SRC_INCLUDE_FIREBASE_LOG_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/messaging.h b/packages/firebase_core/firebase_core/firebase_core/firebase/messaging.h new file mode 100644 index 000000000000..e7c7f5776868 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/messaging.h @@ -0,0 +1,728 @@ +// Copyright 2016 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef FIREBASE_MESSAGING_SRC_INCLUDE_FIREBASE_MESSAGING_H_ +#define FIREBASE_MESSAGING_SRC_INCLUDE_FIREBASE_MESSAGING_H_ + +#include + +#include +#include +#include + +#include "firebase/app.h" +#include "firebase/future.h" +#include "firebase/internal/common.h" + +#if !defined(DOXYGEN) && !defined(SWIG) +FIREBASE_APP_REGISTER_CALLBACKS_REFERENCE(messaging) +#endif // !defined(DOXYGEN) && !defined(SWIG) + +namespace firebase { + +/// @brief Firebase Cloud Messaging API. +/// +/// Firebase Cloud Messaging allows you to send data from your server to your +/// users' devices, and receive messages from devices on the same connection +/// if you're using a XMPP server. +/// +/// The FCM service handles all aspects of queueing of messages and delivery +/// to client applications running on target devices. +namespace messaging { + +/// @brief A class to configure the behavior of Firebase Cloud Messaging. +/// +/// This class contains various configuration options that control some of +/// Firebase Cloud Messaging's behavior. +struct MessagingOptions { + /// Default constructor. + MessagingOptions() : suppress_notification_permission_prompt(false) {} + + /// If true, do not display the prompt to the user requesting permission to + /// allow notifications to this app. If the prompt is suppressed in this way, + /// the developer must manually prompt the user for permission at some point + /// in the future using `RequestPermission()`. + /// + /// If this prompt has already been accepted once in the past the prompt will + /// not be displayed again. + /// + /// This option currently only applies to iOS and tvOS. + bool suppress_notification_permission_prompt; +}; + +/// @brief Data structure for parameters that are unique to the Android +/// implementation. +struct AndroidNotificationParams { + /// The channel id that was provided when the message was sent. + std::string channel_id; +}; + +/// Used for messages that display a notification. +/// +/// On android, this requires that the app is using the Play Services client +/// library. +struct Notification { + Notification() : android(nullptr) {} + +#ifndef SWIG + /// Copy constructor. Makes a deep copy of this Message. + Notification(const Notification& other) : android(nullptr) { *this = other; } +#endif // !SWIG + +#ifndef SWIG + /// Copy assignment operator. Makes a deep copy of this Message. + Notification& operator=(const Notification& other) { + this->title = other.title; + this->body = other.body; + this->icon = other.icon; + this->sound = other.sound; + this->tag = other.tag; + this->color = other.color; + this->click_action = other.click_action; + this->body_loc_key = other.body_loc_key; + this->body_loc_args = other.body_loc_args; + this->title_loc_key = other.title_loc_key; + this->title_loc_args = other.title_loc_args; + delete this->android; + if (other.android) { + this->android = new AndroidNotificationParams(*other.android); + } else { + this->android = nullptr; + } + return *this; + } +#endif // !SWIG + + /// Destructor. + ~Notification() { delete android; } + + /// Indicates notification title. This field is not visible on tvOS, iOS + /// phones and tablets. + std::string title; + + /// Indicates notification body text. + std::string body; + + /// Indicates notification icon. Sets value to myicon for drawable resource + /// myicon. + std::string icon; + + /// Indicates a sound to play when the device receives the notification. + /// Supports default, or the filename of a sound resource bundled in the + /// app. + /// + /// Android sound files must reside in /res/raw/, while iOS and tvOS sound + /// files can be in the main bundle of the client app or in the + /// Library/Sounds folder of the app’s data container. + std::string sound; + + /// Indicates the badge on the client app home icon. iOS and tvOS only. + std::string badge; + + /// Indicates whether each notification results in a new entry in the + /// notification drawer on Android. If not set, each request creates a new + /// notification. If set, and a notification with the same tag is already + /// being shown, the new notification replaces the existing one in the + /// notification drawer. + std::string tag; + + /// Indicates color of the icon, expressed in \#rrggbb format. Android only. + std::string color; + + /// The action associated with a user click on the notification. + /// + /// On Android, if this is set, an activity with a matching intent filter is + /// launched when user clicks the notification. + /// + /// If set on iOS or tvOS, corresponds to category in APNS payload. + std::string click_action; + + /// Indicates the key to the body string for localization. + /// + /// On iOS and tvOS, this corresponds to "loc-key" in APNS payload. + /// + /// On Android, use the key in the app's string resources when populating this + /// value. + std::string body_loc_key; + + /// Indicates the string value to replace format specifiers in body string + /// for localization. + /// + /// On iOS and tvOS, this corresponds to "loc-args" in APNS payload. + /// + /// On Android, these are the format arguments for the string resource. For + /// more information, see [Formatting strings][1]. + /// + /// [1]: + /// https://developer.android.com/guide/topics/resources/string-resource.html#FormattingAndStyling + std::vector body_loc_args; + + /// Indicates the key to the title string for localization. + /// + /// On iOS and tvOS, this corresponds to "title-loc-key" in APNS payload. + /// + /// On Android, use the key in the app's string resources when populating this + /// value. + std::string title_loc_key; + + /// Indicates the string value to replace format specifiers in title string + /// for localization. + /// + /// On iOS and tvOS, this corresponds to "title-loc-args" in APNS payload. + /// + /// On Android, these are the format arguments for the string resource. For + /// more information, see [Formatting strings][1]. + /// + /// [1]: + /// https://developer.android.com/guide/topics/resources/string-resource.html#FormattingAndStyling + std::vector title_loc_args; + + /// Parameters that are unique to the Android implementation. + AndroidNotificationParams* android; +}; + +/// @brief Data structure used to send messages to, and receive messages from, +/// cloud messaging. +struct Message { + /// Initialize the message. + Message() + : time_to_live(0), + notification(nullptr), + notification_opened(false), + sent_time(0) {} + + /// Destructor. + ~Message() { delete notification; } + +#ifndef SWIG + /// Copy constructor. Makes a deep copy of this Message. + Message(const Message& other) : notification(nullptr) { *this = other; } +#endif // !SWIG + +#ifndef SWIG + /// Copy assignment operator. Makes a deep copy of this Message. + Message& operator=(const Message& other) { + this->from = other.from; + this->to = other.to; + this->collapse_key = other.collapse_key; + this->data = other.data; + this->raw_data = other.raw_data; + this->message_id = other.message_id; + this->message_type = other.message_type; + this->priority = other.priority; + this->original_priority = other.original_priority; + this->sent_time = other.sent_time; + this->time_to_live = other.time_to_live; + this->error = other.error; + this->error_description = other.error_description; + delete this->notification; + if (other.notification) { + this->notification = new Notification(*other.notification); + } else { + this->notification = nullptr; + } + this->notification_opened = other.notification_opened; + this->link = other.link; + return *this; + } +#endif // !SWIG + + /// Authenticated ID of the sender. This is a project number in most cases. + /// + /// Any value starting with google.com, goog. or gcm. are reserved. + /// + /// This field is only used for downstream messages received through + /// Listener::OnMessage(). + std::string from; + + /// This parameter specifies the recipient of a message. + /// + /// For example it can be a registration token, a topic name, an Instance ID + /// or project ID. + /// + /// PROJECT_ID@gcm.googleapis.com or Instance ID are accepted. + std::string to; + + /// This parameter identifies a group of messages (e.g., with collapse_key: + /// "Updates Available") that can be collapsed, so that only the last message + /// gets sent when delivery can be resumed. This is intended to avoid sending + /// too many of the same messages when the device comes back online or becomes + /// active. + /// + /// Note that there is no guarantee of the order in which messages get sent. + /// + /// Note: A maximum of 4 different collapse keys is allowed at any given time. + /// This means a FCM connection server can simultaneously store 4 different + /// send-to-sync messages per client app. If you exceed this number, there is + /// no guarantee which 4 collapse keys the FCM connection server will keep. + /// + /// This field is only used for downstream messages received through + /// Listener::OnMessage(). + std::string collapse_key; + + /// The metadata, including all original key/value pairs. Includes some of the + /// HTTP headers used when sending the message. `gcm`, `google` and `goog` + /// prefixes are reserved for internal use. + std::map data; + + /// Binary payload. + std::vector raw_data; + + /// Message ID. This can be specified by sender. Internally a hash of the + /// message ID and other elements will be used for storage. The ID must be + /// unique for each topic subscription - using the same ID may result in + /// overriding the original message or duplicate delivery. + std::string message_id; + + /// Equivalent with a content-type. + /// + /// Defined values: + /// - "deleted_messages" - indicates the server had too many messages and + /// dropped some, and the client should sync with his own server. + /// Current limit is 100 messages stored. + /// - "send_event" - indicates an upstream message has been pushed to the + /// FCM server. It does not guarantee the upstream destination received + /// it. + /// Parameters: "message_id" + /// - "send_error" - indicates an upstream message expired, without being + /// sent to the FCM server. + /// Parameters: "message_id" and "error" + /// + /// If this field is missing, the message is a regular message. + /// + /// This field is only used for downstream messages received through + /// Listener::OnMessage(). + std::string message_type; + + /// Sets the priority of the message. Valid values are "normal" and "high." On + /// iOS and tvOS, these correspond to APNs priority 5 and 10. + /// + /// By default, messages are sent with normal priority. Normal priority + /// optimizes the client app's battery consumption, and should be used unless + /// immediate delivery is required. For messages with normal priority, the app + /// may receive the message with unspecified delay. + /// + /// When a message is sent with high priority, it is sent immediately, and the + /// app can wake a sleeping device and open a network connection to your + /// server. + /// + /// For more information, see [Setting the priority of a message][1]. + /// + /// This field is only used for downstream messages received through + /// Listener::OnMessage(). + /// + /// [1]: + /// https://firebase.google.com/docs/cloud-messaging/concept-options#setting-the-priority-of-a-message + std::string priority; + + /// This parameter specifies 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. For more + /// information, see [Setting the lifespan of a message][1]. + /// + /// This field is only used for downstream messages received through + /// Listener::OnMessage(). + /// + /// [1]: https://firebase.google.com/docs/cloud-messaging/concept-options#ttl + int32_t time_to_live; + + /// Error code. Used in "nack" messages for CCS, and in responses from the + /// server. + /// See the CCS specification for the externally-supported list. + /// + /// This field is only used for downstream messages received through + /// Listener::OnMessage(). + std::string error; + + /// Human readable details about the error. + /// + /// This field is only used for downstream messages received through + /// Listener::OnMessage(). + std::string error_description; + + /// Optional notification to show. This only set if a notification was + /// received with this message, otherwise it is null. + /// + /// The notification is only guaranteed to be valid during the call to + /// Listener::OnMessage(). If you need to keep it around longer you will need + /// to make a copy of either the Message or Notification. Copying the Message + /// object implicitly makes a deep copy of the notification (allocated with + /// new) which is owned by the Message. + /// + /// This field is only used for downstream messages received through + /// Listener::OnMessage(). + Notification* notification; + + /// A flag indicating whether this message was opened by tapping a + /// notification in the OS system tray. If the message was received this way + /// this flag is set to true. + bool notification_opened; + + /// The link into the app from the message. + /// + /// This field is only used for downstream messages received through + /// Listener::OnMessage(). + std::string link; + + /// @cond FIREBASE_APP_INTERNAL + /// Original priority of the message. + std::string original_priority; + + /// UTC timestamp in milliseconds when the message was sent. + /// See https://en.wikipedia.org/wiki/Unix_time for details of UTC. + int64_t sent_time; + /// @endcond +}; + +/// @brief Base class used to receive messages from Firebase Cloud Messaging. +/// +/// You need to override base class methods to handle any events required by the +/// application. Methods are invoked asynchronously and may be invoked on other +/// threads. +class Listener { + public: + virtual ~Listener(); + + /// Called on the client when a message arrives. + /// + /// @param[in] message The data describing this message. + virtual void OnMessage(const Message& message) = 0; + + /// Called on the client when a registration token arrives. This function + /// will eventually be called in response to a call to + /// firebase::messaging::Initialize(...). + /// + /// @param[in] token The registration token. + virtual void OnTokenReceived(const char* token) = 0; +}; + +/// @brief Initialize Firebase Cloud Messaging. +/// +/// After Initialize is called, the implementation may call functions on the +/// Listener provided at any time. +/// +/// @param[in] app The Firebase App object for this application. +/// @param[in] listener A Listener object that listens for events from the +/// Firebase Cloud Messaging servers. +/// +/// @return kInitResultSuccess if initialization succeeded, or +/// kInitResultFailedMissingDependency on Android if Google Play services is +/// not available on the current device. +InitResult Initialize(const App& app, Listener* listener); + +/// @brief Initialize Firebase Cloud Messaging. +/// +/// After Initialize is called, the implementation may call functions on the +/// Listener provided at any time. +/// +/// @param[in] app The Firebase App object for this application. +/// @param[in] listener A Listener object that listens for events from the +/// Firebase Cloud Messaging servers. +/// @param[in] options A set of options that configure the +/// initialzation behavior of Firebase Cloud Messaging. +/// +/// @return kInitResultSuccess if initialization succeeded, or +/// kInitResultFailedMissingDependency on Android if Google Play services is +/// not available on the current device. +InitResult Initialize(const App& app, Listener* listener, + const MessagingOptions& options); + +/// @brief Terminate Firebase Cloud Messaging. +/// +/// Frees resources associated with Firebase Cloud Messaging. +/// +/// @note On Android, the services will not be shut down by this method. +void Terminate(); + +/// Determines if automatic token registration during initalization is enabled. +/// +/// @return true if auto token registration is enabled and false if disabled. +bool IsTokenRegistrationOnInitEnabled(); + +/// Enable or disable token registration during initialization of Firebase Cloud +/// Messaging. +/// +/// This token is what identifies the user to Firebase, so disabling this avoids +/// creating any new identity and automatically sending it to Firebase, unless +/// consent has been granted. +/// +/// If this setting is enabled, it triggers the token registration refresh +/// immediately. This setting is persisted across app restarts and overrides the +/// setting "firebase_messaging_auto_init_enabled" specified in your Android +/// manifest (on Android) or Info.plist (on iOS and tvOS). +/// +///

By default, token registration during initialization is enabled. +/// +/// The registration happens before you can programmatically disable it, so +/// if you need to change the default, (for example, because you want to prompt +/// the user before FCM generates/refreshes a registration token on app +/// startup), add to your application’s manifest: +/// +/// +/// @if NOT_DOXYGEN +/// +/// @else +/// @code +/// <meta-data android:name="firebase_messaging_auto_init_enabled" +/// android:value="false" /> +/// @endcode +/// @endif +/// +/// or on iOS or tvOS to your Info.plist: +/// +/// @if NOT_DOXYGEN +/// FirebaseMessagingAutoInitEnabled +/// +/// @else +/// @code +/// <key>FirebaseMessagingAutoInitEnabled</key> +/// <false/> +/// @endcode +/// @endif +/// +/// @param enable sets if a registration token should be requested on +/// initialization. +void SetTokenRegistrationOnInitEnabled(bool enable); + +#ifndef SWIG +/// @brief Set the listener for events from the Firebase Cloud Messaging +/// servers. +/// +/// A listener must be set for the application to receive messages from +/// the Firebase Cloud Messaging servers. The implementation may call functions +/// on the Listener provided at any time. +/// +/// @param[in] listener A Listener object that listens for events from the +/// Firebase Cloud Messaging servers. +/// +/// @return Pointer to the previously set listener. +Listener* SetListener(Listener* listener); +#endif // !SWIG + +/// Error code returned by Firebase Cloud Messaging C++ functions. +enum Error { + /// The operation was a success, no error occurred. + kErrorNone = 0, + /// Permission to receive notifications was not granted. + kErrorFailedToRegisterForRemoteNotifications, + /// Topic name is invalid for subscription/unsubscription. + kErrorInvalidTopicName, + /// Could not subscribe/unsubscribe because there is no registration token. + kErrorNoRegistrationToken, + /// Unknown error. + kErrorUnknown, +}; + +/// @brief Displays a prompt to the user requesting permission to display +/// notifications. +/// +/// The permission prompt only appears on iOS and tvOS. If the user has +/// already agreed to allow notifications, no prompt is displayed and the +/// returned future is completed immediately. +/// +/// @return A future that completes when the notification prompt has been +/// dismissed. +Future RequestPermission(); + +/// @brief Gets the result of the most recent call to RequestPermission(); +/// +/// @return Result of the most recent call to RequestPermission(). +Future RequestPermissionLastResult(); + +/// @brief Subscribe to receive all messages to the specified topic. +/// +/// Subscribes an app instance to a topic, enabling it to receive messages +/// sent to that topic. +/// +/// Call this function from the main thread. FCM is not thread safe. +/// +/// @param[in] topic The name of the topic to subscribe. Must match the +/// following regular expression: `[a-zA-Z0-9-_.~%]{1,900}`. +Future Subscribe(const char* topic); + +/// @brief Gets the result of the most recent call to Unsubscribe(); +/// +/// @return Result of the most recent call to Unsubscribe(). +Future SubscribeLastResult(); + +/// @brief Unsubscribe from a topic. +/// +/// Unsubscribes an app instance from a topic, stopping it from receiving +/// any further messages sent to that topic. +/// +/// Call this function from the main thread. FCM is not thread safe. +/// +/// @param[in] topic The name of the topic to unsubscribe from. Must match the +/// following regular expression: `[a-zA-Z0-9-_.~%]{1,900}`. +Future Unsubscribe(const char* topic); + +/// @brief Gets the result of the most recent call to Unsubscribe(); +/// +/// @return Result of the most recent call to Unsubscribe(). +Future UnsubscribeLastResult(); + +/// Determines whether Firebase Cloud Messaging exports message delivery metrics +/// to BigQuery. +/// +/// This function is currently only implemented on Android, and returns false +/// with no other behavior on other platforms. +/// +/// @return true if Firebase Cloud Messaging exports message delivery metrics to +/// BigQuery. +bool DeliveryMetricsExportToBigQueryEnabled(); + +/// Enables or disables Firebase Cloud Messaging message delivery metrics export +/// to BigQuery. +/// +/// By default, message delivery metrics are not exported to BigQuery. Use this +/// method to enable or disable the export at runtime. In addition, you can +/// enable the export by adding to your manifest. Note that the run-time method +/// call will override the manifest value. +/// +/// +/// +/// This function is currently only implemented on Android, and has no behavior +/// on other platforms. +/// +/// @param[in] enable Whether Firebase Cloud Messaging should export message +/// delivery metrics to BigQuery. +void SetDeliveryMetricsExportToBigQuery(bool enable); + +/// @brief This creates a Firebase Installations ID, if one does not exist, and +/// sends information about the application and the device where it's running to +/// the Firebase backend. +/// +/// @return A future with the token. +Future GetToken(); + +/// @brief Gets the result of the most recent call to GetToken(); +/// +/// @return Result of the most recent call to GetToken(). +Future GetTokenLastResult(); + +/// @brief Deletes the default token for this Firebase project. +/// +/// Note that this does not delete the Firebase Installations ID that may have +/// been created when generating the token. See Installations.Delete() for +/// deleting that. +/// +/// @return A future that completes when the token is deleted. +Future DeleteToken(); + +/// @brief Gets the result of the most recent call to DeleteToken(); +/// +/// @return Result of the most recent call to DeleteToken(). +Future DeleteTokenLastResult(); + +class PollableListenerImpl; + +/// @brief A listener that can be polled to consume pending `Message`s. +/// +/// This class is intended to be used with applications that have a main loop +/// that frequently updates, such as in the case of a game that has a main +/// loop that updates 30 to 60 times a second. Rather than respond to incoming +/// messages and tokens via the `OnMessage` virtual function, this class will +/// queue up the message internally in a thread-safe manner so that it can be +/// consumed with `PollMessage`. For example: +/// +/// ::firebase::messaging::PollableListener listener; +/// ::firebase::messaging::Initialize(app, &listener); +/// +/// while (true) { +/// std::string token; +/// if (listener.PollRegistrationToken(&token)) { +/// LogMessage("Received a registration token"); +/// } +/// +/// ::firebase::messaging::Message message; +/// while (listener.PollMessage(&message)) { +/// LogMessage("Received a new message"); +/// } +/// +/// // Remainder of application logic... +/// } +class PollableListener : public Listener { + public: + /// @brief The default constructor. + PollableListener(); + + /// @brief The required virtual destructor. + virtual ~PollableListener(); + + /// @brief An implementation of `OnMessage` which adds the incoming messages + /// to a queue, which can be consumed by calling `PollMessage`. + virtual void OnMessage(const Message& message); + + /// @brief An implementation of `OnTokenReceived` which stores the incoming + /// token so that it can be consumed by calling `PollRegistrationToken`. + virtual void OnTokenReceived(const char* token); + + /// @brief Returns the first message queued up, if any. + /// + /// If one or more messages has been received, the first message in the + /// queue will be popped and used to populate the `message` argument and the + /// function will return `true`. If there are no pending messages, `false` is + /// returned. This function should be called in a loop until all messages have + /// been consumed, like so: + /// + /// ::firebase::messaging::Message message; + /// while (listener.PollMessage(&message)) { + /// LogMessage("Received a new message"); + /// } + /// + /// @param[out] message The `Message` struct to be populated. If there were no + /// pending messages, `message` is not modified. + /// + /// @return Returns `true` if there was a pending message, `false` otherwise. + bool PollMessage(Message* message); + + /// @brief Returns the registration key, if a new one has been received. + /// + /// When a new registration token is received, it is cached internally and can + /// be retrieved by calling `PollRegistrationToken`. The cached registration + /// token will be used to populate the `token` argument, then the cache will + /// be cleared and the function will return `true`. If there is no cached + /// registration token this function retuns `false`. + /// + /// std::string token; + /// if (listener.PollRegistrationToken(&token)) { + /// LogMessage("Received a registration token"); + /// } + /// + /// @param[out] token A string to be populated with the new token if one has + /// been received. If there were no new token, the string is left unmodified. + /// + /// @return Returns `true` if there was a new token, `false` otherwise. + bool PollRegistrationToken(std::string* token) { + bool got_token; + std::string token_received = PollRegistrationToken(&got_token); + if (got_token) { + *token = token_received; + } + return got_token; + } + + private: + std::string PollRegistrationToken(bool* got_token); + + // The implementation of the `PollableListener`. + PollableListenerImpl* impl_; +}; + +} // namespace messaging +} // namespace firebase + +#endif // FIREBASE_MESSAGING_SRC_INCLUDE_FIREBASE_MESSAGING_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/remote_config.h b/packages/firebase_core/firebase_core/firebase_core/firebase/remote_config.h new file mode 100644 index 000000000000..a2bd41775775 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/remote_config.h @@ -0,0 +1,526 @@ +// Copyright 2016 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef FIREBASE_REMOTE_CONFIG_SRC_INCLUDE_FIREBASE_REMOTE_CONFIG_H_ +#define FIREBASE_REMOTE_CONFIG_SRC_INCLUDE_FIREBASE_REMOTE_CONFIG_H_ + +#include +#include +#include + +#include "firebase/app.h" +#include "firebase/future.h" +#include "firebase/internal/common.h" +#include "firebase/internal/platform.h" +#ifndef SWIG +#include "firebase/variant.h" +#endif // SWIG + +#if !defined(DOXYGEN) && !defined(SWIG) +FIREBASE_APP_REGISTER_CALLBACKS_REFERENCE(remote_config) +#endif // !defined(DOXYGEN) && !defined(SWIG) + +/// @brief Namespace that encompasses all Firebase APIs. +namespace firebase { + +#ifndef SWIG +/// @brief Firebase Remote Config API. +/// +/// Firebase Remote Config is a cloud service that lets you change the +/// appearance and behavior of your app without requiring users to download an +/// app update. +#endif // SWIG +namespace remote_config { + +/// @brief Describes the most recent fetch request status. +enum LastFetchStatus { + /// The most recent fetch was a success, and its data is ready to be + /// applied, if you have not already done so. + kLastFetchStatusSuccess, + /// The most recent fetch request failed. + kLastFetchStatusFailure, + /// The most recent fetch is still in progress. + kLastFetchStatusPending, +}; + +/// @brief Describes the most recent fetch failure. +enum FetchFailureReason { + /// The fetch has not yet failed. + kFetchFailureReasonInvalid, + /// The most recent fetch failed because it was throttled by the server. + /// (You are sending too many fetch requests in too short a time.) + kFetchFailureReasonThrottled, + /// The most recent fetch failed for an unknown reason. + kFetchFailureReasonError, +}; + +/// @brief Describes the state of the most recent Fetch() call. +/// Normally returned as a result of the GetInfo() function. +struct ConfigInfo { + /// @brief The time (in milliseconds since the epoch) that the last fetch + /// operation completed. + uint64_t fetch_time; + + /// @brief The status of the last fetch request. + LastFetchStatus last_fetch_status; + + /// @brief The reason the most recent fetch failed. + FetchFailureReason last_fetch_failure_reason; + + /// @brief The time (in milliseconds since the epoch) when the refreshing of + /// Remote Config data is throttled. + uint64_t throttled_end_time; +}; + +/// @brief Describes the source a config value was retrieved from. +enum ValueSource { + /// The value was not specified and no default was specified, so a static + /// value (0 for numeric values, an empty string for strings) was returned. + kValueSourceStaticValue, + /// The value was found in the remote data store, and returned. + kValueSourceRemoteValue, + /// The value was not specified, so the specified default value was + /// returned instead. + kValueSourceDefaultValue, +}; + +/// @brief Describes a retrieved value. +struct ValueInfo { + /// Where the config value was retrieved from (Default Config or Active + /// Config). + ValueSource source; + /// If true this indicates conversion to the requested type + /// succeeded, otherwise conversion failed so the static value for the + /// requested type was retrieved instead. + bool conversion_successful; +}; + +/// @brief Keys of API settings. +/// +/// @see SetConfigSetting +/// @see GetConfigSetting +enum ConfigSetting { + /// Set the value associated with this key to "1" to enable developer mode + /// (i.e disable throttling) and "0" to disable. + kConfigSettingDeveloperMode, +}; + +/// @brief The default cache expiration used by Fetch(), equal to 12 hours, +/// in milliseconds. +static const uint64_t kDefaultCacheExpiration = 60 * 60 * 12 * 1000; + +/// @brief The default timeout used by Fetch(), equal to 30 seconds, +/// in milliseconds. +static const uint64_t kDefaultTimeoutInMilliseconds = 30 * 1000; + +/// @brief Describes a mapping of a key to a string value. Used to set default +/// values. +struct ConfigKeyValue { + /// The lookup key string. +#ifndef SWIG + /// + /// @note Ensure this string stays valid for the duration of the + /// call to SetDefaults. +#endif // SWIG + const char* key; + /// The value string to be stored. +#ifndef SWIG + /// + /// @note Ensure this string stays valid for the duration of the + /// call to SetDefaults. +#endif // SWIG + const char* value; +}; + +#ifndef SWIG +/// @brief Describes a mapping of a key to a value of any type. Used to set +/// default values. +struct ConfigKeyValueVariant { + /// The lookup key string. + /// + /// @note Ensure this string stays valid for the duration of the + /// call to SetDefaults. + const char* key; + /// The value to be stored. The type of the Variant determines the type of + /// default data for the given key. + /// + /// @note If you use a Variant of type StaticString, ensure it stays + /// valid for the duration of the call to SetDefaults. + Variant value; +}; +#endif // SWIG + +/// @brief Configurations for Remote Config behavior. +struct ConfigSettings { + /// The timeout specifies how long the client should wait for a connection to + /// the Firebase Remote Config servers. + /// + /// @note A fetch call will fail if it takes longer than the specified timeout + /// to connect to the Remote Config servers. Default is 60 seconds. + uint64_t fetch_timeout_in_milliseconds = kDefaultTimeoutInMilliseconds; + + /// The minimum interval between successive fetch calls. + /// + /// @note Fetches less than duration seconds after the last fetch from the + /// Firebase Remote Config server would use values returned during the last + /// fetch. Default is 12 hours. + uint64_t minimum_fetch_interval_in_milliseconds = kDefaultCacheExpiration; +}; + +namespace internal { +class RemoteConfigInternal; +} // namespace internal + +#ifndef SWIG +/// @brief Entry point for the Firebase C++ SDK for Remote Config. +/// +/// To use the SDK, call firebase::remote_config::RemoteConfig::GetInstance() to +/// obtain an instance of RemoteConfig, then call operations on that instance. +/// The instance contains the complete set of FRC parameter values available to +/// your app. The instance also stores values fetched from the FRC Server until +/// they are made available for use with a call to @ref Activate(). +#endif // SWIG +class RemoteConfig { + public: + ~RemoteConfig(); + + /// @brief Returns a Future that contains ConfigInfo representing the + /// initialization status of this Firebase Remote Config instance. + /// Use this method to ensure Set/Get call not being blocked. + Future EnsureInitialized(); + + /// @brief Get the (possibly still pending) results of the most recent + /// EnsureInitialized() call. + /// + /// @return The future result from the last call to EnsureInitialized(). + Future EnsureInitializedLastResult(); + + /// Asynchronously activates the most recently fetched configs, so that the + /// fetched key value pairs take effect. + /// + /// @return A Future that contains true if fetched configs were + /// activated. The future will contain false if the configs were already + /// activated. + Future Activate(); + + /// @brief Get the (possibly still pending) results of the most recent + /// Activate() call. + /// + /// @return The future result from the last call to Activate(). + Future ActivateLastResult(); + + /// Asynchronously fetches and then activates the fetched configs. + /// + /// If the time elapsed since the last fetch from the Firebase Remote Config + /// backend is more than the default minimum fetch interval, configs are + /// fetched from the backend. + /// + /// After the fetch is complete, the configs are activated so that the fetched + /// key value pairs take effect. + /// + /// @return A Future that contains true if the current call + /// activated the fetched configs; if no configs were fetched from the backend + /// and the local fetched configs have already been activated, the future will + /// contain false. + Future FetchAndActivate(); + + /// @brief Get the (possibly still pending) results of the most recent + /// FetchAndActivate() call. + /// + /// @return The future result from the last call to FetchAndActivate(). + Future FetchAndActivateLastResult(); + + /// @brief Fetches config data from the server. + /// + /// @note This does not actually apply the data or make it accessible, + /// it merely retrieves it and caches it. To accept and access the newly + /// retrieved values, you must call @ref Activate(). + /// + /// Note that this function is asynchronous, and will normally take an + /// unspecified amount of time before completion. + /// + /// @return A Future which can be used to determine when the fetch is + /// complete. + Future Fetch(); + + /// @brief Fetches config data from the server. + /// + /// @note This does not actually apply the data or make it accessible, + /// it merely retrieves it and caches it. To accept and access the newly + /// retrieved values, you must call @ref Activate(). + /// Note that this function is asynchronous, and will normally take an + /// unspecified amount of time before completion. + /// + /// @param[in] cache_expiration_in_seconds The number of seconds to keep + /// previously fetch data available. If cached data is available that is + /// newer than cache_expiration_in_seconds, then the function returns + /// immediately and does not fetch any data. A cache_expiration_in_seconds of + /// zero will always cause a fetch. + /// + /// @return A Future which can be used to determine when the fetch is + /// complete. + Future Fetch(uint64_t cache_expiration_in_seconds); + + /// @brief Get the (possibly still pending) results of the most recent Fetch() + /// call. + /// + /// @return The future result from the last call to Fetch(). + Future FetchLastResult(); + +#if defined(__ANDROID__) + /// @brief Sets the default values, using an XML resource. + /// + /// @note This method is specific to the Android implementation. + /// + /// This completely overwrites all previous default values. + /// + /// @param[in] defaults_resource_id Id for the XML resource, which should be + /// in your applications res/xml folder. + /// + /// @return a Future which can be used to determine when the operation is + /// complete. + Future SetDefaults(int defaults_resource_id); +#endif // __ANDROID__ + +#ifndef SWIG + /// @brief Sets the default values based on a mapping of string to Variant. + /// This allows you to specify defaults of type other than string. + /// + /// The type of each Variant in the map determines the type of data for which + /// you are providing a default. For example, boolean values can be retrieved + /// with GetBool(), integer values can be retrieved with GetLong(), double + /// values can be retrieved with GetDouble(), string values can be retrieved + /// with GetString(), and binary data can be retrieved with GetData(). + /// Aggregate Variant types are not allowed. + /// + /// @see firebase::Variant for more information on how to create a Variant of + /// each type. + /// + /// @note This completely overrides all previous values. + /// + /// @param defaults Array of ConfigKeyValueVariant, representing the new set + /// of defaults to apply. If the same key is specified multiple times, the + /// value associated with the last duplicate key is applied. + /// @param number_of_defaults Number of elements in the defaults array. + /// + /// @return a Future which can be used to determine when the operation is + /// complete. + Future SetDefaults(const ConfigKeyValueVariant* defaults, + size_t number_of_defaults); +#endif // SWIG + + /// @brief Sets the default values based on a string map. + /// + /// @note This completely overrides all previous values. + /// + /// @param defaults Array of ConfigKeyValue, representing the new set of + /// defaults to apply. If the same key is specified multiple times, the + /// value associated with the last duplicate key is applied. + /// @param number_of_defaults Number of elements in the defaults array. + /// + /// @return a Future which can be used to determine when the operation is + /// complete. + Future SetDefaults(const ConfigKeyValue* defaults, + size_t number_of_defaults); + + /// @brief Get the (possibly still pending) results of the most recent + /// SetDefaults() call. + /// + /// @return The future result from the last call to SetDefaults(). + Future SetDefaultsLastResult(); + + /// @brief Asynchronously changes the settings for this Remote Config + /// instance. + /// + /// @param settings The new settings to be applied. + /// + /// @return a Future which can be used to determine when the operation is + /// complete. + Future SetConfigSettings(ConfigSettings settings); + + /// @brief Gets the current settings of the RemoteConfig object. + /// + /// @return A ConfigSettings struct. + ConfigSettings GetConfigSettings(); + + /// @brief Get the (possibly still pending) results of the most recent + /// SetConfigSettings() call. + /// + /// @return The future result from the last call to SetConfigSettings(). + Future SetConfigSettingsLastResult(); + + /// @brief Returns the value associated with a key, converted to a bool. + /// + /// Values of "1", "true", "t", "yes", "y" and "on" are interpreted (case + /// insensitive) as true and "0", "false", "f", "no", "n", "off", + /// and empty strings are interpreted (case insensitive) as + /// false. + /// + /// @param[in] key Key of the value to be retrieved. + /// + /// @return Value associated with the specified key converted to a boolean + /// value. + bool GetBoolean(const char* key); + + /// @brief Returns the value associated with a key, converted to a bool. + /// + /// Values of "1", "true", "t", "yes", "y" and "on" are interpreted (case + /// insensitive) as true and "0", "false", "f", "no", "n", "off", + /// and empty strings are interpreted (case insensitive) as + /// false. + /// + /// @param[in] key Key of the value to be retrieved. + /// @param[out] info A return value, specifying the source of the returned + /// value. + /// + /// @return Value associated with the specified key converted to a boolean + /// value. + bool GetBoolean(const char* key, ValueInfo* info); + + /// @brief Returns the value associated with a key, converted to a 64-bit + /// integer. + /// + /// @param[in] key Key of the value to be retrieved. + /// + /// @return Value associated with the specified key converted to a 64-bit + /// integer. + int64_t GetLong(const char* key); + + /// @brief Returns the value associated with a key, converted to a 64-bit + /// integer. + /// + /// @param[in] key Key of the value to be retrieved. + /// @param[out] info A return value, specifying the source of the returned + /// value. + /// + /// @return Value associated with the specified key converted to a 64-bit + /// integer. + int64_t GetLong(const char* key, ValueInfo* info); + + /// @brief Returns the value associated with a key, converted to a double. + /// + /// @param[in] key Key of the value to be retrieved. + /// + /// @return Value associated with the specified key converted to a double. + double GetDouble(const char* key); + + /// @brief Returns the value associated with a key, converted to a double. + /// + /// @param[in] key Key of the value to be retrieved. + /// @param[out] info A return value, specifying the source of the returned + /// value. + /// + /// @return Value associated with the specified key converted to a double. + double GetDouble(const char* key, ValueInfo* info); + + /// @brief Returns the value associated with a key, converted to a string. + /// + /// @param[in] key Key of the value to be retrieved. + /// + /// @return Value as a string associated with the specified key. + std::string GetString(const char* key); + + /// @brief Returns the value associated with a key, converted to a string. + /// + /// @param[in] key Key of the value to be retrieved. + /// @param[out] info A return value, specifying the source of the returned + /// value. + /// + /// @return Value as a string associated with the specified key. + std::string GetString(const char* key, ValueInfo* info); + + /// @brief Returns the value associated with a key, as a vector of raw + /// byte-data. + /// + /// @param[in] key Key of the value to be retrieved. + /// + /// @return Vector of bytes. + std::vector GetData(const char* key); + + /// @brief Returns the value associated with a key, as a vector of raw + /// byte-data. + /// + /// @param[in] key Key of the value to be retrieved. + /// @param[out] info A return value, specifying the source of the returned + /// value. + /// + /// @return Vector of bytes. + std::vector GetData(const char* key, ValueInfo* info); + + /// @brief Gets the set of keys that start with the given prefix. + /// + /// @param[in] prefix The key prefix to look for. If empty or null, this + /// method will return all keys. + /// + /// @return Set of Remote Config parameter keys that start with the specified + /// prefix. Will return an empty set if there are no keys with the given + /// prefix. + std::vector GetKeysByPrefix(const char* prefix); + + /// @brief Gets the set of all keys. + /// + /// @return Set of all Remote Config parameter keys. + std::vector GetKeys(); + + /// @brief Returns a Map of Firebase Remote Config key value pairs. + /// + /// Evaluates the values of the parameters in the following order: + /// The activated value, if the last successful @ref Activate() contained the + /// key. The default value, if the key was set with @ref SetDefaults(). + std::map GetAll(); + + /// @brief Returns information about the last fetch request, in the form + /// of a ConfigInfo struct. + /// + /// @return A ConfigInfo struct, containing fields reflecting the state + /// of the most recent fetch request. + const ConfigInfo GetInfo(); + + /// Gets the App this remote config object is connected to. + App* app() { return app_; } + + /// Returns the RemoteConfig object for an App. Creates the RemoteConfig if + /// required. + /// + /// To get the RemoteConfig object for the default app, use, + /// GetInstance(GetDefaultFirebaseApp()); + /// + /// If the library RemoteConfig fails to initialize, init_result_out will be + /// written with the result status (if a pointer is given). + /// + /// @param[in] app The App to use for the RemoteConfig object. + static RemoteConfig* GetInstance(App* app); + + private: + explicit RemoteConfig(App* app); + + // Find RemoteConfig instance using App. Return null if the instance does not + // exist. + static RemoteConfig* FindRemoteConfig(App* app); + + // Clean up RemoteConfig instance. + void DeleteInternal(); + + /// The Firebase App this remote config is connected to. + App* app_; + + bool InitInternal(); + + internal::RemoteConfigInternal* internal_; +}; + +} // namespace remote_config +} // namespace firebase + +#endif // FIREBASE_REMOTE_CONFIG_SRC_INCLUDE_FIREBASE_REMOTE_CONFIG_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/storage.h b/packages/firebase_core/firebase_core/firebase_core/firebase/storage.h new file mode 100644 index 000000000000..8d081e4c0ead --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/storage.h @@ -0,0 +1,161 @@ +// Copyright 2016 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_H_ +#define FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_H_ + +#include + +#include "firebase/app.h" +#include "firebase/internal/common.h" +#include "firebase/storage/common.h" +#include "firebase/storage/controller.h" +#include "firebase/storage/listener.h" +#include "firebase/storage/metadata.h" +#include "firebase/storage/storage_reference.h" + +#if !defined(DOXYGEN) +#ifndef SWIG +FIREBASE_APP_REGISTER_CALLBACKS_REFERENCE(storage) +#endif // SWIG +#endif // !defined(DOXYGEN) + +namespace firebase { + +/// Namespace for the Firebase C++ SDK for Cloud Storage. +namespace storage { + +namespace internal { +class StorageInternal; +class MetadataInternal; +} // namespace internal + +class StorageReference; + +#ifndef SWIG +/// @brief Entry point for the Firebase C++ SDK for Cloud Storage. +/// +/// To use the SDK, call firebase::storage::Storage::GetInstance() to +/// obtain an instance of Storage, then use GetReference() to obtain references +/// to child blobs. From there you can upload data with +/// StorageReference::PutStream(), get data via StorageReference::GetStream(). +#endif // SWIG +class Storage { + public: + /// @brief Destructor. You may delete an instance of Storage when + /// you are finished using it, to shut down the Storage library. + ~Storage(); + + /// @brief Get an instance of Storage corresponding to the given App. + /// + /// Cloud Storage uses firebase::App to communicate with Firebase + /// Authentication to authenticate users to the server backend. + /// + /// @param[in] app An instance of firebase::App. Cloud Storage will use + /// this to communicate with Firebase Authentication. + /// @param[out] init_result_out Optional: If provided, write the init result + /// here. Will be set to kInitResultSuccess if initialization succeeded, or + /// kInitResultFailedMissingDependency on Android if Google Play services is + /// not available on the current device. + /// + /// @returns An instance of Storage corresponding to the given App. + static Storage* GetInstance(::firebase::App* app, + InitResult* init_result_out = nullptr); + + /// @brief Get an instance of Storage corresponding to the given App, + /// with the given Cloud Storage URL. + /// + /// Cloud Storage uses firebase::App to communicate with Firebase + /// Authentication to authenticate users to the server backend. + /// + /// @param[in] app An instance of firebase::App. Cloud Storage will use + /// this to communicate with Firebase Authentication. + /// @param[in] url Cloud Storage URL. + /// @param[out] init_result_out Optional: If provided, write the init result + /// here. Will be set to kInitResultSuccess if initialization succeeded, or + /// kInitResultFailedMissingDependency on Android if Google Play services is + /// not available on the current device. + /// + /// @returns An instance of Storage corresponding to the given App. + static Storage* GetInstance(::firebase::App* app, const char* url, + InitResult* init_result_out = nullptr); + + /// @brief Get the firease::App that this Storage was created with. + /// + /// @returns The firebase::App this Storage was created with. + ::firebase::App* app(); + + /// @brief Get the URL that this Storage was created with. + /// + /// @returns The URL this Storage was created with, or an empty + /// string if this Storage was created with default parameters. + std::string url(); + + /// @brief Get a StorageReference to the root of the database. + StorageReference GetReference() const; + + /// @brief Get a StorageReference for the specified path. + StorageReference GetReference(const char* path) const; + /// @brief Get a StorageReference for the specified path. + StorageReference GetReference(const std::string& path) const { + return GetReference(path.c_str()); + } + + /// @brief Get a StorageReference for the provided URL. + StorageReference GetReferenceFromUrl(const char* url) const; + /// @brief Get a StorageReference for the provided URL. + StorageReference GetReferenceFromUrl(const std::string& url) const { + return GetReferenceFromUrl(url.c_str()); + } + + /// @brief Returns the maximum time in seconds to retry a download if a + /// failure occurs. + double max_download_retry_time(); + /// @brief Sets the maximum time to retry a download if a failure occurs. + /// Defaults to 600 seconds (10 minutes). + void set_max_download_retry_time(double max_transfer_retry_seconds); + + /// @brief Returns the maximum time to retry an upload if a failure occurs. + double max_upload_retry_time(); + /// @brief Sets the maximum time to retry an upload if a failure occurs. + /// Defaults to 600 seconds (10 minutes). + void set_max_upload_retry_time(double max_transfer_retry_seconds); + + /// @brief Returns the maximum time to retry operations other than upload + /// and download if a failure occurs. + double max_operation_retry_time(); + /// @brief Sets the maximum time to retry operations other than upload and + /// download if a failure occurs. Defaults to 120 seconds (2 minutes). + void set_max_operation_retry_time(double max_transfer_retry_seconds); + + private: + /// @cond FIREBASE_APP_INTERNAL + friend class Metadata; + friend class internal::MetadataInternal; + + Storage(::firebase::App* app, const char* url); + Storage(const Storage& src); + Storage& operator=(const Storage& src); + + // Destroy the internal_ object. + void DeleteInternal(); + + internal::StorageInternal* internal_; + /// @endcond +}; + +} // namespace storage +} // namespace firebase + +#endif // FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/storage/common.h b/packages/firebase_core/firebase_core/firebase_core/firebase/storage/common.h new file mode 100644 index 000000000000..567ed714920c --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/storage/common.h @@ -0,0 +1,62 @@ +// Copyright 2016 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_COMMON_H_ +#define FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_COMMON_H_ + +namespace firebase { +namespace storage { + +/// Error code returned by Cloud Storage C++ functions. +enum Error { + /// The operation was a success, no error occurred. + kErrorNone = 0, + /// An unknown error occurred. + kErrorUnknown, + /// No object exists at the desired reference. + kErrorObjectNotFound, + /// No bucket is configured for Cloud Storage. + kErrorBucketNotFound, + /// No project is configured for Cloud Storage. + kErrorProjectNotFound, + /// Quota on your Cloud Storage bucket has been exceeded. + kErrorQuotaExceeded, + /// User is unauthenticated. + kErrorUnauthenticated, + /// User is not authorized to perform the desired action. + kErrorUnauthorized, + /// The maximum time limit on an operation (upload, download, delete, etc.) + /// has been exceeded. + kErrorRetryLimitExceeded, + /// File on the client does not match the checksum of the file received by the + /// server. + kErrorNonMatchingChecksum, + /// Size of the downloaded file exceeds the amount of memory allocated for the + /// download. + kErrorDownloadSizeExceeded, + /// User cancelled the operation. + kErrorCancelled, +}; + +/// @brief Get the human-readable error message corresponding to an error code. +/// +/// @param[in] error Error code to get the error message for. +/// +/// @returns Statically-allocated string describing the error. +const char* GetErrorMessage(Error error); + +} // namespace storage +} // namespace firebase + +#endif // FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_COMMON_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/storage/controller.h b/packages/firebase_core/firebase_core/firebase_core/firebase/storage/controller.h new file mode 100644 index 000000000000..42f29aa0c73b --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/storage/controller.h @@ -0,0 +1,146 @@ +// Copyright 2016 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_CONTROLLER_H_ +#define FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_CONTROLLER_H_ + +#include "firebase/storage/storage_reference.h" + +namespace firebase { +namespace storage { + +/// @cond FIREBASE_APP_INTERNAL +namespace internal { +class ControllerInternal; +class ListenerInternal; +class RestOperation; +} // namespace internal +/// @endcond + +/// @brief Controls an ongoing operation, allowing the caller to Pause, Resume +/// or Cancel an ongoing download or upload. +/// +/// An instance of Controller can be constructed and passed to +/// StorageReference::GetBytes(), StorageReference::GetFile(), +/// StorageReference::PutBytes(), or StorageReference::PutFile() to become +/// associated with it. Each Controller can only be associated with one +/// operation at a time. +/// +/// A Controller is also passed as an argument to Listener's callbacks. The +/// Controller passed to a StorageReference operation is not the same object +/// passed to Listener callbacks (though it refers to the same operation), so +/// there are no restrictions on the lifetime of the Controller the user creates +/// (but the Controller passed into a Listener callbacks should only be used +/// from within that callback). +/// +/// This class is currently not thread safe and can only be called on the main +/// thread. +class Controller { + public: + /// @brief Default constructor. + /// + /// You may construct your own Controller to pass into various + /// StorageReference operations. + Controller(); + + /// @brief Destructor. + ~Controller(); + + /// @brief Copy constructor. + /// + /// @param[in] other Controller to copy from. + Controller(const Controller& other); + + /// @brief Copy assignment operator. + /// + /// @param[in] other Controller to copy from. + /// + /// @returns Reference to the destination Controller. + Controller& operator=(const Controller& other); + +#if defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) + /// @brief Move constructor. Moving is an efficient operation for + /// Controller instances. + /// + /// @param[in] other Controller to move from. + Controller(Controller&& other); + + /// @brief Move assignment operator. Moving is an efficient operation for + /// Controller instances. + /// + /// @param[in] other Controller to move from. + /// + /// @returns Reference to the destination Controller. + Controller& operator=(Controller&& other); +#endif // defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) + + /// @brief Pauses the operation currently in progress. + /// + /// @returns True if the operation was successfully paused, false otherwise. + bool Pause(); + + /// @brief Resumes the operation that is paused. + /// + /// @returns True if the operation was successfully resumed, false otherwise. + bool Resume(); + + /// @brief Cancels the operation currently in progress. + /// + /// @returns True if the operation was successfully canceled, false otherwise. + bool Cancel(); + + /// @brief Returns true if the operation is paused. + bool is_paused() const; + + /// @brief Returns the number of bytes transferred so far. + /// + /// @returns The number of bytes transferred so far. + int64_t bytes_transferred() const; + + /// @brief Returns the total bytes to be transferred. + /// + /// @returns The total bytes to be transferred. This will return -1 if + /// the size of the transfer is unknown. + int64_t total_byte_count() const; + + /// @brief Returns the StorageReference associated with this Controller. + /// + /// @returns The StorageReference associated with this Controller. + StorageReference GetReference() const; + + /// @brief Returns true if this Controller is valid, false if it is not + /// valid. An invalid Controller is one that is not associated with an + /// operation. + /// + /// @returns true if this Controller is valid, false if this Controller is + /// invalid. + bool is_valid() const; + + private: + /// @cond FIREBASE_APP_INTERNAL + friend class internal::StorageReferenceInternal; + friend class internal::ControllerInternal; + friend class internal::ListenerInternal; + friend class internal::RestOperation; + + Controller(internal::ControllerInternal* internal); + + internal::ControllerInternal* internal_; + /// @endcond +}; + +} // namespace storage +} // namespace firebase + +#endif // FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_CONTROLLER_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/storage/listener.h b/packages/firebase_core/firebase_core/firebase_core/firebase/storage/listener.h new file mode 100644 index 000000000000..8bd624f61537 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/storage/listener.h @@ -0,0 +1,74 @@ +// Copyright 2016 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_LISTENER_H_ +#define FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_LISTENER_H_ + +#include "firebase/storage/controller.h" + +namespace firebase { +namespace storage { + +/// @cond FIREBASE_APP_INTERNAL +namespace internal { +class ListenerInternal; +class StorageInternal; +class StorageReferenceInternal; +class RestOperation; +} // namespace internal +/// @endcond + +/// @brief Base class used to receive pause and progress events on a running +/// read or write operation. +/// +/// Subclasses of this listener class can be used to receive events about data +/// transfer progress a location. Attach the listener to a location using +/// StorageReference::GetBytes(), StorageReference::GetFile(), +/// StorageReference::PutBytes(), and StorageReference::PutFile(); then +/// OnPaused() will be called whenever the Read or Write operation is paused, +/// and OnProgress() will be called periodically as the transfer makes progress. +class Listener { + public: + /// @brief Constructor. + Listener(); + + /// @brief Virtual destructor. + virtual ~Listener(); + + /// @brief The operation was paused. + /// + /// @param[in] controller A controller that can be used to check the status + /// and make changes to the ongoing operation. + virtual void OnPaused(Controller* controller) = 0; + + /// @brief There has been progress event. + /// + /// @param[in] controller A controller that can be used to check the status + /// and make changes to the ongoing operation. + virtual void OnProgress(Controller* controller) = 0; + + private: + /// @cond FIREBASE_APP_INTERNAL + friend class internal::StorageReferenceInternal; + friend class internal::RestOperation; + + // Platform specific data. + internal::ListenerInternal* impl_; + /// @endcond +}; + +} // namespace storage +} // namespace firebase + +#endif // FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_LISTENER_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/storage/metadata.h b/packages/firebase_core/firebase_core/firebase_core/firebase/storage/metadata.h new file mode 100644 index 000000000000..8d697c1072e7 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/storage/metadata.h @@ -0,0 +1,276 @@ +// Copyright 2016 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_METADATA_H_ +#define FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_METADATA_H_ + +#include +#include +#include +#include + +#include "firebase/internal/common.h" + +namespace firebase { +namespace storage { + +namespace internal { +class MetadataInternal; +class MetadataInternalCommon; +class StorageInternal; +class StorageReferenceInternal; +} // namespace internal + +class Storage; +class StorageReference; + +/// @brief Metadata stores default attributes such as size and content type. +/// +/// Metadata for a StorageReference. You may also store custom metadata key +/// value pairs. Metadata values may be used to authorize operations using +/// declarative validation rules. +class Metadata { + public: + /// @brief Create a default Metadata that you can modify and use. + Metadata(); + +#ifdef INTERNAL_EXPERIMENTAL + Metadata(internal::MetadataInternal* internal); +#endif + + /// @brief Copy constructor. + /// + /// @param[in] other Metadata to copy from. + Metadata(const Metadata& other); + + /// @brief Copy assignment operator. + /// + /// @param[in] other Metadata to copy from. + /// + /// @returns Reference to the destination Metadata. + Metadata& operator=(const Metadata& other); + +#if defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) + /// @brief Move constructor. Moving is an efficient operation for Metadata. + /// + /// @param[in] other Metadata to move from. + Metadata(Metadata&& other); + + /// @brief Move assignment operator. Moving is an efficient operation for + /// Metadata. + /// + /// @param[in] other Metadata to move from. + /// + /// @returns Reference to the destination Metadata. + Metadata& operator=(Metadata&& other); +#endif // defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) + + ~Metadata(); + + /// @brief Return the owning Google Cloud Storage bucket for the + /// StorageReference. + /// + /// @returns The owning Google Cloud Storage bucket for the StorageReference. + const char* bucket() const; + + /// @brief Set the Cache Control setting of the StorageReference. + /// + /// @see https://tools.ietf.org/html/rfc7234#section-5.2 + void set_cache_control(const char* cache_control); + + /// @brief Set the Cache Control setting of the StorageReference. + /// + /// @see https://tools.ietf.org/html/rfc7234#section-5.2 + void set_cache_control(const std::string& cache_control) { + set_cache_control(cache_control.c_str()); + } + + /// @brief Return the Cache Control setting of the StorageReference. + /// + /// @returns The Cache Control setting of the StorageReference. + /// + /// @see https://tools.ietf.org/html/rfc7234#section-5.2 + const char* cache_control() const; + + /// @brief Set the content disposition of the StorageReference. + /// + /// @see https://tools.ietf.org/html/rfc6266 + void set_content_disposition(const char* disposition); + + /// @brief Set the content disposition of the StorageReference. + /// + /// @see https://tools.ietf.org/html/rfc6266 + void set_content_disposition(const std::string& disposition) { + set_content_disposition(disposition.c_str()); + } + + /// @brief Return the content disposition of the StorageReference. + /// + /// @returns The content disposition of the StorageReference. + /// + /// @see https://tools.ietf.org/html/rfc6266 + const char* content_disposition() const; + + /// @brief Set the content encoding for the StorageReference. + /// + /// @see https://tools.ietf.org/html/rfc2616#section-14.11 + void set_content_encoding(const char* encoding); + + /// @brief Set the content encoding for the StorageReference. + /// + /// @see https://tools.ietf.org/html/rfc2616#section-14.11 + void set_content_encoding(const std::string& encoding) { + set_content_encoding(encoding.c_str()); + } + + /// @brief Return the content encoding for the StorageReference. + /// + /// @returns The content encoding for the StorageReference. + /// + /// @see https://tools.ietf.org/html/rfc2616#section-14.11 + const char* content_encoding() const; + + /// @brief Set the content language for the StorageReference. + /// + /// @see https://tools.ietf.org/html/rfc2616#section-14.12 + void set_content_language(const char* language); + + /// @brief Set the content language for the StorageReference. + /// + /// This must be an ISO 639-1 two-letter language code. + /// E.g. "zh", "es", "en". + /// + /// @see https://www.loc.gov/standards/iso639-2/php/code_list.php + void set_content_language(const std::string& language) { + set_content_language(language.c_str()); + } + + /// @brief Return the content language for the StorageReference. + /// + /// @returns The content language for the StorageReference. + /// + /// @see https://tools.ietf.org/html/rfc2616#section-14.12 + const char* content_language() const; + + /// @brief Set the content type of the StorageReference. + /// + /// @see https://tools.ietf.org/html/rfc2616#section-14.17 + void set_content_type(const char* type); + + /// @brief Set the content type of the StorageReference. + /// + /// @see https://tools.ietf.org/html/rfc2616#section-14.17 + void set_content_type(const std::string& type) { + set_content_type(type.c_str()); + } + + /// @brief Return the content type of the StorageReference. + /// + /// @returns The content type of the StorageReference. + /// + /// @see https://tools.ietf.org/html/rfc2616#section-14.17 + const char* content_type() const; + + /// @brief Return the time the StorageReference was created in milliseconds + /// since the epoch. + /// + /// @returns The time the StorageReference was created in milliseconds since + /// the epoch. + int64_t creation_time() const; + + /// @brief Return a map of custom metadata key value pairs. + /// + /// The pointer returned is only valid during the lifetime of the Metadata + /// object that owns it. + /// + /// @returns The keys for custom metadata. + std::map* custom_metadata() const; + + // download_url() and download_urls() are deprecated and removed. + // Please use StorageReference::GetDownloadUrl() instead. + + /// @brief Return a version String indicating what version of the + /// StorageReference. + /// + /// @returns A value indicating the version of the StorageReference. + int64_t generation() const; + + /// @brief Return a version String indicating the version of this + /// StorageMetadata. + /// + /// @returns A value indicating the version of this StorageMetadata. + int64_t metadata_generation() const; + + /// @brief Return a simple name of the StorageReference object. + /// + /// @returns A simple name of the StorageReference object. + const char* name() const; + + /// @brief Return the path of the StorageReference object. + /// + /// @returns The path of the StorageReference object. + const char* path() const; + + /// @brief Return the associated StorageReference to which this Metadata + /// belongs. + /// + /// @returns The associated StorageReference to which this Metadata belongs. + /// If this Metadata is invalid or is not associated with any file, an invalid + /// StorageReference is returned. + StorageReference GetReference() const; + + /// @brief Return the stored Size in bytes of the StorageReference object. + /// + /// @returns The stored Size in bytes of the StorageReference object. + int64_t size_bytes() const; + + /// @brief Return the time the StorageReference was last updated in + /// milliseconds since the epoch. + /// + /// @return The time the StorageReference was last updated in milliseconds + /// since the epoch. + int64_t updated_time() const; + + /// @brief Returns true if this Metadata is valid, false if it is not + /// valid. An invalid Metadata is returned when a method such as + /// StorageReference::GetMetadata() completes with an error. + /// + /// @returns true if this Metadata is valid, false if this Metadata is + /// invalid. + bool is_valid() const; + + /// @brief MD5 hash of the data; encoded using base64. + /// + /// @returns MD5 hash of the data; encoded using base64. + const char* md5_hash() const; + + private: + /// @cond FIREBASE_APP_INTERNAL + friend class StorageReference; + friend class internal::MetadataInternal; + friend class internal::MetadataInternalCommon; + friend class internal::StorageReferenceInternal; + +#ifndef INTERNAL_EXPERIMENTAL + Metadata(internal::MetadataInternal* internal); +#endif + + internal::MetadataInternal* internal_; + /// @endcond +}; + +} // namespace storage +} // namespace firebase + +#endif // FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_METADATA_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/storage/storage_reference.h b/packages/firebase_core/firebase_core/firebase_core/firebase/storage/storage_reference.h new file mode 100644 index 000000000000..e5c7c2f85ae6 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/storage/storage_reference.h @@ -0,0 +1,361 @@ +// Copyright 2016 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_STORAGE_REFERENCE_H_ +#define FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_STORAGE_REFERENCE_H_ + +#include +#include + +#include "firebase/future.h" +#include "firebase/internal/common.h" +#include "firebase/storage/metadata.h" + +namespace firebase { +namespace storage { + +class Controller; +class Listener; +class Storage; + +/// @cond FIREBASE_APP_INTERNAL +namespace internal { +class ControllerInternal; +class MetadataInternal; +class StorageInternal; +class StorageReferenceInternalCommon; +class StorageReferenceInternal; +} // namespace internal +/// @endcond FIREBASE_APP_INTERNAL + +#ifndef SWIG +/// Represents a reference to a Cloud Storage object. +/// Developers can upload and download objects, get/set object metadata, and +/// delete an object at a specified path. +#endif // SWIG +class StorageReference { + public: + /// @brief Default constructor. This creates an invalid StorageReference. + /// Attempting to perform any operations on this reference will fail unless a + /// valid StorageReference has been assigned to it. + StorageReference() : internal_(nullptr) {} + + ~StorageReference(); + + /// @brief Copy constructor. It's totally okay (and efficient) to copy + /// StorageReference instances, as they simply point to the same location. + /// + /// @param[in] reference StorageReference to copy from. + StorageReference(const StorageReference& reference); + + /// @brief Copy assignment operator. It's totally okay (and efficient) to copy + /// StorageReference instances, as they simply point to the same location. + /// + /// @param[in] reference StorageReference to copy from. + /// + /// @returns Reference to the destination StorageReference. + StorageReference& operator=(const StorageReference& reference); + +#if defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) + /// @brief Move constructor. Moving is an efficient operation for + /// StorageReference instances. + /// + /// @param[in] other StorageReference to move data from. + StorageReference(StorageReference&& other); + + /// @brief Move assignment operator. Moving is an efficient operation for + /// StorageReference instances. + /// + /// @param[in] other StorageReference to move data from. + /// + /// @returns Reference to the destination StorageReference. + StorageReference& operator=(StorageReference&& other); +#endif // defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) + + /// @brief Gets the firebase::storage::Storage instance to which we refer. + /// + /// The pointer will remain valid indefinitely. + /// + /// @returns The firebase::storage::Storage instance that this + /// StorageReference refers to. + Storage* storage(); + + /// @brief Gets a reference to a location relative to this one. + /// + /// @param[in] path Path relative to this reference's location. + /// The pointer only needs to be valid during this call. + /// + /// @returns Child relative to this location. + StorageReference Child(const char* path) const; + + /// @brief Gets a reference to a location relative to this one. + /// + /// @param[in] path Path relative to this reference's location. + /// + /// @returns Child relative to this location. + StorageReference Child(const std::string& path) const { + return Child(path.c_str()); + } + + /// @brief Deletes the object at the current path. + /// + /// @returns A Future result, which will complete when the operation either + /// succeeds or fails. When the Future is completed, if its Error is + /// kErrorNone, the operation succeeded. + Future Delete(); + + /// @brief Returns the result of the most recent call to RemoveValue(); + /// + /// @returns The result of the most recent call to RemoveValue(); + Future DeleteLastResult(); + + /// @brief Return the Google Cloud Storage bucket that holds this object. + /// + /// @returns The bucket. + std::string bucket(); + + /// @brief Return the full path of the storage reference, not including + /// the Google Cloud Storage bucket. + /// + /// @returns Full path to the storage reference, not including GCS bucket. + /// For example, for the reference "gs://bucket/path/to/object.txt", the full + /// path would be "path/to/object.txt". + std::string full_path(); + + /// @brief Asynchronously downloads the object from this StorageReference. + /// + /// A byte array will be allocated large enough to hold the entire file in + /// memory. Therefore, using this method will impact memory usage of your + /// process. + /// + /// @param[in] path Path to local file on device to download into. + /// @param[in] listener A listener that will respond to events on this read + /// operation. If not nullptr, a listener that will respond to events on this + /// read operation. The caller is responsible for allocating and deallocating + /// the listener. The same listener can be used for multiple operations. + /// @param[out] controller_out Controls the write operation, providing the + /// ability to pause, resume or cancel an ongoing write operation. If not + /// nullptr, this method will output a Controller here that you can use to + /// control the write operation. + /// + /// @returns A future that returns the number of bytes read. + Future GetFile(const char* path, Listener* listener = nullptr, + Controller* controller_out = nullptr); + + /// @brief Returns the result of the most recent call to GetFile(); + /// + /// @returns The result of the most recent call to GetFile(); + Future GetFileLastResult(); + + /// @brief Asynchronously downloads the object from this StorageReference. + /// + /// A byte array will be allocated large enough to hold the entire file in + /// memory. Therefore, using this method will impact memory usage of your + /// process. + /// + /// @param[in] buffer A byte buffer to read the data into. This buffer must + /// be valid for the duration of the transfer. + /// @param[in] buffer_size The size of the byte buffer. + /// @param[in] listener A listener that will respond to events on this read + /// operation. If not nullptr, a listener that will respond to events on this + /// read operation. The caller is responsible for allocating and deallocating + /// the listener. The same listener can be used for multiple operations. + /// @param[out] controller_out Controls the write operation, providing the + /// ability to pause, resume or cancel an ongoing write operation. If not + /// nullptr, this method will output a Controller here that you can use to + /// control the write operation. + /// + /// @returns A future that returns the number of bytes read. + Future GetBytes(void* buffer, size_t buffer_size, + Listener* listener = nullptr, + Controller* controller_out = nullptr); + + /// @brief Returns the result of the most recent call to GetBytes(); + /// + /// @returns The result of the most recent call to GetBytes(); + Future GetBytesLastResult(); + + /// @brief Asynchronously retrieves a long lived download URL with a revokable + /// token. + /// + /// This can be used to share the file with others, but can be revoked by a + /// developer in the Firebase Console if desired. + /// + /// @returns A Future result, which will complete when the operation either + /// succeeds or fails. When the Future is completed, if its Error is + /// kErrorNone, the operation succeeded and the URL is returned. + Future GetDownloadUrl(); + + /// @brief Returns the result of the most recent call to GetDownloadUrl(); + /// + /// @returns The result of the most recent call to GetDownloadUrl(); + Future GetDownloadUrlLastResult(); + + /// @brief Retrieves metadata associated with an object at this + /// StorageReference. + /// + /// @returns A Future result, which will complete when the operation either + /// succeeds or fails. When the Future is completed, if its Error is + /// kErrorNone, the operation succeeded and the Metadata is returned. + Future GetMetadata(); + + /// @brief Returns the result of the most recent call to GetMetadata(); + /// + /// @returns The result of the most recent call to GetMetadata(); + Future GetMetadataLastResult(); + + /// @brief Updates the metadata associated with this StorageReference. + /// + /// @returns A Future result, which will complete when the operation either + /// succeeds or fails. When the Future is completed, if its Error is + /// kErrorNone, the operation succeeded and the Metadata is returned. + Future UpdateMetadata(const Metadata& metadata); + + /// @brief Returns the result of the most recent call to UpdateMetadata(); + /// + /// @returns The result of the most recent call to UpdateMetadata(); + Future UpdateMetadataLastResult(); + + /// @brief Returns the short name of this object. + /// + /// @returns the short name of this object. + std::string name(); + + /// @brief Returns a new instance of StorageReference pointing to the parent + /// location or null if this instance references the root location. + /// + /// @returns The parent StorageReference. + StorageReference GetParent(); + + /// @brief Asynchronously uploads data to the currently specified + /// StorageReference, without additional metadata. + /// + /// @param[in] buffer A byte buffer to write data from. This buffer must be + /// valid for the duration of the transfer. + /// @param[in] buffer_size The size of the byte buffer. + /// @param[in] listener A listener that will respond to events on this read + /// operation. If not nullptr, a listener that will respond to events on this + /// write operation. The caller is responsible for allocating and deallocating + /// the listener. The same listener can be used for multiple operations. + /// @param[out] controller_out Controls the write operation, providing the + /// ability to pause, resume or cancel an ongoing write operation. If not + /// nullptr, this method will output a Controller here that you can use to + /// control the write operation. + /// + /// @returns A future that returns the Metadata. + Future PutBytes(const void* buffer, size_t buffer_size, + Listener* listener = nullptr, + Controller* controller_out = nullptr); + + /// @brief Asynchronously uploads data to the currently specified + /// StorageReference, without additional metadata. + /// + /// @param[in] buffer A byte buffer to write data from. This buffer must be + /// valid for the duration of the transfer. + /// @param[in] buffer_size The number of bytes to write. + /// @param[in] metadata Metadata containing additional information (MIME type, + /// etc.) about the object being uploaded. + /// @param[in] listener A listener that will respond to events on this read + /// operation. If not nullptr, a listener that will respond to events on this + /// write operation. The caller is responsible for allocating and deallocating + /// the listener. The same listener can be used for multiple operations. + /// @param[out] controller_out Controls the write operation, providing the + /// ability to pause, resume or cancel an ongoing write operation. If not + /// nullptr, this method will output a Controller here that you can use to + /// control the write operation. + /// + /// @returns A future that returns the Metadata. + Future PutBytes(const void* buffer, size_t buffer_size, + const Metadata& metadata, + Listener* listener = nullptr, + Controller* controller_out = nullptr); + + /// @brief Returns the result of the most recent call to PutBytes(); + /// + /// @returns The result of the most recent call to PutBytes(); + Future PutBytesLastResult(); + + /// @brief Asynchronously uploads data to the currently specified + /// StorageReference, without additional metadata. + /// + /// @param[in] path Path to local file on device to upload to Firebase + /// Storage. + /// @param[in] listener A listener that will respond to events on this read + /// operation. If not nullptr, a listener that will respond to events on this + /// write operation. The caller is responsible for allocating and deallocating + /// the listener. The same listener can be used for multiple operations. + /// @param[out] controller_out Controls the write operation, providing the + /// ability to pause, resume or cancel an ongoing write operation. If not + /// nullptr, this method will output a Controller here that you can use to + /// control the write operation. + /// + /// @returns A future that returns the Metadata. + Future PutFile(const char* path, Listener* listener = nullptr, + Controller* controller_out = nullptr); + + /// @brief Asynchronously uploads data to the currently specified + /// StorageReference, without additional metadata. + /// + /// @param[in] path Path to local file on device to upload to Firebase + /// Storage. + /// @param[in] metadata Metadata containing additional information (MIME type, + /// etc.) about the object being uploaded. + /// @param[in] listener A listener that will respond to events on this read + /// operation. If not nullptr, a listener that will respond to events on this + /// write operation. The caller is responsible for allocating and deallocating + /// the listener. The same listener can be used for multiple operations. + /// @param[out] controller_out Controls the write operation, providing the + /// ability to pause, resume or cancel an ongoing write operation. If not + /// nullptr, this method will output a Controller here that you can use to + /// control the write operation. + /// + /// @returns A future that returns the Metadata. + Future PutFile(const char* path, const Metadata& metadata, + Listener* listener = nullptr, + Controller* controller_out = nullptr); + + /// @brief Returns the result of the most recent call to PutFile(); + /// + /// @returns The result of the most recent call to PutFile(); + Future PutFileLastResult(); + + /// @brief Returns true if this StorageReference is valid, false if it is not + /// valid. An invalid StorageReference indicates that the reference is + /// uninitialized (created with the default constructor) or that there was an + /// error retrieving the reference. + /// + /// @returns true if this StorageReference is valid, false if this + /// StorageReference is invalid. + bool is_valid() const; + + private: + /// @cond FIREBASE_APP_INTERNAL + friend class Controller; + friend class internal::ControllerInternal; + friend class Metadata; + friend class internal::MetadataInternal; + friend class Storage; + friend class internal::StorageReferenceInternal; + friend class internal::StorageReferenceInternalCommon; + + StorageReference(internal::StorageReferenceInternal* internal); + + internal::StorageReferenceInternal* internal_; + /// @endcond +}; + +} // namespace storage +} // namespace firebase + +#endif // FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_STORAGE_REFERENCE_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/util.h b/packages/firebase_core/firebase_core/firebase_core/firebase/util.h new file mode 100644 index 000000000000..4c78d45f3ac8 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/util.h @@ -0,0 +1,101 @@ +/* + * Copyright 2016 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_APP_SRC_INCLUDE_FIREBASE_UTIL_H_ +#define FIREBASE_APP_SRC_INCLUDE_FIREBASE_UTIL_H_ + +#include "firebase/app.h" +#include "firebase/future.h" + +namespace firebase { + +struct ModuleInitializerData; + +/// @brief Utility class to help with initializing Firebase modules. +/// +/// This optional class handles a basic Firebase C++ SDK code pattern: attempt +/// to initialize a Firebase module, and if the initialization fails on Android +/// due to Google Play services being unavailable, prompt the user to +/// update/enable Google Play services on their device. +/// +/// If the developer wants more advanced behavior (for example, wait to prompt +/// the user to update or enable Google Play services until later, or opt not to +/// use Firebase modules), they can still initialize each Firebase module +/// individually, and use google_play_services::MakeAvailable() directly if any +/// initializations fail. +class ModuleInitializer { + public: + /// @brief Initialization function, which should initialize a single Firebase + /// module and return the InitResult. + typedef InitResult (*InitializerFn)(App* app, void* context); + + ModuleInitializer(); + virtual ~ModuleInitializer(); + + /// @brief Initialize Firebase modules by calling one or more user-supplied + /// functions, each of which must initialize at most one library, and should + /// return the InitResult of the initialization. + /// + /// This function will run the initializers in order, checking the return + /// value of each. On Android, if the InitResult returned is + /// kInitResultFailedMissingDependency, this indicates that Google Play + /// services is not available and a Firebase module requires it. This function + /// will attempt to fix Google Play services, and will retry initializations + /// where it left off, beginning with the one that failed. + /// + /// @returns A future result. When all of the initializers are completed, the + /// Future will be completed with Error() = 0. If an initializer fails and the + /// situation cannot be fixed, the Future will be completed with Error() equal + /// to the number of initializers that did not succeed (since they are run in + /// order, this tells you which ones failed). + /// + /// @param[in] app The firebase::App that will be passed to the initializers, + /// as well as used to fix Google Play services on Android if needed. + /// + /// @param[in] context User-defined context, which will be passed to the + /// initializer functions. If you don't need this, you can use nullptr. + /// + /// @param[in] init_fns Your initialization functions to call, in an array. At + /// their simplest, these will each simply call a single Firebase module's + /// Initialize(app) and return the result, but you can perform more complex + /// logic if you prefer. + /// + /// @param[in] init_fns_count Number of initialization functions in the + /// supplied array. + /// + /// @note If a pending Initialize() is already running, this function will + /// return the existing Future rather than adding any new functions to the + /// initializer list. + Future Initialize(App* app, void* context, + const InitializerFn* init_fns, size_t init_fns_count); + + /// @brief Initialize one Firebase module by calling a single user-supplied + /// function that should initialize a Firebase module and return the + /// InitResult. @see Initialize(::firebase::App*, void*, const InitializerFn*) + /// for more information. + Future Initialize(App* app, void* context, InitializerFn init_fn); + + /// @brief Get the result of the most recent call to @see Initialize(). + Future InitializeLastResult(); + + private: + ModuleInitializerData* data_; +}; + +// NOLINTNEXTLINE - allow namespace overridden +} // namespace firebase + +#endif // FIREBASE_APP_SRC_INCLUDE_FIREBASE_UTIL_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/variant.h b/packages/firebase_core/firebase_core/firebase_core/firebase/variant.h new file mode 100644 index 000000000000..ef1d552dffa4 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/variant.h @@ -0,0 +1,1197 @@ +/* + * Copyright 2016 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_APP_SRC_INCLUDE_FIREBASE_VARIANT_H_ +#define FIREBASE_APP_SRC_INCLUDE_FIREBASE_VARIANT_H_ + +#include + +#include +#include +#include +#include +#include + +#include "firebase/internal/common.h" + +/// @brief Namespace that encompasses all Firebase APIs. + +namespace firebase { +namespace internal { +class VariantInternal; +} +} // namespace firebase + +namespace firebase { + +// +// SWIG uses the Variant class as a readonly object, and so ignores most of the +// functions. In order to keep things clean, functions that should be exposed +// are explicitly listed in app.SWIG, and everything else is ignored. +// + +/// Variant data type used by Firebase libraries. +class Variant { + public: + /// Type of data that this variant object contains. + enum Type { + /// Null, or no data. + kTypeNull, + /// A 64-bit integer. + kTypeInt64, + /// A double-precision floating point number. + kTypeDouble, + /// A boolean value. + kTypeBool, + /// A statically-allocated string we point to. + kTypeStaticString, + /// A std::string. + kTypeMutableString, + /// A std::vector of Variant. + kTypeVector, + /// A std::map, mapping Variant to Variant. + kTypeMap, + /// An statically-allocated blob of data that we point to. Never constructed + /// by default. Use Variant::FromStaticBlob() to create a Variant of this + /// type. + kTypeStaticBlob, + /// A blob of data that the Variant holds. Never constructed by default. Use + /// Variant::FromMutableBlob() to create a Variant of this type, and copy + /// binary data from an existing source. + kTypeMutableBlob, + + // Note: If you add new types update enum InternalType; + }; + +// +// Because of the VariantVariantMap C# class, we need to hide the constructors +// explicitly, as the SWIG ignore does not seem to work with that macro. +// +#ifndef SWIG + /// @brief Construct a null Variant. + /// + /// The Variant constructed will be of type Null. + Variant() : type_(kInternalTypeNull), value_({}) {} + + /// @brief Construct a Variant with the given templated type. + /// + /// @param[in] value The value to construct the variant. + /// + /// Valid types for this constructor are `int`, `int64_t`, `float`, `double`, + /// `bool`, `const char*`, and `char*` (but see below for additional Variant + /// types). + /// + /// + /// Type `int` or `int64_t`: + /// * The Variant constructed will be of type Int64. + /// + /// Type `double` or `float`: + /// * The Variant constructed will be of type Double. + /// + /// Type `bool`: + /// * The Variant constructed will be of type Bool. + /// + /// Type `const char*`: + /// * The Variant constructed will be of type StaticString, and is_string() + /// will return true. **Note:** If you use this constructor, you must + /// ensure that the memory pointed to stays valid for the life of the + /// Variant, otherwise call mutable_string() or set_mutable_string(), + /// which will copy the string to an internal buffer. + /// + /// Type `char*`: + /// * The Variant constructed will be of type MutableString, and is_string() + /// will return true. + /// + /// Other types will result in compiler error unless using the following + /// constructor overloads: + /// * `std::string` + /// * `std::vector` + /// * `std::vector` where T is convertible to variant type + /// * `T*`, `size_t` where T is convertible to variant type + /// * `std::map` + /// * `std::map` where K and V is convertible to variant type + template + Variant(T value) // NOLINT + : type_(kInternalTypeNull) { + set_value_t(value); + } + + /// @brief Construct a Variant containing the given string value (makes a + /// copy). + /// + /// The Variant constructed will be of type MutableString, and is_string() + /// will return true. + /// + /// @param[in] value The string to use for the Variant. + Variant(const std::string& value) // NOLINT + : type_(kInternalTypeNull) { + set_mutable_string(value); + } + + /// @brief Construct a Variant containing the given std::vector of Variant. + /// + /// The Variant constructed will be of type Vector. + /// + /// @param[in] value The STL vector to copy into the Variant. + Variant(const std::vector& value) // NOLINT + : type_(kInternalTypeNull) { + set_vector(value); + } + + /// @brief Construct a Variant containing the given std::vector of something + /// that can be constructed into a Variant. + /// + /// The Variant constructed will be of type Vector. + /// + /// @param[in] value An STL vector containing elements that can be converted + /// to Variant (such as ints, strings, vectors). A Variant will be created for + /// each element, and copied into the Vector Variant constructed here. + template + Variant(const std::vector& value) // NOLINT + : type_(kInternalTypeNull) { + Clear(kTypeVector); + vector().reserve(value.size()); + for (size_t i = 0; i < value.size(); i++) { + vector().push_back(Variant(static_cast(value[i]))); + } + } + + /// @brief Construct a Variant from an array of supported types into a Vector. + /// + /// The Variant constructed will be of type Vector. + /// + /// @param[in] array_of_values A C array containing elements that can be + /// converted to Variant (such as ints, strings, vectors). A Variant will be + /// created for each element, and copied into the Vector Variant constructed + /// here. + /// @param[in] array_size Number of elements of the array. + template + Variant(const T array_of_values[], size_t array_size) + : type_(kInternalTypeNull) { + Clear(kTypeVector); + vector().reserve(array_size); + for (size_t i = 0; i < array_size; i++) { + vector()[i] = Variant(array_of_values[i]); + } + } + + /// @brief Construct a Variatn containing the given std::map of Variant to + /// Variant. + /// + /// The Variant constructed will be of type Map. + /// + /// @param[in] value The STL map to copy into the Variant. + Variant(const std::map& value) // NOLINT + : type_(kInternalTypeNull) { + set_map(value); + } + + /// @brief Construct a Variant containing the given std::map of something that + /// can be constructed into a Variant, to something that can be constructed + /// into a Variant. + /// + /// The Variant constructed will be of type Map. + /// + /// @param[in] value An STL map containing keys and values that can be + /// converted to Variant (such as ints, strings, vectors). A Variant will be + /// created for each key and for each value, and copied by pairs into the Map + /// Variant constructed here. + template + Variant(const std::map& value) // NOLINT + : type_(kInternalTypeNull) { + Clear(kTypeMap); + for (typename std::map::const_iterator i = value.begin(); + i != value.end(); ++i) { + map().insert(std::make_pair(Variant(i->first), Variant(i->second))); + } + } + + /// @brief Copy constructor. Performs a deep copy. + /// + /// @param[in] other Source Variant to copy from. + Variant(const Variant& other) : type_(kInternalTypeNull) { *this = other; } + + /// @brief Copy assignment operator. Performs a deep copy. + /// + /// @param[in] other Source Variant to copy from. + Variant& operator=(const Variant& other); + +#if defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) + + /// @brief Move constructor. Efficiently moves the more complex data types by + /// simply reassigning pointer ownership. + /// + /// @param[in] other Source Variant to move from. + Variant(Variant&& other) noexcept : type_(kInternalTypeNull) { + *this = std::move(other); + } + + /// @brief Move assignment operator. Efficiently moves the more complex data + /// types by simply reassigning pointer ownership. + /// + /// @param[in] other Source Variant to move from. + Variant& operator=(Variant&& other) noexcept; + +#endif // defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) +#endif // SWIG + + /// Destructor. Frees the memory that this Variant owns. + ~Variant() { Clear(); } + + /// @brief Equality operator. Both the type and the value must be equal + /// (except that static strings CAN be == to mutable strings). For container + /// types, element-by-element comparison is performed. For strings, string + /// comparison is performed. + /// + /// @param[in] other Variant to compare to. + /// + /// @return True if the Variants are of identical types and values, false + /// otherwise. + bool operator==(const Variant& other) const; + + /// @brief Inequality operator, only meant for internal use. + /// + /// Explanation: In order to use Variant as a key for std::map, we must + /// provide a comparison function. This comparison function is ONLY for + /// std::map to be able to use a Variant as a map key. + /// + /// We define v1 < v2 IFF: + /// * If different types, compare type as int: v1.type() < v2.type() + /// (note: this means that Variant(1) < Variant(0.0) - be careful!) + /// * If both are int64: v1.int64_value() < v2.int64_value(); + /// * If both are double: v1.double_value() < v2.double_value() + /// * If both are bool: v1.bool_value() < v2.bool_value(); + /// * If both are either static or mutable strings: strcmp(v1, v2) < 0 + /// * If both are vectors: + /// * If v1[0] < v2[0], that means v1 < v2 == true. Otherwise: + /// * If v1[0] > v2[0], that means v1 < v2 == false. Otherwise: + /// * Continue to the next element of both vectors and compare again. + /// * If you reach the end of one vector first, that vector is considered + /// to be lesser. + /// * If both are maps, iterate similar to vectors (since maps are ordered), + /// but for each element, first compare the key, then the value. + /// * If both are blobs, the smaller-sized blob is considered lesser. If both + /// blobs are the same size, use memcmp to compare the bytes. + /// + /// We have defined this operation such that if !(v1 < v2) && !(v2 < v1), it + /// must follow that v1 == v2. + /// + /// @param[in] other Variant to compare to. + /// + /// @return Results of the comparison, as described in this documentation. + /// + /// @note This will not give you the results you expect if you compare + /// Variants of different types! For example, Variant(0.0) < Variant(1). + bool operator<(const Variant& other) const; + + /// @brief Inequality operator: x != y is evaluated as !(x == y). + /// + /// @param[in] other Variant to compare to. + /// + /// @return Results of the comparison. + bool operator!=(const Variant& other) const { return !(*this == other); } + + /// @brief Inequality operator: x > y is evaluated as y < x + /// + /// @param[in] other Variant to compare to. + /// + /// @return Results of the comparison. + bool operator>(const Variant& other) const { return other < *this; } + + /// @brief Inequality operator: x >= y is evaluated as !(x < y) + /// + /// @param[in] other Variant to compare to. + /// + /// @return Results of the comparison. + bool operator>=(const Variant& other) const { return !(*this < other); } + + /// @brief Inequality operator: x <= y is evaluated as !(x > y) + /// + /// @param[in] other Variant to compare to. + /// + /// @return Results of the comparison. + bool operator<=(const Variant& other) const { return !(*this > other); } + + /// @brief Clear the given Variant data, optionally into a new type. Frees up + /// any memory that might have been allocated. After calling this, you can + /// access the Variant as the new type. + /// + /// @param[in] new_type Optional new type to clear the Variant to. You may + /// immediately begin using the Variant as that new type. + void Clear(Type new_type = kTypeNull); + + // Convenience functions (used similarly to constants). + + /// @brief Get a Variant of type Null. + /// + /// @return A Variant of type Null. + static Variant Null() { return Variant(); } + + /// @brief Get a Variant of integer value 0. + /// + /// @return A Variant of type Int64, with value 0. + static Variant Zero() { return Variant::FromInt64(0L); } + + /// @brief Get a Variant of integer value 1. + /// + /// @return A Variant of type Int64, with value 1. + static Variant One() { return Variant::FromInt64(1L); } + + /// @brief Get a Variant of double value 0.0. + /// + /// @return A Variant of type Double, with value 0.0. + static Variant ZeroPointZero() { return Variant::FromDouble(0.0); } + + /// @brief Get a Variant of double value 1.0. + /// + /// @return A Variant of type Double, with value 1.0. + static Variant OnePointZero() { return Variant::FromDouble(1.0); } + + /// @brief Get a Variant of bool value false. + /// + /// @return A Variant of type Bool, with value false. + static Variant False() { return Variant::FromBool(false); } + + /// @brief Get a Variant of bool value true. + /// + /// @return A Variant of type Bool, with value true. + static Variant True() { return Variant::FromBool(true); } + + /// @brief Get an empty string variant. + /// + /// @return A Variant of type StaticString, referring to an empty string. + static Variant EmptyString() { return Variant::FromStaticString(""); } + + /// @brief Get a Variant containing an empty mutable string. + /// + /// @return A Variant of type MutableString, containing an empty string. + static Variant EmptyMutableString() { + Variant v; + v.Clear(kTypeMutableString); + return v; + } + + /// @brief Get a Variant containing an empty vector. You can immediately call + /// vector() on it to work with the vector it contains. + /// + /// @return A Variant of type Vector, containing no elements. + static Variant EmptyVector() { + Variant v; + v.Clear(kTypeVector); + return v; + } + + /// @brief Get a Variant containing an empty map. You can immediately call + /// map() on + /// it to work with the map it contains. + /// + /// @return A Variant of type Map, containing no elements. + static Variant EmptyMap() { + Variant v; + v.Clear(kTypeMap); + return v; + } + + /// @brief Return a Variant containing an empty mutable blob of the requested + /// size, filled with 0-bytes. + /// + /// @param[in] size_bytes Size of the buffer you want, in bytes. + /// + /// @returns A Variant containing a mutable blob of the requested size, filled + /// with 0-bytes. + static Variant EmptyMutableBlob(size_t size_bytes) { + Variant v; + uint8_t* blank_data = new uint8_t[size_bytes]; + memset(blank_data, 0, size_bytes); + v.Clear(kTypeMutableBlob); + v.set_blob_pointer(blank_data, size_bytes); + return v; + } + + /// @brief Get the current type contained in this Variant. + /// + /// @return The Variant's type. + Type type() const { + // To avoid breaking user code, alias the small string type to mutable + // string. + if (type_ == kInternalTypeSmallString) { + return kTypeMutableString; + } + + return static_cast(type_); + } + + /// @brief Get whether this Variant is currently null. + /// + /// @return True if the Variant is Null, false otherwise. + bool is_null() const { return type() == kTypeNull; } + + /// @brief Get whether this Variant contains an integer. + /// + /// @return True if the Variant's type is Int64, false otherwise. + bool is_int64() const { return type() == kTypeInt64; } + + /// @brief Get whether this Variant contains a double. + /// + /// @return True if the Variant's type is Double, false otherwise. + bool is_double() const { return type() == kTypeDouble; } + + /// @brief Get whether this Variant contains a bool. + /// + /// @return True if the Variant's type is Bool, false otherwise. + bool is_bool() const { return type() == kTypeBool; } + + /// @brief Get whether this Variant contains a vector. + /// + /// @return True if the Variant's type is Vector, false otherwise. + bool is_vector() const { return type() == kTypeVector; } + + /// @brief Get whether this Variant contains a map. + /// + /// @return True if the Variant's type is Map, false otherwise. + bool is_map() const { return type() == kTypeMap; } + + /// @brief Get whether this Variant contains a static string. + /// + /// @return True if the Variant's type is StaticString, false otherwise. + bool is_static_string() const { return type() == kTypeStaticString; } + + /// @brief Get whether this Variant contains a mutable string. + /// + /// @return True if the Variant's type is MutableString, false otherwise. + bool is_mutable_string() const { return type() == kTypeMutableString; } + + /// @brief Get whether this Variant contains a string. + /// + /// @return True if the Variant's type is either StaticString or + /// MutableString or SmallString; false otherwise. + /// + /// @note No matter which type of string the Variant contains, you can read + /// its value via string_value(). + bool is_string() const { + return is_static_string() || is_mutable_string() || is_small_string(); + } + + /// @brief Get whether this Variant contains a static blob. + /// + /// @return True if the Variant's type is StaticBlob, false otherwise. + bool is_static_blob() const { return type() == kTypeStaticBlob; } + + /// @brief Get whether this Variant contains a mutable blob. + /// + /// @return True if the Variant's type is MutableBlob, false otherwise. + bool is_mutable_blob() const { return type() == kTypeMutableBlob; } + + /// @brief Get whether this Variant contains a blob. + /// + /// @return True if the Variant's type is either StaticBlob or + /// MutableBlob; false otherwise. + /// + /// @note No matter which type of blob the Variant contains, you can read + /// its data via blob_data() and get its size via blob_size(). + bool is_blob() const { return is_static_blob() || is_mutable_blob(); } + + /// @brief Get whether this Variant contains a numeric type, Int64 or Double. + /// + /// @return True if the Variant's type is either Int64 or Double; false + /// otherwise. + bool is_numeric() const { return is_int64() || is_double(); } + + /// @brief Get whether this Variant contains a fundamental type: Null, Int64, + /// Double, Bool, or one of the two String types. Essentially + /// !is_containerType(). + /// + /// @return True if the Variant's type is Int64, Double, Bool, or Null; false + /// otherwise. + bool is_fundamental_type() const { + return is_int64() || is_double() || is_string() || is_bool() || is_null(); + } + + /// @brief Get whether this Variant contains a container type: Vector or Map. + /// + /// @return True if the Variant's type is Vector or Map; false otherwise. + bool is_container_type() const { return is_vector() || is_map(); } + + /// @brief Get the current Variant converted into a string. Only valid for + /// fundamental types. + /// + /// Special cases: Booleans will be returned as "true" or "false". Null will + /// be returned as an empty string. The returned string may be either mutable + /// or static, depending on the source type. All other cases will return an + /// empty string. + /// + /// @return A Variant containing a String that represents the value of this + /// original Variant. + Variant AsString() const; + + /// @brief Get the current Variant converted into an integer. Only valid for + /// fundamental types. + /// + /// Special cases: If a String can be parsed as a number + /// via strtol(), it will be. If a Bool is true, this will return 1. All other + /// cases (including non-fundamental types) will return 0. + /// + /// @return A Variant containing an Int64 that represents the value of this + /// original Variant. + Variant AsInt64() const; + + /// @brief Get the current Variant converted into a floating-point + /// number. Only valid for fundamental types. + /// + /// Special cases: If a Bool is true, this will return 1. All other cases will + /// return 0. + /// + /// @return A Variant containing a Double that represents the value of this + /// original Variant. + Variant AsDouble() const; + + /// @brief Get the current Variant converted into a boolean. Null, 0, 0.0, + /// empty strings, empty vectors, empty maps, blobs of size 0, and "false" + /// (case-sensitive) are all considered false. All other values are true. + /// + /// @return A Variant of type Bool containing the original Variant interpreted + /// as a Bool. + Variant AsBool() const; + + /// @brief Mutable accessor for a Variant containing a string. + /// + /// If the Variant contains a static string, it will be converted into a + /// mutable string, which copies the const char*'s data into a std::string. + /// + /// @return Reference to the string contained in this Variant. + /// + /// @note If the Variant is not one of the two String types, this will assert. + std::string& mutable_string() { + if (type_ == kInternalTypeStaticString || + type_ == kInternalTypeSmallString) { + // Automatically promote a static or small string to a mutable string. + set_mutable_string(string_value(), false); + } + assert_is_type(kTypeMutableString); + return *value_.mutable_string_value; + } + + /// @brief Get the size of a blob. This method works with both static + /// and mutable blobs. + /// + /// @return Number of bytes of binary data contained in the blob. + size_t blob_size() const { + assert_is_blob(); + return value_.blob_value.size; + } + + /// @brief Get the pointer to the binary data contained in a blob. + /// This method works with both static and mutable blob. + /// + /// @return Pointer to the binary data. Use blob_size() to get the + /// number of bytes. + const uint8_t* blob_data() const { + assert_is_blob(); + return value_.blob_value.ptr; + } + + /// @brief Get a mutable pointer to the binary data contained in + /// a blob. + /// + /// If the Variant contains a static blob, it will be converted into a mutable + /// blob, which copies the binary data into the Variant's buffer. + /// + /// @returns Pointer to a mutable buffer of binary data. The size of the + /// buffer cannot be changed, but the contents are mutable. + uint8_t* mutable_blob_data() { + if (type_ == kInternalTypeStaticBlob) { + // Automatically promote a static blob to a mutable blob. + set_mutable_blob(blob_data(), blob_size()); + } + assert_is_type(kTypeMutableBlob); + return const_cast(value_.blob_value.ptr); + } + + /// @brief Const accessor for a Variant contianing mutable blob data. + /// + /// @note Unlike the non-const accessor, this accessor cannot "promote" a + /// static blob to mutable, and thus will assert if the Variant you pass in + /// is not of MutableBlob type. + /// + /// @returns Pointer to a mutable buffer of binary data. The size of the + /// buffer cannot be changed, but the contents are mutable. + uint8_t* mutable_blob_data() const { + assert_is_type(kTypeMutableBlob); + return const_cast(value_.blob_value.ptr); + } + + /// @brief Mutable accessor for a Variant containing a vector of Variant + /// data. + /// + /// @return Reference to the vector contained in this Variant. + /// + /// @note If the Variant is not of Vector type, this will assert. + std::vector& vector() { + assert_is_type(kTypeVector); + return *value_.vector_value; + } + /// @brief Mutable accessor for a Variant containing a map of Variant data. + /// + /// @return Reference to the map contained in this Variant. + /// + /// @note If the Variant is not of Map type, this will assert. + std::map& map() { + assert_is_type(kTypeMap); + return *value_.map_value; + } + + /// @brief Const accessor for a Variant containing an integer. + /// + /// @return The integer contained in this Variant. + /// + /// @note If the Variant is not of Int64 type, this will assert. + int64_t int64_value() const { + assert_is_type(kTypeInt64); + return value_.int64_value; + } + + /// @brief Const accessor for a Variant containing a double. + /// + /// @return The double contained in this Variant. + /// + /// @note If the Variant is not of Double type, this will assert. + double double_value() const { + assert_is_type(kTypeDouble); + return value_.double_value; + } + + /// @brief Const accessor for a Variant containing a bool. + /// + /// @return The bool contained in this Variant. + /// + /// @note If the Variant is not of Bool type, this will assert. + const bool& bool_value() const { + assert_is_type(kTypeBool); + return value_.bool_value; + } + + /// @brief Const accessor for a Variant containing a string. + /// + /// This can return both static and mutable strings. The pointer is only + /// guaranteed to persist if this Variant's type is StaticString. + /// + /// @return The string contained in this Variant. + /// + /// @note If the Variant is not of StaticString or MutableString type, this + /// will assert. + const char* string_value() const { + assert_is_string(); + if (type_ == kInternalTypeMutableString) + return value_.mutable_string_value->c_str(); + else if (type_ == kInternalTypeStaticString) + return value_.static_string_value; + else // if (type_ == kInternalTypeSmallString) + return value_.small_string; + } + + /// @brief Const accessor for a Variant containing a string. + /// + /// @note Unlike the non-const accessor, this accessor cannot "promote" a + /// static string to mutable, and thus returns a std::string copy instead of a + /// const reference to a std::string + /// + /// @return std::string with the string contents contained in this Variant. + std::string mutable_string() const { + assert_is_string(); + return string_value(); + } + + /// @brief Const accessor for a Variant containing a vector of Variant data. + /// + /// @return Reference to the vector contained in this Variant. + /// + /// @note If the Variant is not of Vector type, this will assert. + const std::vector& vector() const { + assert_is_type(kTypeVector); + return *value_.vector_value; + } + + /// @brief Const accessor for a Variant containing a map of strings to + /// Variant + /// data. + /// + /// @return Reference to the map contained in this Variant. + /// + /// @note If the Variant is not of Map type, this will assert. + const std::map& map() const { + assert_is_type(kTypeMap); + return *value_.map_value; + } + + /// @brief Sets the Variant value to null. + /// + /// The Variant's type will be Null. + void set_null() { Clear(kTypeNull); } + + /// @brief Sets the Variant to an 64-bit integer value. + /// + /// The Variant's type will be set to Int64. + /// + /// @param[in] value The 64-bit integer value for the Variant. + void set_int64_value(int64_t value) { + Clear(kTypeInt64); + value_.int64_value = value; + } + + /// @brief Sets the Variant to an double-precision floating point value. + /// + /// The Variant's type will be set to Double. + /// + /// @param[in] value The double-precision floating point value for the + /// Variant. + void set_double_value(double value) { + Clear(kTypeDouble); + value_.double_value = value; + } + + /// @brief Sets the Variant to the given boolean value. + /// + /// The Variant's type will be set to Bool. + /// + /// @param[in] value The boolean value for the Variant. + void set_bool_value(bool value) { + Clear(kTypeBool); + value_.bool_value = value; + } + + /// @brief Sets the Variant to point to a static string buffer. + /// + /// The Variant's type will be set to StaticString. + /// + /// @note If you use this method, you must ensure that the memory pointed to + /// stays valid for the life of the Variant, or otherwise call + /// mutable_string() or set_mutable_string(), which will copy the string to an + /// internal buffer. + /// + /// @param[in] value A pointer to the static null-terminated string for the + /// Variant. + void set_string_value(const char* value) { + Clear(kTypeStaticString); + value_.static_string_value = value; + } + + /// @brief Sets the Variant to a mutable string. + /// + /// The Variant's type will be set to MutableString. + /// + /// @param[in] value A pointer to a null-terminated string, which will be + /// copied into to the Variant. + void set_string_value(char* value) { + size_t len = strlen(value); + if (len < kMaxSmallStringSize) { + Clear(static_cast(kInternalTypeSmallString)); + strncpy(value_.small_string, value, len + 1); + } else { + set_mutable_string(std::string(value, len)); + } + } + + /// @brief Sets the Variant to a mutable string. + /// + /// The Variant's type will be set to MutableString. + /// + /// @param[in] value The string to use for the Variant. + void set_string_value(const std::string& value) { set_mutable_string(value); } + + /// @brief Sets the Variant to a copy of the given string. + /// + /// The Variant's type will be set to SmallString if the size of the string is + /// less than kMaxSmallStringSize (8 bytes on x86, 16 bytes on x64) or + /// otherwise set to MutableString. + /// + /// @param[in] value The string to use for the Variant. + /// @param[in] use_small_string Check to see if the input string should be + /// treated as a small string or left as a mutable string + void set_mutable_string(const std::string& value, + bool use_small_string = true) { + if (value.size() < kMaxSmallStringSize && use_small_string) { + Clear(static_cast(kInternalTypeSmallString)); + strncpy(value_.small_string, value.data(), value.size() + 1); + } else { + Clear(kTypeMutableString); + *value_.mutable_string_value = value; + } + } + + /// @brief Sets the Variant to a copy of the given binary data. + /// + /// The Variant's type will be set to MutableBlob. + /// + /// @param[in] src_data The data to use for the Variant. If you + /// pass in nullptr, no data will be copied, but a buffer of the + /// requested size will be allocated. + /// @param[in] size_bytes The size of the data, in bytes. + void set_mutable_blob(const void* src_data, size_t size_bytes) { + uint8_t* dest_data = new uint8_t[size_bytes]; // Will be deleted when + // `this` is deleted. + if (src_data != nullptr) { + memcpy(dest_data, src_data, size_bytes); + } + Clear(kTypeMutableBlob); + set_blob_pointer(dest_data, size_bytes); + } + + /// @brief Sets the Variant to point to static binary data. + /// + /// The Variant's type will be set to kTypeStaticBlob. + /// + /// @param[in] static_data Pointer to statically-allocated binary data. The + /// Variant will point to the data, not copy it. + /// @param[in] size_bytes Size of the data, in bytes. + /// + /// @note If you use this method, you must ensure that the memory pointer to + /// stays valid for the life of the Variant, or otherwise call + /// mutable_blob_data() or set_mutable_blob(), which will copy the data into + /// an internal buffer. + void set_static_blob(const void* static_data, size_t size_bytes) { + Clear(kTypeStaticBlob); + set_blob_pointer(static_data, size_bytes); + } + + /// @brief Sets the Variant to a copy of the given vector. + /// + /// The Variant's type will be set to Vector. + /// + /// @param[in] value The STL vector to copy into the Variant. + + void set_vector(const std::vector& value) { + Clear(kTypeVector); + *value_.vector_value = value; + } + + /// @brief Sets the Variant to a copy of the given map. + /// + /// The Variant's type will be set to Map. + /// + /// @param[in] value The STL map to copy into the Variant. + void set_map(const std::map& value) { + Clear(kTypeMap); + *value_.map_value = value; + } + + /// @brief Assigns an existing string which was allocated on the heap into the + /// Variant without performing a copy. This object will take over ownership of + /// the pointer, and will set the std::string* you pass in to NULL. + /// + /// The Variant's type will be set to MutableString. + /// + /// @param[in, out] str Pointer to a pointer to an STL string. The Variant + /// will take over ownership of the pointer to the string, and set the + /// pointer + /// you passed in to NULL. + void AssignMutableString(std::string** str) { + Clear(kTypeNull); + type_ = kInternalTypeMutableString; + value_.mutable_string_value = *str; + *str = NULL; // NOLINT + } + + /// @brief Assigns an existing vector which was allocated on the heap into the + /// Variant without performing a copy. This object will take over ownership of + /// the pointer, and will set the std::vector* you pass in to NULL. + /// + /// The Variant's type will be set to Vector. + /// + /// @param[in, out] vect Pointer to a pointer to an STL vector. The Variant + /// will take over ownership of the pointer to the vector, and set the + /// pointer + /// you passed in to NULL. + void AssignVector(std::vector** vect) { + Clear(kTypeNull); + type_ = kInternalTypeVector; + value_.vector_value = *vect; + *vect = NULL; // NOLINT + } + + /// @brief Assigns an existing map which was allocated on the heap into the + /// Variant without performing a copy. This object will take over ownership + /// of + /// the map, and will set the std::map** you pass in to NULL. + /// + /// The Variant's type will be set to Map. + /// + /// @param[in, out] map Pointer to a pointer to an STL map. The Variant will + /// take over ownership of the pointer to the map, and set the pointer you + /// passed in to NULL. + void AssignMap(std::map** map) { + Clear(kTypeNull); + type_ = kInternalTypeMap; + value_.map_value = *map; + *map = NULL; // NOLINT + } + + // Convenience methods for the times when constructors are too ambiguious. + + /// @brief Return a Variant from a 64-bit integer. + /// + /// @param[in] value 64-bit integer value to put into the Variant. + /// + /// @returns A Variant containing the 64-bit integer. + static Variant FromInt64(int64_t value) { return Variant(value); } + + /// @brief Return a Variant from a double-precision floating point number. + /// + /// @param[in] value Double-precision floating point value to put into the + /// Variant; + /// + /// @returns A Variant containing the double-precision floating point number. + static Variant FromDouble(double value) { return Variant(value); } + + /// @brief Return a Variant from a boolean. + /// + /// @param[in] value Boolean value to put into the Variant. + /// + /// @returns A Variant containing the Boolean. + static Variant FromBool(bool value) { return Variant(value); } + + /// @brief Return a Variant from a static string. + /// + /// @param[in] value Pointer to statically-allocated null-terminated string. + /// + /// @returns A Variant referring to the string pointer you passed in. + /// + /// @note If you use this function, you must ensure that the memory pointed + /// to stays valid for the life of the Variant, otherwise call + /// mutable_string() or set_mutable_string(), which will copy the string to an + /// internal buffer. + static Variant FromStaticString(const char* value) { return Variant(value); } + + /// @brief Return a Variant from a string. + /// + /// This method makes a copy of the string. + /// + /// @param[in] value String value to copy into the Variant. + /// + /// @returns A Variant containing a copy of the string. + static Variant FromMutableString(const std::string& value) { + return Variant(value); + } + + /// @brief Return a Variant that points to static binary data. + /// + /// @param[in] static_data Pointer to statically-allocated binary data. The + /// Variant will point to the data, not copy it. + /// @param[in] size_bytes Size of the data, in bytes. + /// + /// @returns A Variant pointing to the binary data. + /// + /// @note If you use this function, you must ensure that the memory pointed + /// to stays valid for the life of the Variant, otherwise call + /// mutable_blob() or set_mutable_blob(), which will copy the data to an + /// internal buffer. + static Variant FromStaticBlob(const void* static_data, size_t size_bytes) { + Variant v; + v.set_static_blob(static_data, size_bytes); + return v; + } + + /// @brief Return a Variant containing a copy of binary data. + /// + /// @param[in] src_data Pointer to binary data to be copied into the Variant. + /// @param[in] size_bytes Size of the data, in bytes. + /// + /// @returns A Variant containing a copy of the binary data. + static Variant FromMutableBlob(const void* src_data, size_t size_bytes) { + Variant v; + v.set_mutable_blob(src_data, size_bytes); + return v; + } + + /// @brief Return a Variant from a string, but make it mutable. + /// + /// Only copies the string once, unlike Variant(std::string(value)), which + /// copies the string twice. + /// + /// @param[in] value String value to copy into the Variant and make mutable. + /// + /// @returns A Variant containing a mutable copy of the string. + static Variant MutableStringFromStaticString(const char* value) { + std::string* str = new std::string(value); + Variant v; + v.AssignMutableString(&str); + return v; + } + + /// @brief Get the human-readable type name of a Variant type. + /// + /// @param[in] type Variant type to describe. + /// + /// @returns A string describing the type, suitable for error messages or + /// debugging. For example "Int64" or "MutableString". + static const char* TypeName(Type type); + + private: + // Internal Type of data that this variant object contains to avoid breaking + // API + enum InternalType { + /// Null, or no data. + kInternalTypeNull = kTypeNull, + /// A 64-bit integer. + kInternalTypeInt64 = kTypeInt64, + /// A double-precision floating point number. + kInternalTypeDouble = kTypeDouble, + /// A boolean value. + kInternalTypeBool = kTypeBool, + /// A statically-allocated string we point to. + kInternalTypeStaticString = kTypeStaticString, + /// A std::string. + kInternalTypeMutableString = kTypeMutableString, + /// A std::vector of Variant. + kInternalTypeVector = kTypeVector, + /// A std::map, mapping Variant to Variant. + kInternalTypeMap = kTypeMap, + /// An statically-allocated blob of data that we point to. Never constructed + /// by default. Use Variant::FromStaticBlob() to create a Variant of this + /// type. + kInternalTypeStaticBlob = kTypeStaticBlob, + /// A blob of data that the Variant holds. Never constructed by default. Use + /// Variant::FromMutableBlob() to create a Variant of this type, and copy + /// binary data from an existing source. + kInternalTypeMutableBlob = kTypeMutableBlob, + // A c string stored in the Variant internal data blob as opposed to be + // newed as a std::string. Max size is 16 bytes on x64 and 8 bytes on x86. + kInternalTypeSmallString = kTypeMutableBlob + 1, + // Not a valid type. Used to get the total number of Variant types. + kMaxTypeValue, + }; + + /// Human-readable type names, for error logging. + static const char* const kTypeNames[]; + + /// Assert that this Variant is of the given type, failing if it is not. + void assert_is_type(Type type) const; + + /// Assert that this Variant is NOT of the given type, failing if it is. + void assert_is_not_type(Type type) const; + + /// Assert that this Variant is a static string or mutable string, failing if + /// it is not. + void assert_is_string() const; + + /// Assert that this Variant is a static blob or mutable blob, failing if + /// it is not. + void assert_is_blob() const; + + /// Sets the blob's data pointer, for kTypeStaticBlob and kTypeMutableBlob. + /// Asserts if the Variant isn't a blob. Caller is responsible for managing + /// the pointer's memory and deleting any existing data at the location. + void set_blob_pointer(const void* blob_ptr, size_t size) { + assert_is_blob(); + value_.blob_value.ptr = static_cast(blob_ptr); + value_.blob_value.size = size; + } + + // If you hit a compiler error here it means you are trying to construct a + // variant with unsupported type. Ether cast to correct type or add support + // below. + template + void set_value_t(T value) = delete; + + // Get whether this Variant contains a small string. + bool is_small_string() const { return type_ == kInternalTypeSmallString; } + + // Current type contained in this Variant. + InternalType type_; + + // Older versions of visual studio cant have this inline in the union and do + // sizeof for small string + typedef struct { + const uint8_t* ptr; + size_t size; + } BlobValue; + + // Union of plain old data (scalars or pointers). + union Value { + int64_t int64_value; + double double_value; + bool bool_value; + const char* static_string_value; + std::string* mutable_string_value; + std::vector* vector_value; + std::map* map_value; + BlobValue blob_value; + char small_string[sizeof(BlobValue)]; + } value_; + + static constexpr size_t kMaxSmallStringSize = sizeof(Value::small_string); + + friend class firebase::internal::VariantInternal; +}; + +template <> +inline void Variant::set_value_t(int64_t value) { + set_int64_value(value); +} + +template <> +inline void Variant::set_value_t(int value) { + set_int64_value(static_cast(value)); +} + +template <> +inline void Variant::set_value_t(int16_t value) { + set_int64_value(static_cast(value)); +} + +template <> +inline void Variant::set_value_t(uint8_t value) { + set_int64_value(static_cast(value)); +} + +template <> +inline void Variant::set_value_t(int8_t value) { + set_int64_value(static_cast(value)); +} + +template <> +inline void Variant::set_value_t(char value) { + set_int64_value(static_cast(value)); +} + +template <> +inline void Variant::set_value_t(double value) { + set_double_value(value); +} + +template <> +inline void Variant::set_value_t(float value) { + set_double_value(static_cast(value)); +} + +template <> +inline void Variant::set_value_t(bool value) { + set_bool_value(value); +} + +template <> +inline void Variant::set_value_t(const char* value) { + set_string_value(value); +} + +template <> +inline void Variant::set_value_t(char* value) { + set_mutable_string(value); +} + +// NOLINTNEXTLINE - allow namespace overridden +} // namespace firebase + +#endif // FIREBASE_APP_SRC_INCLUDE_FIREBASE_VARIANT_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/version.h b/packages/firebase_core/firebase_core/firebase_core/firebase/version.h new file mode 100644 index 000000000000..79d77fc8af4a --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/version.h @@ -0,0 +1,68 @@ +// Copyright 2016 Google Inc. All Rights Reserved. + +#ifndef FIREBASE_APP_CLIENT_CPP_SRC_VERSION_H_ +#define FIREBASE_APP_CLIENT_CPP_SRC_VERSION_H_ + +/// @def FIREBASE_VERSION_MAJOR +/// @brief Major version number of the Firebase C++ SDK. +/// @see kFirebaseVersionString +#define FIREBASE_VERSION_MAJOR 10 +/// @def FIREBASE_VERSION_MINOR +/// @brief Minor version number of the Firebase C++ SDK. +/// @see kFirebaseVersionString +#define FIREBASE_VERSION_MINOR 5 +/// @def FIREBASE_VERSION_REVISION +/// @brief Revision number of the Firebase C++ SDK. +/// @see kFirebaseVersionString +#define FIREBASE_VERSION_REVISION 0 + +/// @cond FIREBASE_APP_INTERNAL +#define FIREBASE_STRING_EXPAND(X) #X +#define FIREBASE_STRING(X) FIREBASE_STRING_EXPAND(X) +/// @endcond + +// Version number. +// clang-format off +#define FIREBASE_VERSION_NUMBER_STRING \ + FIREBASE_STRING(FIREBASE_VERSION_MAJOR) "." \ + FIREBASE_STRING(FIREBASE_VERSION_MINOR) "." \ + FIREBASE_STRING(FIREBASE_VERSION_REVISION) +// clang-format on + +// Identifier for version string, e.g. kFirebaseVersionString. +#define FIREBASE_VERSION_IDENTIFIER(library) k##library##VersionString + +// Concatenated version string, e.g. "Firebase C++ x.y.z". +#define FIREBASE_VERSION_STRING(library) \ + #library " C++ " FIREBASE_VERSION_NUMBER_STRING + +#if !defined(DOXYGEN) +#if !defined(_WIN32) && !defined(__CYGWIN__) +#define DEFINE_FIREBASE_VERSION_STRING(library) \ + extern volatile __attribute__((weak)) \ + const char* FIREBASE_VERSION_IDENTIFIER(library); \ + volatile __attribute__((weak)) \ + const char* FIREBASE_VERSION_IDENTIFIER(library) = \ + FIREBASE_VERSION_STRING(library) +#else +#define DEFINE_FIREBASE_VERSION_STRING(library) \ + static const char* FIREBASE_VERSION_IDENTIFIER(library) = \ + FIREBASE_VERSION_STRING(library) +#endif // !defined(_WIN32) && !defined(__CYGWIN__) +#else // if defined(DOXYGEN) + +/// @brief Namespace that encompasses all Firebase APIs. +namespace firebase { + +/// @brief String which identifies the current version of the Firebase C++ +/// SDK. +/// +/// @see FIREBASE_VERSION_MAJOR +/// @see FIREBASE_VERSION_MINOR +/// @see FIREBASE_VERSION_REVISION +static const char* kFirebaseVersionString = FIREBASE_VERSION_STRING; + +} // namespace firebase +#endif // !defined(DOXYGEN) + +#endif // FIREBASE_APP_CLIENT_CPP_SRC_VERSION_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/generate_xml_from_google_services_json.py b/packages/firebase_core/firebase_core/firebase_core/generate_xml_from_google_services_json.py new file mode 100644 index 000000000000..8996cd8490f3 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/generate_xml_from_google_services_json.py @@ -0,0 +1,496 @@ +#!/usr/bin/python + +# Copyright 2016 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Stand-alone implementation of the Gradle Firebase plugin. + +Converts the services json file to xml: +https://googleplex-android.googlesource.com/platform/tools/base/+/studio-master-dev/build-system/google-services/src/main/groovy/com/google/gms/googleservices +""" + +__author__ = 'Wouter van Oortmerssen' + +import argparse +import ctypes +import json +import os +import platform +import sys +from xml.etree import ElementTree + +if platform.system().lower() == 'windows': + import ctypes.wintypes # pylint: disable=g-import-not-at-top + +# Map Python 2's unicode method to encode a string as bytes in python 3. +try: + unicode('') # See whether unicode class is available (Python < 3) +except NameError: + unicode = str # pylint: disable=redefined-builtin,invalid-name + +# Input filename if it isn't set. +DEFAULT_INPUT_FILENAME = 'app/google-services.json' +# Output filename if it isn't set. +DEFAULT_OUTPUT_FILENAME = 'res/values/googleservices.xml' +# Input filename for .plist files, if it isn't set. +DEFAULT_PLIST_INPUT_FILENAME = 'GoogleService-Info.plist' +# Output filename for .json files, if it isn't set. +DEFAULT_JSON_OUTPUT_FILENAME = 'google-services-desktop.json' + +OAUTH_CLIENT_TYPE_ANDROID_APP = 1 +OAUTH_CLIENT_TYPE_WEB = 3 + + +def read_xml_value(xml_node): + """Utility method for reading values from the plist XML. + + Args: + xml_node: An ElementTree node, that contains a value. + + Returns: + The value of the node, or None, if it could not be read. + """ + if xml_node.tag == 'string': + return xml_node.text + elif xml_node.tag == 'integer': + return int(xml_node.text) + elif xml_node.tag == 'real': + return float(xml_node.text) + elif xml_node.tag == 'false': + return 0 + elif xml_node.tag == 'true': + return 1 + else: + # other types of input are ignored. (data, dates, arrays, etc.) + return None + + +def construct_plist_dictionary(xml_root): + """Constructs a dictionary of values based on the contents of a plist file. + + Args: + xml_root: An ElementTree node, that represents the root of the xml file + that is to be parsed. (Which should be a dictionary containing + key-value pairs of the properties that need to be extracted.) + + Returns: + A dictionary, containing key-value pairs for all (supported) entries in the + node. + """ + xml_dict = xml_root.find('dict') + + if xml_dict is None: + return None + + plist_dict = {} + i = 0 + while i < len(xml_dict): + if xml_dict[i].tag == 'key': + key = xml_dict[i].text + i += 1 + if i < len(xml_dict): + value = read_xml_value(xml_dict[i]) + if value is not None: + plist_dict[key] = value + i += 1 + + return plist_dict + + +def update_dict_keys(key_map, input_dict): + """Creates a dict from input_dict with the same values but new keys. + + Two dictionaries are passed to this function: the key_map that represents a + mapping of source keys to destination keys, and the input_dict that is the + dictionary that is to be duplicated, replacing any key that matches a source + key with a destination key. Source keys that are not present in the + input_dict will not have their destination key represented in the result. + + In other words, if key_map is `{'old': 'new', 'foo': 'bar'}`, and input_dict + is `{'old': 10}`, the result will be `{'new': 10}`. + + Args: + key_map (dict): A dictionary of strings to strings that maps source keys to + destination keys. + input_dict (dict): The dictionary of string keys to any value type, which + is to be duplicated, replacing source keys with the corresponding + destination keys from key_map. + + Returns: + dict: A new dictionary with updated keys. + """ + return { + new_key: input_dict[old_key] + for (old_key, new_key) in key_map.items() + if old_key in input_dict + } + + +def construct_google_services_json(xml_dict): + """Constructs a google services json file from a dictionary. + + Args: + xml_dict: A dictionary of all the key/value pairs that are needed for the + output json file. + Returns: + A string representing the output json file. + """ + + try: + json_struct = { + 'project_info': + update_dict_keys( + { + 'GCM_SENDER_ID': 'project_number', + 'DATABASE_URL': 'firebase_url', + 'PROJECT_ID': 'project_id', + 'STORAGE_BUCKET': 'storage_bucket' + }, xml_dict), + 'client': [{ + 'client_info': { + 'mobilesdk_app_id': xml_dict['GOOGLE_APP_ID'], + 'android_client_info': { + 'package_name': xml_dict['BUNDLE_ID'] + } + }, + 'oauth_client': [{ + 'client_id': xml_dict['CLIENT_ID'], + }], + 'api_key': [{ + 'current_key': xml_dict['API_KEY'] + }], + 'services': { + 'analytics_service': { + 'status': xml_dict['IS_ANALYTICS_ENABLED'] + }, + 'appinvite_service': { + 'status': xml_dict['IS_APPINVITE_ENABLED'] + } + } + },], + 'configuration_version': + '1' + } + return json.dumps(json_struct, indent=2) + except KeyError as e: + sys.stderr.write('Could not find key in plist file: [%s]\n' % (e.args[0])) + return None + + +def convert_plist_to_json(plist_string, input_filename): + """Converts an input plist string into a .json file and saves it. + + Args: + plist_string: The contents of the loaded plist file. + + input_filename: The file name that the plist data was read from. + Returns: + the converted string, or None if there were errors. + """ + + try: + root = ElementTree.fromstring(plist_string) + except ElementTree.ParseError: + sys.stderr.write('Error parsing file %s.\n' + 'It does not appear to be valid XML.\n' % (input_filename)) + return None + + plist_dict = construct_plist_dictionary(root) + if plist_dict is None: + sys.stderr.write('In file %s, could not locate a top-level \'dict\' ' + 'element.\n' + 'File format should be plist XML, with a top-level ' + 'dictionary containing project settings as key-value ' + 'pairs.\n' % (input_filename)) + return None + + json_string = construct_google_services_json(plist_dict) + return json_string + + +def gen_string(parent, name, text): + """Generate one element and put into the list of keeps. + + Args: + parent: The object that will hold the string. + name: The name to store the string under. + text: The text of the string. + """ + if text: + prev = parent.get('tools:keep', '') + if prev: + prev += ',' + parent.set('tools:keep', prev + '@string/' + name) + child = ElementTree.SubElement(parent, 'string', { + 'name': name, + 'translatable': 'false' + }) + child.text = text + + +def indent(elem, level=0): + """Recurse through XML tree and add indentation. + + Args: + elem: The element to recurse over + level: The current indentation level. + """ + i = '\n' + level*' ' + if elem is not None: + if not elem.text or not elem.text.strip(): + elem.text = i + ' ' + if not elem.tail or not elem.tail.strip(): + elem.tail = i + for elem in elem: + indent(elem, level+1) + if not elem.tail or not elem.tail.strip(): + elem.tail = i + else: + if level and (not elem.tail or not elem.tail.strip()): + elem.tail = i + + +def argv_as_unicode_win32(): + """Returns unicode command line arguments on windows. + """ + + get_command_line_w = ctypes.cdll.kernel32.GetCommandLineW + get_command_line_w.restype = ctypes.wintypes.LPCWSTR + + # CommandLineToArgvW parses the Unicode command line + command_line_to_argv_w = ctypes.windll.shell32.CommandLineToArgvW + command_line_to_argv_w.argtypes = [ + ctypes.wintypes.LPCWSTR, + ctypes.POINTER(ctypes.c_int) + ] + command_line_to_argv_w.restype = ctypes.POINTER( + ctypes.wintypes.LPWSTR) + + argc = ctypes.c_int(0) + argv = command_line_to_argv_w(get_command_line_w(), argc) + + # Strip the python executable from the arguments if it exists + # (It would be listed as the first argument on the windows command line, but + # not in the arguments to the python script) + sys_argv_len = len(sys.argv) + return [unicode(argv[i]) for i in + range(argc.value - sys_argv_len, argc.value)] + + +def main(): + parser = argparse.ArgumentParser( + description=(( + 'Converts a Firebase %s into %s similar to the Gradle plugin, or ' + 'converts a Firebase %s into a %s suitible for use on desktop apps.' % + (DEFAULT_INPUT_FILENAME, DEFAULT_OUTPUT_FILENAME, + DEFAULT_PLIST_INPUT_FILENAME, DEFAULT_JSON_OUTPUT_FILENAME)))) + parser.add_argument('-i', help='Override input file name', + metavar='FILE', required=False) + parser.add_argument('-o', help='Override destination file name', + metavar='FILE', required=False) + parser.add_argument('-p', help=('Package ID to select within the set of ' + 'packages in the input file. If this is ' + 'not specified, the first package in the ' + 'input file is selected.')) + parser.add_argument('-l', help=('List all package IDs referenced by the ' + 'input file. If this is specified, ' + 'the output file is not created.'), + action='store_true', default=False, required=False) + parser.add_argument('-f', help=('Print project fields from the input file ' + 'in the form \'name=value\\n\' for each ' + 'field. If this is specified, the output ' + 'is not created.'), + action='store_true', default=False, required=False) + parser.add_argument( + '--plist', + help=( + 'Specifies a plist file to convert to a JSON configuration file. ' + 'If this is enabled, the script will expect a .plist file as input, ' + 'which it will convert into %s file. The output file is ' + '*not* suitable for use with Firebase on Android.' % + (DEFAULT_JSON_OUTPUT_FILENAME)), + action='store_true', + default=False, + required=False) + + # python 2 on Windows doesn't handle unicode arguments well, so we need to + # pre-process the command line arguments before trying to parse them. + if platform.system() == 'Windows': + sys.argv = argv_as_unicode_win32() + + args = parser.parse_args() + + if args.plist: + input_filename = DEFAULT_PLIST_INPUT_FILENAME + output_filename = DEFAULT_JSON_OUTPUT_FILENAME + else: + input_filename = DEFAULT_INPUT_FILENAME + output_filename = DEFAULT_OUTPUT_FILENAME + + if args.i: + # Encode the input string (type unicode) as a normal string (type str) + # using the 'utf-8' encoding so that it can be worked with the same as + # input names from other sources (like the defaults). + input_filename_raw = args.i.encode('utf-8') + # Decode the filename to a unicode string using the 'utf-8' encoding to + # properly handle filepaths with unicode characters in them. + input_filename = input_filename_raw.decode('utf-8') + + if args.o: + output_filename = args.o + + with open(input_filename, 'r') as ifile: + file_string = ifile.read() + + json_string = None + if args.plist: + json_string = convert_plist_to_json(file_string, input_filename) + if json_string is None: + return 1 + jsobj = json.loads(json_string) + else: + jsobj = json.loads(file_string) + + root = ElementTree.Element('resources') + root.set('xmlns:tools', 'http://schemas.android.com/tools') + + project_info = jsobj.get('project_info') + if project_info: + gen_string(root, 'firebase_database_url', project_info.get('firebase_url')) + gen_string(root, 'gcm_defaultSenderId', project_info.get('project_number')) + gen_string(root, 'google_storage_bucket', + project_info.get('storage_bucket')) + gen_string(root, 'project_id', project_info.get('project_id')) + + if args.f: + if not project_info: + sys.stderr.write('No project info found in %s.' % input_filename) + return 1 + for field, value in sorted(project_info.items()): + sys.stdout.write('%s=%s\n' % (field, value)) + return 0 + + packages = set() + client_list = jsobj.get('client') + if client_list: + # Search for the user specified package in the file. + selected_package_name = '' + selected_client = client_list[0] + find_package_name = args.p + for client in client_list: + package_name = client.get('client_info', {}).get( + 'android_client_info', {}).get('package_name', '') + if not package_name: + package_name = client.get('oauth_client', {}).get( + 'android_info', {}).get('package_name', '') + if package_name: + if not selected_package_name: + selected_package_name = package_name + selected_client = client + if package_name == find_package_name: + selected_package_name = package_name + selected_client = client + packages.add(package_name) + + if args.p and selected_package_name != find_package_name: + sys.stderr.write('No packages found in %s which match the package ' + 'name %s\n' + '\n' + 'Found the following:\n' + '%s\n' % (input_filename, find_package_name, + '\n'.join(packages))) + return 1 + + client_api_key = selected_client.get('api_key') + if client_api_key: + client_api_key0 = client_api_key[0] + gen_string(root, 'google_api_key', client_api_key0.get('current_key')) + gen_string(root, 'google_crash_reporting_api_key', + client_api_key0.get('current_key')) + + client_info = selected_client.get('client_info') + if client_info: + gen_string(root, 'google_app_id', client_info.get('mobilesdk_app_id')) + + # Only include the first matching OAuth client ID per type. + client_id_web_parsed = False + client_id_android_parsed = False + + oauth_client_list = selected_client.get('oauth_client') + if oauth_client_list: + for oauth_client in oauth_client_list: + client_type = oauth_client.get('client_type') + client_id = oauth_client.get('client_id') + if not (client_type and client_id): continue + if (client_type == OAUTH_CLIENT_TYPE_WEB and + not client_id_web_parsed): + gen_string(root, 'default_web_client_id', client_id) + client_id_web_parsed = True + if (client_type == OAUTH_CLIENT_TYPE_ANDROID_APP and + not client_id_android_parsed): + gen_string(root, 'default_android_client_id', client_id) + client_id_android_parsed = True + + services = selected_client.get('services') + if services: + ads_service = services.get('ads_service') + if ads_service: + gen_string(root, 'test_banner_ad_unit_id', + ads_service.get('test_banner_ad_unit_id')) + gen_string(root, 'test_interstitial_ad_unit_id', + ads_service.get('test_interstitial_ad_unit_id')) + analytics_service = services.get('analytics_service') + if analytics_service: + analytics_property = analytics_service.get('analytics_property') + if analytics_property: + gen_string(root, 'ga_trackingId', + analytics_property.get('tracking_id')) + # enable this once we have an example if this service being present + # in the json data: + maps_service_enabled = False + if maps_service_enabled: + maps_service = services.get('maps_service') + if maps_service: + maps_api_key = maps_service.get('api_key') + if maps_api_key: + for k in range(0, len(maps_api_key)): + # generates potentially multiple of these keys, which is + # the same behavior as the java plugin. + gen_string(root, 'google_maps_key', + maps_api_key[k].get('maps_api_key')) + + tree = ElementTree.ElementTree(root) + + indent(root) + + if args.l: + for package in sorted(packages): + if package: + sys.stdout.write(package + '\n') + else: + path = os.path.dirname(output_filename) + + if path and not os.path.exists(path): + os.makedirs(path) + + if not args.plist: + tree.write(output_filename, 'utf-8', True) + else: + with open(output_filename, 'w') as ofile: + ofile.write(json_string) + + return 0 + +if __name__ == '__main__': + sys.exit(main()) \ No newline at end of file diff --git a/packages/firebase_core/firebase_core/firebase_core/generated_bindings.dart b/packages/firebase_core/firebase_core/firebase_core/generated_bindings.dart new file mode 100644 index 000000000000..f58d1524bee8 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/generated_bindings.dart @@ -0,0 +1,26 @@ +// AUTO GENERATED FILE, DO NOT EDIT. +// +// Generated by `package:ffigen`. +import 'dart:ffi' as ffi; + +class NativeLibrary { + /// Holds the symbol lookup function. + final ffi.Pointer Function(String symbolName) + _lookup; + + /// The symbols are looked up in [dynamicLibrary]. + NativeLibrary(ffi.DynamicLibrary dynamicLibrary) + : _lookup = dynamicLibrary.lookup; + + /// The symbols are looked up with [lookup]. + NativeLibrary.fromLookup( + ffi.Pointer Function(String symbolName) + lookup) + : _lookup = lookup; + + late final ffi.Pointer _firebase = _lookup('firebase'); + + int get firebase => _firebase.value; + + set firebase(int value) => _firebase.value = value; +} diff --git a/packages/firebase_core/firebase_core/firebase_core/google-services-desktop.json b/packages/firebase_core/firebase_core/firebase_core/google-services-desktop.json new file mode 100644 index 000000000000..a3bf216f4de0 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/google-services-desktop.json @@ -0,0 +1,37 @@ +{ + "project_info": { + "project_number": "406099696497", + "firebase_url": "https://flutterfire-e2e-tests-default-rtdb.europe-west1.firebasedatabase.app", + "project_id": "flutterfire-e2e-tests", + "storage_bucket": "flutterfire-e2e-tests.appspot.com" + }, + "client": [ + { + "client_info": { + "mobilesdk_app_id": "1:406099696497:ios:58cbc26aca8e5cf83574d0", + "android_client_info": { + "package_name": "io.flutter.plugins.firebase.auth.example" + } + }, + "oauth_client": [ + { + "client_id": "406099696497-134k3722m01rtrsklhf3b7k8sqa5r7in.apps.googleusercontent.com" + } + ], + "api_key": [ + { + "current_key": "AIzaSyDooSUGSf63Ghq02_iIhtnmwMDs4HlWS6c" + } + ], + "services": { + "analytics_service": { + "status": 0 + }, + "appinvite_service": { + "status": 1 + } + } + } + ], + "configuration_version": "1" +} \ No newline at end of file diff --git a/packages/firebase_core/firebase_core/firebase_core/lib/firebase_core.dart b/packages/firebase_core/firebase_core/firebase_core/lib/firebase_core.dart new file mode 100644 index 000000000000..d1295e26ad15 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/lib/firebase_core.dart @@ -0,0 +1,8 @@ + +import 'firebase_core_platform_interface.dart'; + +class FirebaseCore { + Future getPlatformVersion() { + return FirebaseCorePlatform.instance.getPlatformVersion(); + } +} diff --git a/packages/firebase_core/firebase_core/firebase_core/lib/firebase_core_method_channel.dart b/packages/firebase_core/firebase_core/firebase_core/lib/firebase_core_method_channel.dart new file mode 100644 index 000000000000..5da300fa9013 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/lib/firebase_core_method_channel.dart @@ -0,0 +1,17 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter/services.dart'; + +import 'firebase_core_platform_interface.dart'; + +/// An implementation of [FirebaseCorePlatform] that uses method channels. +class MethodChannelFirebaseCore extends FirebaseCorePlatform { + /// The method channel used to interact with the native platform. + @visibleForTesting + final methodChannel = const MethodChannel('firebase_core'); + + @override + Future getPlatformVersion() async { + final version = await methodChannel.invokeMethod('getPlatformVersion'); + return version; + } +} diff --git a/packages/firebase_core/firebase_core/firebase_core/lib/firebase_core_platform_interface.dart b/packages/firebase_core/firebase_core/firebase_core/lib/firebase_core_platform_interface.dart new file mode 100644 index 000000000000..6f6e165b7957 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/lib/firebase_core_platform_interface.dart @@ -0,0 +1,29 @@ +import 'package:plugin_platform_interface/plugin_platform_interface.dart'; + +import 'firebase_core_method_channel.dart'; + +abstract class FirebaseCorePlatform extends PlatformInterface { + /// Constructs a FirebaseCorePlatform. + FirebaseCorePlatform() : super(token: _token); + + static final Object _token = Object(); + + static FirebaseCorePlatform _instance = MethodChannelFirebaseCore(); + + /// The default instance of [FirebaseCorePlatform] to use. + /// + /// Defaults to [MethodChannelFirebaseCore]. + static FirebaseCorePlatform get instance => _instance; + + /// Platform-specific implementations should set this with their own + /// platform-specific class that extends [FirebaseCorePlatform] when + /// they register themselves. + static set instance(FirebaseCorePlatform instance) { + PlatformInterface.verifyToken(instance, _token); + _instance = instance; + } + + Future getPlatformVersion() { + throw UnimplementedError('platformVersion() has not been implemented.'); + } +} diff --git a/packages/firebase_core/firebase_core/firebase_core/linux/CMakeLists.txt b/packages/firebase_core/firebase_core/firebase_core/linux/CMakeLists.txt new file mode 100644 index 000000000000..5cec31c86b71 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/linux/CMakeLists.txt @@ -0,0 +1,47 @@ +# The Flutter tooling requires that developers have CMake 3.10 or later +# installed. You should not increase this version, as doing so will cause +# the plugin to fail to compile for some customers of the plugin. +cmake_minimum_required(VERSION 3.10) + +# Project-level configuration. +set(PROJECT_NAME "firebase_core") +project(${PROJECT_NAME} LANGUAGES CXX) + +# This value is used when generating builds using this plugin, so it must +# not be changed. +set(PLUGIN_NAME "firebase_core_plugin") + +# Define the plugin library target. Its name must not be changed (see comment +# on PLUGIN_NAME above). +# +# Any new source files that you add to the plugin should be added here. +add_library(${PLUGIN_NAME} SHARED + "firebase_core_plugin.cc" +) + +# Apply a standard set of build settings that are configured in the +# application-level CMakeLists.txt. This can be removed for plugins that want +# full control over build settings. +apply_standard_settings(${PLUGIN_NAME}) + +# Symbols are hidden by default to reduce the chance of accidental conflicts +# between plugins. This should not be removed; any symbols that should be +# exported should be explicitly exported with the FLUTTER_PLUGIN_EXPORT macro. +set_target_properties(${PLUGIN_NAME} PROPERTIES + CXX_VISIBILITY_PRESET hidden) +target_compile_definitions(${PLUGIN_NAME} PRIVATE FLUTTER_PLUGIN_IMPL) + +# Source include directories and library dependencies. Add any plugin-specific +# dependencies here. +target_include_directories(${PLUGIN_NAME} INTERFACE + "${CMAKE_CURRENT_SOURCE_DIR}/include") +target_link_libraries(${PLUGIN_NAME} PRIVATE flutter) +target_link_libraries(${PLUGIN_NAME} PRIVATE PkgConfig::GTK) + +# List of absolute paths to libraries that should be bundled with the plugin. +# This list could contain prebuilt libraries, or libraries created by an +# external build triggered from this build file. +set(firebase_core_bundled_libraries + "" + PARENT_SCOPE +) diff --git a/packages/firebase_core/firebase_core/firebase_core/linux/firebase_core_plugin.cc b/packages/firebase_core/firebase_core/firebase_core/linux/firebase_core_plugin.cc new file mode 100644 index 000000000000..4fd897624ca4 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/linux/firebase_core_plugin.cc @@ -0,0 +1,70 @@ +#include "include/firebase_core/firebase_core_plugin.h" + +#include +#include +#include + +#include + +#define FIREBASE_CORE_PLUGIN(obj) \ + (G_TYPE_CHECK_INSTANCE_CAST((obj), firebase_core_plugin_get_type(), \ + FirebaseCorePlugin)) + +struct _FirebaseCorePlugin { + GObject parent_instance; +}; + +G_DEFINE_TYPE(FirebaseCorePlugin, firebase_core_plugin, g_object_get_type()) + +// Called when a method call is received from Flutter. +static void firebase_core_plugin_handle_method_call( + FirebaseCorePlugin* self, + FlMethodCall* method_call) { + g_autoptr(FlMethodResponse) response = nullptr; + + const gchar* method = fl_method_call_get_name(method_call); + + if (strcmp(method, "getPlatformVersion") == 0) { + struct utsname uname_data = {}; + uname(&uname_data); + g_autofree gchar *version = g_strdup_printf("Linux %s", uname_data.version); + g_autoptr(FlValue) result = fl_value_new_string(version); + response = FL_METHOD_RESPONSE(fl_method_success_response_new(result)); + } else { + response = FL_METHOD_RESPONSE(fl_method_not_implemented_response_new()); + } + + fl_method_call_respond(method_call, response, nullptr); +} + +static void firebase_core_plugin_dispose(GObject* object) { + G_OBJECT_CLASS(firebase_core_plugin_parent_class)->dispose(object); +} + +static void firebase_core_plugin_class_init(FirebaseCorePluginClass* klass) { + G_OBJECT_CLASS(klass)->dispose = firebase_core_plugin_dispose; +} + +static void firebase_core_plugin_init(FirebaseCorePlugin* self) {} + +static void method_call_cb(FlMethodChannel* channel, FlMethodCall* method_call, + gpointer user_data) { + FirebaseCorePlugin* plugin = FIREBASE_CORE_PLUGIN(user_data); + firebase_core_plugin_handle_method_call(plugin, method_call); +} + +void firebase_core_plugin_register_with_registrar(FlPluginRegistrar* registrar) { + FirebaseCorePlugin* plugin = FIREBASE_CORE_PLUGIN( + g_object_new(firebase_core_plugin_get_type(), nullptr)); + + g_autoptr(FlStandardMethodCodec) codec = fl_standard_method_codec_new(); + g_autoptr(FlMethodChannel) channel = + fl_method_channel_new(fl_plugin_registrar_get_messenger(registrar), + "firebase_core", + FL_METHOD_CODEC(codec)); + fl_method_channel_set_method_call_handler(channel, method_call_cb, + g_object_ref(plugin), + g_object_unref); + + g_object_unref(plugin); +} diff --git a/packages/firebase_core/firebase_core/firebase_core/linux/include/firebase_core/firebase_core_plugin.h b/packages/firebase_core/firebase_core/firebase_core/linux/include/firebase_core/firebase_core_plugin.h new file mode 100644 index 000000000000..3f15a61a3e72 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/linux/include/firebase_core/firebase_core_plugin.h @@ -0,0 +1,26 @@ +#ifndef FLUTTER_PLUGIN_FIREBASE_CORE_PLUGIN_H_ +#define FLUTTER_PLUGIN_FIREBASE_CORE_PLUGIN_H_ + +#include + +G_BEGIN_DECLS + +#ifdef FLUTTER_PLUGIN_IMPL +#define FLUTTER_PLUGIN_EXPORT __attribute__((visibility("default"))) +#else +#define FLUTTER_PLUGIN_EXPORT +#endif + +typedef struct _FirebaseCorePlugin FirebaseCorePlugin; +typedef struct { + GObjectClass parent_class; +} FirebaseCorePluginClass; + +FLUTTER_PLUGIN_EXPORT GType firebase_core_plugin_get_type(); + +FLUTTER_PLUGIN_EXPORT void firebase_core_plugin_register_with_registrar( + FlPluginRegistrar* registrar); + +G_END_DECLS + +#endif // FLUTTER_PLUGIN_FIREBASE_CORE_PLUGIN_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/pubspec.yaml b/packages/firebase_core/firebase_core/firebase_core/pubspec.yaml new file mode 100644 index 000000000000..ce38f84906e8 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/pubspec.yaml @@ -0,0 +1,34 @@ +name: firebase_core +description: A new Flutter plugin project. +version: 0.0.1 +homepage: + +environment: + sdk: '>=2.19.2 <3.0.0' + flutter: '>=2.5.0' + +dependencies: + ffi: ^2.0.1 + flutter: + sdk: flutter + plugin_platform_interface: ^2.0.2 + +dev_dependencies: + flutter_test: + sdk: flutter + flutter_lints: ^2.0.0 + ffigen: ^7.2.6 + +flutter: + plugin: + platforms: + linux: + pluginClass: FirebaseCorePlugin + +ffigen: + output: 'generated_bindings.dart' + headers: + entry-points: + - 'firebase/app.h' + include-directives: + - 'firebase/**.h' diff --git a/packages/firebase_core/firebase_core/firebase_core/test/firebase_core_method_channel_test.dart b/packages/firebase_core/firebase_core/firebase_core/test/firebase_core_method_channel_test.dart new file mode 100644 index 000000000000..70c7fc5e7362 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/test/firebase_core_method_channel_test.dart @@ -0,0 +1,24 @@ +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:firebase_core/firebase_core_method_channel.dart'; + +void main() { + MethodChannelFirebaseCore platform = MethodChannelFirebaseCore(); + const MethodChannel channel = MethodChannel('firebase_core'); + + TestWidgetsFlutterBinding.ensureInitialized(); + + setUp(() { + channel.setMockMethodCallHandler((MethodCall methodCall) async { + return '42'; + }); + }); + + tearDown(() { + channel.setMockMethodCallHandler(null); + }); + + test('getPlatformVersion', () async { + expect(await platform.getPlatformVersion(), '42'); + }); +} diff --git a/packages/firebase_core/firebase_core/firebase_core/test/firebase_core_test.dart b/packages/firebase_core/firebase_core/firebase_core/test/firebase_core_test.dart new file mode 100644 index 000000000000..bb8e54416b4e --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/test/firebase_core_test.dart @@ -0,0 +1,29 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:firebase_core/firebase_core.dart'; +import 'package:firebase_core/firebase_core_platform_interface.dart'; +import 'package:firebase_core/firebase_core_method_channel.dart'; +import 'package:plugin_platform_interface/plugin_platform_interface.dart'; + +class MockFirebaseCorePlatform + with MockPlatformInterfaceMixin + implements FirebaseCorePlatform { + + @override + Future getPlatformVersion() => Future.value('42'); +} + +void main() { + final FirebaseCorePlatform initialPlatform = FirebaseCorePlatform.instance; + + test('$MethodChannelFirebaseCore is the default instance', () { + expect(initialPlatform, isInstanceOf()); + }); + + test('getPlatformVersion', () async { + FirebaseCore firebaseCorePlugin = FirebaseCore(); + MockFirebaseCorePlatform fakePlatform = MockFirebaseCorePlatform(); + FirebaseCorePlatform.instance = fakePlatform; + + expect(await firebaseCorePlugin.getPlatformVersion(), '42'); + }); +} From b4d91269af0c9b07162bc6eabfc92ccb8dc62955 Mon Sep 17 00:00:00 2001 From: Guillaume Bernos Date: Mon, 6 Mar 2023 14:52:47 +0100 Subject: [PATCH 02/65] add windows --- .../firebase_core/firebase_core/.metadata | 12 +- .../firebase_core/example/windows/.gitignore | 17 ++ .../example/windows/CMakeLists.txt | 101 ++++++ .../example/windows/flutter/CMakeLists.txt | 104 +++++++ .../example/windows/runner/CMakeLists.txt | 40 +++ .../example/windows/runner/Runner.rc | 121 ++++++++ .../example/windows/runner/flutter_window.cpp | 66 ++++ .../example/windows/runner/flutter_window.h | 33 ++ .../example/windows/runner/main.cpp | 43 +++ .../example/windows/runner/resource.h | 16 + .../windows/runner/resources/app_icon.ico | Bin 0 -> 33772 bytes .../windows/runner/runner.exe.manifest | 20 ++ .../example/windows/runner/utils.cpp | 64 ++++ .../example/windows/runner/utils.h | 19 ++ .../example/windows/runner/win32_window.cpp | 288 ++++++++++++++++++ .../example/windows/runner/win32_window.h | 102 +++++++ .../firebase_core/firebase_core/pubspec.yaml | 2 + .../firebase_core/windows/.gitignore | 17 ++ .../firebase_core/windows/CMakeLists.txt | 53 ++++ .../windows/firebase_core_plugin.cpp | 59 ++++ .../windows/firebase_core_plugin.h | 32 ++ .../windows/firebase_core_plugin_c_api.cpp | 12 + .../firebase_core_plugin_c_api.h | 23 ++ 23 files changed, 1238 insertions(+), 6 deletions(-) create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/windows/.gitignore create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/windows/CMakeLists.txt create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/windows/flutter/CMakeLists.txt create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/windows/runner/CMakeLists.txt create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/windows/runner/Runner.rc create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/windows/runner/flutter_window.cpp create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/windows/runner/flutter_window.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/windows/runner/main.cpp create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/windows/runner/resource.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/windows/runner/resources/app_icon.ico create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/windows/runner/runner.exe.manifest create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/windows/runner/utils.cpp create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/windows/runner/utils.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/windows/runner/win32_window.cpp create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/windows/runner/win32_window.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/windows/.gitignore create mode 100644 packages/firebase_core/firebase_core/firebase_core/windows/CMakeLists.txt create mode 100644 packages/firebase_core/firebase_core/firebase_core/windows/firebase_core_plugin.cpp create mode 100644 packages/firebase_core/firebase_core/firebase_core/windows/firebase_core_plugin.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/windows/firebase_core_plugin_c_api.cpp create mode 100644 packages/firebase_core/firebase_core/firebase_core/windows/include/firebase_core/firebase_core_plugin_c_api.h diff --git a/packages/firebase_core/firebase_core/firebase_core/.metadata b/packages/firebase_core/firebase_core/firebase_core/.metadata index 74867a0b132b..97ef0fff36d0 100644 --- a/packages/firebase_core/firebase_core/firebase_core/.metadata +++ b/packages/firebase_core/firebase_core/firebase_core/.metadata @@ -4,7 +4,7 @@ # This file should be version controlled. version: - revision: 9944297138845a94256f1cf37beb88ff9a8e811a + revision: 12cb4eb7a009f52b347b62ade7cb4854b926af72 channel: stable project_type: plugin @@ -13,11 +13,11 @@ project_type: plugin migration: platforms: - platform: root - create_revision: 9944297138845a94256f1cf37beb88ff9a8e811a - base_revision: 9944297138845a94256f1cf37beb88ff9a8e811a - - platform: linux - create_revision: 9944297138845a94256f1cf37beb88ff9a8e811a - base_revision: 9944297138845a94256f1cf37beb88ff9a8e811a + create_revision: 12cb4eb7a009f52b347b62ade7cb4854b926af72 + base_revision: 12cb4eb7a009f52b347b62ade7cb4854b926af72 + - platform: windows + create_revision: 12cb4eb7a009f52b347b62ade7cb4854b926af72 + base_revision: 12cb4eb7a009f52b347b62ade7cb4854b926af72 # User provided section diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/.gitignore b/packages/firebase_core/firebase_core/firebase_core/example/windows/.gitignore new file mode 100644 index 000000000000..d492d0d98c8f --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/windows/.gitignore @@ -0,0 +1,17 @@ +flutter/ephemeral/ + +# Visual Studio user-specific files. +*.suo +*.user +*.userosscache +*.sln.docstates + +# Visual Studio build-related files. +x64/ +x86/ + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!*.[Cc]ache/ diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/CMakeLists.txt b/packages/firebase_core/firebase_core/firebase_core/example/windows/CMakeLists.txt new file mode 100644 index 000000000000..ddf92aa378e1 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/windows/CMakeLists.txt @@ -0,0 +1,101 @@ +# Project-level configuration. +cmake_minimum_required(VERSION 3.14) +project(firebase_core_example LANGUAGES CXX) + +# The name of the executable created for the application. Change this to change +# the on-disk name of your application. +set(BINARY_NAME "firebase_core_example") + +# Explicitly opt in to modern CMake behaviors to avoid warnings with recent +# versions of CMake. +cmake_policy(SET CMP0063 NEW) + +# Define build configuration option. +get_property(IS_MULTICONFIG GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG) +if(IS_MULTICONFIG) + set(CMAKE_CONFIGURATION_TYPES "Debug;Profile;Release" + CACHE STRING "" FORCE) +else() + if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) + set(CMAKE_BUILD_TYPE "Debug" CACHE + STRING "Flutter build mode" FORCE) + set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS + "Debug" "Profile" "Release") + endif() +endif() +# Define settings for the Profile build mode. +set(CMAKE_EXE_LINKER_FLAGS_PROFILE "${CMAKE_EXE_LINKER_FLAGS_RELEASE}") +set(CMAKE_SHARED_LINKER_FLAGS_PROFILE "${CMAKE_SHARED_LINKER_FLAGS_RELEASE}") +set(CMAKE_C_FLAGS_PROFILE "${CMAKE_C_FLAGS_RELEASE}") +set(CMAKE_CXX_FLAGS_PROFILE "${CMAKE_CXX_FLAGS_RELEASE}") + +# Use Unicode for all projects. +add_definitions(-DUNICODE -D_UNICODE) + +# Compilation settings that should be applied to most targets. +# +# Be cautious about adding new options here, as plugins use this function by +# default. In most cases, you should add new options to specific targets instead +# of modifying this function. +function(APPLY_STANDARD_SETTINGS TARGET) + target_compile_features(${TARGET} PUBLIC cxx_std_17) + target_compile_options(${TARGET} PRIVATE /W4 /WX /wd"4100") + target_compile_options(${TARGET} PRIVATE /EHsc) + target_compile_definitions(${TARGET} PRIVATE "_HAS_EXCEPTIONS=0") + target_compile_definitions(${TARGET} PRIVATE "$<$:_DEBUG>") +endfunction() + +# Flutter library and tool build rules. +set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") +add_subdirectory(${FLUTTER_MANAGED_DIR}) + +# Application build; see runner/CMakeLists.txt. +add_subdirectory("runner") + +# Generated plugin build rules, which manage building the plugins and adding +# them to the application. +include(flutter/generated_plugins.cmake) + + +# === Installation === +# Support files are copied into place next to the executable, so that it can +# run in place. This is done instead of making a separate bundle (as on Linux) +# so that building and running from within Visual Studio will work. +set(BUILD_BUNDLE_DIR "$") +# Make the "install" step default, as it's required to run. +set(CMAKE_VS_INCLUDE_INSTALL_TO_DEFAULT_BUILD 1) +if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) + set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) +endif() + +set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") +set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}") + +install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +if(PLUGIN_BUNDLED_LIBRARIES) + install(FILES "${PLUGIN_BUNDLED_LIBRARIES}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endif() + +# Fully re-copy the assets directory on each build to avoid having stale files +# from a previous install. +set(FLUTTER_ASSET_DIR_NAME "flutter_assets") +install(CODE " + file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") + " COMPONENT Runtime) +install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" + DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) + +# Install the AOT library on non-Debug builds only. +install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + CONFIGURATIONS Profile;Release + COMPONENT Runtime) diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/flutter/CMakeLists.txt b/packages/firebase_core/firebase_core/firebase_core/example/windows/flutter/CMakeLists.txt new file mode 100644 index 000000000000..930d2071a324 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/windows/flutter/CMakeLists.txt @@ -0,0 +1,104 @@ +# This file controls Flutter-level build steps. It should not be edited. +cmake_minimum_required(VERSION 3.14) + +set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") + +# Configuration provided via flutter tool. +include(${EPHEMERAL_DIR}/generated_config.cmake) + +# TODO: Move the rest of this into files in ephemeral. See +# https://github.com/flutter/flutter/issues/57146. +set(WRAPPER_ROOT "${EPHEMERAL_DIR}/cpp_client_wrapper") + +# === Flutter Library === +set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/flutter_windows.dll") + +# Published to parent scope for install step. +set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) +set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) +set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) +set(AOT_LIBRARY "${PROJECT_DIR}/build/windows/app.so" PARENT_SCOPE) + +list(APPEND FLUTTER_LIBRARY_HEADERS + "flutter_export.h" + "flutter_windows.h" + "flutter_messenger.h" + "flutter_plugin_registrar.h" + "flutter_texture_registrar.h" +) +list(TRANSFORM FLUTTER_LIBRARY_HEADERS PREPEND "${EPHEMERAL_DIR}/") +add_library(flutter INTERFACE) +target_include_directories(flutter INTERFACE + "${EPHEMERAL_DIR}" +) +target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}.lib") +add_dependencies(flutter flutter_assemble) + +# === Wrapper === +list(APPEND CPP_WRAPPER_SOURCES_CORE + "core_implementations.cc" + "standard_codec.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_CORE PREPEND "${WRAPPER_ROOT}/") +list(APPEND CPP_WRAPPER_SOURCES_PLUGIN + "plugin_registrar.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_PLUGIN PREPEND "${WRAPPER_ROOT}/") +list(APPEND CPP_WRAPPER_SOURCES_APP + "flutter_engine.cc" + "flutter_view_controller.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_APP PREPEND "${WRAPPER_ROOT}/") + +# Wrapper sources needed for a plugin. +add_library(flutter_wrapper_plugin STATIC + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_PLUGIN} +) +apply_standard_settings(flutter_wrapper_plugin) +set_target_properties(flutter_wrapper_plugin PROPERTIES + POSITION_INDEPENDENT_CODE ON) +set_target_properties(flutter_wrapper_plugin PROPERTIES + CXX_VISIBILITY_PRESET hidden) +target_link_libraries(flutter_wrapper_plugin PUBLIC flutter) +target_include_directories(flutter_wrapper_plugin PUBLIC + "${WRAPPER_ROOT}/include" +) +add_dependencies(flutter_wrapper_plugin flutter_assemble) + +# Wrapper sources needed for the runner. +add_library(flutter_wrapper_app STATIC + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_APP} +) +apply_standard_settings(flutter_wrapper_app) +target_link_libraries(flutter_wrapper_app PUBLIC flutter) +target_include_directories(flutter_wrapper_app PUBLIC + "${WRAPPER_ROOT}/include" +) +add_dependencies(flutter_wrapper_app flutter_assemble) + +# === Flutter tool backend === +# _phony_ is a non-existent file to force this command to run every time, +# since currently there's no way to get a full input/output list from the +# flutter tool. +set(PHONY_OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/_phony_") +set_source_files_properties("${PHONY_OUTPUT}" PROPERTIES SYMBOLIC TRUE) +add_custom_command( + OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} + ${CPP_WRAPPER_SOURCES_CORE} ${CPP_WRAPPER_SOURCES_PLUGIN} + ${CPP_WRAPPER_SOURCES_APP} + ${PHONY_OUTPUT} + COMMAND ${CMAKE_COMMAND} -E env + ${FLUTTER_TOOL_ENVIRONMENT} + "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.bat" + windows-x64 $ + VERBATIM +) +add_custom_target(flutter_assemble DEPENDS + "${FLUTTER_LIBRARY}" + ${FLUTTER_LIBRARY_HEADERS} + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_PLUGIN} + ${CPP_WRAPPER_SOURCES_APP} +) diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/CMakeLists.txt b/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/CMakeLists.txt new file mode 100644 index 000000000000..394917c053a0 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/CMakeLists.txt @@ -0,0 +1,40 @@ +cmake_minimum_required(VERSION 3.14) +project(runner LANGUAGES CXX) + +# Define the application target. To change its name, change BINARY_NAME in the +# top-level CMakeLists.txt, not the value here, or `flutter run` will no longer +# work. +# +# Any new source files that you add to the application should be added here. +add_executable(${BINARY_NAME} WIN32 + "flutter_window.cpp" + "main.cpp" + "utils.cpp" + "win32_window.cpp" + "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" + "Runner.rc" + "runner.exe.manifest" +) + +# Apply the standard set of build settings. This can be removed for applications +# that need different build settings. +apply_standard_settings(${BINARY_NAME}) + +# Add preprocessor definitions for the build version. +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION=\"${FLUTTER_VERSION}\"") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MAJOR=${FLUTTER_VERSION_MAJOR}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MINOR=${FLUTTER_VERSION_MINOR}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_PATCH=${FLUTTER_VERSION_PATCH}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_BUILD=${FLUTTER_VERSION_BUILD}") + +# Disable Windows macros that collide with C++ standard library functions. +target_compile_definitions(${BINARY_NAME} PRIVATE "NOMINMAX") + +# Add dependency libraries and include directories. Add any application-specific +# dependencies here. +target_link_libraries(${BINARY_NAME} PRIVATE flutter flutter_wrapper_app) +target_link_libraries(${BINARY_NAME} PRIVATE "dwmapi.lib") +target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") + +# Run the Flutter tool portions of the build. This must not be removed. +add_dependencies(${BINARY_NAME} flutter_assemble) diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/Runner.rc b/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/Runner.rc new file mode 100644 index 000000000000..c0d7fe21c712 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/Runner.rc @@ -0,0 +1,121 @@ +// Microsoft Visual C++ generated resource script. +// +#pragma code_page(65001) +#include "resource.h" + +#define APSTUDIO_READONLY_SYMBOLS +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 2 resource. +// +#include "winres.h" + +///////////////////////////////////////////////////////////////////////////// +#undef APSTUDIO_READONLY_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +// English (United States) resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) +LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US + +#ifdef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// TEXTINCLUDE +// + +1 TEXTINCLUDE +BEGIN + "resource.h\0" +END + +2 TEXTINCLUDE +BEGIN + "#include ""winres.h""\r\n" + "\0" +END + +3 TEXTINCLUDE +BEGIN + "\r\n" + "\0" +END + +#endif // APSTUDIO_INVOKED + + +///////////////////////////////////////////////////////////////////////////// +// +// Icon +// + +// Icon with lowest ID value placed first to ensure application icon +// remains consistent on all systems. +IDI_APP_ICON ICON "resources\\app_icon.ico" + + +///////////////////////////////////////////////////////////////////////////// +// +// Version +// + +#if defined(FLUTTER_VERSION_MAJOR) && defined(FLUTTER_VERSION_MINOR) && defined(FLUTTER_VERSION_PATCH) && defined(FLUTTER_VERSION_BUILD) +#define VERSION_AS_NUMBER FLUTTER_VERSION_MAJOR,FLUTTER_VERSION_MINOR,FLUTTER_VERSION_PATCH,FLUTTER_VERSION_BUILD +#else +#define VERSION_AS_NUMBER 1,0,0,0 +#endif + +#if defined(FLUTTER_VERSION) +#define VERSION_AS_STRING FLUTTER_VERSION +#else +#define VERSION_AS_STRING "1.0.0" +#endif + +VS_VERSION_INFO VERSIONINFO + FILEVERSION VERSION_AS_NUMBER + PRODUCTVERSION VERSION_AS_NUMBER + FILEFLAGSMASK VS_FFI_FILEFLAGSMASK +#ifdef _DEBUG + FILEFLAGS VS_FF_DEBUG +#else + FILEFLAGS 0x0L +#endif + FILEOS VOS__WINDOWS32 + FILETYPE VFT_APP + FILESUBTYPE 0x0L +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "040904e4" + BEGIN + VALUE "CompanyName", "com.example" "\0" + VALUE "FileDescription", "firebase_core_example" "\0" + VALUE "FileVersion", VERSION_AS_STRING "\0" + VALUE "InternalName", "firebase_core_example" "\0" + VALUE "LegalCopyright", "Copyright (C) 2023 com.example. All rights reserved." "\0" + VALUE "OriginalFilename", "firebase_core_example.exe" "\0" + VALUE "ProductName", "firebase_core_example" "\0" + VALUE "ProductVersion", VERSION_AS_STRING "\0" + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x409, 1252 + END +END + +#endif // English (United States) resources +///////////////////////////////////////////////////////////////////////////// + + + +#ifndef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 3 resource. +// + + +///////////////////////////////////////////////////////////////////////////// +#endif // not APSTUDIO_INVOKED diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/flutter_window.cpp b/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/flutter_window.cpp new file mode 100644 index 000000000000..b25e363efa42 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/flutter_window.cpp @@ -0,0 +1,66 @@ +#include "flutter_window.h" + +#include + +#include "flutter/generated_plugin_registrant.h" + +FlutterWindow::FlutterWindow(const flutter::DartProject& project) + : project_(project) {} + +FlutterWindow::~FlutterWindow() {} + +bool FlutterWindow::OnCreate() { + if (!Win32Window::OnCreate()) { + return false; + } + + RECT frame = GetClientArea(); + + // The size here must match the window dimensions to avoid unnecessary surface + // creation / destruction in the startup path. + flutter_controller_ = std::make_unique( + frame.right - frame.left, frame.bottom - frame.top, project_); + // Ensure that basic setup of the controller was successful. + if (!flutter_controller_->engine() || !flutter_controller_->view()) { + return false; + } + RegisterPlugins(flutter_controller_->engine()); + SetChildContent(flutter_controller_->view()->GetNativeWindow()); + + flutter_controller_->engine()->SetNextFrameCallback([&]() { + this->Show(); + }); + + return true; +} + +void FlutterWindow::OnDestroy() { + if (flutter_controller_) { + flutter_controller_ = nullptr; + } + + Win32Window::OnDestroy(); +} + +LRESULT +FlutterWindow::MessageHandler(HWND hwnd, UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + // Give Flutter, including plugins, an opportunity to handle window messages. + if (flutter_controller_) { + std::optional result = + flutter_controller_->HandleTopLevelWindowProc(hwnd, message, wparam, + lparam); + if (result) { + return *result; + } + } + + switch (message) { + case WM_FONTCHANGE: + flutter_controller_->engine()->ReloadSystemFonts(); + break; + } + + return Win32Window::MessageHandler(hwnd, message, wparam, lparam); +} diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/flutter_window.h b/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/flutter_window.h new file mode 100644 index 000000000000..6da0652f05f2 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/flutter_window.h @@ -0,0 +1,33 @@ +#ifndef RUNNER_FLUTTER_WINDOW_H_ +#define RUNNER_FLUTTER_WINDOW_H_ + +#include +#include + +#include + +#include "win32_window.h" + +// A window that does nothing but host a Flutter view. +class FlutterWindow : public Win32Window { + public: + // Creates a new FlutterWindow hosting a Flutter view running |project|. + explicit FlutterWindow(const flutter::DartProject& project); + virtual ~FlutterWindow(); + + protected: + // Win32Window: + bool OnCreate() override; + void OnDestroy() override; + LRESULT MessageHandler(HWND window, UINT const message, WPARAM const wparam, + LPARAM const lparam) noexcept override; + + private: + // The project to run. + flutter::DartProject project_; + + // The Flutter instance hosted by this window. + std::unique_ptr flutter_controller_; +}; + +#endif // RUNNER_FLUTTER_WINDOW_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/main.cpp b/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/main.cpp new file mode 100644 index 000000000000..2b640e48b2b0 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/main.cpp @@ -0,0 +1,43 @@ +#include +#include +#include + +#include "flutter_window.h" +#include "utils.h" + +int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev, + _In_ wchar_t *command_line, _In_ int show_command) { + // Attach to console when present (e.g., 'flutter run') or create a + // new console when running with a debugger. + if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent()) { + CreateAndAttachConsole(); + } + + // Initialize COM, so that it is available for use in the library and/or + // plugins. + ::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED); + + flutter::DartProject project(L"data"); + + std::vector command_line_arguments = + GetCommandLineArguments(); + + project.set_dart_entrypoint_arguments(std::move(command_line_arguments)); + + FlutterWindow window(project); + Win32Window::Point origin(10, 10); + Win32Window::Size size(1280, 720); + if (!window.Create(L"firebase_core_example", origin, size)) { + return EXIT_FAILURE; + } + window.SetQuitOnClose(true); + + ::MSG msg; + while (::GetMessage(&msg, nullptr, 0, 0)) { + ::TranslateMessage(&msg); + ::DispatchMessage(&msg); + } + + ::CoUninitialize(); + return EXIT_SUCCESS; +} diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/resource.h b/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/resource.h new file mode 100644 index 000000000000..66a65d1e4a79 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/resource.h @@ -0,0 +1,16 @@ +//{{NO_DEPENDENCIES}} +// Microsoft Visual C++ generated include file. +// Used by Runner.rc +// +#define IDI_APP_ICON 101 + +// Next default values for new objects +// +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_NEXT_RESOURCE_VALUE 102 +#define _APS_NEXT_COMMAND_VALUE 40001 +#define _APS_NEXT_CONTROL_VALUE 1001 +#define _APS_NEXT_SYMED_VALUE 101 +#endif +#endif diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/resources/app_icon.ico b/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/resources/app_icon.ico new file mode 100644 index 0000000000000000000000000000000000000000..c04e20caf6370ebb9253ad831cc31de4a9c965f6 GIT binary patch literal 33772 zcmeHQc|26z|35SKE&G-*mXah&B~fFkXr)DEO&hIfqby^T&>|8^_Ub8Vp#`BLl3lbZ zvPO!8k!2X>cg~Elr=IVxo~J*a`+9wR=A83c-k-DFd(XM&UI1VKCqM@V;DDtJ09WB} zRaHKiW(GT00brH|0EeTeKVbpbGZg?nK6-j827q-+NFM34gXjqWxJ*a#{b_apGN<-L_m3#8Z26atkEn& ze87Bvv^6vVmM+p+cQ~{u%=NJF>#(d;8{7Q{^rWKWNtf14H}>#&y7$lqmY6xmZryI& z($uy?c5-+cPnt2%)R&(KIWEXww>Cnz{OUpT>W$CbO$h1= z#4BPMkFG1Y)x}Ui+WXr?Z!w!t_hjRq8qTaWpu}FH{MsHlU{>;08goVLm{V<&`itk~ zE_Ys=D(hjiy+5=?=$HGii=Y5)jMe9|wWoD_K07(}edAxh`~LBorOJ!Cf@f{_gNCC| z%{*04ViE!#>@hc1t5bb+NO>ncf@@Dv01K!NxH$3Eg1%)|wLyMDF8^d44lV!_Sr}iEWefOaL z8f?ud3Q%Sen39u|%00W<#!E=-RpGa+H8}{ulxVl4mwpjaU+%2pzmi{3HM)%8vb*~-M9rPUAfGCSos8GUXp02|o~0BTV2l#`>>aFV&_P$ejS;nGwSVP8 zMbOaG7<7eKD>c12VdGH;?2@q7535sa7MN*L@&!m?L`ASG%boY7(&L5imY#EQ$KrBB z4@_tfP5m50(T--qv1BJcD&aiH#b-QC>8#7Fx@3yXlonJI#aEIi=8&ChiVpc#N=5le zM*?rDIdcpawoc5kizv$GEjnveyrp3sY>+5_R5;>`>erS%JolimF=A^EIsAK zsPoVyyUHCgf0aYr&alx`<)eb6Be$m&`JYSuBu=p8j%QlNNp$-5C{b4#RubPb|CAIS zGE=9OFLP7?Hgc{?k45)84biT0k&-C6C%Q}aI~q<(7BL`C#<6HyxaR%!dFx7*o^laG z=!GBF^cwK$IA(sn9y6>60Rw{mYRYkp%$jH z*xQM~+bp)G$_RhtFPYx2HTsWk80+p(uqv9@I9)y{b$7NK53rYL$ezbmRjdXS?V}fj zWxX_feWoLFNm3MG7pMUuFPs$qrQWO9!l2B(SIuy2}S|lHNbHzoE+M2|Zxhjq9+Ws8c{*}x^VAib7SbxJ*Q3EnY5lgI9 z=U^f3IW6T=TWaVj+2N%K3<%Un;CF(wUp`TC&Y|ZjyFu6co^uqDDB#EP?DV5v_dw~E zIRK*BoY9y-G_ToU2V_XCX4nJ32~`czdjT!zwme zGgJ0nOk3U4@IE5JwtM}pwimLjk{ln^*4HMU%Fl4~n(cnsLB}Ja-jUM>xIB%aY;Nq8 z)Fp8dv1tkqKanv<68o@cN|%thj$+f;zGSO7H#b+eMAV8xH$hLggtt?O?;oYEgbq@= zV(u9bbd12^%;?nyk6&$GPI%|+<_mEpJGNfl*`!KV;VfmZWw{n{rnZ51?}FDh8we_L z8OI9nE31skDqJ5Oa_ybn7|5@ui>aC`s34p4ZEu6-s!%{uU45$Zd1=p$^^dZBh zu<*pDDPLW+c>iWO$&Z_*{VSQKg7=YEpS3PssPn1U!lSm6eZIho*{@&20e4Y_lRklKDTUCKI%o4Pc<|G^Xgu$J^Q|B87U;`c1zGwf^-zH*VQ^x+i^OUWE0yd z;{FJq)2w!%`x7yg@>uGFFf-XJl4H`YtUG%0slGKOlXV`q?RP>AEWg#x!b{0RicxGhS!3$p7 zij;{gm!_u@D4$Ox%>>bPtLJ> zwKtYz?T_DR1jN>DkkfGU^<#6sGz|~p*I{y`aZ>^Di#TC|Z!7j_O1=Wo8thuit?WxR zh9_S>kw^{V^|g}HRUF=dcq>?q(pHxw!8rx4dC6vbQVmIhmICF#zU!HkHpQ>9S%Uo( zMw{eC+`&pb=GZRou|3;Po1}m46H6NGd$t<2mQh}kaK-WFfmj_66_17BX0|j-E2fe3Jat}ijpc53 zJV$$;PC<5aW`{*^Z6e5##^`Ed#a0nwJDT#Qq~^e8^JTA=z^Kl>La|(UQ!bI@#ge{Dzz@61p-I)kc2?ZxFt^QQ}f%ldLjO*GPj(5)V9IyuUakJX=~GnTgZ4$5!3E=V#t`yOG4U z(gphZB6u2zsj=qNFLYShhg$}lNpO`P9xOSnO*$@@UdMYES*{jJVj|9z-}F^riksLK zbsU+4-{281P9e2UjY6tse^&a)WM1MFw;p#_dHhWI7p&U*9TR0zKdVuQed%6{otTsq z$f~S!;wg#Bd9kez=Br{m|66Wv z#g1xMup<0)H;c2ZO6su_ii&m8j&+jJz4iKnGZ&wxoQX|5a>v&_e#6WA!MB_4asTxLRGQCC5cI(em z%$ZfeqP>!*q5kU>a+BO&ln=4Jm>Ef(QE8o&RgLkk%2}4Tf}U%IFP&uS7}&|Q-)`5< z+e>;s#4cJ-z%&-^&!xsYx777Wt(wZY9(3(avmr|gRe4cD+a8&!LY`1^T?7x{E<=kdY9NYw>A;FtTvQ=Y&1M%lyZPl$ss1oY^Sl8we}n}Aob#6 zl4jERwnt9BlSoWb@3HxYgga(752Vu6Y)k4yk9u~Kw>cA5&LHcrvn1Y-HoIuFWg~}4 zEw4bR`mXZQIyOAzo)FYqg?$5W<;^+XX%Uz61{-L6@eP|lLH%|w?g=rFc;OvEW;^qh z&iYXGhVt(G-q<+_j}CTbPS_=K>RKN0&;dubh0NxJyDOHFF;<1k!{k#7b{|Qok9hac z;gHz}6>H6C6RnB`Tt#oaSrX0p-j-oRJ;_WvS-qS--P*8}V943RT6kou-G=A+7QPGQ z!ze^UGxtW3FC0$|(lY9^L!Lx^?Q8cny(rR`es5U;-xBhphF%_WNu|aO<+e9%6LuZq zt(0PoagJG<%hyuf;te}n+qIl_Ej;czWdc{LX^pS>77s9t*2b4s5dvP_!L^3cwlc)E!(!kGrg~FescVT zZCLeua3f4;d;Tk4iXzt}g}O@nlK3?_o91_~@UMIl?@77Qc$IAlLE95#Z=TES>2E%z zxUKpK{_HvGF;5%Q7n&vA?`{%8ohlYT_?(3A$cZSi)MvIJygXD}TS-3UwyUxGLGiJP znblO~G|*uA^|ac8E-w#}uBtg|s_~s&t>-g0X%zIZ@;o_wNMr_;{KDg^O=rg`fhDZu zFp(VKd1Edj%F zWHPl+)FGj%J1BO3bOHVfH^3d1F{)*PL&sRX`~(-Zy3&9UQX)Z;c51tvaI2E*E7!)q zcz|{vpK7bjxix(k&6=OEIBJC!9lTkUbgg?4-yE{9+pFS)$Ar@vrIf`D0Bnsed(Cf? zObt2CJ>BKOl>q8PyFO6w)+6Iz`LW%T5^R`U_NIW0r1dWv6OY=TVF?N=EfA(k(~7VBW(S;Tu5m4Lg8emDG-(mOSSs=M9Q&N8jc^Y4&9RqIsk(yO_P(mcCr}rCs%1MW1VBrn=0-oQN(Xj!k%iKV zb%ricBF3G4S1;+8lzg5PbZ|$Se$)I=PwiK=cDpHYdov2QO1_a-*dL4KUi|g&oh>(* zq$<`dQ^fat`+VW?m)?_KLn&mp^-@d=&7yGDt<=XwZZC=1scwxO2^RRI7n@g-1o8ps z)&+et_~)vr8aIF1VY1Qrq~Xe``KJrQSnAZ{CSq3yP;V*JC;mmCT6oRLSs7=GA?@6g zUooM}@tKtx(^|aKK8vbaHlUQqwE0}>j&~YlN3H#vKGm@u)xxS?n9XrOWUfCRa< z`20Fld2f&;gg7zpo{Adh+mqNntMc-D$N^yWZAZRI+u1T1zWHPxk{+?vcS1D>08>@6 zLhE@`gt1Y9mAK6Z4p|u(5I%EkfU7rKFSM=E4?VG9tI;a*@?6!ey{lzN5=Y-!$WFSe z&2dtO>^0@V4WRc#L&P%R(?@KfSblMS+N+?xUN$u3K4Ys%OmEh+tq}fnU}i>6YHM?< zlnL2gl~sF!j!Y4E;j3eIU-lfa`RsOL*Tt<%EFC0gPzoHfNWAfKFIKZN8}w~(Yi~=q z>=VNLO2|CjkxP}RkutxjV#4fWYR1KNrPYq5ha9Wl+u>ipsk*I(HS@iLnmGH9MFlTU zaFZ*KSR0px>o+pL7BbhB2EC1%PJ{67_ z#kY&#O4@P=OV#-79y_W>Gv2dxL*@G7%LksNSqgId9v;2xJ zrh8uR!F-eU$NMx@S*+sk=C~Dxr9Qn7TfWnTupuHKuQ$;gGiBcU>GF5sWx(~4IP3`f zWE;YFO*?jGwYh%C3X<>RKHC-DZ!*r;cIr}GLOno^3U4tFSSoJp%oHPiSa%nh=Zgn% z14+8v@ygy0>UgEN1bczD6wK45%M>psM)y^)IfG*>3ItX|TzV*0i%@>L(VN!zdKb8S?Qf7BhjNpziA zR}?={-eu>9JDcl*R=OP9B8N$IcCETXah9SUDhr{yrld{G;PnCWRsPD7!eOOFBTWUQ=LrA_~)mFf&!zJX!Oc-_=kT<}m|K52 z)M=G#;p;Rdb@~h5D{q^K;^fX-m5V}L%!wVC2iZ1uu401Ll}#rocTeK|7FAeBRhNdQ zCc2d^aQnQp=MpOmak60N$OgS}a;p(l9CL`o4r(e-nN}mQ?M&isv-P&d$!8|1D1I(3-z!wi zTgoo)*Mv`gC?~bm?S|@}I|m-E2yqPEvYybiD5azInexpK8?9q*$9Yy9-t%5jU8~ym zgZDx>!@ujQ=|HJnwp^wv-FdD{RtzO9SnyfB{mH_(c!jHL*$>0o-(h(eqe*ZwF6Lvu z{7rkk%PEqaA>o+f{H02tzZ@TWy&su?VNw43! z-X+rN`6llvpUms3ZiSt)JMeztB~>9{J8SPmYs&qohxdYFi!ra8KR$35Zp9oR)eFC4 zE;P31#3V)n`w$fZ|4X-|%MX`xZDM~gJyl2W;O$H25*=+1S#%|53>|LyH za@yh+;325%Gq3;J&a)?%7X%t@WXcWL*BaaR*7UEZad4I8iDt7^R_Fd`XeUo256;sAo2F!HcIQKk;h})QxEsPE5BcKc7WyerTchgKmrfRX z!x#H_%cL#B9TWAqkA4I$R^8{%do3Y*&(;WFmJ zU7Dih{t1<{($VtJRl9|&EB?|cJ)xse!;}>6mSO$o5XIx@V|AA8ZcoD88ZM?C*;{|f zZVmf94_l1OmaICt`2sTyG!$^UeTHx9YuUP!omj(r|7zpm5475|yXI=rR>>fteLI+| z)MoiGho0oEt=*J(;?VY0QzwCqw@cVm?d7Y!z0A@u#H?sCJ*ecvyhj& z-F77lO;SH^dmf?L>3i>?Z*U}Em4ZYV_CjgfvzYsRZ+1B!Uo6H6mbS<-FFL`ytqvb& zE7+)2ahv-~dz(Hs+f})z{*4|{)b=2!RZK;PWwOnO=hG7xG`JU5>bAvUbdYd_CjvtHBHgtGdlO+s^9ca^Bv3`t@VRX2_AD$Ckg36OcQRF zXD6QtGfHdw*hx~V(MV-;;ZZF#dJ-piEF+s27z4X1qi5$!o~xBnvf=uopcn7ftfsZc zy@(PuOk`4GL_n(H9(E2)VUjqRCk9kR?w)v@xO6Jm_Mx})&WGEl=GS0#)0FAq^J*o! zAClhvoTsNP*-b~rN{8Yym3g{01}Ep^^Omf=SKqvN?{Q*C4HNNAcrowIa^mf+3PRy! z*_G-|3i8a;+q;iP@~Of_$(vtFkB8yOyWt2*K)vAn9El>=D;A$CEx6b*XF@4y_6M+2 zpeW`RHoI_p(B{%(&jTHI->hmNmZjHUj<@;7w0mx3&koy!2$@cfX{sN19Y}euYJFn& z1?)+?HCkD0MRI$~uB2UWri})0bru_B;klFdwsLc!ne4YUE;t41JqfG# zZJq6%vbsdx!wYeE<~?>o4V`A3?lN%MnKQ`z=uUivQN^vzJ|C;sdQ37Qn?;lpzg})y z)_2~rUdH}zNwX;Tp0tJ78+&I=IwOQ-fl30R79O8@?Ub8IIA(6I`yHn%lARVL`%b8+ z4$8D-|MZZWxc_)vu6@VZN!HsI$*2NOV&uMxBNzIbRgy%ob_ zhwEH{J9r$!dEix9XM7n&c{S(h>nGm?el;gaX0@|QnzFD@bne`el^CO$yXC?BDJ|Qg z+y$GRoR`?ST1z^e*>;!IS@5Ovb7*RlN>BV_UC!7E_F;N#ky%1J{+iixp(dUJj93aK zzHNN>R-oN7>kykHClPnoPTIj7zc6KM(Pnlb(|s??)SMb)4!sMHU^-ntJwY5Big7xv zb1Ew`Xj;|D2kzGja*C$eS44(d&RMU~c_Y14V9_TLTz0J#uHlsx`S6{nhsA0dWZ#cG zJ?`fO50E>*X4TQLv#nl%3GOk*UkAgt=IY+u0LNXqeln3Z zv$~&Li`ZJOKkFuS)dJRA>)b_Da%Q~axwA_8zNK{BH{#}#m}zGcuckz}riDE-z_Ms> zR8-EqAMcfyGJCtvTpaUVQtajhUS%c@Yj}&6Zz;-M7MZzqv3kA7{SuW$oW#=0az2wQ zg-WG@Vb4|D`pl~Il54N7Hmsauc_ne-a!o5#j3WaBBh@Wuefb!QJIOn5;d)%A#s+5% zuD$H=VNux9bE-}1&bcYGZ+>1Fo;3Z@e&zX^n!?JK*adSbONm$XW9z;Q^L>9U!}Toj2WdafJ%oL#h|yWWwyAGxzfrAWdDTtaKl zK4`5tDpPg5>z$MNv=X0LZ0d6l%D{(D8oT@+w0?ce$DZ6pv>{1&Ok67Ix1 zH}3=IEhPJEhItCC8E=`T`N5(k?G=B4+xzZ?<4!~ ze~z6Wk9!CHTI(0rLJ4{JU?E-puc;xusR?>G?;4vt;q~iI9=kDL=z0Rr%O$vU`30X$ zDZRFyZ`(omOy@u|i6h;wtJlP;+}$|Ak|k2dea7n?U1*$T!sXqqOjq^NxLPMmk~&qI zYg0W?yK8T(6+Ea+$YyspKK?kP$+B`~t3^Pib_`!6xCs32!i@pqXfFV6PmBIR<-QW= zN8L{pt0Vap0x`Gzn#E@zh@H)0FfVfA_Iu4fjYZ+umO1LXIbVc$pY+E234u)ttcrl$ z>s92z4vT%n6cMb>=XT6;l0+9e(|CZG)$@C7t7Z7Ez@a)h)!hyuV&B5K%%)P5?Lk|C zZZSVzdXp{@OXSP0hoU-gF8s8Um(#xzjP2Vem zec#-^JqTa&Y#QJ>-FBxd7tf`XB6e^JPUgagB8iBSEps;92KG`!#mvVcPQ5yNC-GEG zTiHEDYfH+0O15}r^+ z#jxj=@x8iNHWALe!P3R67TwmhItn**0JwnzSV2O&KE8KcT+0hWH^OPD1pwiuyx=b@ zNf5Jh0{9X)8;~Es)$t@%(3!OnbY+`@?i{mGX7Yy}8T_*0a6g;kaFPq;*=px5EhO{Cp%1kI<0?*|h8v!6WnO3cCJRF2-CRrU3JiLJnj@6;L)!0kWYAc_}F{2P))3HmCrz zQ&N&gE70;`!6*eJ4^1IR{f6j4(-l&X!tjHxkbHA^Zhrnhr9g{exN|xrS`5Pq=#Xf& zG%P=#ra-TyVFfgW%cZo5OSIwFL9WtXAlFOa+ubmI5t*3=g#Y zF%;70p5;{ZeFL}&}yOY1N1*Q;*<(kTB!7vM$QokF)yr2FlIU@$Ph58$Bz z0J?xQG=MlS4L6jA22eS42g|9*9pX@$#*sUeM(z+t?hr@r5J&D1rx}2pW&m*_`VDCW zUYY@v-;bAO0HqoAgbbiGGC<=ryf96}3pouhy3XJrX+!!u*O_>Si38V{uJmQ&USptX zKp#l(?>%^7;2%h(q@YWS#9;a!JhKlkR#Vd)ERILlgu!Hr@jA@V;sk4BJ-H#p*4EqC zDGjC*tl=@3Oi6)Bn^QwFpul18fpkbpg0+peH$xyPBqb%`$OUhPKyWb32o7clB*9Z< zN=i~NLjavrLtwgJ01bufP+>p-jR2I95|TpmKpQL2!oV>g(4RvS2pK4*ou%m(h6r3A zX#s&`9LU1ZG&;{CkOK!4fLDTnBys`M!vuz>Q&9OZ0hGQl!~!jSDg|~s*w52opC{sB ze|Cf2luD(*G13LcOAGA!s2FjSK8&IE5#W%J25w!vM0^VyQM!t)inj&RTiJ!wXzFgz z3^IqzB7I0L$llljsGq})thBy9UOyjtFO_*hYM_sgcMk>44jeH0V1FDyELc{S1F-;A zS;T^k^~4biG&V*Irq}O;e}j$$+E_#G?HKIn05iP3j|87TkGK~SqG!-KBg5+mN(aLm z8ybhIM`%C19UX$H$KY6JgXbY$0AT%rEpHC;u`rQ$Y=rxUdsc5*Kvc8jaYaO$^)cI6){P6K0r)I6DY4Wr4&B zLQUBraey#0HV|&c4v7PVo3n$zHj99(TZO^3?Ly%C4nYvJTL9eLBLHsM3WKKD>5!B` zQ=BsR3aR6PD(Fa>327E2HAu5TM~Wusc!)>~(gM)+3~m;92Jd;FnSib=M5d6;;5{%R zb4V7DEJ0V!CP-F*oU?gkc>ksUtAYP&V4ND5J>J2^jt*vcFflQWCrB&fLdT%O59PVJ zhid#toR=FNgD!q3&r8#wEBr`!wzvQu5zX?Q>nlSJ4i@WC*CN*-xU66F^V5crWevQ9gsq$I@z1o(a=k7LL~ z7m_~`o;_Ozha1$8Q}{WBehvAlO4EL60y5}8GDrZ< zXh&F}71JbW2A~8KfEWj&UWV#4+Z4p`b{uAj4&WC zha`}X@3~+Iz^WRlOHU&KngK>#j}+_o@LdBC1H-`gT+krWX3-;!)6?{FBp~%20a}FL zFP9%Emqcwa#(`=G>BBZ0qZDQhmZKJg_g8<=bBFKWr!dyg(YkpE+|R*SGpDVU!+VlU zFC54^DLv}`qa%49T>nNiA9Q7Ips#!Xx90tCU2gvK`(F+GPcL=J^>No{)~we#o@&mUb6c$ zCc*<|NJBk-#+{j9xkQ&ujB zI~`#kN~7W!f*-}wkG~Ld!JqZ@tK}eeSnsS5J1fMFXm|`LJx&}5`@dK3W^7#Wnm+_P zBZkp&j1fa2Y=eIjJ0}gh85jt43kaIXXv?xmo@eHrka!Z|vQv12HN#+!I5E z`(fbuW>gFiJL|uXJ!vKt#z3e3HlVdboH7;e#i3(2<)Fg-I@BR!qY#eof3MFZ&*Y@l zI|KJf&ge@p2Dq09Vu$$Qxb7!}{m-iRk@!)%KL)txi3;~Z4Pb}u@GsW;ELiWeG9V51 znX#}B&4Y2E7-H=OpNE@q{%hFLxwIpBF2t{vPREa8_{linXT;#1vMRWjOzLOP$-hf( z>=?$0;~~PnkqY;~K{EM6Vo-T(0K{A0}VUGmu*hR z{tw3hvBN%N3G3Yw`X5Te+F{J`(3w1s3-+1EbnFQKcrgrX1Jqvs@ADGe%M0s$EbK$$ zK)=y=upBc6SjGYAACCcI=Y*6Fi8_jgwZlLxD26fnQfJmb8^gHRN5(TemhX@0e=vr> zg`W}6U>x6VhoA3DqsGGD9uL1DhB3!OXO=k}59TqD@(0Nb{)Ut_luTioK_>7wjc!5C zIr@w}b`Fez3)0wQfKl&bae7;PcTA7%?f2xucM0G)wt_KO!Ewx>F~;=BI0j=Fb4>pp zv}0R^xM4eti~+^+gE$6b81p(kwzuDti(-K9bc|?+pJEl@H+jSYuxZQV8rl8 zjp@M{#%qItIUFN~KcO9Hed*`$5A-2~pAo~K&<-Q+`9`$CK>rzqAI4w~$F%vs9s{~x zg4BP%Gy*@m?;D6=SRX?888Q6peF@_4Z->8wAH~Cn!R$|Hhq2cIzFYqT_+cDourHbY z0qroxJnrZ4Gh+Ay+F`_c%+KRT>y3qw{)89?=hJ@=KO=@ep)aBJ$c!JHfBMJpsP*3G za7|)VJJ8B;4?n{~ldJF7%jmb`-ftIvNd~ekoufG(`K(3=LNc;HBY& z(lp#q8XAD#cIf}k49zX_i`*fO+#!zKA&%T3j@%)R+#yag067CU%yUEe47>wzGU8^` z1EXFT^@I!{J!F8!X?S6ph8J=gUi5tl93*W>7}_uR<2N2~e}FaG?}KPyugQ=-OGEZs z!GBoyYY+H*ANn4?Z)X4l+7H%`17i5~zRlRIX?t)6_eu=g2Q`3WBhxSUeea+M-S?RL zX9oBGKn%a!H+*hx4d2(I!gsi+@SQK%<{X22M~2tMulJoa)0*+z9=-YO+;DFEm5eE1U9b^B(Z}2^9!Qk`!A$wUE z7$Ar5?NRg2&G!AZqnmE64eh^Anss3i!{}%6@Et+4rr!=}!SBF8eZ2*J3ujCWbl;3; z48H~goPSv(8X61fKKdpP!Z7$88NL^Z?j`!^*I?-P4X^pMxyWz~@$(UeAcTSDd(`vO z{~rc;9|GfMJcApU3k}22a!&)k4{CU!e_ny^Y3cO;tOvOMKEyWz!vG(Kp*;hB?d|R3`2X~=5a6#^o5@qn?J-bI8Ppip{-yG z!k|VcGsq!jF~}7DMr49Wap-s&>o=U^T0!Lcy}!(bhtYsPQy z4|EJe{12QL#=c(suQ89Mhw9<`bui%nx7Nep`C&*M3~vMEACmcRYYRGtANq$F%zh&V zc)cEVeHz*Z1N)L7k-(k3np#{GcDh2Q@ya0YHl*n7fl*ZPAsbU-a94MYYtA#&!c`xGIaV;yzsmrjfieTEtqB_WgZp2*NplHx=$O{M~2#i_vJ{ps-NgK zQsxKK_CBM2PP_je+Xft`(vYfXXgIUr{=PA=7a8`2EHk)Ym2QKIforz# tySWtj{oF3N9@_;i*Fv5S)9x^z=nlWP>jpp-9)52ZmLVA=i*%6g{{fxOO~wEK literal 0 HcmV?d00001 diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/runner.exe.manifest b/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/runner.exe.manifest new file mode 100644 index 000000000000..a42ea7687cb6 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/runner.exe.manifest @@ -0,0 +1,20 @@ + + + + + PerMonitorV2 + + + + + + + + + + + + + + + diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/utils.cpp b/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/utils.cpp new file mode 100644 index 000000000000..f5bf9fa0f536 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/utils.cpp @@ -0,0 +1,64 @@ +#include "utils.h" + +#include +#include +#include +#include + +#include + +void CreateAndAttachConsole() { + if (::AllocConsole()) { + FILE *unused; + if (freopen_s(&unused, "CONOUT$", "w", stdout)) { + _dup2(_fileno(stdout), 1); + } + if (freopen_s(&unused, "CONOUT$", "w", stderr)) { + _dup2(_fileno(stdout), 2); + } + std::ios::sync_with_stdio(); + FlutterDesktopResyncOutputStreams(); + } +} + +std::vector GetCommandLineArguments() { + // Convert the UTF-16 command line arguments to UTF-8 for the Engine to use. + int argc; + wchar_t** argv = ::CommandLineToArgvW(::GetCommandLineW(), &argc); + if (argv == nullptr) { + return std::vector(); + } + + std::vector command_line_arguments; + + // Skip the first argument as it's the binary name. + for (int i = 1; i < argc; i++) { + command_line_arguments.push_back(Utf8FromUtf16(argv[i])); + } + + ::LocalFree(argv); + + return command_line_arguments; +} + +std::string Utf8FromUtf16(const wchar_t* utf16_string) { + if (utf16_string == nullptr) { + return std::string(); + } + int target_length = ::WideCharToMultiByte( + CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, + -1, nullptr, 0, nullptr, nullptr); + std::string utf8_string; + if (target_length == 0 || target_length > utf8_string.max_size()) { + return utf8_string; + } + utf8_string.resize(target_length); + int converted_length = ::WideCharToMultiByte( + CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, + -1, utf8_string.data(), + target_length, nullptr, nullptr); + if (converted_length == 0) { + return std::string(); + } + return utf8_string; +} diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/utils.h b/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/utils.h new file mode 100644 index 000000000000..3879d5475579 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/utils.h @@ -0,0 +1,19 @@ +#ifndef RUNNER_UTILS_H_ +#define RUNNER_UTILS_H_ + +#include +#include + +// Creates a console for the process, and redirects stdout and stderr to +// it for both the runner and the Flutter library. +void CreateAndAttachConsole(); + +// Takes a null-terminated wchar_t* encoded in UTF-16 and returns a std::string +// encoded in UTF-8. Returns an empty std::string on failure. +std::string Utf8FromUtf16(const wchar_t* utf16_string); + +// Gets the command line arguments passed in as a std::vector, +// encoded in UTF-8. Returns an empty std::vector on failure. +std::vector GetCommandLineArguments(); + +#endif // RUNNER_UTILS_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/win32_window.cpp b/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/win32_window.cpp new file mode 100644 index 000000000000..041a38554745 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/win32_window.cpp @@ -0,0 +1,288 @@ +#include "win32_window.h" + +#include +#include + +#include "resource.h" + +namespace { + +/// Window attribute that enables dark mode window decorations. +/// +/// Redefined in case the developer's machine has a Windows SDK older than +/// version 10.0.22000.0. +/// See: https://docs.microsoft.com/windows/win32/api/dwmapi/ne-dwmapi-dwmwindowattribute +#ifndef DWMWA_USE_IMMERSIVE_DARK_MODE +#define DWMWA_USE_IMMERSIVE_DARK_MODE 20 +#endif + +constexpr const wchar_t kWindowClassName[] = L"FLUTTER_RUNNER_WIN32_WINDOW"; + +/// Registry key for app theme preference. +/// +/// A value of 0 indicates apps should use dark mode. A non-zero or missing +/// value indicates apps should use light mode. +constexpr const wchar_t kGetPreferredBrightnessRegKey[] = + L"Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize"; +constexpr const wchar_t kGetPreferredBrightnessRegValue[] = L"AppsUseLightTheme"; + +// The number of Win32Window objects that currently exist. +static int g_active_window_count = 0; + +using EnableNonClientDpiScaling = BOOL __stdcall(HWND hwnd); + +// Scale helper to convert logical scaler values to physical using passed in +// scale factor +int Scale(int source, double scale_factor) { + return static_cast(source * scale_factor); +} + +// Dynamically loads the |EnableNonClientDpiScaling| from the User32 module. +// This API is only needed for PerMonitor V1 awareness mode. +void EnableFullDpiSupportIfAvailable(HWND hwnd) { + HMODULE user32_module = LoadLibraryA("User32.dll"); + if (!user32_module) { + return; + } + auto enable_non_client_dpi_scaling = + reinterpret_cast( + GetProcAddress(user32_module, "EnableNonClientDpiScaling")); + if (enable_non_client_dpi_scaling != nullptr) { + enable_non_client_dpi_scaling(hwnd); + } + FreeLibrary(user32_module); +} + +} // namespace + +// Manages the Win32Window's window class registration. +class WindowClassRegistrar { + public: + ~WindowClassRegistrar() = default; + + // Returns the singleton registar instance. + static WindowClassRegistrar* GetInstance() { + if (!instance_) { + instance_ = new WindowClassRegistrar(); + } + return instance_; + } + + // Returns the name of the window class, registering the class if it hasn't + // previously been registered. + const wchar_t* GetWindowClass(); + + // Unregisters the window class. Should only be called if there are no + // instances of the window. + void UnregisterWindowClass(); + + private: + WindowClassRegistrar() = default; + + static WindowClassRegistrar* instance_; + + bool class_registered_ = false; +}; + +WindowClassRegistrar* WindowClassRegistrar::instance_ = nullptr; + +const wchar_t* WindowClassRegistrar::GetWindowClass() { + if (!class_registered_) { + WNDCLASS window_class{}; + window_class.hCursor = LoadCursor(nullptr, IDC_ARROW); + window_class.lpszClassName = kWindowClassName; + window_class.style = CS_HREDRAW | CS_VREDRAW; + window_class.cbClsExtra = 0; + window_class.cbWndExtra = 0; + window_class.hInstance = GetModuleHandle(nullptr); + window_class.hIcon = + LoadIcon(window_class.hInstance, MAKEINTRESOURCE(IDI_APP_ICON)); + window_class.hbrBackground = 0; + window_class.lpszMenuName = nullptr; + window_class.lpfnWndProc = Win32Window::WndProc; + RegisterClass(&window_class); + class_registered_ = true; + } + return kWindowClassName; +} + +void WindowClassRegistrar::UnregisterWindowClass() { + UnregisterClass(kWindowClassName, nullptr); + class_registered_ = false; +} + +Win32Window::Win32Window() { + ++g_active_window_count; +} + +Win32Window::~Win32Window() { + --g_active_window_count; + Destroy(); +} + +bool Win32Window::Create(const std::wstring& title, + const Point& origin, + const Size& size) { + Destroy(); + + const wchar_t* window_class = + WindowClassRegistrar::GetInstance()->GetWindowClass(); + + const POINT target_point = {static_cast(origin.x), + static_cast(origin.y)}; + HMONITOR monitor = MonitorFromPoint(target_point, MONITOR_DEFAULTTONEAREST); + UINT dpi = FlutterDesktopGetDpiForMonitor(monitor); + double scale_factor = dpi / 96.0; + + HWND window = CreateWindow( + window_class, title.c_str(), WS_OVERLAPPEDWINDOW, + Scale(origin.x, scale_factor), Scale(origin.y, scale_factor), + Scale(size.width, scale_factor), Scale(size.height, scale_factor), + nullptr, nullptr, GetModuleHandle(nullptr), this); + + if (!window) { + return false; + } + + UpdateTheme(window); + + return OnCreate(); +} + +bool Win32Window::Show() { + return ShowWindow(window_handle_, SW_SHOWNORMAL); +} + +// static +LRESULT CALLBACK Win32Window::WndProc(HWND const window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + if (message == WM_NCCREATE) { + auto window_struct = reinterpret_cast(lparam); + SetWindowLongPtr(window, GWLP_USERDATA, + reinterpret_cast(window_struct->lpCreateParams)); + + auto that = static_cast(window_struct->lpCreateParams); + EnableFullDpiSupportIfAvailable(window); + that->window_handle_ = window; + } else if (Win32Window* that = GetThisFromHandle(window)) { + return that->MessageHandler(window, message, wparam, lparam); + } + + return DefWindowProc(window, message, wparam, lparam); +} + +LRESULT +Win32Window::MessageHandler(HWND hwnd, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + switch (message) { + case WM_DESTROY: + window_handle_ = nullptr; + Destroy(); + if (quit_on_close_) { + PostQuitMessage(0); + } + return 0; + + case WM_DPICHANGED: { + auto newRectSize = reinterpret_cast(lparam); + LONG newWidth = newRectSize->right - newRectSize->left; + LONG newHeight = newRectSize->bottom - newRectSize->top; + + SetWindowPos(hwnd, nullptr, newRectSize->left, newRectSize->top, newWidth, + newHeight, SWP_NOZORDER | SWP_NOACTIVATE); + + return 0; + } + case WM_SIZE: { + RECT rect = GetClientArea(); + if (child_content_ != nullptr) { + // Size and position the child window. + MoveWindow(child_content_, rect.left, rect.top, rect.right - rect.left, + rect.bottom - rect.top, TRUE); + } + return 0; + } + + case WM_ACTIVATE: + if (child_content_ != nullptr) { + SetFocus(child_content_); + } + return 0; + + case WM_DWMCOLORIZATIONCOLORCHANGED: + UpdateTheme(hwnd); + return 0; + } + + return DefWindowProc(window_handle_, message, wparam, lparam); +} + +void Win32Window::Destroy() { + OnDestroy(); + + if (window_handle_) { + DestroyWindow(window_handle_); + window_handle_ = nullptr; + } + if (g_active_window_count == 0) { + WindowClassRegistrar::GetInstance()->UnregisterWindowClass(); + } +} + +Win32Window* Win32Window::GetThisFromHandle(HWND const window) noexcept { + return reinterpret_cast( + GetWindowLongPtr(window, GWLP_USERDATA)); +} + +void Win32Window::SetChildContent(HWND content) { + child_content_ = content; + SetParent(content, window_handle_); + RECT frame = GetClientArea(); + + MoveWindow(content, frame.left, frame.top, frame.right - frame.left, + frame.bottom - frame.top, true); + + SetFocus(child_content_); +} + +RECT Win32Window::GetClientArea() { + RECT frame; + GetClientRect(window_handle_, &frame); + return frame; +} + +HWND Win32Window::GetHandle() { + return window_handle_; +} + +void Win32Window::SetQuitOnClose(bool quit_on_close) { + quit_on_close_ = quit_on_close; +} + +bool Win32Window::OnCreate() { + // No-op; provided for subclasses. + return true; +} + +void Win32Window::OnDestroy() { + // No-op; provided for subclasses. +} + +void Win32Window::UpdateTheme(HWND const window) { + DWORD light_mode; + DWORD light_mode_size = sizeof(light_mode); + LSTATUS result = RegGetValue(HKEY_CURRENT_USER, kGetPreferredBrightnessRegKey, + kGetPreferredBrightnessRegValue, + RRF_RT_REG_DWORD, nullptr, &light_mode, + &light_mode_size); + + if (result == ERROR_SUCCESS) { + BOOL enable_dark_mode = light_mode == 0; + DwmSetWindowAttribute(window, DWMWA_USE_IMMERSIVE_DARK_MODE, + &enable_dark_mode, sizeof(enable_dark_mode)); + } +} diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/win32_window.h b/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/win32_window.h new file mode 100644 index 000000000000..c86632d8a6b9 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/win32_window.h @@ -0,0 +1,102 @@ +#ifndef RUNNER_WIN32_WINDOW_H_ +#define RUNNER_WIN32_WINDOW_H_ + +#include + +#include +#include +#include + +// A class abstraction for a high DPI-aware Win32 Window. Intended to be +// inherited from by classes that wish to specialize with custom +// rendering and input handling +class Win32Window { + public: + struct Point { + unsigned int x; + unsigned int y; + Point(unsigned int x, unsigned int y) : x(x), y(y) {} + }; + + struct Size { + unsigned int width; + unsigned int height; + Size(unsigned int width, unsigned int height) + : width(width), height(height) {} + }; + + Win32Window(); + virtual ~Win32Window(); + + // Creates a win32 window with |title| that is positioned and sized using + // |origin| and |size|. New windows are created on the default monitor. Window + // sizes are specified to the OS in physical pixels, hence to ensure a + // consistent size this function will scale the inputted width and height as + // as appropriate for the default monitor. The window is invisible until + // |Show| is called. Returns true if the window was created successfully. + bool Create(const std::wstring& title, const Point& origin, const Size& size); + + // Show the current window. Returns true if the window was successfully shown. + bool Show(); + + // Release OS resources associated with window. + void Destroy(); + + // Inserts |content| into the window tree. + void SetChildContent(HWND content); + + // Returns the backing Window handle to enable clients to set icon and other + // window properties. Returns nullptr if the window has been destroyed. + HWND GetHandle(); + + // If true, closing this window will quit the application. + void SetQuitOnClose(bool quit_on_close); + + // Return a RECT representing the bounds of the current client area. + RECT GetClientArea(); + + protected: + // Processes and route salient window messages for mouse handling, + // size change and DPI. Delegates handling of these to member overloads that + // inheriting classes can handle. + virtual LRESULT MessageHandler(HWND window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept; + + // Called when CreateAndShow is called, allowing subclass window-related + // setup. Subclasses should return false if setup fails. + virtual bool OnCreate(); + + // Called when Destroy is called. + virtual void OnDestroy(); + + private: + friend class WindowClassRegistrar; + + // OS callback called by message pump. Handles the WM_NCCREATE message which + // is passed when the non-client area is being created and enables automatic + // non-client DPI scaling so that the non-client area automatically + // responsponds to changes in DPI. All other messages are handled by + // MessageHandler. + static LRESULT CALLBACK WndProc(HWND const window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept; + + // Retrieves a class instance pointer for |window| + static Win32Window* GetThisFromHandle(HWND const window) noexcept; + + // Update the window frame's theme to match the system theme. + static void UpdateTheme(HWND const window); + + bool quit_on_close_ = false; + + // window handle for top level window. + HWND window_handle_ = nullptr; + + // window handle for hosted content. + HWND child_content_ = nullptr; +}; + +#endif // RUNNER_WIN32_WINDOW_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/pubspec.yaml b/packages/firebase_core/firebase_core/firebase_core/pubspec.yaml index ce38f84906e8..c942173c517b 100644 --- a/packages/firebase_core/firebase_core/firebase_core/pubspec.yaml +++ b/packages/firebase_core/firebase_core/firebase_core/pubspec.yaml @@ -24,6 +24,8 @@ flutter: platforms: linux: pluginClass: FirebaseCorePlugin + windows: + pluginClass: FirebaseCorePluginCApi ffigen: output: 'generated_bindings.dart' diff --git a/packages/firebase_core/firebase_core/firebase_core/windows/.gitignore b/packages/firebase_core/firebase_core/firebase_core/windows/.gitignore new file mode 100644 index 000000000000..b3eb2be169a5 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/windows/.gitignore @@ -0,0 +1,17 @@ +flutter/ + +# Visual Studio user-specific files. +*.suo +*.user +*.userosscache +*.sln.docstates + +# Visual Studio build-related files. +x64/ +x86/ + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!*.[Cc]ache/ diff --git a/packages/firebase_core/firebase_core/firebase_core/windows/CMakeLists.txt b/packages/firebase_core/firebase_core/firebase_core/windows/CMakeLists.txt new file mode 100644 index 000000000000..2f368229d6e9 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/windows/CMakeLists.txt @@ -0,0 +1,53 @@ +# The Flutter tooling requires that developers have a version of Visual Studio +# installed that includes CMake 3.14 or later. You should not increase this +# version, as doing so will cause the plugin to fail to compile for some +# customers of the plugin. +cmake_minimum_required(VERSION 3.14) + +# Project-level configuration. +set(PROJECT_NAME "firebase_core") +project(${PROJECT_NAME} LANGUAGES CXX) + +# This value is used when generating builds using this plugin, so it must +# not be changed +set(PLUGIN_NAME "firebase_core_plugin") + +# Any new source files that you add to the plugin should be added here. +list(APPEND PLUGIN_SOURCES + "firebase_core_plugin.cpp" + "firebase_core_plugin.h" +) + +# Define the plugin library target. Its name must not be changed (see comment +# on PLUGIN_NAME above). +add_library(${PLUGIN_NAME} SHARED + "include/firebase_core/firebase_core_plugin_c_api.h" + "firebase_core_plugin_c_api.cpp" + ${PLUGIN_SOURCES} +) + +# Apply a standard set of build settings that are configured in the +# application-level CMakeLists.txt. This can be removed for plugins that want +# full control over build settings. +apply_standard_settings(${PLUGIN_NAME}) + +# Symbols are hidden by default to reduce the chance of accidental conflicts +# between plugins. This should not be removed; any symbols that should be +# exported should be explicitly exported with the FLUTTER_PLUGIN_EXPORT macro. +set_target_properties(${PLUGIN_NAME} PROPERTIES + CXX_VISIBILITY_PRESET hidden) +target_compile_definitions(${PLUGIN_NAME} PRIVATE FLUTTER_PLUGIN_IMPL) + +# Source include directories and library dependencies. Add any plugin-specific +# dependencies here. +target_include_directories(${PLUGIN_NAME} INTERFACE + "${CMAKE_CURRENT_SOURCE_DIR}/include") +target_link_libraries(${PLUGIN_NAME} PRIVATE flutter flutter_wrapper_plugin) + +# List of absolute paths to libraries that should be bundled with the plugin. +# This list could contain prebuilt libraries, or libraries created by an +# external build triggered from this build file. +set(firebase_core_bundled_libraries + "" + PARENT_SCOPE +) diff --git a/packages/firebase_core/firebase_core/firebase_core/windows/firebase_core_plugin.cpp b/packages/firebase_core/firebase_core/firebase_core/windows/firebase_core_plugin.cpp new file mode 100644 index 000000000000..e92cfe868845 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/windows/firebase_core_plugin.cpp @@ -0,0 +1,59 @@ +#include "firebase_core_plugin.h" + +// This must be included before many other Windows headers. +#include + +// For getPlatformVersion; remove unless needed for your plugin implementation. +#include + +#include +#include +#include + +#include +#include + +namespace firebase_core { + +// static +void FirebaseCorePlugin::RegisterWithRegistrar( + flutter::PluginRegistrarWindows *registrar) { + auto channel = + std::make_unique>( + registrar->messenger(), "firebase_core", + &flutter::StandardMethodCodec::GetInstance()); + + auto plugin = std::make_unique(); + + channel->SetMethodCallHandler( + [plugin_pointer = plugin.get()](const auto &call, auto result) { + plugin_pointer->HandleMethodCall(call, std::move(result)); + }); + + registrar->AddPlugin(std::move(plugin)); +} + +FirebaseCorePlugin::FirebaseCorePlugin() {} + +FirebaseCorePlugin::~FirebaseCorePlugin() {} + +void FirebaseCorePlugin::HandleMethodCall( + const flutter::MethodCall &method_call, + std::unique_ptr> result) { + if (method_call.method_name().compare("getPlatformVersion") == 0) { + std::ostringstream version_stream; + version_stream << "Windows "; + if (IsWindows10OrGreater()) { + version_stream << "10+"; + } else if (IsWindows8OrGreater()) { + version_stream << "8"; + } else if (IsWindows7OrGreater()) { + version_stream << "7"; + } + result->Success(flutter::EncodableValue(version_stream.str())); + } else { + result->NotImplemented(); + } +} + +} // namespace firebase_core diff --git a/packages/firebase_core/firebase_core/firebase_core/windows/firebase_core_plugin.h b/packages/firebase_core/firebase_core/firebase_core/windows/firebase_core_plugin.h new file mode 100644 index 000000000000..fe99490af2c2 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/windows/firebase_core_plugin.h @@ -0,0 +1,32 @@ +#ifndef FLUTTER_PLUGIN_FIREBASE_CORE_PLUGIN_H_ +#define FLUTTER_PLUGIN_FIREBASE_CORE_PLUGIN_H_ + +#include +#include + +#include + +namespace firebase_core { + +class FirebaseCorePlugin : public flutter::Plugin { + public: + static void RegisterWithRegistrar(flutter::PluginRegistrarWindows *registrar); + + FirebaseCorePlugin(); + + virtual ~FirebaseCorePlugin(); + + // Disallow copy and assign. + FirebaseCorePlugin(const FirebaseCorePlugin&) = delete; + FirebaseCorePlugin& operator=(const FirebaseCorePlugin&) = delete; + + private: + // Called when a method is called on this plugin's channel from Dart. + void HandleMethodCall( + const flutter::MethodCall &method_call, + std::unique_ptr> result); +}; + +} // namespace firebase_core + +#endif // FLUTTER_PLUGIN_FIREBASE_CORE_PLUGIN_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/windows/firebase_core_plugin_c_api.cpp b/packages/firebase_core/firebase_core/firebase_core/windows/firebase_core_plugin_c_api.cpp new file mode 100644 index 000000000000..f0ca223fcf26 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/windows/firebase_core_plugin_c_api.cpp @@ -0,0 +1,12 @@ +#include "include/firebase_core/firebase_core_plugin_c_api.h" + +#include + +#include "firebase_core_plugin.h" + +void FirebaseCorePluginCApiRegisterWithRegistrar( + FlutterDesktopPluginRegistrarRef registrar) { + firebase_core::FirebaseCorePlugin::RegisterWithRegistrar( + flutter::PluginRegistrarManager::GetInstance() + ->GetRegistrar(registrar)); +} diff --git a/packages/firebase_core/firebase_core/firebase_core/windows/include/firebase_core/firebase_core_plugin_c_api.h b/packages/firebase_core/firebase_core/firebase_core/windows/include/firebase_core/firebase_core_plugin_c_api.h new file mode 100644 index 000000000000..4ef141db19bd --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/windows/include/firebase_core/firebase_core_plugin_c_api.h @@ -0,0 +1,23 @@ +#ifndef FLUTTER_PLUGIN_FIREBASE_CORE_PLUGIN_C_API_H_ +#define FLUTTER_PLUGIN_FIREBASE_CORE_PLUGIN_C_API_H_ + +#include + +#ifdef FLUTTER_PLUGIN_IMPL +#define FLUTTER_PLUGIN_EXPORT __declspec(dllexport) +#else +#define FLUTTER_PLUGIN_EXPORT __declspec(dllimport) +#endif + +#if defined(__cplusplus) +extern "C" { +#endif + +FLUTTER_PLUGIN_EXPORT void FirebaseCorePluginCApiRegisterWithRegistrar( + FlutterDesktopPluginRegistrarRef registrar); + +#if defined(__cplusplus) +} // extern "C" +#endif + +#endif // FLUTTER_PLUGIN_FIREBASE_CORE_PLUGIN_C_API_H_ From 153c0d93ad9e3d169f72d170b197ecc2b86e07ab Mon Sep 17 00:00:00 2001 From: Guillaume Bernos Date: Mon, 6 Mar 2023 15:24:46 +0100 Subject: [PATCH 03/65] add windows --- .../flutter/generated_plugin_registrant.cc | 14 +++++++++++ .../flutter/generated_plugin_registrant.h | 15 ++++++++++++ .../windows/flutter/generated_plugins.cmake | 24 +++++++++++++++++++ .../firebase_core/windows/CMakeLists.txt | 12 ++++++++++ 4 files changed, 65 insertions(+) create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/windows/flutter/generated_plugin_registrant.cc create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/windows/flutter/generated_plugin_registrant.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/windows/flutter/generated_plugins.cmake diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/flutter/generated_plugin_registrant.cc b/packages/firebase_core/firebase_core/firebase_core/example/windows/flutter/generated_plugin_registrant.cc new file mode 100644 index 000000000000..1a82e7d01dce --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/windows/flutter/generated_plugin_registrant.cc @@ -0,0 +1,14 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#include "generated_plugin_registrant.h" + +#include + +void RegisterPlugins(flutter::PluginRegistry* registry) { + FirebaseCorePluginCApiRegisterWithRegistrar( + registry->GetRegistrarForPlugin("FirebaseCorePluginCApi")); +} diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/flutter/generated_plugin_registrant.h b/packages/firebase_core/firebase_core/firebase_core/example/windows/flutter/generated_plugin_registrant.h new file mode 100644 index 000000000000..dc139d85a931 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/windows/flutter/generated_plugin_registrant.h @@ -0,0 +1,15 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#ifndef GENERATED_PLUGIN_REGISTRANT_ +#define GENERATED_PLUGIN_REGISTRANT_ + +#include + +// Registers Flutter plugins. +void RegisterPlugins(flutter::PluginRegistry* registry); + +#endif // GENERATED_PLUGIN_REGISTRANT_ diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/flutter/generated_plugins.cmake b/packages/firebase_core/firebase_core/firebase_core/example/windows/flutter/generated_plugins.cmake new file mode 100644 index 000000000000..fa8a39bab15e --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/windows/flutter/generated_plugins.cmake @@ -0,0 +1,24 @@ +# +# Generated file, do not edit. +# + +list(APPEND FLUTTER_PLUGIN_LIST + firebase_core +) + +list(APPEND FLUTTER_FFI_PLUGIN_LIST +) + +set(PLUGIN_BUNDLED_LIBRARIES) + +foreach(plugin ${FLUTTER_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/windows plugins/${plugin}) + target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) + list(APPEND PLUGIN_BUNDLED_LIBRARIES $) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) +endforeach(plugin) + +foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/windows plugins/${ffi_plugin}) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries}) +endforeach(ffi_plugin) diff --git a/packages/firebase_core/firebase_core/firebase_core/windows/CMakeLists.txt b/packages/firebase_core/firebase_core/firebase_core/windows/CMakeLists.txt index 2f368229d6e9..c6ef1ebf3727 100644 --- a/packages/firebase_core/firebase_core/firebase_core/windows/CMakeLists.txt +++ b/packages/firebase_core/firebase_core/firebase_core/windows/CMakeLists.txt @@ -26,6 +26,18 @@ add_library(${PLUGIN_NAME} SHARED ${PLUGIN_SOURCES} ) +# Add Firebase libraries to the target using the function from the SDK. +add_subdirectory(${FIREBASE_CPP_SDK_DIR} bin/ EXCLUDE_FROM_ALL) + +# The Firebase C++ library `firebase_app` is required, +# and it must always be listed last. + +# Add the Firebase SDKs for the products you want to use in your app +# For example, to use Firebase Authentication and Firebase Realtime Database +set(firebase_libs firebase_auth firebase_app) +target_link_libraries(${target_name} "${firebase_libs}") + + # Apply a standard set of build settings that are configured in the # application-level CMakeLists.txt. This can be removed for plugins that want # full control over build settings. From 8f199736a65327d835e3a14080289c0d8f10ad3f Mon Sep 17 00:00:00 2001 From: Guillaume Bernos Date: Mon, 6 Mar 2023 16:15:41 +0100 Subject: [PATCH 04/65] add windows --- .../firebase_core/windows/CMakeLists.txt | 18 +++++++----------- 1 file changed, 7 insertions(+), 11 deletions(-) diff --git a/packages/firebase_core/firebase_core/firebase_core/windows/CMakeLists.txt b/packages/firebase_core/firebase_core/firebase_core/windows/CMakeLists.txt index c6ef1ebf3727..bd3c3fdc2bdb 100644 --- a/packages/firebase_core/firebase_core/firebase_core/windows/CMakeLists.txt +++ b/packages/firebase_core/firebase_core/firebase_core/windows/CMakeLists.txt @@ -26,17 +26,6 @@ add_library(${PLUGIN_NAME} SHARED ${PLUGIN_SOURCES} ) -# Add Firebase libraries to the target using the function from the SDK. -add_subdirectory(${FIREBASE_CPP_SDK_DIR} bin/ EXCLUDE_FROM_ALL) - -# The Firebase C++ library `firebase_app` is required, -# and it must always be listed last. - -# Add the Firebase SDKs for the products you want to use in your app -# For example, to use Firebase Authentication and Firebase Realtime Database -set(firebase_libs firebase_auth firebase_app) -target_link_libraries(${target_name} "${firebase_libs}") - # Apply a standard set of build settings that are configured in the # application-level CMakeLists.txt. This can be removed for plugins that want @@ -52,6 +41,13 @@ target_compile_definitions(${PLUGIN_NAME} PRIVATE FLUTTER_PLUGIN_IMPL) # Source include directories and library dependencies. Add any plugin-specific # dependencies here. + +add_subdirectory(${FIREBASE_CPP_SDK_DIR} bin/ EXCLUDE_FROM_ALL) +target_include_directories(${PLUGIN_NAME} INTERFACE + "${FIREBASE_CPP_SDK_DIR}/include") +set(firebase_libs firebase_auth firebase_database firebase_app) +target_link_libraries(${PLUGIN_NAME} PRIVATE "${firebase_libs}") + target_include_directories(${PLUGIN_NAME} INTERFACE "${CMAKE_CURRENT_SOURCE_DIR}/include") target_link_libraries(${PLUGIN_NAME} PRIVATE flutter flutter_wrapper_plugin) From 7ffbf8c94f1a331dc552409e0eaeaee037090c62 Mon Sep 17 00:00:00 2001 From: Guillaume Bernos Date: Mon, 6 Mar 2023 17:09:15 +0100 Subject: [PATCH 05/65] add windows --- .../example/bin/CMakeFiles/generate.stamp | 1 + .../bin/CMakeFiles/generate.stamp.depend | 5 + .../firebase_core/example/bin/INSTALL.vcxproj | 165 ++++++++++++++++++ .../example/bin/INSTALL.vcxproj.filters | 13 ++ .../example/bin/cmake_install.cmake | 34 ++++ .../runner/google-services-desktop.json | 37 ++++ .../firebase_core/windows/CMakeLists.txt | 4 +- .../windows/firebase_core_plugin.cpp | 4 + 8 files changed, 261 insertions(+), 2 deletions(-) create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/bin/CMakeFiles/generate.stamp create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/bin/CMakeFiles/generate.stamp.depend create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/bin/INSTALL.vcxproj create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/bin/INSTALL.vcxproj.filters create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/bin/cmake_install.cmake create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/windows/runner/google-services-desktop.json diff --git a/packages/firebase_core/firebase_core/firebase_core/example/bin/CMakeFiles/generate.stamp b/packages/firebase_core/firebase_core/firebase_core/example/bin/CMakeFiles/generate.stamp new file mode 100644 index 000000000000..9b5f49fa9f14 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/bin/CMakeFiles/generate.stamp @@ -0,0 +1 @@ +# CMake generation timestamp file for this directory. diff --git a/packages/firebase_core/firebase_core/firebase_core/example/bin/CMakeFiles/generate.stamp.depend b/packages/firebase_core/firebase_core/firebase_core/example/bin/CMakeFiles/generate.stamp.depend new file mode 100644 index 000000000000..5b8da13f857a --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/bin/CMakeFiles/generate.stamp.depend @@ -0,0 +1,5 @@ +# CMake generation dependency list for this directory. +C:/Program Files/Microsoft Visual Studio/2022/Community/Common7/IDE/CommonExtensions/Microsoft/CMake/CMake/share/cmake-3.25/Modules/FindPackageHandleStandardArgs.cmake +C:/Program Files/Microsoft Visual Studio/2022/Community/Common7/IDE/CommonExtensions/Microsoft/CMake/CMake/share/cmake-3.25/Modules/FindPackageMessage.cmake +C:/Program Files/Microsoft Visual Studio/2022/Community/Common7/IDE/CommonExtensions/Microsoft/CMake/CMake/share/cmake-3.25/Modules/FindPkgConfig.cmake +C:/Users/guill/Downloads/firebase_cpp_sdk_10.5.0/firebase_cpp_sdk/CMakeLists.txt diff --git a/packages/firebase_core/firebase_core/firebase_core/example/bin/INSTALL.vcxproj b/packages/firebase_core/firebase_core/firebase_core/example/bin/INSTALL.vcxproj new file mode 100644 index 000000000000..05091bebad78 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/bin/INSTALL.vcxproj @@ -0,0 +1,165 @@ + + + + x64 + + + + Debug + x64 + + + Profile + x64 + + + Release + x64 + + + + {B2284ACE-B264-3C77-ADAD-5516EBC85159} + Win32Proj + 10.0.22000.0 + x64 + INSTALL + NoUpgrade + + + + Utility + MultiByte + v143 + + + Utility + MultiByte + v143 + + + Utility + MultiByte + v143 + + + + + + + + + + <_ProjectFileVersion>10.0.20506.1 + $(Platform)\$(Configuration)\$(ProjectName)\ + $(Platform)\$(Configuration)\$(ProjectName)\ + $(Platform)\$(Configuration)\$(ProjectName)\ + + + + Always + + setlocal +"C:\Program Files\Microsoft Visual Studio\2022\Community\Common7\IDE\CommonExtensions\Microsoft\CMake\CMake\bin\cmake.exe" -DBUILD_TYPE=$(Configuration) -P cmake_install.cmake +if %errorlevel% neq 0 goto :cmEnd +:cmEnd +endlocal & call :cmErrorLevel %errorlevel% & goto :cmDone +:cmErrorLevel +exit /b %1 +:cmDone +if %errorlevel% neq 0 goto :VCEnd + + + + + Always + + setlocal +"C:\Program Files\Microsoft Visual Studio\2022\Community\Common7\IDE\CommonExtensions\Microsoft\CMake\CMake\bin\cmake.exe" -DBUILD_TYPE=$(Configuration) -P cmake_install.cmake +if %errorlevel% neq 0 goto :cmEnd +:cmEnd +endlocal & call :cmErrorLevel %errorlevel% & goto :cmDone +:cmErrorLevel +exit /b %1 +:cmDone +if %errorlevel% neq 0 goto :VCEnd + + + + + Always + + setlocal +"C:\Program Files\Microsoft Visual Studio\2022\Community\Common7\IDE\CommonExtensions\Microsoft\CMake\CMake\bin\cmake.exe" -DBUILD_TYPE=$(Configuration) -P cmake_install.cmake +if %errorlevel% neq 0 goto :cmEnd +:cmEnd +endlocal & call :cmErrorLevel %errorlevel% & goto :cmDone +:cmErrorLevel +exit /b %1 +:cmDone +if %errorlevel% neq 0 goto :VCEnd + + + + + + setlocal +cd . +if %errorlevel% neq 0 goto :cmEnd +:cmEnd +endlocal & call :cmErrorLevel %errorlevel% & goto :cmDone +:cmErrorLevel +exit /b %1 +:cmDone +if %errorlevel% neq 0 goto :VCEnd + %(AdditionalInputs) + C:\Users\guill\Developer\flutterfire\packages\firebase_core\firebase_core\firebase_core\example\bin\CMakeFiles\INSTALL_force + false + false + + setlocal +cd . +if %errorlevel% neq 0 goto :cmEnd +:cmEnd +endlocal & call :cmErrorLevel %errorlevel% & goto :cmDone +:cmErrorLevel +exit /b %1 +:cmDone +if %errorlevel% neq 0 goto :VCEnd + %(AdditionalInputs) + C:\Users\guill\Developer\flutterfire\packages\firebase_core\firebase_core\firebase_core\example\bin\CMakeFiles\INSTALL_force + false + false + + setlocal +cd . +if %errorlevel% neq 0 goto :cmEnd +:cmEnd +endlocal & call :cmErrorLevel %errorlevel% & goto :cmDone +:cmErrorLevel +exit /b %1 +:cmDone +if %errorlevel% neq 0 goto :VCEnd + %(AdditionalInputs) + C:\Users\guill\Developer\flutterfire\packages\firebase_core\firebase_core\firebase_core\example\bin\CMakeFiles\INSTALL_force + false + false + + + + + {DC08768F-F57C-313C-94F0-E16194F54223} + ZERO_CHECK + false + Never + + + {DF648812-5598-379C-A5B5-8A3EAC6BC5B0} + ALL_BUILD + false + Never + + + + + + \ No newline at end of file diff --git a/packages/firebase_core/firebase_core/firebase_core/example/bin/INSTALL.vcxproj.filters b/packages/firebase_core/firebase_core/firebase_core/example/bin/INSTALL.vcxproj.filters new file mode 100644 index 000000000000..69fed1abf535 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/bin/INSTALL.vcxproj.filters @@ -0,0 +1,13 @@ + + + + + CMake Rules + + + + + {EAE753BC-CF7B-3081-8331-9EFFB2F8D8A5} + + + diff --git a/packages/firebase_core/firebase_core/firebase_core/example/bin/cmake_install.cmake b/packages/firebase_core/firebase_core/firebase_core/example/bin/cmake_install.cmake new file mode 100644 index 000000000000..8cf9b6c06b96 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/bin/cmake_install.cmake @@ -0,0 +1,34 @@ +# Install script for directory: C:/Users/guill/Downloads/firebase_cpp_sdk_10.5.0/firebase_cpp_sdk + +# Set the install prefix +if(NOT DEFINED CMAKE_INSTALL_PREFIX) + set(CMAKE_INSTALL_PREFIX "$") +endif() +string(REGEX REPLACE "/$" "" CMAKE_INSTALL_PREFIX "${CMAKE_INSTALL_PREFIX}") + +# Set the install configuration name. +if(NOT DEFINED CMAKE_INSTALL_CONFIG_NAME) + if(BUILD_TYPE) + string(REGEX REPLACE "^[^A-Za-z0-9_]+" "" + CMAKE_INSTALL_CONFIG_NAME "${BUILD_TYPE}") + else() + set(CMAKE_INSTALL_CONFIG_NAME "Release") + endif() + message(STATUS "Install configuration: \"${CMAKE_INSTALL_CONFIG_NAME}\"") +endif() + +# Set the component getting installed. +if(NOT CMAKE_INSTALL_COMPONENT) + if(COMPONENT) + message(STATUS "Install component: \"${COMPONENT}\"") + set(CMAKE_INSTALL_COMPONENT "${COMPONENT}") + else() + set(CMAKE_INSTALL_COMPONENT) + endif() +endif() + +# Is this installation the result of a crosscompile? +if(NOT DEFINED CMAKE_CROSSCOMPILING) + set(CMAKE_CROSSCOMPILING "FALSE") +endif() + diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/google-services-desktop.json b/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/google-services-desktop.json new file mode 100644 index 000000000000..a3bf216f4de0 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/google-services-desktop.json @@ -0,0 +1,37 @@ +{ + "project_info": { + "project_number": "406099696497", + "firebase_url": "https://flutterfire-e2e-tests-default-rtdb.europe-west1.firebasedatabase.app", + "project_id": "flutterfire-e2e-tests", + "storage_bucket": "flutterfire-e2e-tests.appspot.com" + }, + "client": [ + { + "client_info": { + "mobilesdk_app_id": "1:406099696497:ios:58cbc26aca8e5cf83574d0", + "android_client_info": { + "package_name": "io.flutter.plugins.firebase.auth.example" + } + }, + "oauth_client": [ + { + "client_id": "406099696497-134k3722m01rtrsklhf3b7k8sqa5r7in.apps.googleusercontent.com" + } + ], + "api_key": [ + { + "current_key": "AIzaSyDooSUGSf63Ghq02_iIhtnmwMDs4HlWS6c" + } + ], + "services": { + "analytics_service": { + "status": 0 + }, + "appinvite_service": { + "status": 1 + } + } + } + ], + "configuration_version": "1" +} \ No newline at end of file diff --git a/packages/firebase_core/firebase_core/firebase_core/windows/CMakeLists.txt b/packages/firebase_core/firebase_core/firebase_core/windows/CMakeLists.txt index bd3c3fdc2bdb..e75e1384506a 100644 --- a/packages/firebase_core/firebase_core/firebase_core/windows/CMakeLists.txt +++ b/packages/firebase_core/firebase_core/firebase_core/windows/CMakeLists.txt @@ -41,8 +41,8 @@ target_compile_definitions(${PLUGIN_NAME} PRIVATE FLUTTER_PLUGIN_IMPL) # Source include directories and library dependencies. Add any plugin-specific # dependencies here. - -add_subdirectory(${FIREBASE_CPP_SDK_DIR} bin/ EXCLUDE_FROM_ALL) +set(MSVC_RUNTIME_MODE MD) +add_subdirectory(C:/Users/guill/Downloads/firebase_cpp_sdk_10.5.0/firebase_cpp_sdk C:/Users/guill/Developer/flutterfire/packages/firebase_core/firebase_core/firebase_core/example/bin/ EXCLUDE_FROM_ALL) target_include_directories(${PLUGIN_NAME} INTERFACE "${FIREBASE_CPP_SDK_DIR}/include") set(firebase_libs firebase_auth firebase_database firebase_app) diff --git a/packages/firebase_core/firebase_core/firebase_core/windows/firebase_core_plugin.cpp b/packages/firebase_core/firebase_core/firebase_core/windows/firebase_core_plugin.cpp index e92cfe868845..7dd2b9945a72 100644 --- a/packages/firebase_core/firebase_core/firebase_core/windows/firebase_core_plugin.cpp +++ b/packages/firebase_core/firebase_core/firebase_core/windows/firebase_core_plugin.cpp @@ -2,6 +2,7 @@ // This must be included before many other Windows headers. #include +#include "firebase/app.h" // For getPlatformVersion; remove unless needed for your plugin implementation. #include @@ -12,6 +13,7 @@ #include #include +using ::firebase::App; namespace firebase_core { @@ -41,6 +43,8 @@ void FirebaseCorePlugin::HandleMethodCall( const flutter::MethodCall &method_call, std::unique_ptr> result) { if (method_call.method_name().compare("getPlatformVersion") == 0) { + App* app = App::Create(); + std::cout << static_cast(reinterpret_cast(app)); std::ostringstream version_stream; version_stream << "Windows "; if (IsWindows10OrGreater()) { From 1efb81fe686cf99e6fe59e6f59fa58e155074612 Mon Sep 17 00:00:00 2001 From: Guillaume Bernos Date: Mon, 6 Mar 2023 17:19:28 +0100 Subject: [PATCH 06/65] right position for google service file --- .../example/google-services-desktop.json | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/google-services-desktop.json diff --git a/packages/firebase_core/firebase_core/firebase_core/example/google-services-desktop.json b/packages/firebase_core/firebase_core/firebase_core/example/google-services-desktop.json new file mode 100644 index 000000000000..a3bf216f4de0 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/google-services-desktop.json @@ -0,0 +1,37 @@ +{ + "project_info": { + "project_number": "406099696497", + "firebase_url": "https://flutterfire-e2e-tests-default-rtdb.europe-west1.firebasedatabase.app", + "project_id": "flutterfire-e2e-tests", + "storage_bucket": "flutterfire-e2e-tests.appspot.com" + }, + "client": [ + { + "client_info": { + "mobilesdk_app_id": "1:406099696497:ios:58cbc26aca8e5cf83574d0", + "android_client_info": { + "package_name": "io.flutter.plugins.firebase.auth.example" + } + }, + "oauth_client": [ + { + "client_id": "406099696497-134k3722m01rtrsklhf3b7k8sqa5r7in.apps.googleusercontent.com" + } + ], + "api_key": [ + { + "current_key": "AIzaSyDooSUGSf63Ghq02_iIhtnmwMDs4HlWS6c" + } + ], + "services": { + "analytics_service": { + "status": 0 + }, + "appinvite_service": { + "status": 1 + } + } + } + ], + "configuration_version": "1" +} \ No newline at end of file From 856a6df6cbaa2db07f8ca694641dc84a596232b5 Mon Sep 17 00:00:00 2001 From: Guillaume Bernos Date: Mon, 6 Mar 2023 17:21:03 +0100 Subject: [PATCH 07/65] add windows --- .../firebase_core/firebase_core/windows/CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/firebase_core/firebase_core/firebase_core/windows/CMakeLists.txt b/packages/firebase_core/firebase_core/firebase_core/windows/CMakeLists.txt index e75e1384506a..35c68f4a1910 100644 --- a/packages/firebase_core/firebase_core/firebase_core/windows/CMakeLists.txt +++ b/packages/firebase_core/firebase_core/firebase_core/windows/CMakeLists.txt @@ -42,7 +42,7 @@ target_compile_definitions(${PLUGIN_NAME} PRIVATE FLUTTER_PLUGIN_IMPL) # Source include directories and library dependencies. Add any plugin-specific # dependencies here. set(MSVC_RUNTIME_MODE MD) -add_subdirectory(C:/Users/guill/Downloads/firebase_cpp_sdk_10.5.0/firebase_cpp_sdk C:/Users/guill/Developer/flutterfire/packages/firebase_core/firebase_core/firebase_core/example/bin/ EXCLUDE_FROM_ALL) +add_subdirectory(${FIREBASE_CPP_SDK_DIR} bin/ EXCLUDE_FROM_ALL) target_include_directories(${PLUGIN_NAME} INTERFACE "${FIREBASE_CPP_SDK_DIR}/include") set(firebase_libs firebase_auth firebase_database firebase_app) From dca79583964a624f0870d6aa4453e1c6c97bfb68 Mon Sep 17 00:00:00 2001 From: Guillaume Bernos Date: Tue, 21 Feb 2023 07:50:40 +0100 Subject: [PATCH 08/65] feat: integration of C++ desktop SDK --- .../firebase_core/firebase_core/.gitignore | 30 + .../firebase_core/firebase_core/.metadata | 30 + .../firebase_core/.vscode/settings.json | 3 + .../firebase_core/firebase_core/CHANGELOG.md | 3 + .../firebase_core/GoogleService-Info.plist | 38 + .../firebase_core/firebase_core/LICENSE | 1 + .../firebase_core/firebase_core/README.md | 15 + .../firebase_core/analysis_options.yaml | 4 + .../firebase_core/example/.gitignore | 44 + .../firebase_core/example/README.md | 16 + .../example/analysis_options.yaml | 29 + .../firebase_core/example/lib/main.dart | 63 + .../firebase_core/example/linux/.gitignore | 1 + .../example/linux/CMakeLists.txt | 150 +++ .../example/linux/flutter/CMakeLists.txt | 88 ++ .../flutter/generated_plugin_registrant.cc | 15 + .../flutter/generated_plugin_registrant.h | 15 + .../linux/flutter/generated_plugins.cmake | 24 + .../firebase_core/example/linux/main.cc | 6 + .../example/linux/my_application.cc | 104 ++ .../example/linux/my_application.h | 18 + .../firebase_core/example/pubspec.yaml | 83 ++ .../example/test/widget_test.dart | 27 + .../firebase_core/firebase/admob.h | 215 +++ .../firebase/admob/banner_view.h | 427 ++++++ .../firebase/admob/interstitial_ad.h | 259 ++++ .../firebase/admob/native_express_ad_view.h | 446 ++++++ .../firebase/admob/rewarded_video.h | 407 ++++++ .../firebase_core/firebase/admob/types.h | 244 ++++ .../firebase_core/firebase/analytics.h | 569 ++++++++ .../firebase/analytics/event_names.h | 472 +++++++ .../firebase/analytics/parameter_names.h | 755 +++++++++++ .../firebase/analytics/user_property_names.h | 50 + .../firebase_core/firebase/app.h | 787 +++++++++++ .../firebase_core/firebase/auth.h | 939 +++++++++++++ .../firebase_core/firebase/auth/credential.h | 633 +++++++++ .../firebase_core/firebase/auth/types.h | 473 +++++++ .../firebase_core/firebase/auth/user.h | 501 +++++++ .../firebase_core/firebase/database.h | 199 +++ .../firebase_core/firebase/database/common.h | 83 ++ .../firebase/database/data_snapshot.h | 205 +++ .../firebase/database/database_reference.h | 477 +++++++ .../firebase/database/disconnection.h | 156 +++ .../firebase/database/listener.h | 112 ++ .../firebase/database/mutable_data.h | 165 +++ .../firebase_core/firebase/database/query.h | 358 +++++ .../firebase/database/transaction.h | 102 ++ .../firebase_core/firebase/dynamic_links.h | 117 ++ .../firebase/dynamic_links/components.h | 336 +++++ .../firebase_core/firebase/firestore.h | 458 +++++++ .../firebase/firestore/collection_reference.h | 183 +++ .../firebase/firestore/document_change.h | 203 +++ .../firebase/firestore/document_reference.h | 351 +++++ .../firebase/firestore/document_snapshot.h | 297 ++++ .../firebase/firestore/field_path.h | 205 +++ .../firebase/firestore/field_value.h | 436 ++++++ .../firebase/firestore/firestore_errors.h | 116 ++ .../firebase/firestore/firestore_version.h | 29 + .../firebase/firestore/geo_point.h | 120 ++ .../firestore/listener_registration.h | 130 ++ .../firestore/load_bundle_task_progress.h | 101 ++ .../firebase/firestore/map_field_value.h | 37 + .../firebase/firestore/metadata_changes.h | 41 + .../firebase_core/firebase/firestore/query.h | 683 ++++++++++ .../firebase/firestore/query_snapshot.h | 194 +++ .../firebase/firestore/set_options.h | 161 +++ .../firebase/firestore/settings.h | 247 ++++ .../firebase/firestore/snapshot_metadata.h | 159 +++ .../firebase_core/firebase/firestore/source.h | 59 + .../firebase/firestore/timestamp.h | 252 ++++ .../firebase/firestore/transaction.h | 143 ++ .../firebase/firestore/transaction_options.h | 137 ++ .../firebase/firestore/write_batch.h | 188 +++ .../firebase_core/firebase/functions.h | 115 ++ .../firebase/functions/callable_reference.h | 124 ++ .../firebase/functions/callable_result.h | 96 ++ .../firebase_core/firebase/functions/common.h | 202 +++ .../firebase_core/firebase/future.h | 533 ++++++++ .../firebase_core/firebase/gma.h | 207 +++ .../firebase_core/firebase/gma/ad_view.h | 267 ++++ .../firebase/gma/interstitial_ad.h | 128 ++ .../firebase_core/firebase/gma/rewarded_ad.h | 152 +++ .../firebase_core/firebase/gma/types.h | 939 +++++++++++++ .../firebase_core/firebase/installations.h | 123 ++ .../firebase_core/firebase/internal/common.h | 128 ++ .../firebase/internal/future_impl.h | 359 +++++ .../firebase_core/firebase/internal/mutex.h | 100 ++ .../firebase/internal/platform.h | 110 ++ .../firebase/internal/type_traits.h | 134 ++ .../firebase_core/firebase/log.h | 54 + .../firebase_core/firebase/messaging.h | 728 ++++++++++ .../firebase_core/firebase/remote_config.h | 526 ++++++++ .../firebase_core/firebase/storage.h | 161 +++ .../firebase_core/firebase/storage/common.h | 62 + .../firebase/storage/controller.h | 146 ++ .../firebase_core/firebase/storage/listener.h | 74 + .../firebase_core/firebase/storage/metadata.h | 276 ++++ .../firebase/storage/storage_reference.h | 361 +++++ .../firebase_core/firebase/util.h | 101 ++ .../firebase_core/firebase/variant.h | 1197 +++++++++++++++++ .../firebase_core/firebase/version.h | 68 + .../generate_xml_from_google_services_json.py | 496 +++++++ .../firebase_core/generated_bindings.dart | 26 + .../google-services-desktop.json | 37 + .../firebase_core/lib/firebase_core.dart | 8 + .../lib/firebase_core_method_channel.dart | 17 + .../lib/firebase_core_platform_interface.dart | 29 + .../firebase_core/linux/CMakeLists.txt | 47 + .../linux/firebase_core_plugin.cc | 70 + .../firebase_core/firebase_core_plugin.h | 26 + .../firebase_core/firebase_core/pubspec.yaml | 34 + .../firebase_core_method_channel_test.dart | 24 + .../test/firebase_core_test.dart | 29 + 113 files changed, 23538 insertions(+) create mode 100644 packages/firebase_core/firebase_core/firebase_core/.gitignore create mode 100644 packages/firebase_core/firebase_core/firebase_core/.metadata create mode 100644 packages/firebase_core/firebase_core/firebase_core/.vscode/settings.json create mode 100644 packages/firebase_core/firebase_core/firebase_core/CHANGELOG.md create mode 100644 packages/firebase_core/firebase_core/firebase_core/GoogleService-Info.plist create mode 100644 packages/firebase_core/firebase_core/firebase_core/LICENSE create mode 100644 packages/firebase_core/firebase_core/firebase_core/README.md create mode 100644 packages/firebase_core/firebase_core/firebase_core/analysis_options.yaml create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/.gitignore create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/README.md create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/analysis_options.yaml create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/lib/main.dart create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/linux/.gitignore create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/linux/CMakeLists.txt create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/linux/flutter/CMakeLists.txt create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/linux/flutter/generated_plugin_registrant.cc create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/linux/flutter/generated_plugin_registrant.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/linux/flutter/generated_plugins.cmake create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/linux/main.cc create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/linux/my_application.cc create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/linux/my_application.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/pubspec.yaml create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/test/widget_test.dart create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/admob.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/admob/banner_view.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/admob/interstitial_ad.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/admob/native_express_ad_view.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/admob/rewarded_video.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/admob/types.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/analytics.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/analytics/event_names.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/analytics/parameter_names.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/analytics/user_property_names.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/app.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/auth.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/auth/credential.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/auth/types.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/auth/user.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/database.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/database/common.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/database/data_snapshot.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/database/database_reference.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/database/disconnection.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/database/listener.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/database/mutable_data.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/database/query.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/database/transaction.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/dynamic_links.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/dynamic_links/components.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/collection_reference.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/document_change.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/document_reference.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/document_snapshot.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/field_path.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/field_value.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/firestore_errors.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/firestore_version.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/geo_point.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/listener_registration.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/load_bundle_task_progress.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/map_field_value.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/metadata_changes.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/query.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/query_snapshot.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/set_options.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/settings.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/snapshot_metadata.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/source.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/timestamp.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/transaction.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/transaction_options.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/write_batch.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/functions.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/functions/callable_reference.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/functions/callable_result.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/functions/common.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/future.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/gma.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/gma/ad_view.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/gma/interstitial_ad.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/gma/rewarded_ad.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/gma/types.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/installations.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/internal/common.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/internal/future_impl.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/internal/mutex.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/internal/platform.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/internal/type_traits.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/log.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/messaging.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/remote_config.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/storage.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/storage/common.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/storage/controller.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/storage/listener.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/storage/metadata.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/storage/storage_reference.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/util.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/variant.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/version.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/generate_xml_from_google_services_json.py create mode 100644 packages/firebase_core/firebase_core/firebase_core/generated_bindings.dart create mode 100644 packages/firebase_core/firebase_core/firebase_core/google-services-desktop.json create mode 100644 packages/firebase_core/firebase_core/firebase_core/lib/firebase_core.dart create mode 100644 packages/firebase_core/firebase_core/firebase_core/lib/firebase_core_method_channel.dart create mode 100644 packages/firebase_core/firebase_core/firebase_core/lib/firebase_core_platform_interface.dart create mode 100644 packages/firebase_core/firebase_core/firebase_core/linux/CMakeLists.txt create mode 100644 packages/firebase_core/firebase_core/firebase_core/linux/firebase_core_plugin.cc create mode 100644 packages/firebase_core/firebase_core/firebase_core/linux/include/firebase_core/firebase_core_plugin.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/pubspec.yaml create mode 100644 packages/firebase_core/firebase_core/firebase_core/test/firebase_core_method_channel_test.dart create mode 100644 packages/firebase_core/firebase_core/firebase_core/test/firebase_core_test.dart diff --git a/packages/firebase_core/firebase_core/firebase_core/.gitignore b/packages/firebase_core/firebase_core/firebase_core/.gitignore new file mode 100644 index 000000000000..96486fd93024 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/.gitignore @@ -0,0 +1,30 @@ +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.buildlog/ +.history +.svn/ +migrate_working_dir/ + +# IntelliJ related +*.iml +*.ipr +*.iws +.idea/ + +# The .vscode folder contains launch configuration and tasks you configure in +# VS Code which you may wish to be included in version control, so this line +# is commented out by default. +#.vscode/ + +# Flutter/Dart/Pub related +# Libraries should not include pubspec.lock, per https://dart.dev/guides/libraries/private-files#pubspeclock. +/pubspec.lock +**/doc/api/ +.dart_tool/ +.packages +build/ diff --git a/packages/firebase_core/firebase_core/firebase_core/.metadata b/packages/firebase_core/firebase_core/firebase_core/.metadata new file mode 100644 index 000000000000..74867a0b132b --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/.metadata @@ -0,0 +1,30 @@ +# This file tracks properties of this Flutter project. +# Used by Flutter tool to assess capabilities and perform upgrades etc. +# +# This file should be version controlled. + +version: + revision: 9944297138845a94256f1cf37beb88ff9a8e811a + channel: stable + +project_type: plugin + +# Tracks metadata for the flutter migrate command +migration: + platforms: + - platform: root + create_revision: 9944297138845a94256f1cf37beb88ff9a8e811a + base_revision: 9944297138845a94256f1cf37beb88ff9a8e811a + - platform: linux + create_revision: 9944297138845a94256f1cf37beb88ff9a8e811a + base_revision: 9944297138845a94256f1cf37beb88ff9a8e811a + + # User provided section + + # List of Local paths (relative to this file) that should be + # ignored by the migrate tool. + # + # Files that are not part of the templates will be ignored by default. + unmanaged_files: + - 'lib/main.dart' + - 'ios/Runner.xcodeproj/project.pbxproj' diff --git a/packages/firebase_core/firebase_core/firebase_core/.vscode/settings.json b/packages/firebase_core/firebase_core/firebase_core/.vscode/settings.json new file mode 100644 index 000000000000..deec1e1d3994 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/.vscode/settings.json @@ -0,0 +1,3 @@ +{ + "cmake.sourceDirectory": "${workspaceFolder}/linux" +} diff --git a/packages/firebase_core/firebase_core/firebase_core/CHANGELOG.md b/packages/firebase_core/firebase_core/firebase_core/CHANGELOG.md new file mode 100644 index 000000000000..41cc7d8192ec --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/CHANGELOG.md @@ -0,0 +1,3 @@ +## 0.0.1 + +* TODO: Describe initial release. diff --git a/packages/firebase_core/firebase_core/firebase_core/GoogleService-Info.plist b/packages/firebase_core/firebase_core/firebase_core/GoogleService-Info.plist new file mode 100644 index 000000000000..f325ead98dbc --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/GoogleService-Info.plist @@ -0,0 +1,38 @@ + + + + + CLIENT_ID + 406099696497-134k3722m01rtrsklhf3b7k8sqa5r7in.apps.googleusercontent.com + REVERSED_CLIENT_ID + com.googleusercontent.apps.406099696497-134k3722m01rtrsklhf3b7k8sqa5r7in + ANDROID_CLIENT_ID + 406099696497-17qn06u8a0dc717u8ul7s49ampk13lul.apps.googleusercontent.com + API_KEY + AIzaSyDooSUGSf63Ghq02_iIhtnmwMDs4HlWS6c + GCM_SENDER_ID + 406099696497 + PLIST_VERSION + 1 + BUNDLE_ID + io.flutter.plugins.firebase.auth.example + PROJECT_ID + flutterfire-e2e-tests + STORAGE_BUCKET + flutterfire-e2e-tests.appspot.com + IS_ADS_ENABLED + + IS_ANALYTICS_ENABLED + + IS_APPINVITE_ENABLED + + IS_GCM_ENABLED + + IS_SIGNIN_ENABLED + + GOOGLE_APP_ID + 1:406099696497:ios:58cbc26aca8e5cf83574d0 + DATABASE_URL + https://flutterfire-e2e-tests-default-rtdb.europe-west1.firebasedatabase.app + + \ No newline at end of file diff --git a/packages/firebase_core/firebase_core/firebase_core/LICENSE b/packages/firebase_core/firebase_core/firebase_core/LICENSE new file mode 100644 index 000000000000..ba75c69f7f21 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/LICENSE @@ -0,0 +1 @@ +TODO: Add your license here. diff --git a/packages/firebase_core/firebase_core/firebase_core/README.md b/packages/firebase_core/firebase_core/firebase_core/README.md new file mode 100644 index 000000000000..b373aba55a5f --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/README.md @@ -0,0 +1,15 @@ +# firebase_core + +A new Flutter plugin project. + +## Getting Started + +This project is a starting point for a Flutter +[plug-in package](https://flutter.dev/developing-packages/), +a specialized package that includes platform-specific implementation code for +Android and/or iOS. + +For help getting started with Flutter development, view the +[online documentation](https://flutter.dev/docs), which offers tutorials, +samples, guidance on mobile development, and a full API reference. + diff --git a/packages/firebase_core/firebase_core/firebase_core/analysis_options.yaml b/packages/firebase_core/firebase_core/firebase_core/analysis_options.yaml new file mode 100644 index 000000000000..a5744c1cfbe7 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/analysis_options.yaml @@ -0,0 +1,4 @@ +include: package:flutter_lints/flutter.yaml + +# Additional information about this file can be found at +# https://dart.dev/guides/language/analysis-options diff --git a/packages/firebase_core/firebase_core/firebase_core/example/.gitignore b/packages/firebase_core/firebase_core/firebase_core/example/.gitignore new file mode 100644 index 000000000000..24476c5d1eb5 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/.gitignore @@ -0,0 +1,44 @@ +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.buildlog/ +.history +.svn/ +migrate_working_dir/ + +# IntelliJ related +*.iml +*.ipr +*.iws +.idea/ + +# The .vscode folder contains launch configuration and tasks you configure in +# VS Code which you may wish to be included in version control, so this line +# is commented out by default. +#.vscode/ + +# Flutter/Dart/Pub related +**/doc/api/ +**/ios/Flutter/.last_build_id +.dart_tool/ +.flutter-plugins +.flutter-plugins-dependencies +.packages +.pub-cache/ +.pub/ +/build/ + +# Symbolication related +app.*.symbols + +# Obfuscation related +app.*.map.json + +# Android Studio will place build artifacts here +/android/app/debug +/android/app/profile +/android/app/release diff --git a/packages/firebase_core/firebase_core/firebase_core/example/README.md b/packages/firebase_core/firebase_core/firebase_core/example/README.md new file mode 100644 index 000000000000..d1f452146bce --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/README.md @@ -0,0 +1,16 @@ +# firebase_core_example + +Demonstrates how to use the firebase_core plugin. + +## Getting Started + +This project is a starting point for a Flutter application. + +A few resources to get you started if this is your first Flutter project: + +- [Lab: Write your first Flutter app](https://docs.flutter.dev/get-started/codelab) +- [Cookbook: Useful Flutter samples](https://docs.flutter.dev/cookbook) + +For help getting started with Flutter development, view the +[online documentation](https://docs.flutter.dev/), which offers tutorials, +samples, guidance on mobile development, and a full API reference. diff --git a/packages/firebase_core/firebase_core/firebase_core/example/analysis_options.yaml b/packages/firebase_core/firebase_core/firebase_core/example/analysis_options.yaml new file mode 100644 index 000000000000..61b6c4de17c9 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/analysis_options.yaml @@ -0,0 +1,29 @@ +# This file configures the analyzer, which statically analyzes Dart code to +# check for errors, warnings, and lints. +# +# The issues identified by the analyzer are surfaced in the UI of Dart-enabled +# IDEs (https://dart.dev/tools#ides-and-editors). The analyzer can also be +# invoked from the command line by running `flutter analyze`. + +# The following line activates a set of recommended lints for Flutter apps, +# packages, and plugins designed to encourage good coding practices. +include: package:flutter_lints/flutter.yaml + +linter: + # The lint rules applied to this project can be customized in the + # section below to disable rules from the `package:flutter_lints/flutter.yaml` + # included above or to enable additional rules. A list of all available lints + # and their documentation is published at + # https://dart-lang.github.io/linter/lints/index.html. + # + # Instead of disabling a lint rule for the entire project in the + # section below, it can also be suppressed for a single line of code + # or a specific dart file by using the `// ignore: name_of_lint` and + # `// ignore_for_file: name_of_lint` syntax on the line or in the file + # producing the lint. + rules: + # avoid_print: false # Uncomment to disable the `avoid_print` rule + # prefer_single_quotes: true # Uncomment to enable the `prefer_single_quotes` rule + +# Additional information about this file can be found at +# https://dart.dev/guides/language/analysis-options diff --git a/packages/firebase_core/firebase_core/firebase_core/example/lib/main.dart b/packages/firebase_core/firebase_core/firebase_core/example/lib/main.dart new file mode 100644 index 000000000000..4e2b473ad9e0 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/lib/main.dart @@ -0,0 +1,63 @@ +import 'package:flutter/material.dart'; +import 'dart:async'; + +import 'package:flutter/services.dart'; +import 'package:firebase_core/firebase_core.dart'; + +void main() { + runApp(const MyApp()); +} + +class MyApp extends StatefulWidget { + const MyApp({super.key}); + + @override + State createState() => _MyAppState(); +} + +class _MyAppState extends State { + String _platformVersion = 'Unknown'; + final _firebaseCorePlugin = FirebaseCore(); + + @override + void initState() { + super.initState(); + initPlatformState(); + } + + // Platform messages are asynchronous, so we initialize in an async method. + Future initPlatformState() async { + String platformVersion; + // Platform messages may fail, so we use a try/catch PlatformException. + // We also handle the message potentially returning null. + try { + platformVersion = + await _firebaseCorePlugin.getPlatformVersion() ?? 'Unknown platform version'; + } on PlatformException { + platformVersion = 'Failed to get platform version.'; + } + + // If the widget was removed from the tree while the asynchronous platform + // message was in flight, we want to discard the reply rather than calling + // setState to update our non-existent appearance. + if (!mounted) return; + + setState(() { + _platformVersion = platformVersion; + }); + } + + @override + Widget build(BuildContext context) { + return MaterialApp( + home: Scaffold( + appBar: AppBar( + title: const Text('Plugin example app'), + ), + body: Center( + child: Text('Running on: $_platformVersion\n'), + ), + ), + ); + } +} diff --git a/packages/firebase_core/firebase_core/firebase_core/example/linux/.gitignore b/packages/firebase_core/firebase_core/firebase_core/example/linux/.gitignore new file mode 100644 index 000000000000..d3896c98444f --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/linux/.gitignore @@ -0,0 +1 @@ +flutter/ephemeral diff --git a/packages/firebase_core/firebase_core/firebase_core/example/linux/CMakeLists.txt b/packages/firebase_core/firebase_core/firebase_core/example/linux/CMakeLists.txt new file mode 100644 index 000000000000..9ae42276201e --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/linux/CMakeLists.txt @@ -0,0 +1,150 @@ +# Project-level configuration. +cmake_minimum_required(VERSION 3.10) +project(runner LANGUAGES CXX) + +# The name of the executable created for the application. Change this to change +# the on-disk name of your application. +set(BINARY_NAME "firebase_core_example") +# The unique GTK application identifier for this application. See: +# https://wiki.gnome.org/HowDoI/ChooseApplicationID +set(APPLICATION_ID "com.example.firebase_core") + +# Explicitly opt in to modern CMake behaviors to avoid warnings with recent +# versions of CMake. +cmake_policy(SET CMP0063 NEW) + +# Load bundled libraries from the lib/ directory relative to the binary. +set(CMAKE_INSTALL_RPATH "$ORIGIN/lib") + +# Root filesystem for cross-building. +if(FLUTTER_TARGET_PLATFORM_SYSROOT) + set(CMAKE_SYSROOT ${FLUTTER_TARGET_PLATFORM_SYSROOT}) + set(CMAKE_FIND_ROOT_PATH ${CMAKE_SYSROOT}) + set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) + set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY) + set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) + set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) +endif() + +# Define build configuration options. +if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) + set(CMAKE_BUILD_TYPE "Debug" CACHE + STRING "Flutter build mode" FORCE) + set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS + "Debug" "Profile" "Release") +endif() + +# Compilation settings that should be applied to most targets. +# +# Be cautious about adding new options here, as plugins use this function by +# default. In most cases, you should add new options to specific targets instead +# of modifying this function. +function(APPLY_STANDARD_SETTINGS TARGET) + target_compile_features(${TARGET} PUBLIC cxx_std_14) + target_compile_options(${TARGET} PRIVATE -Wall -Werror) + target_compile_options(${TARGET} PRIVATE "$<$>:-O3>") + target_compile_definitions(${TARGET} PRIVATE "$<$>:NDEBUG>") +endfunction() + +# Flutter library and tool build rules. +set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") +add_subdirectory(${FLUTTER_MANAGED_DIR}) + +# Add Firebase libraries to the target using the function from the SDK. +add_subdirectory(${FIREBASE_CPP_SDK_DIR} bin/ EXCLUDE_FROM_ALL) + +# The Firebase C++ library `firebase_app` is required, +# and it must always be listed last. + +# Add the Firebase SDKs for the products you want to use in your app +# For example, to use Firebase Authentication and Firebase Realtime Database +set(firebase_libs firebase_auth firebase_database firebase_app) +target_link_libraries(${target_name} "${firebase_libs}") + + +# System-level dependencies. +find_package(PkgConfig REQUIRED) +pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) + +add_definitions(-DAPPLICATION_ID="${APPLICATION_ID}") + +# Define the application target. To change its name, change BINARY_NAME above, +# not the value here, or `flutter run` will no longer work. +# +# Any new source files that you add to the application should be added here. +add_executable(${BINARY_NAME} + "main.cc" + "my_application.cc" + "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" +) + +# Apply the standard set of build settings. This can be removed for applications +# that need different build settings. +apply_standard_settings(${BINARY_NAME}) + +# Add dependency libraries. Add any application-specific dependencies here. +target_link_libraries(${BINARY_NAME} PRIVATE flutter) +target_link_libraries(${BINARY_NAME} PRIVATE PkgConfig::GTK) + +# Run the Flutter tool portions of the build. This must not be removed. +add_dependencies(${BINARY_NAME} flutter_assemble) + +# Only the install-generated bundle's copy of the executable will launch +# correctly, since the resources must in the right relative locations. To avoid +# people trying to run the unbundled copy, put it in a subdirectory instead of +# the default top-level location. +set_target_properties(${BINARY_NAME} + PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/intermediates_do_not_run" +) + +# Generated plugin build rules, which manage building the plugins and adding +# them to the application. +include(flutter/generated_plugins.cmake) + + +# === Installation === +# By default, "installing" just makes a relocatable bundle in the build +# directory. +set(BUILD_BUNDLE_DIR "${PROJECT_BINARY_DIR}/bundle") +if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) + set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) +endif() + +# Start with a clean build bundle directory every time. +install(CODE " + file(REMOVE_RECURSE \"${BUILD_BUNDLE_DIR}/\") + " COMPONENT Runtime) + +set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") +set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}/lib") + +install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +foreach(bundled_library ${PLUGIN_BUNDLED_LIBRARIES}) + install(FILES "${bundled_library}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endforeach(bundled_library) + +# Fully re-copy the assets directory on each build to avoid having stale files +# from a previous install. +set(FLUTTER_ASSET_DIR_NAME "flutter_assets") +install(CODE " + file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") + " COMPONENT Runtime) +install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" + DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) + +# Install the AOT library on non-Debug builds only. +if(NOT CMAKE_BUILD_TYPE MATCHES "Debug") + install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endif() diff --git a/packages/firebase_core/firebase_core/firebase_core/example/linux/flutter/CMakeLists.txt b/packages/firebase_core/firebase_core/firebase_core/example/linux/flutter/CMakeLists.txt new file mode 100644 index 000000000000..d5bd01648a96 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/linux/flutter/CMakeLists.txt @@ -0,0 +1,88 @@ +# This file controls Flutter-level build steps. It should not be edited. +cmake_minimum_required(VERSION 3.10) + +set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") + +# Configuration provided via flutter tool. +include(${EPHEMERAL_DIR}/generated_config.cmake) + +# TODO: Move the rest of this into files in ephemeral. See +# https://github.com/flutter/flutter/issues/57146. + +# Serves the same purpose as list(TRANSFORM ... PREPEND ...), +# which isn't available in 3.10. +function(list_prepend LIST_NAME PREFIX) + set(NEW_LIST "") + foreach(element ${${LIST_NAME}}) + list(APPEND NEW_LIST "${PREFIX}${element}") + endforeach(element) + set(${LIST_NAME} "${NEW_LIST}" PARENT_SCOPE) +endfunction() + +# === Flutter Library === +# System-level dependencies. +find_package(PkgConfig REQUIRED) +pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) +pkg_check_modules(GLIB REQUIRED IMPORTED_TARGET glib-2.0) +pkg_check_modules(GIO REQUIRED IMPORTED_TARGET gio-2.0) + +set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/libflutter_linux_gtk.so") + +# Published to parent scope for install step. +set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) +set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) +set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) +set(AOT_LIBRARY "${PROJECT_DIR}/build/lib/libapp.so" PARENT_SCOPE) + +list(APPEND FLUTTER_LIBRARY_HEADERS + "fl_basic_message_channel.h" + "fl_binary_codec.h" + "fl_binary_messenger.h" + "fl_dart_project.h" + "fl_engine.h" + "fl_json_message_codec.h" + "fl_json_method_codec.h" + "fl_message_codec.h" + "fl_method_call.h" + "fl_method_channel.h" + "fl_method_codec.h" + "fl_method_response.h" + "fl_plugin_registrar.h" + "fl_plugin_registry.h" + "fl_standard_message_codec.h" + "fl_standard_method_codec.h" + "fl_string_codec.h" + "fl_value.h" + "fl_view.h" + "flutter_linux.h" +) +list_prepend(FLUTTER_LIBRARY_HEADERS "${EPHEMERAL_DIR}/flutter_linux/") +add_library(flutter INTERFACE) +target_include_directories(flutter INTERFACE + "${EPHEMERAL_DIR}" +) +target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}") +target_link_libraries(flutter INTERFACE + PkgConfig::GTK + PkgConfig::GLIB + PkgConfig::GIO +) +add_dependencies(flutter flutter_assemble) + +# === Flutter tool backend === +# _phony_ is a non-existent file to force this command to run every time, +# since currently there's no way to get a full input/output list from the +# flutter tool. +add_custom_command( + OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} + ${CMAKE_CURRENT_BINARY_DIR}/_phony_ + COMMAND ${CMAKE_COMMAND} -E env + ${FLUTTER_TOOL_ENVIRONMENT} + "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.sh" + ${FLUTTER_TARGET_PLATFORM} ${CMAKE_BUILD_TYPE} + VERBATIM +) +add_custom_target(flutter_assemble DEPENDS + "${FLUTTER_LIBRARY}" + ${FLUTTER_LIBRARY_HEADERS} +) diff --git a/packages/firebase_core/firebase_core/firebase_core/example/linux/flutter/generated_plugin_registrant.cc b/packages/firebase_core/firebase_core/firebase_core/example/linux/flutter/generated_plugin_registrant.cc new file mode 100644 index 000000000000..15034725064f --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/linux/flutter/generated_plugin_registrant.cc @@ -0,0 +1,15 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#include "generated_plugin_registrant.h" + +#include + +void fl_register_plugins(FlPluginRegistry* registry) { + g_autoptr(FlPluginRegistrar) firebase_core_registrar = + fl_plugin_registry_get_registrar_for_plugin(registry, "FirebaseCorePlugin"); + firebase_core_plugin_register_with_registrar(firebase_core_registrar); +} diff --git a/packages/firebase_core/firebase_core/firebase_core/example/linux/flutter/generated_plugin_registrant.h b/packages/firebase_core/firebase_core/firebase_core/example/linux/flutter/generated_plugin_registrant.h new file mode 100644 index 000000000000..e0f0a47bc08f --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/linux/flutter/generated_plugin_registrant.h @@ -0,0 +1,15 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#ifndef GENERATED_PLUGIN_REGISTRANT_ +#define GENERATED_PLUGIN_REGISTRANT_ + +#include + +// Registers Flutter plugins. +void fl_register_plugins(FlPluginRegistry* registry); + +#endif // GENERATED_PLUGIN_REGISTRANT_ diff --git a/packages/firebase_core/firebase_core/firebase_core/example/linux/flutter/generated_plugins.cmake b/packages/firebase_core/firebase_core/firebase_core/example/linux/flutter/generated_plugins.cmake new file mode 100644 index 000000000000..1d55b5b0bf79 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/linux/flutter/generated_plugins.cmake @@ -0,0 +1,24 @@ +# +# Generated file, do not edit. +# + +list(APPEND FLUTTER_PLUGIN_LIST + firebase_core +) + +list(APPEND FLUTTER_FFI_PLUGIN_LIST +) + +set(PLUGIN_BUNDLED_LIBRARIES) + +foreach(plugin ${FLUTTER_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/linux plugins/${plugin}) + target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) + list(APPEND PLUGIN_BUNDLED_LIBRARIES $) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) +endforeach(plugin) + +foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/linux plugins/${ffi_plugin}) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries}) +endforeach(ffi_plugin) diff --git a/packages/firebase_core/firebase_core/firebase_core/example/linux/main.cc b/packages/firebase_core/firebase_core/firebase_core/example/linux/main.cc new file mode 100644 index 000000000000..e7c5c5437037 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/linux/main.cc @@ -0,0 +1,6 @@ +#include "my_application.h" + +int main(int argc, char** argv) { + g_autoptr(MyApplication) app = my_application_new(); + return g_application_run(G_APPLICATION(app), argc, argv); +} diff --git a/packages/firebase_core/firebase_core/firebase_core/example/linux/my_application.cc b/packages/firebase_core/firebase_core/firebase_core/example/linux/my_application.cc new file mode 100644 index 000000000000..b699538ff8ee --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/linux/my_application.cc @@ -0,0 +1,104 @@ +#include "my_application.h" + +#include +#ifdef GDK_WINDOWING_X11 +#include +#endif + +#include "flutter/generated_plugin_registrant.h" + +struct _MyApplication { + GtkApplication parent_instance; + char** dart_entrypoint_arguments; +}; + +G_DEFINE_TYPE(MyApplication, my_application, GTK_TYPE_APPLICATION) + +// Implements GApplication::activate. +static void my_application_activate(GApplication* application) { + MyApplication* self = MY_APPLICATION(application); + GtkWindow* window = + GTK_WINDOW(gtk_application_window_new(GTK_APPLICATION(application))); + + // Use a header bar when running in GNOME as this is the common style used + // by applications and is the setup most users will be using (e.g. Ubuntu + // desktop). + // If running on X and not using GNOME then just use a traditional title bar + // in case the window manager does more exotic layout, e.g. tiling. + // If running on Wayland assume the header bar will work (may need changing + // if future cases occur). + gboolean use_header_bar = TRUE; +#ifdef GDK_WINDOWING_X11 + GdkScreen* screen = gtk_window_get_screen(window); + if (GDK_IS_X11_SCREEN(screen)) { + const gchar* wm_name = gdk_x11_screen_get_window_manager_name(screen); + if (g_strcmp0(wm_name, "GNOME Shell") != 0) { + use_header_bar = FALSE; + } + } +#endif + if (use_header_bar) { + GtkHeaderBar* header_bar = GTK_HEADER_BAR(gtk_header_bar_new()); + gtk_widget_show(GTK_WIDGET(header_bar)); + gtk_header_bar_set_title(header_bar, "firebase_core_example"); + gtk_header_bar_set_show_close_button(header_bar, TRUE); + gtk_window_set_titlebar(window, GTK_WIDGET(header_bar)); + } else { + gtk_window_set_title(window, "firebase_core_example"); + } + + gtk_window_set_default_size(window, 1280, 720); + gtk_widget_show(GTK_WIDGET(window)); + + g_autoptr(FlDartProject) project = fl_dart_project_new(); + fl_dart_project_set_dart_entrypoint_arguments(project, self->dart_entrypoint_arguments); + + FlView* view = fl_view_new(project); + gtk_widget_show(GTK_WIDGET(view)); + gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(view)); + + fl_register_plugins(FL_PLUGIN_REGISTRY(view)); + + gtk_widget_grab_focus(GTK_WIDGET(view)); +} + +// Implements GApplication::local_command_line. +static gboolean my_application_local_command_line(GApplication* application, gchar*** arguments, int* exit_status) { + MyApplication* self = MY_APPLICATION(application); + // Strip out the first argument as it is the binary name. + self->dart_entrypoint_arguments = g_strdupv(*arguments + 1); + + g_autoptr(GError) error = nullptr; + if (!g_application_register(application, nullptr, &error)) { + g_warning("Failed to register: %s", error->message); + *exit_status = 1; + return TRUE; + } + + g_application_activate(application); + *exit_status = 0; + + return TRUE; +} + +// Implements GObject::dispose. +static void my_application_dispose(GObject* object) { + MyApplication* self = MY_APPLICATION(object); + g_clear_pointer(&self->dart_entrypoint_arguments, g_strfreev); + G_OBJECT_CLASS(my_application_parent_class)->dispose(object); +} + +static void my_application_class_init(MyApplicationClass* klass) { + G_APPLICATION_CLASS(klass)->activate = my_application_activate; + G_APPLICATION_CLASS(klass)->local_command_line = my_application_local_command_line; + G_OBJECT_CLASS(klass)->dispose = my_application_dispose; +} + +static void my_application_init(MyApplication* self) {} + +MyApplication* my_application_new() { + return MY_APPLICATION(g_object_new(my_application_get_type(), + "application-id", APPLICATION_ID, + "flags", G_APPLICATION_NON_UNIQUE, + nullptr)); +} diff --git a/packages/firebase_core/firebase_core/firebase_core/example/linux/my_application.h b/packages/firebase_core/firebase_core/firebase_core/example/linux/my_application.h new file mode 100644 index 000000000000..72271d5e4170 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/linux/my_application.h @@ -0,0 +1,18 @@ +#ifndef FLUTTER_MY_APPLICATION_H_ +#define FLUTTER_MY_APPLICATION_H_ + +#include + +G_DECLARE_FINAL_TYPE(MyApplication, my_application, MY, APPLICATION, + GtkApplication) + +/** + * my_application_new: + * + * Creates a new Flutter-based application. + * + * Returns: a new #MyApplication. + */ +MyApplication* my_application_new(); + +#endif // FLUTTER_MY_APPLICATION_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/example/pubspec.yaml b/packages/firebase_core/firebase_core/firebase_core/example/pubspec.yaml new file mode 100644 index 000000000000..dd3d2b2c7b7e --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/pubspec.yaml @@ -0,0 +1,83 @@ +name: firebase_core_example +description: Demonstrates how to use the firebase_core plugin. +# The following line prevents the package from being accidentally published to +# pub.dev using `flutter pub publish`. This is preferred for private packages. +publish_to: 'none' # Remove this line if you wish to publish to pub.dev + +environment: + sdk: '>=2.19.2 <3.0.0' + +# Dependencies specify other packages that your package needs in order to work. +# To automatically upgrade your package dependencies to the latest versions +# consider running `flutter pub upgrade --major-versions`. Alternatively, +# dependencies can be manually updated by changing the version numbers below to +# the latest version available on pub.dev. To see which dependencies have newer +# versions available, run `flutter pub outdated`. +dependencies: + flutter: + sdk: flutter + + firebase_core: + # When depending on this package from a real application you should use: + # firebase_core: ^x.y.z + # See https://dart.dev/tools/pub/dependencies#version-constraints + # The example app is bundled with the plugin so we use a path dependency on + # the parent directory to use the current plugin's version. + path: ../ + + # The following adds the Cupertino Icons font to your application. + # Use with the CupertinoIcons class for iOS style icons. + cupertino_icons: ^1.0.2 + +dev_dependencies: + flutter_test: + sdk: flutter + + # The "flutter_lints" package below contains a set of recommended lints to + # encourage good coding practices. The lint set provided by the package is + # activated in the `analysis_options.yaml` file located at the root of your + # package. See that file for information about deactivating specific lint + # rules and activating additional ones. + flutter_lints: ^2.0.0 + +# For information on the generic Dart part of this file, see the +# following page: https://dart.dev/tools/pub/pubspec + +# The following section is specific to Flutter packages. +flutter: + + # The following line ensures that the Material Icons font is + # included with your application, so that you can use the icons in + # the material Icons class. + uses-material-design: true + + # To add assets to your application, add an assets section, like this: + # assets: + # - images/a_dot_burr.jpeg + # - images/a_dot_ham.jpeg + + # An image asset can refer to one or more resolution-specific "variants", see + # https://flutter.dev/assets-and-images/#resolution-aware + + # For details regarding adding assets from package dependencies, see + # https://flutter.dev/assets-and-images/#from-packages + + # To add custom fonts to your application, add a fonts section here, + # in this "flutter" section. Each entry in this list should have a + # "family" key with the font family name, and a "fonts" key with a + # list giving the asset and other descriptors for the font. For + # example: + # fonts: + # - family: Schyler + # fonts: + # - asset: fonts/Schyler-Regular.ttf + # - asset: fonts/Schyler-Italic.ttf + # style: italic + # - family: Trajan Pro + # fonts: + # - asset: fonts/TrajanPro.ttf + # - asset: fonts/TrajanPro_Bold.ttf + # weight: 700 + # + # For details regarding fonts from package dependencies, + # see https://flutter.dev/custom-fonts/#from-packages diff --git a/packages/firebase_core/firebase_core/firebase_core/example/test/widget_test.dart b/packages/firebase_core/firebase_core/firebase_core/example/test/widget_test.dart new file mode 100644 index 000000000000..d343f68407e8 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/test/widget_test.dart @@ -0,0 +1,27 @@ +// This is a basic Flutter widget test. +// +// To perform an interaction with a widget in your test, use the WidgetTester +// utility in the flutter_test package. For example, you can send tap and scroll +// gestures. You can also use WidgetTester to find child widgets in the widget +// tree, read text, and verify that the values of widget properties are correct. + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'package:firebase_core_example/main.dart'; + +void main() { + testWidgets('Verify Platform version', (WidgetTester tester) async { + // Build our app and trigger a frame. + await tester.pumpWidget(const MyApp()); + + // Verify that platform version is retrieved. + expect( + find.byWidgetPredicate( + (Widget widget) => widget is Text && + widget.data!.startsWith('Running on:'), + ), + findsOneWidget, + ); + }); +} diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/admob.h b/packages/firebase_core/firebase_core/firebase_core/firebase/admob.h new file mode 100644 index 000000000000..957c86b7e168 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/admob.h @@ -0,0 +1,215 @@ +/* + * Copyright 2016 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_H_ +#define FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_H_ + +#include "firebase/internal/platform.h" + +#if FIREBASE_PLATFORM_ANDROID +#include +#endif // FIREBASE_PLATFORM_ANDROID + +#include "firebase/admob/banner_view.h" +#include "firebase/admob/interstitial_ad.h" +#include "firebase/admob/rewarded_video.h" +#include "firebase/admob/types.h" +#include "firebase/app.h" +#include "firebase/internal/common.h" + +#if !defined(DOXYGEN) && !defined(SWIG) +FIREBASE_APP_REGISTER_CALLBACKS_REFERENCE(admob) +#endif // !defined(DOXYGEN) && !defined(SWIG) + +namespace firebase { + +/// @deprecated The functionality in the firebase::admob namespace +/// has been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the new +/// SDK in our migration guide. +/// +/// @brief API for AdMob with Firebase. +/// +/// The AdMob API allows you to load and display mobile ads using the Google +/// Mobile Ads SDK. Each ad format has its own header file. +namespace admob { + +/// @deprecated +/// @brief Initializes AdMob via Firebase. +/// +/// The functionality in the firebase::admob namespace has +/// been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the +/// new SDK in our migration +/// guide. +/// +/// @param app The Firebase app for which to initialize mobile ads. +/// +/// @return kInitResultSuccess if initialization succeeded, or +/// kInitResultFailedMissingDependency on Android if Google Play services is not +/// available on the current device and the Google Mobile Ads SDK requires +/// Google Play services (for example, when using 'play-services-ads-lite'). +FIREBASE_DEPRECATED InitResult Initialize(const ::firebase::App& app); + +/// @deprecated +/// @brief Initializes AdMob via Firebase with the publisher's AdMob app ID. +/// +/// The functionality in the firebase::admob namespace has +/// been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the +/// new SDK in our migration +/// guide. +/// +/// Initializing the Google Mobile Ads SDK with the AdMob app ID at app launch +/// allows the SDK to fetch app-level settings and perform configuration tasks +/// as early as possible. This can help reduce latency for the initial ad +/// request. AdMob app IDs are unique identifiers given to mobile apps when +/// they're registered in the AdMob console. To find your app ID in the AdMob +/// console, click the App management (https://apps.admob.com/#account/appmgmt:) +/// option under the settings dropdown (located in the upper right-hand corner). +/// App IDs have the form ca-app-pub-XXXXXXXXXXXXXXXX~NNNNNNNNNN. +/// +/// @param[in] app The Firebase app for which to initialize mobile ads. +/// @param[in] admob_app_id The publisher's AdMob app ID. +/// +/// @return kInitResultSuccess if initialization succeeded, or +/// kInitResultFailedMissingDependency on Android if Google Play services is not +/// available on the current device and the Google Mobile Ads SDK requires +/// Google Play services (for example, when using 'play-services-ads-lite'). +FIREBASE_DEPRECATED InitResult Initialize(const ::firebase::App& app, + const char* admob_app_id); + +#if FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) +/// @deprecated +/// @brief Initializes AdMob without Firebase for Android. +/// +/// The functionality in the firebase::admob namespace has +/// been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the +/// new SDK in our migration +/// guide. +/// +/// The arguments to @ref Initialize are platform-specific so the caller must do +/// something like this: +/// @code +/// #if defined(__ANDROID__) +/// firebase::admob::Initialize(jni_env, activity); +/// #else +/// firebase::admob::Initialize(); +/// #endif +/// @endcode +/// +/// @param[in] jni_env JNIEnv pointer. +/// @param[in] activity Activity used to start the application. +/// +/// @return kInitResultSuccess if initialization succeeded, or +/// kInitResultFailedMissingDependency on Android if Google Play services is not +/// available on the current device and the AdMob SDK requires +/// Google Play services (for example when using 'play-services-ads-lite'). +FIREBASE_DEPRECATED InitResult Initialize(JNIEnv* jni_env, jobject activity); + +/// @deprecated +/// @brief Initializes AdMob via Firebase with the publisher's AdMob app ID. +/// +/// The functionality in the firebase::admob namespace has +/// been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the +/// new SDK in our migration +/// guide. +/// +/// Initializing the Google Mobile Ads SDK with the AdMob app ID at app launch +/// allows the SDK to fetch app-level settings and perform configuration tasks +/// as early as possible. This can help reduce latency for the initial ad +/// request. AdMob app IDs are unique identifiers given to mobile apps when +/// they're registered in the AdMob console. To find your app ID in the AdMob +/// console, click the App management (https://apps.admob.com/#account/appmgmt:) +/// option under the settings dropdown (located in the upper right-hand corner). +/// App IDs have the form ca-app-pub-XXXXXXXXXXXXXXXX~NNNNNNNNNN. +/// +/// The arguments to @ref Initialize are platform-specific so the caller must do +/// something like this: +/// @code +/// #if defined(__ANDROID__) +/// firebase::admob::Initialize(jni_env, activity, admob_app_id); +/// #else +/// firebase::admob::Initialize(admob_app_id); +/// #endif +/// @endcode +/// +/// @param[in] jni_env JNIEnv pointer. +/// @param[in] activity Activity used to start the application. +/// @param[in] admob_app_id The publisher's AdMob app ID. +/// +/// @return kInitResultSuccess if initialization succeeded, or +/// kInitResultFailedMissingDependency on Android if Google Play services is not +/// available on the current device and the AdMob SDK requires +/// Google Play services (for example when using 'play-services-ads-lite'). +FIREBASE_DEPRECATED InitResult Initialize(JNIEnv* jni_env, jobject activity, + const char* admob_app_id); +#endif // defined(__ANDROID__) || defined(DOXYGEN) +#if !FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) +/// @deprecated +/// @brief Initializes AdMob without Firebase for iOS. +/// +/// The functionality in the firebase::admob namespace has +/// been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the +/// new SDK in our migration +/// guide. +FIREBASE_DEPRECATED InitResult Initialize(); + +/// @deprecated +/// @brief Initializes AdMob with the publisher's AdMob app ID and without +/// Firebase for iOS. +/// +/// The functionality in the firebase::admob namespace has +/// been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the +/// new SDK in our migration +/// guide. +/// +/// Initializing the Google Mobile Ads SDK with the AdMob app ID at app launch +/// allows the SDK to fetch app-level settings and perform configuration tasks +/// as early as possible. This can help reduce latency for the initial ad +/// request. AdMob app IDs are unique identifiers given to mobile apps when +/// they're registered in the AdMob console. To find your app ID in the AdMob +/// console, click the App management (https://apps.admob.com/#account/appmgmt:) +/// option under the settings dropdown (located in the upper right-hand corner). +/// App IDs have the form ca-app-pub-XXXXXXXXXXXXXXXX~NNNNNNNNNN. +/// +/// @param[in] admob_app_id The publisher's AdMob app ID. +/// +/// @return kInitResultSuccess if initialization succeeded +FIREBASE_DEPRECATED InitResult Initialize(const char* admob_app_id); +#endif // !defined(__ANDROID__) || defined(DOXYGEN) + +/// @deprecated +/// @brief Terminate AdMob. +/// +/// The functionality in the firebase::admob namespace has +/// been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the +/// new SDK in our migration +/// guide. +/// +/// Frees resources associated with AdMob that were allocated during +/// @ref firebase::admob::Initialize(). +FIREBASE_DEPRECATED void Terminate(); + +} // namespace admob +} // namespace firebase + +#endif // FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/admob/banner_view.h b/packages/firebase_core/firebase_core/firebase_core/firebase/admob/banner_view.h new file mode 100644 index 000000000000..2d691f2d3a77 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/admob/banner_view.h @@ -0,0 +1,427 @@ +/* + * Copyright 2016 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_BANNER_VIEW_H_ +#define FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_BANNER_VIEW_H_ + +#include "firebase/admob/types.h" +#include "firebase/future.h" +#include "firebase/internal/common.h" + +namespace firebase { +namespace admob { + +namespace internal { +// Forward declaration for platform-specific data, implemented in each library. +class BannerViewInternal; +} // namespace internal + +/// @deprecated The functionality in the firebase::admob namespace +/// has been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the new +/// SDK in our migration guide. +/// +/// @brief Loads and displays AdMob banner ads. +/// +/// Each BannerView object corresponds to a single AdMob banner placement. There +/// are methods to load an ad, move it, show it and hide it, and retrieve the +/// bounds of the ad onscreen. +/// +/// BannerView objects maintain a presentation state that indicates whether +/// or not they're currently onscreen, as well as a set of bounds (stored in a +/// @ref BoundingBox struct), but otherwise provide information about +/// their current state through Futures. Methods like @ref Initialize, +/// @ref LoadAd, and @ref Hide each have a corresponding @ref Future from which +/// the result of the last call can be determined. The two variants of +/// @ref MoveTo share a single result @ref Future, since they're essentially the +/// same action. +/// +/// In addition, applications can create their own subclasses of +/// @ref BannerView::Listener, pass an instance to the @ref SetListener method, +/// and receive callbacks whenever the presentation state or bounding box of the +/// ad changes. +/// +/// For example, you could initialize, load, and show a banner view while +/// checking the result of the previous action at each step as follows: +/// +/// @code +/// namespace admob = ::firebase::admob; +/// admob::BannerView* banner_view = new admob::BannerView(); +/// banner_view->Initialize(ad_parent, "YOUR_AD_UNIT_ID", desired_ad_size) +/// @endcode +/// +/// Then, later: +/// +/// @code +/// if (banner_view->InitializeLastResult().status() == +/// ::firebase::kFutureStatusComplete && +/// banner_view->InitializeLastResult().error() == +/// firebase::admob::kAdMobErrorNone) { +/// banner_view->LoadAd(your_ad_request); +/// } +/// @endcode +/// +class BannerView { + public: +#ifdef INTERNAL_EXPERIMENTAL +// LINT.IfChange +#endif // INTERNAL_EXPERIMENTAL + /// @deprecated + /// @brief The presentation state of a @ref BannerView. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + enum PresentationState { + /// BannerView is currently hidden. + kPresentationStateHidden = 0, + /// BannerView is visible, but does not contain an ad. + kPresentationStateVisibleWithoutAd, + /// BannerView is visible and contains an ad. + kPresentationStateVisibleWithAd, + /// BannerView is visible and has opened a partial overlay on the screen. + kPresentationStateOpenedPartialOverlay, + /// BannerView is completely covering the screen or has caused focus to + /// leave the application (for example, when opening an external browser + /// during a clickthrough). + kPresentationStateCoveringUI, + }; +#ifdef INTERNAL_EXPERIMENTAL +// LINT.ThenChange(//depot_firebase_cpp/admob/client/cpp/src_java/com/google/firebase/admob/internal/cpp/ConstantsHelper.java) +#endif // INTERNAL_EXPERIMENTAL + +#ifdef INTERNAL_EXPERIMENTAL +// LINT.IfChange +#endif // INTERNAL_EXPERIMENTAL + /// @deprecated + /// @brief The possible screen positions for a @ref BannerView. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + enum Position { + /// Top of the screen, horizontally centered. + kPositionTop = 0, + /// Bottom of the screen, horizontally centered. + kPositionBottom, + /// Top-left corner of the screen. + kPositionTopLeft, + /// Top-right corner of the screen. + kPositionTopRight, + /// Bottom-left corner of the screen. + kPositionBottomLeft, + /// Bottom-right corner of the screen. + kPositionBottomRight, + }; +#ifdef INTERNAL_EXPERIMENTAL +// LINT.ThenChange(//depot_firebase_cpp/admob/client/cpp/src_java/com/google/firebase/admob/internal/cpp/ConstantsHelper.java) +#endif // INTERNAL_EXPERIMENTAL + + /// @deprecated + /// @brief A listener class that developers can extend and pass to a @ref + /// BannerView object's @ref SetListener method to be notified of changes to + /// the presentation state and bounding box. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + class Listener { + public: + /// @deprecated + /// @brief This method is called when the @ref BannerView object's + /// presentation state changes. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + /// @param[in] banner_view The banner view whose presentation state changed. + /// @param[in] state The new presentation state. + virtual void OnPresentationStateChanged(BannerView* banner_view, + PresentationState state) = 0; + /// @deprecated + /// @brief This method is called when the @ref BannerView object's bounding + /// box changes. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + /// @param[in] banner_view The banner view whose bounding box changed. + /// @param[in] box The new bounding box. + virtual void OnBoundingBoxChanged(BannerView* banner_view, + BoundingBox box) = 0; + virtual ~Listener(); + }; + + /// @deprecated + /// @brief Creates an uninitialized @ref BannerView object. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + /// + /// @ref Initialize must be called before the object is used. + FIREBASE_DEPRECATED BannerView(); + + ~BannerView(); + + /// @deprecated + /// @brief Initializes the @ref BannerView object. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + /// @param[in] parent The platform-specific UI element that will host the ad. + /// @param[in] ad_unit_id The ad unit ID to use when requesting ads. + /// @param[in] size The desired ad size for the banner. + FIREBASE_DEPRECATED Future Initialize(AdParent parent, + const char* ad_unit_id, + AdSize size); + + /// @deprecated + /// @brief Returns a @ref Future that has the status of the last call to + /// @ref Initialize. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + FIREBASE_DEPRECATED Future InitializeLastResult() const; + + /// @deprecated + /// @brief Begins an asynchronous request for an ad. If successful, the ad + /// will automatically be displayed in the BannerView. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + /// @param[in] request An AdRequest struct with information about the request + /// to be made (such as targeting info). + FIREBASE_DEPRECATED Future LoadAd(const AdRequest& request); + + /// @deprecated + /// @brief Returns a @ref Future containing the status of the last call to + /// @ref LoadAd. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + FIREBASE_DEPRECATED Future LoadAdLastResult() const; + + /// @deprecated + /// @brief Hides the BannerView. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + FIREBASE_DEPRECATED Future Hide(); + + /// @deprecated + /// @brief Returns a @ref Future containing the status of the last call to + /// @ref Hide. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + FIREBASE_DEPRECATED Future HideLastResult() const; + + /// @deprecated + /// @brief Shows the @ref BannerView. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + FIREBASE_DEPRECATED Future Show(); + + /// @deprecated + /// @brief Returns a @ref Future containing the status of the last call to + /// @ref Show. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + FIREBASE_DEPRECATED Future ShowLastResult() const; + + /// @deprecated + /// @brief Pauses the @ref BannerView. Should be called whenever the C++ + /// engine pauses or the application loses focus. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + FIREBASE_DEPRECATED Future Pause(); + + /// @deprecated + /// @brief Returns a @ref Future containing the status of the last call to + /// @ref Pause. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + FIREBASE_DEPRECATED Future PauseLastResult() const; + + /// @deprecated + /// @brief Resumes the @ref BannerView after pausing. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + FIREBASE_DEPRECATED Future Resume(); + + /// @deprecated + /// @brief Returns a @ref Future containing the status of the last call to + /// @ref Resume. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + FIREBASE_DEPRECATED Future ResumeLastResult() const; + + /// @deprecated + /// @brief Cleans up and deallocates any resources used by the @ref + /// BannerView. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + FIREBASE_DEPRECATED Future Destroy(); + + /// @deprecated + /// @brief Returns a @ref Future containing the status of the last call to + /// @ref Destroy. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + FIREBASE_DEPRECATED Future DestroyLastResult() const; + + /// @deprecated + /// @brief Moves the @ref BannerView so that its top-left corner is located at + /// (x, y). Coordinates are in pixels from the top-left corner of the screen. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + /// @param[in] x The desired horizontal coordinate. + /// @param[in] y The desired vertical coordinate. + FIREBASE_DEPRECATED Future MoveTo(int x, int y); + + /// @deprecated + /// @brief Moves the @ref BannerView so that it's located at the given + /// pre-defined position. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + /// @param[in] position The pre-defined position to which to move the + /// @ref BannerView. + FIREBASE_DEPRECATED Future MoveTo(Position position); + + /// @deprecated + /// @brief Returns a @ref Future containing the status of the last call to + /// either version of @ref MoveTo. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + FIREBASE_DEPRECATED Future MoveToLastResult() const; + + /// @deprecated + /// @brief Returns the current presentation state of the @ref BannerView. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + /// @return The current presentation state. + FIREBASE_DEPRECATED PresentationState presentation_state() const; + + /// @deprecated + /// @brief Retrieves the @ref BannerView's current onscreen size and location. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + FIREBASE_DEPRECATED BoundingBox bounding_box() const; + + /// @deprecated + /// @brief Sets the @ref Listener for this object. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + /// @param[in] listener A valid BannerView::Listener to receive callbacks. + FIREBASE_DEPRECATED void SetListener(Listener* listener); + + private: + // An internal, platform-specific implementation object that this class uses + // to interact with the Google Mobile Ads SDKs for iOS and Android. + internal::BannerViewInternal* internal_; +}; + +} // namespace admob +} // namespace firebase + +#endif // FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_BANNER_VIEW_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/admob/interstitial_ad.h b/packages/firebase_core/firebase_core/firebase_core/firebase/admob/interstitial_ad.h new file mode 100644 index 000000000000..b201ab7c3487 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/admob/interstitial_ad.h @@ -0,0 +1,259 @@ +/* + * Copyright 2016 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_INTERSTITIAL_AD_H_ +#define FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_INTERSTITIAL_AD_H_ + +#include "firebase/admob/types.h" +#include "firebase/future.h" +#include "firebase/internal/common.h" + +namespace firebase { +namespace admob { + +namespace internal { +// Forward declaration for platform-specific data, implemented in each library. +class InterstitialAdInternal; +} // namespace internal + +/// @deprecated The functionality in the firebase::admob namespace +/// has been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the new +/// SDK in our migration guide. +/// +/// @brief Loads and displays AdMob interstitial ads. +/// +/// @ref InterstitialAd is a single-use object that can load and show a +/// single AdMob interstitial ad. +/// +/// InterstitialAd objects maintain a presentation state that indicates whether +/// or not they're currently onscreen, but otherwise provide information about +/// their current state through Futures. @ref Initialize, @ref LoadAd, and +/// @ref Show each have a corresponding @ref Future from which you can determine +/// result of the previous call. +/// +/// In addition, applications can create their own subclasses of +/// @ref InterstitialAd::Listener, pass an instance to the @ref SetListener +/// method, and receive callbacks whenever the presentation state changes. +/// +/// Here's how one might initialize, load, and show an interstitial ad while +/// checking against the result of the previous action at each step: +/// +/// @code +/// namespace admob = ::firebase::admob; +/// admob::InterstitialAd* interstitial = new admob::InterstitialAd(); +/// interstitial->Initialize(ad_parent, "YOUR_AD_UNIT_ID") +/// @endcode +/// +/// Then, later: +/// +/// @code +/// if (interstitial->InitializeLastResult().status() == +/// ::firebase::kFutureStatusComplete && +/// interstitial->InitializeLastResult().error() == +/// firebase::admob::kAdMobErrorNone) { +/// interstitial->LoadAd(my_ad_request); +/// } +/// @endcode +/// +/// And after that: +/// +/// @code +/// if (interstitial->LoadAdLastResult().status() == +/// ::firebase::kFutureStatusComplete && +/// interstitial->LoadAdLastResult().error() == +/// firebase::admob::kAdMobErrorNone)) { +/// interstitial->Show(); +/// } +/// @endcode +/// +class InterstitialAd { + public: +#ifdef INTERNAL_EXPERIMENTAL +// LINT.IfChange +#endif // INTERNAL_EXPERIMENTAL + /// @deprecated + /// @brief The presentation states of an @ref InterstitialAd. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + enum PresentationState { + /// InterstitialAd is not currently being shown. + kPresentationStateHidden = 0, + /// InterstitialAd is being shown or has caused focus to leave the + /// application (for example, when opening an external browser during a + /// clickthrough). + kPresentationStateCoveringUI, + }; +#ifdef INTERNAL_EXPERIMENTAL +// LINT.ThenChange(//depot_firebase_cpp/admob/client/cpp/src_java/com/google/firebase/admob/internal/cpp/InterstitialAdHelper.java) +#endif // INTERNAL_EXPERIMENTAL + + /// @deprecated + /// @brief A listener class that developers can extend and pass to an + /// @ref InterstitialAd object's @ref SetListener method to be notified of + /// presentation state changes. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + /// @param[in] interstitial_ad The interstitial ad whose presentation state + /// changed. + /// @param[in] state The new presentation state. + virtual void OnPresentationStateChanged(InterstitialAd* interstitial_ad, + PresentationState state) = 0; + virtual ~Listener(); + }; + + /// @deprecated + /// @brief Creates an uninitialized @ref InterstitialAd object. + /// @ref Initialize must be called before the object is used. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + FIREBASE_DEPRECATED InterstitialAd(); + + ~InterstitialAd(); + + /// @deprecated + /// @brief Initialize the @ref InterstitialAd object. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + /// @param[in] parent The platform-specific UI element that will host the ad. + /// @param[in] ad_unit_id The ad unit ID to use in loading the ad. + FIREBASE_DEPRECATED Future Initialize(AdParent parent, + const char* ad_unit_id); + + /// @deprecated + /// @brief Returns a @ref Future containing the status of the last call to + /// @ref Initialize. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + FIREBASE_DEPRECATED Future InitializeLastResult() const; + + /// @deprecated + /// @brief Begins an asynchronous request for an ad. + /// + /// The @ref InterstitialAd::presentation_state method can be used to track + /// the progress of the request. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + /// @param[in] request An AdRequest struct with information about the request + /// to be made (such as targeting info). + FIREBASE_DEPRECATED Future LoadAd(const AdRequest& request); + + /// @deprecated + /// @brief Returns a @ref Future containing the status of the last call to + /// @ref LoadAd. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + FIREBASE_DEPRECATED Future LoadAdLastResult() const; + + /// @deprecated + /// @brief Shows the @ref InterstitialAd. This should not be called unless an + /// ad has already been loaded. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + FIREBASE_DEPRECATED Future Show(); + + /// @deprecated + /// @brief Returns a @ref Future containing the status of the last call to + /// @ref Show. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + FIREBASE_DEPRECATED Future ShowLastResult() const; + + /// @deprecated + /// @brief Returns the current presentation state of the @ref InterstitialAd. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + /// @return The current presentation state. + FIREBASE_DEPRECATED PresentationState presentation_state() const; + + /// @deprecated + /// @brief Sets the @ref Listener for this @ref InterstitialAd. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + /// @param[in] listener A valid InterstititalAd::Listener to receive + /// callbacks. + FIREBASE_DEPRECATED void SetListener(Listener* listener); + + private: + // An internal, platform-specific implementation object that this class uses + // to interact with the Google Mobile Ads SDKs for iOS and Android. + internal::InterstitialAdInternal* internal_; +}; + +} // namespace admob +} // namespace firebase + +#endif // FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_INTERSTITIAL_AD_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/admob/native_express_ad_view.h b/packages/firebase_core/firebase_core/firebase_core/firebase/admob/native_express_ad_view.h new file mode 100644 index 000000000000..7e571967825e --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/admob/native_express_ad_view.h @@ -0,0 +1,446 @@ +/* + * Copyright 2016 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_NATIVE_EXPRESS_AD_VIEW_H_ +#define FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_NATIVE_EXPRESS_AD_VIEW_H_ + +#include "firebase/admob/types.h" +#include "firebase/future.h" +#include "firebase/internal/common.h" + +namespace firebase { +namespace admob { + +namespace internal { +// Forward declaration for platform-specific data, implemented in each library. +class NativeExpressAdViewInternal; +} // namespace internal + +/// @deprecated The functionality in the firebase::admob namespace +/// has been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the new +/// SDK in our migration guide. +/// Native Express Ads has been discontinued, and are no longer served. +/// +/// @brief Loads and displays ads from AdMob Native Ads Express. +/// +/// Each NativeExpressAdView object corresponds to a single AdMob Native Express +/// ad placement. There are methods to load an ad, move it, show it and hide it, +/// and retrieve the bounds of the ad onscreen. +/// +/// NativeExpressAdView objects maintain a presentation state that indicates +/// whether or not they're currently onscreen, as well as a set of bounds +/// (stored in a @ref BoundingBox struct), but otherwise provide information +/// about their current state through Futures. Methods like @ref Initialize, +/// @ref LoadAd, and @ref Hide each have a corresponding @ref Future from which +/// the result of the last call can be determined. The two variants of +/// @ref MoveTo share a single result @ref Future, since they're essentially the +/// same action. +/// +/// In addition, applications can create their own subclasses of +/// @ref NativeExpressAdView::Listener, pass an instance to the @ref SetListener +/// method, and receive callbacks whenever the presentation state or bounding +/// box of the ad changes. +/// +/// For example, you could initialize, load, and show a native express ad view +/// while checking the result of the previous action at each step as follows: +/// +/// @code +/// namespace admob = ::firebase::admob; +/// admob::NativeExpressAdView* ad_view = new admob::NativeExpressAdView(); +/// ad_view->Initialize(ad_parent, "YOUR_AD_UNIT_ID", desired_ad_size) +/// @endcode +/// +/// Then, later: +/// +/// @code +/// if (ad_view->InitializeLastResult().Status() == +/// ::firebase::kFutureStatusComplete && +/// ad_view->InitializeLastResult().Error() == +/// firebase::admob::kAdMobErrorNone) { +/// ad_view->LoadAd(your_ad_request); +/// } +/// @endcode +class NativeExpressAdView { + public: +#ifdef INTERNAL_EXPERIMENTAL +// LINT.IfChange +#endif // INTERNAL_EXPERIMENTAL + /// @deprecated + /// @brief The presentation state of a @ref NativeExpressAdView. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + enum PresentationState { + /// NativeExpressAdView is currently hidden. + kPresentationStateHidden = 0, + /// NativeExpressAdView is visible, but does not contain an ad. + kPresentationStateVisibleWithoutAd, + /// NativeExpressAdView is visible and contains an ad. + kPresentationStateVisibleWithAd, + /// NativeExpressAdView is visible and has opened a partial overlay on the + /// screen. + kPresentationStateOpenedPartialOverlay, + /// NativeExpressAdView is completely covering the screen or has caused + /// focus to leave the application (for example, when opening an external + /// browser during a clickthrough). + kPresentationStateCoveringUI, + }; +#ifdef INTERNAL_EXPERIMENTAL +// LINT.ThenChange(//depot_firebase_cpp/admob/client/cpp/src_java/com/google/firebase/admob/internal/cpp/ConstantsHelper.java) +#endif // INTERNAL_EXPERIMENTAL + +#ifdef INTERNAL_EXPERIMENTAL +// LINT.IfChange +#endif // INTERNAL_EXPERIMENTAL + /// @deprecated + /// @brief The possible screen positions for a @ref NativeExpressAdView. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + enum Position { + /// Top of the screen, horizontally centered. + kPositionTop = 0, + /// Bottom of the screen, horizontally centered. + kPositionBottom, + /// Top-left corner of the screen. + kPositionTopLeft, + /// Top-right corner of the screen. + kPositionTopRight, + /// Bottom-left corner of the screen. + kPositionBottomLeft, + /// Bottom-right corner of the screen. + kPositionBottomRight, + }; +#ifdef INTERNAL_EXPERIMENTAL +// LINT.ThenChange(//depot_firebase_cpp/admob/client/cpp/src_java/com/google/firebase/admob/internal/cpp/ConstantsHelper.java) +#endif // INTERNAL_EXPERIMENTAL + + /// @deprecated + /// @brief A listener class that developers can extend and pass to a + /// @ref NativeExpressAdView object's @ref SetListener method to be notified + /// of changes to the presentation state and bounding box. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + class Listener { + public: + /// @deprecated + /// @brief This method is called when the @ref NativeExpressAdView object's + /// presentation state changes. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + /// @param[in] ad_view The native express ad view whose presentation state + /// changed. + /// @param[in] state The new presentation state. + FIREBASE_DEPRECATED virtual void OnPresentationStateChanged( + NativeExpressAdView* ad_view, PresentationState state) = 0; + + /// @deprecated + /// @brief This method is called when the @ref NativeExpressAdView object's + /// bounding box changes. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + /// + /// @ref Initialize must be called before the object is used. + FIREBASE_DEPRECATED NativeExpressAdView(); + + ~NativeExpressAdView(); + + /// @deprecated + /// @brief Initializes the @ref NativeExpressAdView object. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + /// @param[in] parent The platform-specific UI element that will host the ad. + /// @param[in] ad_unit_id The ad unit ID to use when requesting ads. + /// @param[in] size The desired ad size for the native express ad. + FIREBASE_DEPRECATED Future Initialize(AdParent parent, + const char* ad_unit_id, + AdSize size); + + /// @deprecated + /// @brief Returns a @ref Future that has the status of the last call to + /// @ref Initialize. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + FIREBASE_DEPRECATED Future InitializeLastResult() const; + + /// @deprecated + /// @brief Begins an asynchronous request for an ad. If successful, the ad + /// will automatically be displayed in the NativeExpressAdView. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + /// @param[in] request An AdRequest struct with information about the request + /// to be made (such as targeting info). + FIREBASE_DEPRECATED Future LoadAd(const AdRequest& request); + + /// @deprecated + /// @brief Returns a @ref Future containing the status of the last call to + /// @ref LoadAd. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + FIREBASE_DEPRECATED Future LoadAdLastResult() const; + + /// @deprecated + /// @brief Hides the NativeExpressAdView. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + FIREBASE_DEPRECATED Future Hide(); + + /// @deprecated + /// @brief Returns a @ref Future containing the status of the last call to + /// @ref Hide. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + FIREBASE_DEPRECATED Future HideLastResult() const; + + /// @deprecated + /// @brief Shows the @ref NativeExpressAdView. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + FIREBASE_DEPRECATED Future Show(); + + /// @deprecated + /// @brief Returns a @ref Future containing the status of the last call to + /// @ref Show. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + FIREBASE_DEPRECATED Future ShowLastResult() const; + + /// @deprecated + /// @brief Pauses the @ref NativeExpressAdView. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + /// + /// Should be called whenever the C++ engine pauses or the application loses + /// focus. + FIREBASE_DEPRECATED Future Pause(); + + /// @deprecated + /// @brief Returns a @ref Future containing the status of the last call to + /// @ref Pause. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + FIREBASE_DEPRECATED Future PauseLastResult() const; + + /// @deprecated + /// @brief Resumes the @ref NativeExpressAdView after pausing. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + FIREBASE_DEPRECATED Future Resume(); + + /// @deprecated + /// @brief Returns a @ref Future containing the status of the last call to + /// @ref Resume. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + FIREBASE_DEPRECATED Future ResumeLastResult() const; + + /// @deprecated + /// @brief Cleans up and deallocates any resources used by the + /// @ref NativeExpressAdView. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + FIREBASE_DEPRECATED Future Destroy(); + + /// @deprecated + /// @brief Returns a @ref Future containing the status of the last call to + /// @ref Destroy. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + FIREBASE_DEPRECATED Future DestroyLastResult() const; + + /// @deprecated + /// @brief Moves the @ref NativeExpressAdView so that its top-left corner is + /// located at (x, y). Coordinates are in pixels from the top-left corner of + /// the screen. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + /// + /// When built for Android, the library will not display an ad on top of or + /// beneath an Activity's status bar. If a call to MoveTo would result in an + /// overlap, the @ref NativeExpressAdView is placed just below the status bar, + /// so no overlap occurs. + /// @param[in] x The desired horizontal coordinate. + /// @param[in] y The desired vertical coordinate. + FIREBASE_DEPRECATED Future MoveTo(int x, int y); + + /// @deprecated + /// @brief Moves the @ref NativeExpressAdView so that it's located at the + /// given pre-defined position. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + /// @param[in] position The pre-defined position to which to move the + /// @ref NativeExpressAdView. + FIREBASE_DEPRECATED Future MoveTo(Position position); + + /// @deprecated + /// @brief Returns a @ref Future containing the status of the last call to + /// either version of @ref MoveTo. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + FIREBASE_DEPRECATED Future MoveToLastResult() const; + + /// @deprecated + /// @brief Returns the current presentation state of the + /// @ref NativeExpressAdView. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + /// @return The current presentation state. + FIREBASE_DEPRECATED PresentationState GetPresentationState() const; + + /// @deprecated + /// @brief Retrieves the @ref NativeExpressAdView's current onscreen size and + /// location. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + /// @return The current size and location. Values are in pixels, and location + /// coordinates originate from the top-left corner of the screen. + FIREBASE_DEPRECATED BoundingBox GetBoundingBox() const; + + /// @deprecated + /// @brief Sets the @ref Listener for this object. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + /// @param[in] listener A valid NativeExpressAdView::Listener to receive + /// callbacks. + FIREBASE_DEPRECATED void SetListener(Listener* listener); + + private: + // An internal, platform-specific implementation object that this class uses + // to interact with the Google Mobile Ads SDKs for iOS and Android. + internal::NativeExpressAdViewInternal* internal_; +}; + +} // namespace admob +} // namespace firebase + +#endif // FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_NATIVE_EXPRESS_AD_VIEW_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/admob/rewarded_video.h b/packages/firebase_core/firebase_core/firebase_core/firebase/admob/rewarded_video.h new file mode 100644 index 000000000000..32bea80b5550 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/admob/rewarded_video.h @@ -0,0 +1,407 @@ +/* + * Copyright 2016 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_REWARDED_VIDEO_H_ +#define FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_REWARDED_VIDEO_H_ + +#include +#include + +#include "firebase/admob/types.h" +#include "firebase/future.h" + +namespace firebase { + +// Forward declaration of Firebase's internal Mutex. +class Mutex; + +namespace admob { + +/// @deprecated The functionality in the firebase::admob namespace +/// has been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the new +/// SDK in our migration guide. +/// +/// @brief Loads and displays rewarded video ads via AdMob mediation. +/// +/// The rewarded_video namespace contains methods to load and display rewarded +/// video ads via the Google Mobile Ads SDK. The underlying SDK objects for +/// rewarded video on Android and iOS are singletons, so there are no objects +/// to represent individual ads here. Instead, methods in the rewarded_video +/// namespace are invoked to initialize, load, and show. +/// +/// The basic steps for loading and displaying an ad are: +/// +/// 1. Call @ref Initialize to init the library and mediation adapters. +/// 2. Call @ref LoadAd to load an ad (some SDKs may have cached an ad at init +/// time). +/// 3. Call @ref Show to show the ad to the user. +/// 4. Repeat steps 2 and 3 as desired. +/// 5. Call @ref Destroy when your app is completely finished showing rewarded +/// video ads. +/// +/// Note that Initialize must be the very first thing called, and @ref Destroy +/// must be the very last. +/// +/// The library maintains a presentation state that indicates whether or not an +/// ad is currently onscreen, but otherwise provides information about its +/// current state through Futures. @ref Initialize, @ref LoadAd, and so on each +/// have a corresponding @ref Future from which apps can determine the result of +/// the previous call. +/// +/// In addition, applications can create their own subclasses of @ref Listener, +/// pass an instance to the @ref SetListener method, and receive callbacks +/// whenever the presentation state changes or an ad has been viewed in full and +/// the user is due a reward. +/// +/// Here's how one might initialize, load, and show a rewarded video ad while +/// checking against the result of the previous action at each step: +/// +/// @code +/// firebase::admob::rewarded_video::Initialize(); +/// @endcode +/// +/// Then, later: +/// +/// @code +/// if (firebase::admob::rewarded_video::InitializeLastResult().status() == +/// firebase::kFutureStatusComplete && +/// firebase::admob::rewarded_video::InitializeLastResult().error() == +/// firebase::admob::kAdMobErrorNone) { +/// firebase::admob::rewarded_video::LoadAd(my_ad_unit_str, my_ad_request); +/// } +/// @endcode +/// +/// And after that: +/// +/// @code +/// if (firebase::admob::rewarded_video::LoadAdLastResult().status() == +/// firebase::kFutureStatusComplete && +/// firebase::admob::rewarded_video::LoadAdLastResult().error() == +/// firebase::admob::kAdMobErrorNone) { +/// firebase::admob::rewarded_video::Show(my_ad_parent); +/// } +/// @endcode +namespace rewarded_video { +#ifdef INTERNAL_EXPERIMENTAL +// LINT.IfChange +#endif // INTERNAL_EXPERIMENTAL +/// @deprecated +/// @brief The possible presentation states for rewarded video. +/// +/// The functionality in the firebase::admob namespace has +/// been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the +/// new SDK in our migration +/// guide. +enum PresentationState { + /// No ad is currently being shown. + kPresentationStateHidden = 0, + /// A rewarded video ad is completely covering the screen or has caused + /// focus to leave the application (for example, when opening an external + /// browser during a clickthrough), but the video associated with the ad has + /// yet to begin playing. + kPresentationStateCoveringUI, + /// All of the above conditions are true *except* that the video associated + /// with the ad began playing at some point in the past. + kPresentationStateVideoHasStarted, + /// The rewarded video has played and completed. + kPresentationStateVideoHasCompleted, +}; +#ifdef INTERNAL_EXPERIMENTAL +// LINT.ThenChange(//depot_firebase_cpp/admob/client/cpp/src_java/com/google/firebase/admob/internal/cpp/RewardedVideoHelper.java) +#endif // INTERNAL_EXPERIMENTAL + +/// @deprecated +/// @brief A reward to be given to the user in exchange for watching a rewarded +/// video ad. +/// +/// The functionality in the firebase::admob namespace has +/// been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the +/// new SDK in our migration +/// guide. +struct RewardItem { + /// The reward amount. + float amount; + /// A string description of the type of reward (such as "coins" or "points"). + std::string reward_type; +}; + +/// @deprecated +/// @brief A listener class that developers can extend and pass to @ref +/// SetListener to be notified of rewards and changes to the presentation state. +/// +/// The functionality in the firebase::admob namespace has +/// been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the +/// new SDK in our migration +/// guide. +class Listener { + public: + /// @deprecated + /// @brief Invoked when the user should be given a reward for watching an ad. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + /// @param[in] reward The user's reward. + FIREBASE_DEPRECATED virtual void OnRewarded(RewardItem reward) = 0; + + /// @deprecated + /// @brief Invoked when the presentation state of the ad changes. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + /// @param[in] state The new presentation state. + FIREBASE_DEPRECATED virtual void OnPresentationStateChanged( + PresentationState state) = 0; + + virtual ~Listener(); +}; + +/// @deprecated +/// @brief A polling-based listener that developers can instantiate and pass to +/// @ref SetListener in order to queue rewards for later retrieval. +/// +/// The functionality in the firebase::admob namespace has +/// been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the +/// new SDK in our migration +/// guide. +/// +/// The @ref PollReward method should be used to retrieve awards granted by the +/// Mobile Ads SDK and queued by this class. +/// @ref rewarded_video::presentation_state can be used to poll the current +/// presentation state, so no additional method has been added for it. +class PollableRewardListener : public Listener { + public: + /// @deprecated + /// @brief Default constructor. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + FIREBASE_DEPRECATED PollableRewardListener(); + ~PollableRewardListener(); + + /// @deprecated + /// @brief Invoked when the user should be given a reward for watching an ad. + /// + /// Deprecated. The functionality in the firebase::admob + /// namespace has been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the new + /// SDK in our migration + /// guide. + FIREBASE_DEPRECATED void OnRewarded(RewardItem reward); + + /// @deprecated + /// @brief nvoked when the presentation state of the ad changes. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + FIREBASE_DEPRECATED void OnPresentationStateChanged(PresentationState state); + + /// @deprecated + /// @brief Pop the oldest queued reward, and copy its data into the provided + /// RewardItem. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + /// + /// If no reward is available, the struct is unchanged. + /// @param reward Pointer to a struct that reward data can be copied into. + /// @returns true if a reward was popped and data was copied, false otherwise. + FIREBASE_DEPRECATED bool PollReward(RewardItem* reward); + + private: + Mutex* mutex_; + + // Rewards granted by the Mobile Ads SDK. + std::queue rewards_; +}; + +/// @deprecated +/// @brief Initializes rewarded video. This must be the first method invoked in +/// this namespace. +/// +/// The functionality in the firebase::admob namespace has +/// been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the +/// new SDK in our migration +/// guide. +FIREBASE_DEPRECATED Future Initialize(); + +/// @deprecated +/// @brief Returns a @ref Future that has the status of the last call to +/// @ref Initialize. +/// +/// The functionality in the firebase::admob namespace has +/// been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the +/// new SDK in our migration +/// guide. +FIREBASE_DEPRECATED Future InitializeLastResult(); + +/// @deprecated +/// @brief Begins an asynchronous request for an ad. +/// +/// The functionality in the firebase::admob namespace has +/// been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the +/// new SDK in our migration +/// guide. +/// @param[in] ad_unit_id The ad unit ID to use in the request. +/// @param[in] request An AdRequest struct with information about the request +/// to be made (such as targeting info). +FIREBASE_DEPRECATED Future LoadAd(const char* ad_unit_id, + const AdRequest& request); + +/// @deprecated +/// @brief Returns a @ref Future containing the status of the last call to +/// @ref LoadAd. +/// +/// The functionality in the firebase::admob namespace has +/// been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the +/// new SDK in our migration +/// guide. +FIREBASE_DEPRECATED Future LoadAdLastResult(); + +/// @deprecated +/// @brief Shows an ad, assuming one has loaded. +/// +/// The functionality in the firebase::admob namespace has +/// been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the +/// new SDK in our migration +/// guide. +/// +/// @ref LoadAd must be called before this method. +/// @param[in] parent An @ref AdParent that is a reference to an iOS +/// UIView or an Android Activity. +FIREBASE_DEPRECATED Future Show(AdParent parent); + +/// @deprecated +/// @brief Returns a @ref Future containing the status of the last call to +/// @ref Show. +/// +/// Deprecated. The functionality in the firebase::admob +/// namespace has been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the new +/// SDK in our migration +/// guide. +FIREBASE_DEPRECATED Future ShowLastResult(); + +/// @deprecated +/// @brief Pauses any background processing associated with rewarded video. +/// +/// The functionality in the firebase::admob namespace has +/// been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the +/// new SDK in our migration +/// guide. +/// +/// Should be called whenever the C++ engine pauses or the application loses +/// focus. +FIREBASE_DEPRECATED Future Pause(); + +/// @deprecated +/// @brief Returns a @ref Future containing the status of the last call to +/// @ref Pause. +/// +/// The functionality in the firebase::admob namespace has +/// been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the +/// new SDK in our migration +/// guide. +FIREBASE_DEPRECATED Future PauseLastResult(); + +/// @deprecated +/// @brief Resumes the rewarded video system after pausing. +/// +/// The functionality in the firebase::admob namespace has +/// been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the +/// new SDK in our migration +/// guide. +FIREBASE_DEPRECATED Future Resume(); + +/// @deprecated +/// @brief Returns a @ref Future containing the status of the last call to +/// @ref Resume. +/// +/// The functionality in the firebase::admob namespace has +/// been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the +/// new SDK in our migration +/// guide. +FIREBASE_DEPRECATED Future ResumeLastResult(); + +/// @deprecated +/// @brief Cleans up and deallocates any resources used by rewarded video. +/// +/// The functionality in the firebase::admob namespace has +/// been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the +/// new SDK in our migration +/// guide. +/// +/// No other methods in rewarded_video should be called once this method has +/// been invoked. The system is closed for business at that point. +FIREBASE_DEPRECATED void Destroy(); + +/// @deprecated +/// @brief Returns the current presentation state, indicating if an ad is +/// visible or if a video has started playing. +/// +/// The functionality in the firebase::admob namespace has +/// been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the +/// new SDK in our migration +/// guide. +/// @return The current presentation state. +FIREBASE_DEPRECATED PresentationState presentation_state(); + +/// @deprecated +/// @brief Sets the @ref Listener that should receive callbacks. +/// +/// The functionality in the firebase::admob namespace has +/// been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the +/// new SDK in our migration +/// guide. +/// @param[in] listener A valid Listener. +FIREBASE_DEPRECATED void SetListener(Listener* listener); + +} // namespace rewarded_video +} // namespace admob +} // namespace firebase + +#endif // FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_REWARDED_VIDEO_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/admob/types.h b/packages/firebase_core/firebase_core/firebase_core/firebase/admob/types.h new file mode 100644 index 000000000000..21a8379f2d96 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/admob/types.h @@ -0,0 +1,244 @@ +/* + * Copyright 2016 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_TYPES_H_ +#define FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_TYPES_H_ + +#include "firebase/internal/platform.h" + +#if FIREBASE_PLATFORM_ANDROID +#include +#elif FIREBASE_PLATFORM_IOS || FIREBASE_PLATFORM_TVOS +extern "C" { +#include +} // extern "C" +#endif // FIREBASE_PLATFORM_ANDROID, FIREBASE_PLATFORM_IOS, + // FIREBASE_PLATFORM_TVOS + +namespace firebase { +namespace admob { + +/// @deprecated The functionality in the firebase::admob namespace +/// has been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the new +/// SDK in our migration guide. +/// +/// @brief This is a platform specific datatype that is required to create an +/// AdMob ad. +/// +/// The following defines the datatype on each platform: +///

    +///
  • Android: A `jobject` which references an Android Activity.
  • +///
  • iOS: An `id` which references an iOS UIView.
  • +///
+/// +#if FIREBASE_PLATFORM_ANDROID +/// An Android Activity from Java. +typedef jobject AdParent; +#elif FIREBASE_PLATFORM_IOS || FIREBASE_PLATFORM_TVOS +/// A pointer to an iOS UIView. +typedef id AdParent; +#else +/// A void pointer for stub classes. +typedef void *AdParent; +#endif // FIREBASE_PLATFORM_ANDROID, FIREBASE_PLATFORM_IOS, + // FIREBASE_PLATFORM_TVOS + +#ifdef INTERNAL_EXPERIMENTAL +// LINT.IfChange +#endif // INTERNAL_EXPERIMENTAL +/// @deprecated +/// @brief Error codes returned by Future::error(). +/// +/// The functionality in the firebase::admob namespace has +/// been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the +/// new SDK in our migration +/// guide. +enum AdMobError { + /// Call completed successfully. + kAdMobErrorNone, + /// The ad has not been fully initialized. + kAdMobErrorUninitialized, + /// The ad is already initialized (repeat call). + kAdMobErrorAlreadyInitialized, + /// A call has failed because an ad is currently loading. + kAdMobErrorLoadInProgress, + /// A call to load an ad has failed due to an internal SDK error. + kAdMobErrorInternalError, + /// A call to load an ad has failed due to an invalid request. + kAdMobErrorInvalidRequest, + /// A call to load an ad has failed due to a network error. + kAdMobErrorNetworkError, + /// A call to load an ad has failed because no ad was available to serve. + kAdMobErrorNoFill, + /// An attempt has been made to show an ad on an Android Activity that has + /// no window token (such as one that's not done initializing). + kAdMobErrorNoWindowToken, + /// Fallback error for any unidentified cases. + kAdMobErrorUnknown, +}; +#ifdef INTERNAL_EXPERIMENTAL +// LINT.ThenChange(//depot_firebase_cpp/admob/client/cpp/src_java/com/google/firebase/admob/internal/cpp/ConstantsHelper.java) +#endif // INTERNAL_EXPERIMENTAL + +/// @deprecated +/// @brief Types of ad sizes. +/// +/// The functionality in the firebase::admob namespace has +/// been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the +/// new SDK in our migration +/// guide. +enum AdSizeType { kAdSizeStandard = 0 }; + +/// @deprecated +/// @brief An ad size value to be used in requesting ads. +/// +/// The functionality in the firebase::admob namespace has +/// been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the +/// new SDK in our migration +/// guide. +struct AdSize { + /// The type of ad size. + AdSizeType ad_size_type; + /// Height of the ad (in points or dp). + int height; + /// Width of the ad (in points or dp). + int width; +}; + +/// @deprecated +/// @brief Gender information used as part of the +/// @ref firebase::admob::AdRequest struct. +/// +/// The functionality in the firebase::admob namespace has +/// been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the +/// new SDK in our migration +/// guide. +enum Gender { + /// The gender of the current user is unknown or unspecified by the + /// publisher. + kGenderUnknown = 0, + /// The current user is known to be male. + kGenderMale, + /// The current user is known to be female. + kGenderFemale +}; + +/// @deprecated +/// @brief Indicates whether an ad request is considered tagged for +/// child-directed treatment. +/// +/// The functionality in the firebase::admob namespace has +/// been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the +/// new SDK in our migration +/// guide. +enum ChildDirectedTreatmentState { + /// The child-directed status for the request is not indicated. + kChildDirectedTreatmentStateUnknown = 0, + /// The request is tagged for child-directed treatment. + kChildDirectedTreatmentStateTagged, + /// The request is not tagged for child-directed treatment. + kChildDirectedTreatmentStateNotTagged +}; + +/// @deprecated +/// @brief Generic Key-Value container used for the "extras" values in an +/// @ref firebase::admob::AdRequest. +/// +/// The functionality in the firebase::admob namespace has +/// been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the +/// new SDK in our migration +/// guide. +struct KeyValuePair { + /// The name for an "extra." + const char *key; + /// The value for an "extra." + const char *value; +}; + +/// @deprecated +/// @brief The information needed to request an ad. +/// +/// The functionality in the firebase::admob namespace has +/// been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the +/// new SDK in our migration +/// guide. +struct AdRequest { + /// An array of test device IDs specifying devices that test ads will be + /// returned for. + const char **test_device_ids; + /// The number of entries in the array referenced by test_device_ids. + unsigned int test_device_id_count; + /// An array of keywords or phrases describing the current user activity, such + /// as "Sports Scores" or "Football." + const char **keywords; + /// The number of entries in the array referenced by keywords. + unsigned int keyword_count; + /// A @ref KeyValuePair specifying additional parameters accepted by an ad + /// network. + const KeyValuePair *extras; + /// The number of entries in the array referenced by extras. + unsigned int extras_count; + /// The day the user was born. Specify the user's birthday to increase ad + /// relevancy. + int birthday_day; + /// The month the user was born. Specify the user's birthday to increase ad + /// relevancy. + int birthday_month; + /// The year the user was born. Specify the user's birthday to increase ad + /// relevancy. + int birthday_year; + /// The user's @ref Gender. Specify the user's gender to increase ad + /// relevancy. + Gender gender; + /// Specifies whether the request should be considered as child-directed for + /// purposes of the Children’s Online Privacy Protection Act (COPPA). + ChildDirectedTreatmentState tagged_for_child_directed_treatment; +}; + +/// @deprecated +/// @brief The screen location and dimensions of an ad view once it has been +/// initialized. +/// +/// The functionality in the firebase::admob namespace has +/// been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the +/// new SDK in our migration +/// guide. +struct BoundingBox { + /// Default constructor which initializes all member variables to 0. + BoundingBox() : height(0), width(0), x(0), y(0) {} + /// Height of the ad in pixels. + int height; + /// Width of the ad in pixels. + int width; + /// Horizontal position of the ad in pixels from the left. + int x; + /// Vertical position of the ad in pixels from the top. + int y; +}; + +} // namespace admob +} // namespace firebase + +#endif // FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_TYPES_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/analytics.h b/packages/firebase_core/firebase_core/firebase_core/firebase/analytics.h new file mode 100644 index 000000000000..973890b20fce --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/analytics.h @@ -0,0 +1,569 @@ +/* + * Copyright 2016 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_ANALYTICS_SRC_INCLUDE_FIREBASE_ANALYTICS_H_ +#define FIREBASE_ANALYTICS_SRC_INCLUDE_FIREBASE_ANALYTICS_H_ + +#include +#include +#include +#include + +#include "firebase/app.h" +#include "firebase/future.h" +#include "firebase/internal/common.h" +#include "firebase/variant.h" + +#if !defined(DOXYGEN) && !defined(SWIG) +FIREBASE_APP_REGISTER_CALLBACKS_REFERENCE(analytics) +#endif // !defined(DOXYGEN) && !defined(SWIG) + +/// @brief Namespace that encompasses all Firebase APIs. +namespace firebase { + +/// @brief Firebase Analytics API. +/// +/// See the developer guides for general +/// information on using Firebase Analytics in your apps. +namespace analytics { + +/// @brief Event parameter. +/// +/// Parameters supply information that contextualize events (see @ref LogEvent). +/// You can associate up to 25 unique Parameters with each event type (name). +/// +/// +/// @if swig_examples +/// Common event types are provided as static properties of the +/// FirebaseAnalytics class (e.g FirebaseAnalytics.EventPostScore) where +/// parameters of these events are also provided in this FirebaseAnalytics +/// class (e.g FirebaseAnalytics.ParameterScore). +/// +/// You are not limited to the set of event types and parameter names +/// suggested in FirebaseAnalytics class properties. Additional Parameters can +/// be supplied for suggested event types or custom Parameters for custom event +/// types. +/// @endif +/// +/// @if cpp_examples +/// Common event types (names) are suggested in @ref event_names +/// (%event_names.h) with parameters of common event types defined in +/// @ref parameter_names (%parameter_names.h). +/// +/// You are not limited to the set of event types and parameter names suggested +/// in @ref event_names (%event_names.h) and %parameter_names.h respectively. +/// Additional Parameters can be supplied for suggested event types or custom +/// Parameters for custom event types. +/// @endif +/// +/// Parameter names must be a combination of letters and digits +/// (matching the regular expression [a-zA-Z0-9]) between 1 and 40 characters +/// long starting with a letter [a-zA-Z] character. The "firebase_", +/// "google_" and "ga_" prefixes are reserved and should not be used. +/// +/// Parameter string values can be up to 100 characters long. +/// +/// +/// @if swig_examples +/// An array of Parameter class instances can be passed to LogEvent in order +/// to associate parameters's of an event with values where each value can be +/// a double, 64-bit integer or string. +/// @endif +/// +/// @if cpp_examples +/// An array of this structure is passed to LogEvent in order to associate +/// parameter's of an event (Parameter::name) with values (Parameter::value) +/// where each value can be a double, 64-bit integer or string. +/// @endif +/// +/// For example, a game may log an achievement event along with the +/// character the player is using and the level they're currently on: +/// +/// +/// @if swig_examples +/// @code{.cs} +/// using Firebase.Analytics; +/// +/// int currentLevel = GetCurrentLevel(); +/// Parameter[] AchievementParameters = { +/// new Parameter(FirebaseAnalytics.ParameterAchievementID, +/// "ultimate_wizard"), +/// new Parameter(FirebaseAnalytics.ParameterCharacter, "mysterion"), +/// new Parameter(FirebaseAnalytics.ParameterLevel, currentLevel), +/// }; +/// FirebaseAnalytics.LogEvent(FirebaseAnalytics.EventLevelUp, +/// AchievementParameters); +/// @endcode +/// @endif +/// +/// @if cpp_examples +/// @code{.cpp} +/// using namespace firebase::analytics; +/// int64_t current_level = GetCurrentLevel(); +/// const Parameter achievement_parameters[] = { +/// Parameter(kParameterAchievementID, "ultimate_wizard"), +/// Parameter(kParameterCharacter, "mysterion"), +/// Parameter(kParameterLevel, current_level), +/// }; +/// LogEvent(kEventUnlockAchievement, achievement_parameters, +/// sizeof(achievement_parameters) / +/// sizeof(achievement_parameters[0])); +/// @endcode +/// @endif +/// +struct Parameter { +#ifndef SWIG + /// Construct an empty parameter. + /// + /// This is provided to allow initialization after construction. + Parameter() : name(nullptr) {} +#endif // !SWIG + +// +// We don't want to pull in Variant in the C# interface. +// +#ifndef SWIG + /// Construct a parameter. + /// + /// @param parameter_name Name of the parameter (see Parameter::name). + /// @param parameter_value Value for the parameter. Variants can + /// hold numbers and strings. + Parameter(const char* parameter_name, Variant parameter_value) + : name(parameter_name) { + value = parameter_value; + } +#endif // !SWIG + + /// Construct a 64-bit integer parameter. + /// + /// @param parameter_name Name of the parameter. + /// @if cpp_examples + /// (see Parameter::name). + /// @endif + /// + /// @if swig_examples + /// Parameter names must be a combination of letters and digits + /// (matching the regular expression [a-zA-Z0-9]) between 1 and 40 characters + /// long starting with a letter [a-zA-Z] character. + /// @endif + /// + /// @param parameter_value Integer value for the parameter. + Parameter(const char* parameter_name, int parameter_value) + : name(parameter_name) { + value = parameter_value; + } + + /// Construct a 64-bit integer parameter. + /// + /// @param parameter_name Name of the parameter. + /// @if cpp_examples + /// (see Parameter::name). + /// @endif + /// + /// @if swig_examples + /// Parameter names must be a combination of letters and digits + /// (matching the regular expression [a-zA-Z0-9]) between 1 and 40 characters + /// long starting with a letter [a-zA-Z] character. + /// @endif + /// + /// @param parameter_value Integer value for the parameter. + Parameter(const char* parameter_name, int64_t parameter_value) + : name(parameter_name) { + value = parameter_value; + } + + /// Construct a floating point parameter. + /// + /// @param parameter_name Name of the parameter. + /// @if cpp_examples + /// (see Parameter::name). + /// @endif + /// + /// @if swig_examples + /// Parameter names must be a combination of letters and digits + /// (matching the regular expression [a-zA-Z0-9]) between 1 and 40 characters + /// long starting with a letter [a-zA-Z] character. + /// @endif + /// + /// @param parameter_value Floating point value for the parameter. + Parameter(const char* parameter_name, double parameter_value) + : name(parameter_name) { + value = parameter_value; + } + + /// Construct a string parameter. + /// + /// @param parameter_name Name of the parameter. + /// @if cpp_examples + /// (see Parameter::name). + /// @endif + /// + /// @if swig_examples + /// Parameter names must be a combination of letters and digits + /// (matching the regular expression [a-zA-Z0-9]) between 1 and 40 characters + /// long starting with a letter [a-zA-Z] character. + /// @endif + /// + /// @param parameter_value String value for the parameter, can be up to 100 + /// characters long. + Parameter(const char* parameter_name, const char* parameter_value) + : name(parameter_name) { + value = parameter_value; + } + +#ifndef SWIG + // + // Skipping implementation values because the C# API members are + // immutable, and there's no other need to read these values in + // C#. The class just needs to be passed to the C++ layers. + // This also avoids having to solve the nested union, which is + // unsupported in swig. + // + + /// @brief Name of the parameter. + /// + /// Parameter names must be a combination of letters and digits + /// (matching the regular expression [a-zA-Z0-9]) between 1 and 40 characters + /// long starting with a letter [a-zA-Z] character. The "firebase_", + /// "google_" and "ga_" prefixes are reserved and should not be used. + const char* name; + /// @brief Value of the parameter. + /// + /// See firebase::Variant for usage information. + /// @note String values can be up to 100 characters long. + Variant value; +#endif // SWIG +}; + +/// @brief Initialize the Analytics API. +/// +/// This must be called prior to calling any other methods in the +/// firebase::analytics namespace. +/// +/// @param[in] app Default @ref firebase::App instance. +/// +/// @see firebase::App::GetInstance(). +void Initialize(const App& app); + +/// @brief Terminate the Analytics API. +/// +/// Cleans up resources associated with the API. +void Terminate(); + +/// @brief Sets whether analytics collection is enabled for this app on this +/// device. +/// +/// This setting is persisted across app sessions. By default it is enabled. +/// +/// @param[in] enabled true to enable analytics collection, false to disable. +void SetAnalyticsCollectionEnabled(bool enabled); + +/// @brief The type of consent to set. +/// +/// Supported consent types are kConsentTypeAdStorage and +/// kConsentTypeAnalyticsStorage. Omitting a type retains its previous status. +enum ConsentType { kConsentTypeAdStorage = 0, kConsentTypeAnalyticsStorage }; + +/// @brief The status value of the consent type. +/// +/// Supported statuses are kConsentStatusGranted and kConsentStatusDenied. +enum ConsentStatus { kConsentStatusGranted = 0, kConsentStatusDenied }; + +/// @brief Sets the applicable end user consent state (e.g., for device +/// identifiers) for this app on this device. +/// +/// Use the consent map to specify individual consent type values. Settings are +/// persisted across app sessions. By default consent types are set to +/// "granted". +void SetConsent(const std::map& consent_settings); + +/// @brief Log an event with one string parameter. +/// +/// @param[in] name Name of the event to log. Should contain 1 to 40 +/// alphanumeric characters or underscores. The name must start with an +/// alphabetic character. Some event names are reserved. +/// +/// @if swig_examples +/// See the FirebaseAnalytics.Event properties for the list of reserved event +/// names. +/// @endif +/// +/// @if cpp_examples +/// See @ref event_names (%event_names.h) for the list of reserved event names. +/// @endif +/// The "firebase_" prefix is reserved and should not be used. Note that event +/// names are case-sensitive and that logging two events whose names differ +/// only in case will result in two distinct events. +/// @param[in] parameter_name Name of the parameter to log. +/// For more information, see @ref Parameter. +/// @param[in] parameter_value Value of the parameter to log. +/// +/// +/// @if swig_examples +/// @see LogEvent(string, Parameter[]) +/// @endif +/// +/// @if cpp_examples +/// @see LogEvent(const char*, const Parameter*, size_t) +/// @endif +void LogEvent(const char* name, const char* parameter_name, + const char* parameter_value); + +/// @brief Log an event with one float parameter. +/// +/// @param[in] name Name of the event to log. Should contain 1 to 40 +/// alphanumeric characters or underscores. The name must start with an +/// alphabetic character. Some event names are reserved. +/// +/// @if swig_examples +/// See the FirebaseAnalytics.Event properties for the list of reserved event +/// names. +/// @endif +/// +/// @if cpp_examples +/// See @ref event_names (%event_names.h) for the list of reserved event names. +/// @endif +/// The "firebase_" prefix is reserved and should not be used. Note that event +/// names are case-sensitive and that logging two events whose names differ +/// only in case will result in two distinct events. +/// @param[in] parameter_name Name of the parameter to log. +/// For more information, see @ref Parameter. +/// @param[in] parameter_value Value of the parameter to log. +/// +/// +/// @if swig_examples +/// @see LogEvent(string, Parameter[]) +/// @endif +/// +/// @if cpp_examples +/// @see LogEvent(const char*, const Parameter*, size_t) +/// @endif +void LogEvent(const char* name, const char* parameter_name, + const double parameter_value); + +/// @brief Log an event with one 64-bit integer parameter. +/// +/// @param[in] name Name of the event to log. Should contain 1 to 40 +/// alphanumeric characters or underscores. The name must start with an +/// alphabetic character. Some event names are reserved. +/// +/// @if swig_examples +/// See the FirebaseAnalytics.Event properties for the list of reserved event +/// names. +/// @endif +/// +/// @if cpp_examples +/// See @ref event_names (%event_names.h) for the list of reserved event names. +/// @endif +/// The "firebase_" prefix is reserved and should not be used. Note that event +/// names are case-sensitive and that logging two events whose names differ +/// only in case will result in two distinct events. +/// @param[in] parameter_name Name of the parameter to log. +/// For more information, see @ref Parameter. +/// @param[in] parameter_value Value of the parameter to log. +/// +/// +/// @if swig_examples +/// @see LogEvent(string, Parameter[]) +/// @endif +/// +/// @if cpp_examples +/// @see LogEvent(const char*, const Parameter*, size_t) +/// @endif +void LogEvent(const char* name, const char* parameter_name, + const int64_t parameter_value); + +/// @brief Log an event with one integer parameter +/// (stored as a 64-bit integer). +/// +/// @param[in] name Name of the event to log. Should contain 1 to 40 +/// alphanumeric characters or underscores. The name must start with an +/// alphabetic character. Some event names are reserved. +/// +/// @if swig_examples +/// See the FirebaseAnalytics.Event properties for the list of reserved event +/// names. +/// @endif +/// +/// @if cpp_examples +/// See @ref event_names (%event_names.h) for the list of reserved event names. +/// @endif +/// The "firebase_" prefix is reserved and should not be used. Note that event +/// names are case-sensitive and that logging two events whose names differ +/// only in case will result in two distinct events. +/// @param[in] parameter_name Name of the parameter to log. +/// For more information, see @ref Parameter. +/// @param[in] parameter_value Value of the parameter to log. +/// +/// +/// @if swig_examples +/// @see LogEvent(string, Parameter[]) +/// @endif +/// +/// @if cpp_examples +/// @see LogEvent(const char*, const Parameter*, size_t) +/// @endif +void LogEvent(const char* name, const char* parameter_name, + const int parameter_value); + +/// @brief Log an event with no parameters. +/// +/// @param[in] name Name of the event to log. Should contain 1 to 40 +/// alphanumeric characters or underscores. The name must start with an +/// alphabetic character. Some event names are reserved. +/// +/// @if swig_examples +/// See the FirebaseAnalytics.Event properties for the list of reserved event +/// names. +/// @endif +/// +/// @if cpp_examples +/// See @ref event_names (%event_names.h) for the list of reserved event names. +/// @endif +/// The "firebase_" prefix is reserved and should not be used. Note that event +/// names are case-sensitive and that logging two events whose names differ +/// only in case will result in two distinct events. +/// +/// +/// @if swig_examples +/// @see LogEvent(string, Parameter[]) +/// @endif +/// +/// @if cpp_examples +/// @see LogEvent(const char*, const Parameter*, size_t) +/// @endif +void LogEvent(const char* name); + +// clang-format off +#ifdef SWIG +// Modify the following overload with unsafe, so that we can do some pinning +// in the C# code. +%csmethodmodifiers LogEvent "public unsafe" +#endif // SWIG +// clang-format on + +/// @brief Log an event with associated parameters. +/// +/// An Event is an important occurrence in your app that you want to +/// measure. You can report up to 500 different types of events per app and +/// you can associate up to 25 unique parameters with each Event type. +/// +/// Some common events are documented in @ref event_names (%event_names.h), +/// but you may also choose to specify custom event types that are associated +/// with your specific app. +/// +/// @param[in] name Name of the event to log. Should contain 1 to 40 +/// alphanumeric characters or underscores. The name must start with an +/// alphabetic character. Some event names are reserved. See @ref event_names +/// (%event_names.h) for the list of reserved event names. The "firebase_" +/// prefix is reserved and should not be used. Note that event names are +/// case-sensitive and that logging two events whose names differ only in +/// case will result in two distinct events. +/// @param[in] parameters Array of Parameter structures. +/// @param[in] number_of_parameters Number of elements in the parameters +/// array. +void LogEvent(const char* name, const Parameter* parameters, + size_t number_of_parameters); + +/// Initiates on-device conversion measurement given a user email address on iOS +/// and tvOS (no-op on Android). On iOS and tvOS, this method requires the +/// dependency GoogleAppMeasurementOnDeviceConversion to be linked in, +/// otherwise the invocation results in a no-op. +/// @param[in] email_address User email address. Include a domain name for all +/// email addresses (e.g. gmail.com or hotmail.co.jp). +void InitiateOnDeviceConversionMeasurementWithEmailAddress( + const char* email_address); + +/// @brief Set a user property to the given value. +/// +/// Properties associated with a user allow a developer to segment users +/// into groups that are useful to their application. Up to 25 properties +/// can be associated with a user. +/// +/// Suggested property names are listed @ref user_property_names +/// (%user_property_names.h) but you're not limited to this set. For example, +/// the "gamertype" property could be used to store the type of player where +/// a range of values could be "casual", "mid_core", or "core". +/// +/// @param[in] name Name of the user property to set. This must be a +/// combination of letters and digits (matching the regular expression +/// [a-zA-Z0-9] between 1 and 40 characters long starting with a letter +/// [a-zA-Z] character. +/// @param[in] property Value to set the user property to. Set this +/// argument to NULL or nullptr to remove the user property. The value can be +/// between 1 to 100 characters long. +void SetUserProperty(const char* name, const char* property); + +/// @brief Sets the user ID property. +/// +/// This feature must be used in accordance with +/// Google's Privacy +/// Policy +/// +/// @param[in] user_id The user ID associated with the user of this app on this +/// device. The user ID must be non-empty and no more than 256 characters long. +/// Setting user_id to NULL or nullptr removes the user ID. +void SetUserId(const char* user_id); + +/// @brief Sets the duration of inactivity that terminates the current session. +/// +/// @note The default value is 1800000 (30 minutes). +/// +/// @param milliseconds The duration of inactivity that terminates the current +/// session. +void SetSessionTimeoutDuration(int64_t milliseconds); + +/// Clears all analytics data for this app from the device and resets the app +/// instance id. +void ResetAnalyticsData(); + +/// Get the instance ID from the analytics service. +/// +/// @note This is *not* the same ID as the ID returned by +/// @if cpp_examples +/// firebase::instance_id::InstanceId. +/// @else +/// Firebase.InstanceId.FirebaseInstanceId. +/// @endif +/// +/// @returns Object which can be used to retrieve the analytics instance ID. +Future GetAnalyticsInstanceId(); + +/// Get the result of the most recent GetAnalyticsInstanceId() call. +/// +/// @returns Object which can be used to retrieve the analytics instance ID. +Future GetAnalyticsInstanceIdLastResult(); + +/// Asynchronously retrieves the identifier of the current app +/// session. +/// +/// The session ID retrieval could fail due to Analytics collection +/// disabled, or if the app session was expired. +/// +/// @returns Object which can be used to retrieve the identifier of the current +/// app session. +Future GetSessionId(); + +/// Get the result of the most recent GetSessionId() call. +/// +/// @returns Object which can be used to retrieve the identifier of the current +/// app session. +Future GetSessionIdLastResult(); + +} // namespace analytics +} // namespace firebase + +#endif // FIREBASE_ANALYTICS_SRC_INCLUDE_FIREBASE_ANALYTICS_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/analytics/event_names.h b/packages/firebase_core/firebase_core/firebase_core/firebase/analytics/event_names.h new file mode 100644 index 000000000000..4f1d4e5a0e2b --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/analytics/event_names.h @@ -0,0 +1,472 @@ +// Copyright 2023 Google Inc. All Rights Reserved. + +#ifndef FIREBASE_ANALYTICS_CLIENT_CPP_INCLUDE_FIREBASE_ANALYTICS_EVENT_NAMES_H_ +#define FIREBASE_ANALYTICS_CLIENT_CPP_INCLUDE_FIREBASE_ANALYTICS_EVENT_NAMES_H_ + +/// @brief Namespace that encompasses all Firebase APIs. +namespace firebase { +/// @brief Firebase Analytics API. +namespace analytics { + + + +/// @defgroup event_names Analytics Events +/// +/// Predefined event names. +/// +/// An Event is an important occurrence in your app that you want to +/// measure. You can report up to 500 different types of Events per app +/// and you can associate up to 25 unique parameters with each Event type. +/// Some common events are suggested below, but you may also choose to +/// specify custom Event types that are associated with your specific app. +/// Each event type is identified by a unique name. Event names can be up +/// to 40 characters long, may only contain alphanumeric characters and +/// underscores ("_"), and must start with an alphabetic character. The +/// "firebase_", "google_", and "ga_" prefixes are reserved and should not +/// be used. +/// @{ + + +/// Ad Impression event. This event signifies when a user sees an ad +/// impression. Note: If you supply the @c AnalyticsParameterValue +/// parameter, you must also supply the @c AnalyticsParameterCurrency +/// parameter so that revenue metrics can be computed accurately. Params: +/// +///
    +///
  • @c AnalyticsParameterAdPlatform (String) (optional)
  • +///
  • @c AnalyticsParameterAdFormat (String) (optional)
  • +///
  • @c AnalyticsParameterAdSource (String) (optional)
  • +///
  • @c AnalyticsParameterAdUnitName (String) (optional)
  • +///
  • @c AnalyticsParameterCurrency (String) (optional)
  • +///
  • @c AnalyticsParameterValue (Double) (optional)
  • +///
+static const char*const kEventAdImpression = + "ad_impression"; + +/// Add Payment Info event. This event signifies that a user has submitted +/// their payment information. Note: If you supply the @c +/// AnalyticsParameterValue parameter, you must also supply the @c +/// AnalyticsParameterCurrency parameter so that revenue metrics can be +/// computed accurately. Params: +/// +///
    +///
  • @c AnalyticsParameterCoupon (String) (optional)
  • +///
  • @c AnalyticsParameterCurrency (String) (optional)
  • +///
  • @c AnalyticsParameterItems ([[String: Any]]) (optional)
  • +///
  • @c AnalyticsParameterPaymentType (String) (optional)
  • +///
  • @c AnalyticsParameterValue (Double) (optional)
  • +///
+static const char*const kEventAddPaymentInfo = + "add_payment_info"; + +/// Add Shipping Info event. This event signifies that a user has +/// submitted their shipping information. Note: If you supply the @c +/// AnalyticsParameterValue parameter, you must also supply the @c +/// AnalyticsParameterCurrency parameter so that revenue metrics can be +/// computed accurately. Params: +/// +///
    +///
  • @c AnalyticsParameterCoupon (String) (optional)
  • +///
  • @c AnalyticsParameterCurrency (String) (optional)
  • +///
  • @c AnalyticsParameterItems ([[String: Any]]) (optional)
  • +///
  • @c AnalyticsParameterShippingTier (String) (optional)
  • +///
  • @c AnalyticsParameterValue (Double) (optional)
  • +///
+static const char*const kEventAddShippingInfo = + "add_shipping_info"; + +/// E-Commerce Add To Cart event. This event signifies that an item(s) was +/// added to a cart for purchase. Add this event to a funnel with @c +/// AnalyticsEventPurchase to gauge the effectiveness of your +/// checParameter(kout, If you supply the @c AnalyticsParameterValue +/// parameter), you must also supply the @c AnalyticsParameterCurrency +/// parameter so that revenue metrics can be computed accurately. Params: +/// +///
    +///
  • @c AnalyticsParameterCurrency (String) (optional)
  • +///
  • @c AnalyticsParameterItems ([[String: Any]]) (optional)
  • +///
  • @c AnalyticsParameterValue (Double) (optional)
  • +///
+static const char*const kEventAddToCart = "add_to_cart"; + +/// E-Commerce Add To Wishlist event. This event signifies that an item +/// was added to a wishlist. Use this event to identify popular gift +/// items. Note: If you supply the @c AnalyticsParameterValue parameter, +/// you must also supply the @c AnalyticsParameterCurrency parameter so +/// that revenue metrics can be computed accurately. Params: +/// +///
    +///
  • @c AnalyticsParameterCurrency (String) (optional)
  • +///
  • @c AnalyticsParameterItems ([[String: Any]]) (optional)
  • +///
  • @c AnalyticsParameterValue (Double) (optional)
  • +///
+static const char*const kEventAddToWishlist = + "add_to_wishlist"; + +/// App Open event. By logging this event when an App becomes active, +/// developers can understand how often users leave and return during the +/// course of a Session. Although Sessions are automatically reported, +/// this event can provide further clarification around the continuous +/// engagement of app-users. +static const char*const kEventAppOpen = "app_open"; + +/// E-Commerce Begin Checkout event. This event signifies that a user has +/// begun the process of checking out. Add this event to a funnel with +/// your @c AnalyticsEventPurchase event to gauge the effectiveness of +/// your checkout process. Note: If you supply the @c +/// AnalyticsParameterValue parameter, you must also supply the @c +/// AnalyticsParameterCurrency parameter so that revenue metrics can be +/// computed accurately. Params: +/// +///
    +///
  • @c AnalyticsParameterCoupon (String) (optional)
  • +///
  • @c AnalyticsParameterCurrency (String) (optional)
  • +///
  • @c AnalyticsParameterItems ([[String: Any]]) (optional)
  • +///
  • @c AnalyticsParameterValue (Double) (optional)
  • +///
+static const char*const kEventBeginCheckout = + "begin_checkout"; + +/// Campaign Detail event. Log this event to supply the referral details +/// of a re-engagement campaign. Note: you must supply at least one of the +/// required parameters AnalyticsParameterSource, AnalyticsParameterMedium +/// or AnalyticsParameterCampaign. Params: +/// +///
    +///
  • @c AnalyticsParameterSource (String)
  • +///
  • @c AnalyticsParameterMedium (String)
  • +///
  • @c AnalyticsParameterCampaign (String)
  • +///
  • @c AnalyticsParameterTerm (String) (optional)
  • +///
  • @c AnalyticsParameterContent (String) (optional)
  • +///
  • @c AnalyticsParameterAdNetworkClickID (String) (optional)
  • +///
  • @c AnalyticsParameterCP1 (String) (optional)
  • +///
  • @c AnalyticsParameterCampaignID (String) (optional)
  • +///
  • @c AnalyticsParameterCreativeFormat (String) (optional)
  • +///
  • @c AnalyticsParameterMarketingTactic (String) (optional)
  • +///
  • @c AnalyticsParameterSourcePlatform (String) (optional)
  • +///
+static const char*const kEventCampaignDetails = + "campaign_details"; + +/// Earn Virtual Currency event. This event tracks the awarding of virtual +/// currency in your app. Log this along with @c +/// AnalyticsEventSpendVirtualCurrency to better understand your virtual +/// economy. Params: +/// +///
    +///
  • @c AnalyticsParameterVirtualCurrencyName (String)
  • +///
  • @c AnalyticsParameterValue (Int or Double)
  • +///
+static const char*const kEventEarnVirtualCurrency + = "earn_virtual_currency"; + +/// Generate Lead event. Log this event when a lead has been generated in +/// the app to understand the efficacy of your install and re-engagement +/// campaigns. Note: If you supply the @c AnalyticsParameterValue +/// parameter, you must also supply the @c AnalyticsParameterCurrency +/// parameter so that revenue metrics can be computed accurately. Params: +/// +///
    +///
  • @c AnalyticsParameterCurrency (String) (optional)
  • +///
  • @c AnalyticsParameterValue (Double) (optional)
  • +///
+static const char*const kEventGenerateLead = + "generate_lead"; + +/// Join Group event. Log this event when a user joins a group such as a +/// guild, team or family. Use this event to analyze how popular certain +/// groups or social features are in your app. Params: +/// +///
    +///
  • @c AnalyticsParameterGroupID (String)
  • +///
+static const char*const kEventJoinGroup = "join_group"; + +/// Level End event. Log this event when the user finishes a level. +/// Params: +/// +///
    +///
  • @c AnalyticsParameterLevelName (String)
  • +///
  • @c AnalyticsParameterSuccess (String)
  • +///
+static const char*const kEventLevelEnd = "level_end"; + +/// Level Start event. Log this event when the user starts a new level. +/// Params: +/// +///
    +///
  • @c AnalyticsParameterLevelName (String)
  • +///
+static const char*const kEventLevelStart = "level_start"; + +/// Level Up event. This event signifies that a player has leveled up in +/// your gaming app. It can help you gauge the level distribution of your +/// userbase and help you identify certain levels that are difficult to +/// pass. Params: +/// +///
    +///
  • @c AnalyticsParameterLevel (Int)
  • +///
  • @c AnalyticsParameterCharacter (String) (optional)
  • +///
+static const char*const kEventLevelUp = "level_up"; + +/// Login event. Apps with a login feature can report this event to +/// signify that a user has logged in. +static const char*const kEventLogin = "login"; + +/// Post Score event. Log this event when the user posts a score in your +/// gaming app. This event can help you understand how users are actually +/// performing in your game and it can help you correlate high scores with +/// certain audiences or behaviors. Params: +/// +///
    +///
  • @c AnalyticsParameterScore (Int)
  • +///
  • @c AnalyticsParameterLevel (Int) (optional)
  • +///
  • @c AnalyticsParameterCharacter (String) (optional)
  • +///
+static const char*const kEventPostScore = "post_score"; + +/// E-Commerce Purchase event. This event signifies that an item(s) was +/// purchased by a user. Note: This is different from the in-app purchase +/// event, which is reported automatically for App Store-based apps. Note: +/// If you supply the @c AnalyticsParameterValue parameter, you must also +/// supply the @c AnalyticsParameterCurrency parameter so that revenue +/// metrics can be computed accurately. Params: +/// +///
    +///
  • @c AnalyticsParameterAffiliation (String) (optional)
  • +///
  • @c AnalyticsParameterCoupon (String) (optional)
  • +///
  • @c AnalyticsParameterCurrency (String) (optional)
  • +///
  • @c AnalyticsParameterEndDate (String) (optional)
  • +///
  • @c AnalyticsParameterItemID (String) (optional)
  • +///
  • @c AnalyticsParameterItems ([[String: Any]]) (optional)
  • +///
  • @c AnalyticsParameterShipping (Double) (optional)
  • +///
  • @c AnalyticsParameterStartDate (String) (optional)
  • +///
  • @c AnalyticsParameterTax (Double) (optional)
  • +///
  • @c AnalyticsParameterTransactionID (String) (optional)
  • +///
  • @c AnalyticsParameterValue (Double) (optional)
  • +///
+static const char*const kEventPurchase = "purchase"; + +/// E-Commerce Refund event. This event signifies that a refund was +/// issued. Note: If you supply the @c AnalyticsParameterValue parameter, +/// you must also supply the @c AnalyticsParameterCurrency parameter so +/// that revenue metrics can be computed accurately. Params: +/// +///
    +///
  • @c AnalyticsParameterAffiliation (String) (optional)
  • +///
  • @c AnalyticsParameterCoupon (String) (optional)
  • +///
  • @c AnalyticsParameterCurrency (String) (optional)
  • +///
  • @c AnalyticsParameterItems ([[String: Any]]) (optional)
  • +///
  • @c AnalyticsParameterShipping (Double) (optional)
  • +///
  • @c AnalyticsParameterTax (Double) (optional)
  • +///
  • @c AnalyticsParameterTransactionID (String) (optional)
  • +///
  • @c AnalyticsParameterValue (Double) (optional)
  • +///
+static const char*const kEventRefund = "refund"; + +/// E-Commerce Remove from Cart event. This event signifies that an +/// item(s) was removed from a cart. Note: If you supply the @c +/// AnalyticsParameterValue parameter, you must also supply the @c +/// AnalyticsParameterCurrency parameter so that revenue metrics can be +/// computed accurately. Params: +/// +///
    +///
  • @c AnalyticsParameterCurrency (String) (optional)
  • +///
  • @c AnalyticsParameterItems ([[String: Any]]) (optional)
  • +///
  • @c AnalyticsParameterValue (Double) (optional)
  • +///
+static const char*const kEventRemoveFromCart = + "remove_from_cart"; + +/// Screen View event. This event signifies a screen view. Use this when a +/// screen transition occurs. This event can be logged irrespective of +/// whether automatic screen tracking is enabled. Params: +/// +///
    +///
  • @c AnalyticsParameterScreenClass (String) (optional)
  • +///
  • @c AnalyticsParameterScreenName (String) (optional)
  • +///
+static const char*const kEventScreenView = "screen_view"; + +/// Search event. Apps that support search features can use this event to +/// contextualize search operations by supplying the appropriate, +/// corresponding parameters. This event can help you identify the most +/// popular content in your app. Params: +/// +///
    +///
  • @c AnalyticsParameterSearchTerm (String)
  • +///
  • @c AnalyticsParameterStartDate (String) (optional)
  • +///
  • @c AnalyticsParameterEndDate (String) (optional)
  • +///
  • @c AnalyticsParameterNumberOfNights (Int) (optional) for hotel bookings
  • +///
  • @c AnalyticsParameterNumberOfRooms (Int) (optional) for hotel bookings
  • +///
  • @c AnalyticsParameterNumberOfPassengers (Int) (optional) for travel bookings
  • +///
  • @c AnalyticsParameterOrigin (String) (optional)
  • +///
  • @c AnalyticsParameterDestination (String) (optional)
  • +///
  • @c AnalyticsParameterTravelClass (String) (optional) for travel bookings
  • +///
+static const char*const kEventSearch = "search"; + +/// Select Content event. This general purpose event signifies that a user +/// has selected some content of a certain type in an app. The content can +/// be any object in your app. This event can help you identify popular +/// content and categories of content in your app. Params: +/// +///
    +///
  • @c AnalyticsParameterContentType (String)
  • +///
  • @c AnalyticsParameterItemID (String)
  • +///
+static const char*const kEventSelectContent = + "select_content"; + +/// Select Item event. This event signifies that an item was selected by a +/// user from a list. Use the appropriate parameters to contextualize the +/// event. Use this event to discover the most popular items selected. +/// Params: +/// +///
    +///
  • @c AnalyticsParameterItems ([[String: Any]]) (optional)
  • +///
  • @c AnalyticsParameterItemListID (String) (optional)
  • +///
  • @c AnalyticsParameterItemListName (String) (optional)
  • +///
+static const char*const kEventSelectItem = "select_item"; + +/// Select promotion event. This event signifies that a user has selected +/// a promotion offer. Use the appropriate parameters to contextualize the +/// event, such as the item(s) for which the promotion applies. Params: +/// +///
    +///
  • @c AnalyticsParameterCreativeName (String) (optional)
  • +///
  • @c AnalyticsParameterCreativeSlot (String) (optional)
  • +///
  • @c AnalyticsParameterItems ([[String: Any]]) (optional)
  • +///
  • @c AnalyticsParameterLocationID (String) (optional)
  • +///
  • @c AnalyticsParameterPromotionID (String) (optional)
  • +///
  • @c AnalyticsParameterPromotionName (String) (optional)
  • +///
+static const char*const kEventSelectPromotion = + "select_promotion"; + +/// Share event. Apps with social features can log the Share event to +/// identify the most viral content. Params: +/// +///
    +///
  • @c AnalyticsParameterContentType (String)
  • +///
  • @c AnalyticsParameterItemID (String)
  • +///
+static const char*const kEventShare = "share"; + +/// Sign Up event. This event indicates that a user has signed up for an +/// account in your app. The parameter signifies the method by which the +/// user signed up. Use this event to understand the different behaviors +/// between logged in and logged out users. Params: +/// +///
    +///
  • @c AnalyticsParameterMethod (String)
  • +///
+static const char*const kEventSignUp = "sign_up"; + +/// Spend Virtual Currency event. This event tracks the sale of virtual +/// goods in your app and can help you identify which virtual goods are +/// the most popular objects of purchase. Params: +/// +///
    +///
  • @c AnalyticsParameterItemName (String)
  • +///
  • @c AnalyticsParameterVirtualCurrencyName (String)
  • +///
  • @c AnalyticsParameterValue (Int or Double)
  • +///
+static const char*const kEventSpendVirtualCurrency + = "spend_virtual_currency"; + +/// Tutorial Begin event. This event signifies the start of the +/// on-boarding process in your app. Use this in a funnel with @c +/// AnalyticsEventTutorialComplete to understand how many users complete +/// this process and move on to the full app experience. +static const char*const kEventTutorialBegin = + "tutorial_begin"; + +/// Tutorial End event. Use this event to signify the user's completion of +/// your app's on-boarding process. Add this to a funnel with @c +/// AnalyticsEventTutorialBegin to gauge the completion rate of your +/// on-boarding process. +static const char*const kEventTutorialComplete = + "tutorial_complete"; + +/// Unlock Achievement event. Log this event when the user has unlocked an +/// achievement in your game. Since achievements generally represent the +/// breadth of a gaming experience, this event can help you understand how +/// many users are experiencing all that your game has to offer. Params: +/// +///
    +///
  • @c AnalyticsParameterAchievementID (String)
  • +///
+static const char*const kEventUnlockAchievement = + "unlock_achievement"; + +/// E-commerce View Cart event. This event signifies that a user has +/// viewed their cart. Use this to analyze your purchase funnel. Note: If +/// you supply the @c AnalyticsParameterValue parameter, you must also +/// supply the @c AnalyticsParameterCurrency parameter so that revenue +/// metrics can be computed accurately. Params: +/// +///
    +///
  • @c AnalyticsParameterCurrency (String) (optional)
  • +///
  • @c AnalyticsParameterItems ([[String: Any]]) (optional)
  • +///
  • @c AnalyticsParameterValue (Double) (optional)
  • +///
+static const char*const kEventViewCart = "view_cart"; + +/// View Item event. This event signifies that a user has viewed an item. +/// Use the appropriate parameters to contextualize the event. Use this +/// event to discover the most popular items viewed in your app. Note: If +/// you supply the @c AnalyticsParameterValue parameter, you must also +/// supply the @c AnalyticsParameterCurrency parameter so that revenue +/// metrics can be computed accurately. Params: +/// +///
    +///
  • @c AnalyticsParameterCurrency (String) (optional)
  • +///
  • @c AnalyticsParameterItems ([[String: Any]]) (optional)
  • +///
  • @c AnalyticsParameterValue (Double) (optional)
  • +///
+static const char*const kEventViewItem = "view_item"; + +/// View Item List event. Log this event when a user sees a list of items +/// or offerings. Params: +/// +///
    +///
  • @c AnalyticsParameterItems ([[String: Any]]) (optional)
  • +///
  • @c AnalyticsParameterItemListID (String) (optional)
  • +///
  • @c AnalyticsParameterItemListName (String) (optional)
  • +///
+static const char*const kEventViewItemList = + "view_item_list"; + +/// View Promotion event. This event signifies that a promotion was shown +/// to a user. Add this event to a funnel with the @c +/// AnalyticsEventAddToCart and @c AnalyticsEventPurchase to gauge your +/// conversion process. Params: +/// +///
    +///
  • @c AnalyticsParameterCreativeName (String) (optional)
  • +///
  • @c AnalyticsParameterCreativeSlot (String) (optional)
  • +///
  • @c AnalyticsParameterItems ([[String: Any]]) (optional)
  • +///
  • @c AnalyticsParameterLocationID (String) (optional)
  • +///
  • @c AnalyticsParameterPromotionID (String) (optional)
  • +///
  • @c AnalyticsParameterPromotionName (String) (optional)
  • +///
+static const char*const kEventViewPromotion = + "view_promotion"; + +/// View Search Results event. Log this event when the user has been +/// presented with the results of a search. Params: +/// +///
    +///
  • @c AnalyticsParameterSearchTerm (String)
  • +///
+static const char*const kEventViewSearchResults = + "view_search_results"; +/// @} + +} // namespace analytics +} // namespace firebase + +#endif // FIREBASE_ANALYTICS_CLIENT_CPP_INCLUDE_FIREBASE_ANALYTICS_EVENT_NAMES_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/analytics/parameter_names.h b/packages/firebase_core/firebase_core/firebase_core/firebase/analytics/parameter_names.h new file mode 100644 index 000000000000..fcc43c22fbc8 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/analytics/parameter_names.h @@ -0,0 +1,755 @@ +// Copyright 2023 Google Inc. All Rights Reserved. + +#ifndef FIREBASE_ANALYTICS_CLIENT_CPP_INCLUDE_FIREBASE_ANALYTICS_PARAMETER_NAMES_H_ +#define FIREBASE_ANALYTICS_CLIENT_CPP_INCLUDE_FIREBASE_ANALYTICS_PARAMETER_NAMES_H_ + +/// @brief Namespace that encompasses all Firebase APIs. +namespace firebase { +/// @brief Firebase Analytics API. +namespace analytics { + + + +/// @defgroup parameter_names Analytics Parameters +/// +/// Predefined event parameter names. +/// +/// Params supply information that contextualize Events. You can associate +/// up to 25 unique Params with each Event type. Some Params are suggested +/// below for certain common Events, but you are not limited to these. You +/// may supply extra Params for suggested Events or custom Params for +/// Custom events. Param names can be up to 40 characters long, may only +/// contain alphanumeric characters and underscores ("_"), and must start +/// with an alphabetic character. Param values can be up to 100 characters +/// long. The "firebase_", "google_", and "ga_" prefixes are reserved and +/// should not be used. +/// @{ + + +/// Game achievement ID (String). +/// @code +/// let params = [ +/// AnalyticsParameterAchievementID : "10_matches_won", +/// // ... +/// ] +/// @endcode +static const char*const kParameterAchievementID = + "achievement_id"; + +/// The ad format (e.g. Banner, Interstitial, Rewarded, Native, Rewarded +/// Interstitial, Instream). (String). +/// @code +/// let params = [ +/// AnalyticsParameterAdFormat : "Banner", +/// // ... +/// ] +/// @endcode +static const char*const kParameterAdFormat = + "ad_format"; + +/// Ad Network Click ID (String). Used for network-specific click IDs +/// which vary in format. +/// @code +/// let params = [ +/// AnalyticsParameterAdNetworParameter(kClickID, "1234567"), +/// // ... +/// ] +/// @endcode +static const char*const kParameterAdNetworkClickID + = "aclid"; + +/// The ad platform (e.g. MoPub, IronSource) (String). +/// @code +/// let params = [ +/// AnalyticsParameterAdPlatform : "MoPub", +/// // ... +/// ] +/// @endcode +static const char*const kParameterAdPlatform = + "ad_platform"; + +/// The ad source (e.g. AdColony) (String). +/// @code +/// let params = [ +/// AnalyticsParameterAdSource : "AdColony", +/// // ... +/// ] +/// @endcode +static const char*const kParameterAdSource = + "ad_source"; + +/// The ad unit name (e.g. Banner_03) (String). +/// @code +/// let params = [ +/// AnalyticsParameterAdUnitName : "Banner_03", +/// // ... +/// ] +/// @endcode +static const char*const kParameterAdUnitName = + "ad_unit_name"; + +/// A product affiliation to designate a supplying company or brick and +/// mortar store location +/// (String). @code +/// let params = [ +/// AnalyticsParameterAffiliation : "Google Store", +/// // ... +/// ] +/// @endcode +static const char*const kParameterAffiliation = + "affiliation"; + +/// Campaign custom parameter (String). Used as a method of capturing +/// custom data in a campaign. Use varies by network. +/// @code +/// let params = [ +/// AnalyticsParameterCP1 : "custom_data", +/// // ... +/// ] +/// @endcode +static const char*const kParameterCP1 = "cp1"; + +/// The individual campaign name, slogan, promo code, etc. Some networks +/// have pre-defined macro to capture campaign information, otherwise can +/// be populated by developer. Highly Recommended (String). +/// @code +/// let params = [ +/// AnalyticsParameterCampaign : "winter_promotion", +/// // ... +/// ] +/// @endcode +static const char*const kParameterCampaign = + "campaign"; + +/// Campaign ID (String). Used for keyword analysis to identify a specific +/// product promotion or strategic campaign. This is a required key for +/// GA4 data import. +/// @code +/// let params = [ +/// AnalyticsParameterCampaignID : "7877652710", +/// // ... +/// ] +/// @endcode +static const char*const kParameterCampaignID = + "campaign_id"; + +/// Character used in game (String). +/// @code +/// let params = [ +/// AnalyticsParameterCharacter : "beat_boss", +/// // ... +/// ] +/// @endcode +static const char*const kParameterCharacter = + "character"; + +/// Campaign content (String). +static const char*const kParameterContent = "content"; + +/// Type of content selected (String). +/// @code +/// let params = [ +/// AnalyticsParameterContentType : "news article", +/// // ... +/// ] +/// @endcode +static const char*const kParameterContentType = + "content_type"; + +/// Coupon code used for a purchase (String). +/// @code +/// let params = [ +/// AnalyticsParameterCoupon : "SUMMER_FUN", +/// // ... +/// ] +/// @endcode +static const char*const kParameterCoupon = "coupon"; + +/// Creative Format (String). Used to identify the high-level +/// classification of the type of ad served by a specific campaign. +/// @code +/// let params = [ +/// AnalyticsParameterCreativeFormat : "display", +/// // ... +/// ] +/// @endcode +static const char*const kParameterCreativeFormat = + "creative_format"; + +/// The name of a creative used in a promotional spot (String). +/// @code +/// let params = [ +/// AnalyticsParameterCreativeName : "Summer Sale", +/// // ... +/// ] +/// @endcode +static const char*const kParameterCreativeName = + "creative_name"; + +/// The name of a creative slot (String). +/// @code +/// let params = [ +/// AnalyticsParameterCreativeSlot : "summer_banner2", +/// // ... +/// ] +/// @endcode +static const char*const kParameterCreativeSlot = + "creative_slot"; + +/// Currency of the purchase or items associated with the event, in +/// 3-letter +/// ISO_4217 format (String). +/// @code +/// let params = [ +/// AnalyticsParameterCurrency : "USD", +/// // ... +/// ] +/// @endcode +static const char*const kParameterCurrency = + "currency"; + +/// Flight or Travel destination (String). +/// @code +/// let params = [ +/// AnalyticsParameterDestination : "Mountain View, CA", +/// // ... +/// ] +/// @endcode +static const char*const kParameterDestination = + "destination"; + +/// Monetary value of discount associated with a purchase (Double). +/// @code +/// let params = [ +/// AnalyticsParameterDiscount : 2.0, +/// AnalyticsParameterCurrency : "USD", // e.g. $2.00 USD +/// // ... +/// ] +/// @endcode +static const char*const kParameterDiscount = + "discount"; + +/// The arrival date, check-out date or rental end date for the item. This +/// should be in YYYY-MM-DD format (String). +/// @code +/// let params = [ +/// AnalyticsParameterEndDate : "2015-09-14", +/// // ... +/// ] +/// @endcode +static const char*const kParameterEndDate = "end_date"; + +/// Indicates that the associated event should either extend the current +/// session or start a new session if no session was active when the event +/// was logged. Specify 1 to extend the current session or to start a new +/// session; any other value will not extend or start a session. +/// @code +/// let params = [ +/// AnalyticsParameterExtendSession : 1, +/// // ... +/// ] +/// @endcode +static const char*const kParameterExtendSession = + "extend_session"; + +/// Flight number for travel events (String). +/// @code +/// let params = [ +/// AnalyticsParameterFlightNumber : "ZZ800", +/// // ... +/// ] +/// @endcode +static const char*const kParameterFlightNumber = + "flight_number"; + +/// Group/clan/guild ID (String). +/// @code +/// let params = [ +/// AnalyticsParameterGroupID : "g1", +/// // ... +/// ] +/// @endcode +static const char*const kParameterGroupID = "group_id"; + +/// The index of the item in a list (Int). +/// @code +/// let params = [ +/// AnalyticsParameterIndex : 5, +/// // ... +/// ] +/// @endcode +static const char*const kParameterIndex = "index"; + +/// Item brand (String). +/// @code +/// let params = [ +/// AnalyticsParameterItemBrand : "Google", +/// // ... +/// ] +/// @endcode +static const char*const kParameterItemBrand = + "item_brand"; + +/// Item category (context-specific) (String). +/// @code +/// let params = [ +/// AnalyticsParameterItemCategory : "pants", +/// // ... +/// ] +/// @endcode +static const char*const kParameterItemCategory = + "item_category"; + +/// Item Category (context-specific) (String). +/// @code +/// let params = [ +/// AnalyticsParameterItemCategory2 : "pants", +/// // ... +/// ] +/// @endcode +static const char*const kParameterItemCategory2 = + "item_category2"; + +/// Item Category (context-specific) (String). +/// @code +/// let params = [ +/// AnalyticsParameterItemCategory3 : "pants", +/// // ... +/// ] +/// @endcode +static const char*const kParameterItemCategory3 = + "item_category3"; + +/// Item Category (context-specific) (String). +/// @code +/// let params = [ +/// AnalyticsParameterItemCategory4 : "pants", +/// // ... +/// ] +/// @endcode +static const char*const kParameterItemCategory4 = + "item_category4"; + +/// Item Category (context-specific) (String). +/// @code +/// let params = [ +/// AnalyticsParameterItemCategory5 : "pants", +/// // ... +/// ] +/// @endcode +static const char*const kParameterItemCategory5 = + "item_category5"; + +/// Item ID (context-specific) (String). +/// @code +/// let params = [ +/// AnalyticsParameterItemID : "SKU_12345", +/// // ... +/// ] +/// @endcode +static const char*const kParameterItemID = "item_id"; + +/// The ID of the list in which the item was presented to the +/// user (String). +/// @code +/// let params = [ +/// AnalyticsParameterItemListID : "ABC123", +/// // ... +/// ] +/// @endcode +static const char*const kParameterItemListID = + "item_list_id"; + +/// The name of the list in which the item was presented to the user +/// (String). +/// @code +/// let params = [ +/// AnalyticsParameterItemListName : "Related products", +/// // ... +/// ] +/// @endcode +static const char*const kParameterItemListName = + "item_list_name"; + +/// Item Name (context-specific) (String). +/// @code +/// let params = [ +/// AnalyticsParameterItemName : "jeggings", +/// // ... +/// ] +/// @endcode +static const char*const kParameterItemName = + "item_name"; + +/// Item variant (String). +/// @code +/// let params = [ +/// AnalyticsParameterItemVariant : "Black", +/// // ... +/// ] +/// @endcode +static const char*const kParameterItemVariant = + "item_variant"; + +/// The list of items involved in the transaction expressed as `[[String: +/// Any]]`. +/// @code +/// let params = [ +/// AnalyticsParameterItems : [ +/// [AnalyticsParameterItemName : "jeggings", AnalyticsParameterItemCategory : "pants"], +/// [AnalyticsParameterItemName : "boots", AnalyticsParameterItemCategory : "shoes"], +/// ], +/// ] +/// @endcode +static const char*const kParameterItems = "items"; + +/// Level in game (Int). +/// @code +/// let params = [ +/// AnalyticsParameterLevel : 42, +/// // ... +/// ] +/// @endcode +static const char*const kParameterLevel = "level"; + +/// The name of a level in a game (String). +/// @code +/// let params = [ +/// AnalyticsParameterLevelName : "room_1", +/// // ... +/// ] +/// @endcode +static const char*const kParameterLevelName = + "level_name"; + +/// Location (String). The Google Place ID +/// that corresponds to the associated event. Alternatively, you can supply your own custom +/// Location ID. +/// @code +/// let params = [ +/// AnalyticsParameterLocation : "ChIJiyj437sx3YAR9kUWC8QkLzQ", +/// // ... +/// ] +/// @endcode +static const char*const kParameterLocation = + "location"; + +/// The location associated with the event. Preferred to be the Google +/// Place ID that corresponds to the +/// associated item but could be overridden to a custom location ID +/// string.(String). +/// @code +/// let params = [ +/// AnalyticsParameterLocationID : "ChIJiyj437sx3YAR9kUWC8QkLzQ", +/// // ... +/// ] +/// @endcode +static const char*const kParameterLocationID = + "location_id"; + +/// Marketing Tactic (String). Used to identify the targeting criteria +/// applied to a specific campaign. +/// @code +/// let params = [ +/// AnalyticsParameterMarParameter(ketingTactic, "Remarketing"), +/// // ... +/// ] +/// @endcode +static const char*const kParameterMarketingTactic + = "marketing_tactic"; + +/// The advertising or marParameter(keting, cpc, banner, email), push. +/// Highly recommended (String). +/// @code +/// let params = [ +/// AnalyticsParameterMedium : "email", +/// // ... +/// ] +/// @endcode +static const char*const kParameterMedium = "medium"; + +/// A particular approach used in an operation; for example, "facebook" or +/// "email" in the context of a sign_up or login event. (String). +/// @code +/// let params = [ +/// AnalyticsParameterMethod : "google", +/// // ... +/// ] +/// @endcode +static const char*const kParameterMethod = "method"; + +/// Number of nights staying at hotel (Int). +/// @code +/// let params = [ +/// AnalyticsParameterNumberOfNights : 3, +/// // ... +/// ] +/// @endcode +static const char*const kParameterNumberOfNights + = "number_of_nights"; + +/// Number of passengers traveling (Int). +/// @code +/// let params = [ +/// AnalyticsParameterNumberOfPassengers : 11, +/// // ... +/// ] +/// @endcode +static const char*const kParameterNumberOfPassengers + = "number_of_passengers"; + +/// Number of rooms for travel events (Int). +/// @code +/// let params = [ +/// AnalyticsParameterNumberOfRooms : 2, +/// // ... +/// ] +/// @endcode +static const char*const kParameterNumberOfRooms = + "number_of_rooms"; + +/// Flight or Travel origin (String). +/// @code +/// let params = [ +/// AnalyticsParameterOrigin : "Mountain View, CA", +/// // ... +/// ] +/// @endcode +static const char*const kParameterOrigin = "origin"; + +/// The chosen method of payment (String). +/// @code +/// let params = [ +/// AnalyticsParameterPaymentType : "Visa", +/// // ... +/// ] +/// @endcode +static const char*const kParameterPaymentType = + "payment_type"; + +/// Purchase price (Double). +/// @code +/// let params = [ +/// AnalyticsParameterPrice : 1.0, +/// AnalyticsParameterCurrency : "USD", // e.g. $1.00 USD +/// // ... +/// ] +/// @endcode +static const char*const kParameterPrice = "price"; + +/// The ID of a product promotion (String). +/// @code +/// let params = [ +/// AnalyticsParameterPromotionID : "ABC123", +/// // ... +/// ] +/// @endcode +static const char*const kParameterPromotionID = + "promotion_id"; + +/// The name of a product promotion (String). +/// @code +/// let params = [ +/// AnalyticsParameterPromotionName : "Summer Sale", +/// // ... +/// ] +/// @endcode +static const char*const kParameterPromotionName = + "promotion_name"; + +/// Purchase quantity (Int). +/// @code +/// let params = [ +/// AnalyticsParameterQuantity : 1, +/// // ... +/// ] +/// @endcode +static const char*const kParameterQuantity = + "quantity"; + +/// Score in game (Int). +/// @code +/// let params = [ +/// AnalyticsParameterScore : 4200, +/// // ... +/// ] +/// @endcode +static const char*const kParameterScore = "score"; + +/// Current screen class, such as the class name of the UIViewController, +/// logged with screen_view event and added to every event (String). +/// @code +/// let params = [ +/// AnalyticsParameterScreenClass : "LoginViewController", +/// // ... +/// ] +/// @endcode +static const char*const kParameterScreenClass = + "screen_class"; + +/// Current screen name, such as the name of the UIViewController, logged +/// with screen_view event and added to every event (String). +/// @code +/// let params = [ +/// AnalyticsParameterScreenName : "LoginView", +/// // ... +/// ] +/// @endcode +static const char*const kParameterScreenName = + "screen_name"; + +/// The search string/keywords used (String). +/// @code +/// let params = [ +/// AnalyticsParameterSearchTerm : "periodic table", +/// // ... +/// ] +/// @endcode +static const char*const kParameterSearchTerm = + "search_term"; + +/// Shipping cost associated with a transaction (Double). +/// @code +/// let params = [ +/// AnalyticsParameterShipping : 5.99, +/// AnalyticsParameterCurrency : "USD", // e.g. $5.99 USD +/// // ... +/// ] +/// @endcode +static const char*const kParameterShipping = + "shipping"; + +/// The shipping tier (e.g. Ground, Air, Next-day) selected for delivery +/// of the purchased item (String). +/// @code +/// let params = [ +/// AnalyticsParameterShippingTier : "Ground", +/// // ... +/// ] +/// @endcode +static const char*const kParameterShippingTier = + "shipping_tier"; + +/// The origin of your traffic, such as an Ad network (for example, +/// google) or partner (urban airship). Identify the advertiser, site, +/// publication, etc. that is sending traffic to your property. Highly +/// recommended (String). +/// @code +/// let params = [ +/// AnalyticsParameterSource : "InMobi", +/// // ... +/// ] +/// @endcode +static const char*const kParameterSource = "source"; + +/// Source Platform (String). Used to identify the platform responsible +/// for directing traffic to a given Analytics property (e.g., a buying +/// platform where budgets, targeting criteria, etc. are set, a platform +/// for managing organic traffic data, etc.). +/// @code +/// let params = [ +/// AnalyticsParameterSourcePlatform : "sa360", +/// // ... +/// ] +/// @endcode +static const char*const kParameterSourcePlatform = + "source_platform"; + +/// The departure date, check-in date or rental start date for the item. +/// This should be in YYYY-MM-DD format (String). +/// @code +/// let params = [ +/// AnalyticsParameterStartDate : "2015-09-14", +/// // ... +/// ] +/// @endcode +static const char*const kParameterStartDate = + "start_date"; + +/// The result of an operation. Specify 1 to indicate success and 0 to +/// indicate failure (Int). +/// @code +/// let params = [ +/// AnalyticsParameterSuccess : 1, +/// // ... +/// ] +/// @endcode +static const char*const kParameterSuccess = "success"; + +/// Tax cost associated with a transaction (Double). +/// @code +/// let params = [ +/// AnalyticsParameterTax : 2.43, +/// AnalyticsParameterCurrency : "USD", // e.g. $2.43 USD +/// // ... +/// ] +/// @endcode +static const char*const kParameterTax = "tax"; + +/// If you're manually tagging keyword campaigns, you should use utm_term +/// to specify the keyword (String). +/// @code +/// let params = [ +/// AnalyticsParameterTerm : "game", +/// // ... +/// ] +/// @endcode +static const char*const kParameterTerm = "term"; + +/// The unique identifier of a transaction (String). +/// @code +/// let params = [ +/// AnalyticsParameterTransactionID : "T12345", +/// // ... +/// ] +/// @endcode +static const char*const kParameterTransactionID = + "transaction_id"; + +/// Travel class (String). +/// @code +/// let params = [ +/// AnalyticsParameterTravelClass : "business", +/// // ... +/// ] +/// @endcode +static const char*const kParameterTravelClass = + "travel_class"; + +/// A context-specific numeric value which is accumulated automatically +/// for each event type. This is a general purpose parameter that is +/// useful for accumulating a key metric that pertains to an event. +/// Examples include revenue, distance, time and points. Value should be +/// specified as Int or Double. Notes: Values for pre-defined +/// currency-related events (such as @c AnalyticsEventAddToCart) should be +/// supplied using Double and must be accompanied by a @c +/// AnalyticsParameterCurrency parameter. The valid range of accumulated +/// values is [-9,223,372,036,854.77, 9,223,372,036,854.77]. Supplying a +/// non-numeric value, omitting the corresponding @c +/// AnalyticsParameterCurrency parameter, or supplying an invalid +/// currency code for conversion events will cause that +/// conversion to be omitted from reporting. +/// @code +/// let params = [ +/// AnalyticsParameterValue : 3.99, +/// AnalyticsParameterCurrency : "USD", // e.g. $3.99 USD +/// // ... +/// ] +/// @endcode +static const char*const kParameterValue = "value"; + +/// Name of virtual currency type (String). +/// @code +/// let params = [ +/// AnalyticsParameterVirtualCurrencyName : "virtual_currency_name", +/// // ... +/// ] +/// @endcode +static const char*const kParameterVirtualCurrencyName + = "virtual_currency_name"; +/// @} + +} // namespace analytics +} // namespace firebase + +#endif // FIREBASE_ANALYTICS_CLIENT_CPP_INCLUDE_FIREBASE_ANALYTICS_PARAMETER_NAMES_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/analytics/user_property_names.h b/packages/firebase_core/firebase_core/firebase_core/firebase/analytics/user_property_names.h new file mode 100644 index 000000000000..155fea86e6f9 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/analytics/user_property_names.h @@ -0,0 +1,50 @@ +// Copyright 2023 Google Inc. All Rights Reserved. + +#ifndef FIREBASE_ANALYTICS_CLIENT_CPP_INCLUDE_FIREBASE_ANALYTICS_USER_PROPERTY_NAMES_H_ +#define FIREBASE_ANALYTICS_CLIENT_CPP_INCLUDE_FIREBASE_ANALYTICS_USER_PROPERTY_NAMES_H_ + +/// @brief Namespace that encompasses all Firebase APIs. +namespace firebase { +/// @brief Firebase Analytics API. +namespace analytics { + + + +/// @defgroup user_property_names Analytics User Properties +/// +/// Predefined user property names. +/// +/// A UserProperty is an attribute that describes the app-user. By +/// supplying UserProperties, you can later analyze different behaviors of +/// various segments of your userbase. You may supply up to 25 unique +/// UserProperties per app, and you can use the name and value of your +/// choosing for each one. UserProperty names can be up to 24 characters +/// long, may only contain alphanumeric characters and underscores ("_"), +/// and must start with an alphabetic character. UserProperty values can +/// be up to 36 characters long. The "firebase_", "google_", and "ga_" +/// prefixes are reserved and should not be used. +/// @{ + + +/// Indicates whether events logged by Google Analytics can be used to +/// personalize ads for the user. Set to "YES" to enable, or "NO" to +/// disable. Default is enabled. See the +/// documentation for +/// more details and information about related settings. +/// +/// @code +/// Analytics.setUserProperty("NO", forName: AnalyticsUserPropertyAllowAdPersonalizationSignals) +/// @endcode +static const char*const kUserPropertyAllowAdPersonalizationSignals + = "allow_personalized_ads"; + +/// The method used to sign in. For example, "google", "facebook" or +/// "twitter". +static const char*const kUserPropertySignUpMethod + = "sign_up_method"; +/// @} + +} // namespace analytics +} // namespace firebase + +#endif // FIREBASE_ANALYTICS_CLIENT_CPP_INCLUDE_FIREBASE_ANALYTICS_USER_PROPERTY_NAMES_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/app.h b/packages/firebase_core/firebase_core/firebase_core/firebase/app.h new file mode 100644 index 000000000000..0501f38ac0c8 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/app.h @@ -0,0 +1,787 @@ +/* + * Copyright 2016 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_APP_SRC_INCLUDE_FIREBASE_APP_H_ +#define FIREBASE_APP_SRC_INCLUDE_FIREBASE_APP_H_ + +#include "firebase/internal/platform.h" + +#if FIREBASE_PLATFORM_ANDROID +#include +#endif // FIREBASE_PLATFORM_ANDROID + +#include +#include +#include + +#if FIREBASE_PLATFORM_IOS || FIREBASE_PLATFORM_TVOS +#ifdef __OBJC__ +@class FIRApp; +#endif // __OBJC__ +#endif // FIREBASE_PLATFORM_IOS + +namespace firebase { + +#ifdef FIREBASE_LINUX_BUILD_CONFIG_STRING +// Check to see if the shared object compiler string matches the input +void CheckCompilerString(const char* input); +#endif // FIREBASE_LINUX_BUILD_CONFIG_STRING + +// Predeclarations. +#ifdef INTERNAL_EXPERIMENTAL +namespace internal { +class FunctionRegistry; +} // namespace internal +#endif // INTERNAL_EXPERIMENTAL + +#ifdef INTERNAL_EXPERIMENTAL +#if FIREBASE_PLATFORM_DESKTOP +namespace heartbeat { +class HeartbeatController; // forward declaration +} // namespace heartbeat +#endif // FIREBASE_PLATFORM_DESKTOP +#endif // INTERNAL_EXPERIMENTAL + +namespace internal { +class AppInternal; +} // namespace internal + +/// @brief Reports whether a Firebase module initialized successfully. +enum InitResult { + /// The given library was successfully initialized. + kInitResultSuccess = 0, + + /// The given library failed to initialize due to a missing dependency. + /// + /// On Android, this typically means that Google Play services is not + /// available and the library requires it. + /// @if cpp_examples + /// Use google_play_services::CheckAvailability() and + /// google_play_services::MakeAvailable() to resolve this issue. + /// @endif + /// + /// @if swig_examples + /// Use FirebaseApp.CheckDependencies() and + /// FirebaseApp.FixDependenciesAsync() to resolve this issue. + /// @endif + /// + /// + /// Also, on Android, this value can be returned if the Java dependencies of a + /// Firebase component are not included in the application, causing + /// initialization to fail. This means that the application's build + /// environment is not configured correctly. To resolve the problem, + /// see the SDK setup documentation for the set of Java dependencies (AARs) + /// required for the component that failed to initialize. + kInitResultFailedMissingDependency +}; + +/// @brief Default name for firebase::App() objects. +extern const char* const kDefaultAppName; + +/// @brief Options that control the creation of a Firebase App. +/// @if cpp_examples +/// @see firebase::App +/// @endif +/// +/// @if swig_examples +/// @see FirebaseApp +/// @endif +/// +class AppOptions { + friend class App; + + public: + /// @brief Create AppOptions. + /// + /// @if cpp_examples + /// To create a firebase::App object, the Firebase application identifier + /// and API key should be set using set_app_id() and set_api_key() + /// respectively. + /// + /// @see firebase::App::Create(). + /// @endif + /// + /// @if swig_examples + /// To create a FirebaseApp object, the Firebase application identifier + /// and API key should be set using AppId and ApiKey respectively. + /// + /// @see FirebaseApp.Create(). + /// @endif + /// + AppOptions() {} + + /// Set the Firebase app ID used to uniquely identify an instance of an app. + /// + /// This is the mobilesdk_app_id in the Android google-services.json config + /// file or GOOGLE_APP_ID in the GoogleService-Info.plist. + /// + /// This only needs to be specified if your application does not include + /// google-services.json or GoogleService-Info.plist in its resources. + void set_app_id(const char* id) { app_id_ = id; } + + /// Retrieves the app ID. + /// + /// @if cpp_examples + /// @see set_app_id(). + /// @endif + /// + /// + /// @xmlonly + /// + /// Gets or sets the App Id. + /// + /// This is the mobilesdk_app_id in the Android google-services.json config + /// file or GOOGLE_APP_ID in the GoogleService-Info.plist. + /// + /// This only needs to be specified if your application does not include + /// google-services.json or GoogleService-Info.plist in its resources. + /// + /// @endxmlonly + /// + const char* app_id() const { return app_id_.c_str(); } + + /// API key used to authenticate requests from your app. + /// + /// For example, "AIzaSyDdVgKwhZl0sTTTLZ7iTmt1r3N2cJLnaDk" used to identify + /// your app to Google servers. + /// + /// This only needs to be specified if your application does not include + /// google-services.json or GoogleService-Info.plist in its resources. + void set_api_key(const char* key) { api_key_ = key; } + + /// Get the API key. + /// + /// @if cpp_examples + /// @see set_api_key(). + /// @endif + /// + /// + /// @xmlonly + /// + /// Gets or sets the API key used to authenticate requests from your app. + /// + /// For example, \"AIzaSyDdVgKwhZl0sTTTLZ7iTmt1r3N2cJLnaDk\" used to identify + /// your app to Google servers. + /// + /// This only needs to be specified if your application does not include + /// google-services.json or GoogleService-Info.plist in its resources. + /// + /// @endxmlonly + /// + const char* api_key() const { return api_key_.c_str(); } + + /// Set the Firebase Cloud Messaging sender ID. + /// + /// For example "012345678901", used to configure Firebase Cloud Messaging. + /// + /// This only needs to be specified if your application does not include + /// google-services.json or GoogleService-Info.plist in its resources. + void set_messaging_sender_id(const char* sender_id) { + fcm_sender_id_ = sender_id; + } + + /// Get the Firebase Cloud Messaging sender ID. + /// + /// @if cpp_examples + /// @see set_messaging_sender_id(). + /// @endif + /// + /// + /// @xmlonly + /// + /// Gets or sets the messaging sender Id. + /// + /// This only needs to be specified if your application does not include + /// google-services.json or GoogleService-Info.plist in its resources. + /// + /// @endxmlonly + /// + const char* messaging_sender_id() const { return fcm_sender_id_.c_str(); } + + /// Set the database root URL, e.g. @"http://abc-xyz-123.firebaseio.com". + void set_database_url(const char* url) { database_url_ = url; } + + /// Get database root URL, e.g. @"http://abc-xyz-123.firebaseio.com". + /// + /// + /// @xmlonly + /// + /// Gets or sets the database root URL, e.g. + /// @\"http://abc-xyz-123.firebaseio.com\". + /// + /// @endxmlonly + /// + const char* database_url() const { return database_url_.c_str(); } + + /// @cond FIREBASE_APP_INTERNAL + + /// Set the tracking ID for Google Analytics, e.g. @"UA-12345678-1". + void set_ga_tracking_id(const char* id) { ga_tracking_id_ = id; } + + /// Get the tracking ID for Google Analytics, + /// + /// @if cpp_examples + /// @see set_ga_tracking_id(). + /// @endif + /// + const char* ga_tracking_id() const { return ga_tracking_id_.c_str(); } + + /// @endcond + + /// Set the Google Cloud Storage bucket name, + /// e.g. @\"abc-xyz-123.storage.firebase.com\". + void set_storage_bucket(const char* bucket) { storage_bucket_ = bucket; } + + /// Get the Google Cloud Storage bucket name, + /// @see set_storage_bucket(). + /// + /// @xmlonly + /// + /// Gets or sets the Google Cloud Storage bucket name, e.g. + /// @\"abc-xyz-123.storage.firebase.com\". + /// + /// @endxmlonly + /// + const char* storage_bucket() const { return storage_bucket_.c_str(); } + + /// Set the Google Cloud project ID. + void set_project_id(const char* project) { project_id_ = project; } + + /// Get the Google Cloud project ID. + /// + /// This is the project_id in the Android google-services.json config + /// file or PROJECT_ID in the GoogleService-Info.plist. + /// + /// @xmlonly + /// + /// Gets the Google Cloud project ID. + /// + /// This is the project_id in the Android google-services.json config + /// file or PROJECT_ID in the GoogleService-Info.plist. + /// + /// @endxmlonly + /// + const char* project_id() const { return project_id_.c_str(); } + +#ifdef INTERNAL_EXPERIMENTAL + /// @brief set the iOS client ID. + /// + /// This is the clientID in the GoogleService-Info.plist. + void set_client_id(const char* client_id) { client_id_ = client_id; } + + /// @brief Get the iOS client ID. + /// + /// This is the client_id in the GoogleService-Info.plist. + const char* client_id() const { return client_id_.c_str(); } +#endif // INTERNAL_EXPERIMENTAL + +#ifdef INTERNAL_EXPERIMENTAL + /// @brief Set the Android or iOS client project name. + /// + /// This is the project_name in the Android google-services.json config + /// file or BUNDLE_ID in the GoogleService-Info.plist. + void set_package_name(const char* package_name) { + package_name_ = package_name; + } + + /// @brief Get the Android or iOS client project name. + /// + /// This is the project_name in the Android google-services.json config + /// file or BUNDLE_ID in the GoogleService-Info.plist. + const char* package_name() const { return package_name_.c_str(); } +#endif // INTERNAL_EXPERIMENTAL + + /// @brief Load options from a config string. + /// + /// @param[in] config A JSON string that contains Firebase configuration i.e. + /// the content of the downloaded google-services.json file. + /// @param[out] options Optional: If provided, load options into it. + /// + /// @returns An instance containing the loaded options if successful. + /// If the options argument to this function is null, this method returns an + /// AppOptions instance allocated from the heap. + static AppOptions* LoadFromJsonConfig(const char* config, + AppOptions* options = nullptr); + +#if INTERNAL_EXPERIMENTAL + /// @brief Determine whether the specified options match this set of options. + /// + /// Fields of this object that are empty are ignored in the comparison. + /// + /// @param[in] options Options to compare with. + bool operator==(const AppOptions& options) const { + return (package_name_.empty() || package_name_ == options.package_name_) && + (api_key_.empty() || api_key_ == options.api_key_) && + (app_id_.empty() || app_id_ == options.app_id_) && + (database_url_.empty() || database_url_ == options.database_url_) && + (ga_tracking_id_.empty() || + ga_tracking_id_ == options.ga_tracking_id_) && + (fcm_sender_id_.empty() || + fcm_sender_id_ == options.fcm_sender_id_) && + (storage_bucket_.empty() || + storage_bucket_ == options.storage_bucket_) && + (project_id_.empty() || project_id_ == options.project_id_); + } +#endif // INTERNAL_EXPERIMENTAL + +#if INTERNAL_EXPERIMENTAL + /// @brief Determine whether the specified options don't match this set of + /// options. + /// + /// Fields of this object that are empty are ignored in the comparison. + /// + /// @param[in] options Options to compare with. + bool operator!=(const AppOptions& options) const { + return !operator==(options); + } +#endif // INTERNAL_EXPERIMENTAL + +#if INTERNAL_EXPERIMENTAL +#if FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) + /// @brief Load default options from the resource file. + /// + /// @param[in] jni_env JNI environment required to allow Firebase services + /// to interact with the Android framework. + /// @param[in] activity JNI reference to the Android activity, required to + /// allow Firebase services to interact with the Android application. + /// @param options Options to populate from a resource file. + /// + /// @return An instance containing the loaded options if successful. + /// If the options argument to this function is null, this method returns an + /// AppOptions instance allocated from the heap.. + static AppOptions* LoadDefault(AppOptions* options, JNIEnv* jni_env, + jobject activity); +#endif // FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) + +#if !FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) + /// @brief Load default options from the resource file. + /// + /// @param options Options to populate from a resource file. + /// + /// @return An instance containing the loaded options if successful. + /// If the options argument to this function is null, this method returns an + /// AppOptions instance allocated from the heap. + static AppOptions* LoadDefault(AppOptions* options); +#endif // !FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) +#endif // INTERNAL_EXPERIMENTAL + +#if INTERNAL_EXPERIMENTAL +#if FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) + /// @brief Attempt to populate required options with default values if not + /// specified. + /// + /// @param[in] jni_env JNI environment required to allow Firebase services + /// to interact with the Android framework. + /// @param[in] activity JNI reference to the Android activity, required to + /// allow Firebase services to interact with the Android application. + /// + /// @return true if successful, false otherwise. + bool PopulateRequiredWithDefaults(JNIEnv* jni_env, jobject activity); +#endif // FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) + +#if !FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) + /// @brief Attempt to populate required options with default values if not + /// specified. + /// + /// @return true if successful, false otherwise. + bool PopulateRequiredWithDefaults(); +#endif // !FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) +#endif // INTERNAL_EXPERIMENTAL + + /// @cond FIREBASE_APP_INTERNAL + private: + /// Application package name (e.g Android package name or iOS bundle ID). + std::string package_name_; + /// API key used to communicate with Google Servers. + std::string api_key_; + /// ID of the app. + std::string app_id_; + /// ClientID of the app. + std::string client_id_; + /// Database root URL. + std::string database_url_; + /// Google analytics tracking ID. + std::string ga_tracking_id_; + /// FCM sender ID. + std::string fcm_sender_id_; + /// Google Cloud Storage bucket name. + std::string storage_bucket_; + /// Google Cloud project ID. + std::string project_id_; + /// @endcond +}; + +/// @brief Firebase application object. +/// +/// @if cpp_examples +/// firebase::App acts as a conduit for communication between all Firebase +/// services used by an application. +/// +/// For example: +/// @code +/// #if defined(__ANDROID__) +/// firebase::App::Create(firebase::AppOptions(), jni_env, activity); +/// #else +/// firebase::App::Create(firebase::AppOptions()); +/// #endif // defined(__ANDROID__) +/// @endcode +/// @endif +/// +/// @if swig_examples +/// FirebaseApp acts as a conduit for communication between all Firebase +/// services used by an application. A default instance is created +/// automatically, based on settings in your Firebase configuration file, +/// and all of the Firebase APIs connect with it automatically. +/// @endif +class App { + public: + ~App(); + +#if !FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) + /// @brief Initializes the default firebase::App with default options. + /// + /// @note This method is specific to non-Android implementations. + /// + /// @return New App instance, the App should not be destroyed for the + /// lifetime of the application. If default options can't be loaded this + /// will return null. + static App* Create(); +#endif // !FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) + +#ifndef SWIG +// +// For Unity, we actually use the simpler, iOS version for both platforms +// +#if FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) + /// @brief Initializes the default firebase::App with default options. + /// + /// @note This method is specific to the Android implementation. + /// + /// @param[in] jni_env JNI environment required to allow Firebase services + /// to interact with the Android framework. + /// @param[in] activity JNI reference to the Android activity, required to + /// allow Firebase services to interact with the Android application. + /// + /// @return New App instance. The App should not be destroyed for the + /// lifetime of the application. If default options can't be loaded this + /// will return null. + static App* Create(JNIEnv* jni_env, jobject activity); +#endif // FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) +#endif // SWIG + +#if !FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) + /// @brief Initializes the default firebase::App with the given options. + /// + /// @note This method is specific to non-Android implementations. + /// + /// Options are copied at initialization time, so changes to the object are + /// ignored. + /// @param[in] options Options that control the creation of the App. + /// + /// @return New App instance, the App should not be destroyed for the + /// lifetime of the application. + static App* Create(const AppOptions& options); +#endif // !FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) + +#ifndef SWIG +// +// For Unity, we actually use the simpler, iOS version for both platforms +// +#if FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) + /// @brief Initializes the default firebase::App with the given options. + /// + /// @note This method is specific to the Android implementation. + /// + /// Options are copied at initialization time, so changes to the object are + /// ignored. + /// @param[in] options Options that control the creation of the App. + /// @param[in] jni_env JNI environment required to allow Firebase services + /// to interact with the Android framework. + /// @param[in] activity JNI reference to the Android activity, required to + /// allow Firebase services to interact with the Android application. + /// + /// @return New App instance. The App should not be destroyed for the + /// lifetime of the application. + static App* Create(const AppOptions& options, JNIEnv* jni_env, + jobject activity); +#endif // FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) +#endif // SWIG + +#if !FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) + /// @brief Initializes a firebase::App with the given options that operates + /// on the named app. + /// + /// @note This method is specific to non-Android implementations. + /// + /// Options are copied at initialization time, so changes to the object are + /// ignored. + /// @param[in] options Options that control the creation of the App. + /// @param[in] name Name of this App instance. This is only required when + /// one application uses multiple App instances. + /// + /// @return New App instance, the App should not be destroyed for the + /// lifetime of the application. + static App* Create(const AppOptions& options, const char* name); +#endif // !FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) + +#ifndef SWIG +// +// For Unity, we actually use the simpler iOS version for both platforms +// +#if FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) + /// @brief Initializes a firebase::App with the given options that operates + /// on the named app. + /// + /// @note This method is specific to the Android implementation. + /// + /// Options are copied at initialization time, so changes to the object are + /// ignored. + /// @param[in] options Options that control the creation of the App. + /// @param[in] name Name of this App instance. This is only required when + /// one application uses multiple App instances. + /// @param[in] jni_env JNI environment required to allow Firebase services + /// to interact with the Android framework. + /// @param[in] activity JNI reference to the Android activity, required to + /// allow Firebase services to interact with the Android application. + /// + /// @return New App instance. The App should not be destroyed for the + /// lifetime of the application. + static App* Create(const AppOptions& options, const char* name, + JNIEnv* jni_env, jobject activity); +#endif // FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) +#endif // SWIG + + /// Get the default App, or nullptr if none has been created. + static App* GetInstance(); + + /// Get the App with the given name, or nullptr if none have been created. + static App* GetInstance(const char* name); + +#ifndef SWIG +// +// Unity doesn't need the JNI from here, it has its method to access JNI. +// +#if FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) + /// Get Java virtual machine, retrieved from the initial JNI environment. + /// @note This method is specific to the Android implementation. + /// + /// @return JNI Java virtual machine object. + JavaVM* java_vm() const; + /// Get JNI environment, needed for performing JNI calls, set on creation. + /// This is not trivial as the correct environment needs to retrieved per + /// thread. + /// @note This method is specific to the Android implementation. + /// + /// @return JNI environment object. + JNIEnv* GetJNIEnv() const; + /// Get a global reference to the Android activity provided to the App on + /// creation. Also serves as the Context needed for Firebase calls. + /// @note This method is specific to the Android implementation. + /// + /// @return Global JNI reference to the Android activity used to create + /// the App. The reference count of the returned object is not increased. + jobject activity() const { return activity_; } +#endif // FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) +#endif // SWIG + + /// Get the name of this App instance. + /// + /// @return The name of this App instance. If a name wasn't provided via + /// Create(), this returns @ref kDefaultAppName. + /// + /// @xmlonly + /// + /// Get the name of this FirebaseApp instance. + /// If a name wasn't provided via Create(), this will match @ref DefaultName. + /// + /// @endxmlonly + /// + const char* name() const { return name_.c_str(); } + + /// Get options the App was created with. + /// + /// @return Options used to create the App. + /// + /// @xmlonly + /// + /// @brief Get the AppOptions the FirebaseApp was created with. + /// @return AppOptions used to create the FirebaseApp. + /// + /// @endxmlonly + /// + const AppOptions& options() const { return options_; } + +#ifdef INTERNAL_EXPERIMENTAL + /// Sets whether automatic data collection is enabled for all products. + /// + /// By default, automatic data collection is enabled. To disable automatic + /// data collection in your mobile app, add to your Android application's + /// manifest: + /// + /// @if NOT_DOXYGEN + /// + /// @else + /// @code + /// <meta-data android:name="firebase_data_collection_default_enabled" + /// android:value="false" /> + /// @endcode + /// @endif + /// + /// or on iOS to your Info.plist: + /// + /// @if NOT_DOXYGEN + /// FirebaseDataCollectionDefaultEnabled + /// + /// @else + /// @code + /// <key>FirebaseDataCollectionDefaultEnabled</key> + /// <false/> + /// @endcode + /// @endif + /// + /// Once your mobile app is set to disable automatic data collection, you can + /// ask users to consent to data collection, and then enable it after their + /// approval by calling this method. + /// + /// This value is persisted across runs of the app so that it can be set once + /// when users have consented to collection. + /// + /// @param enabled Whether or not to enable automatic data collection. + void SetDataCollectionDefaultEnabled(bool enabled); + + /// Gets whether automatic data collection is enabled for all + /// products. Defaults to true unless + /// "firebase_data_collection_default_enabled" is set to false in your + /// Android manifest and FirebaseDataCollectionDefaultEnabled is set to NO + /// in your iOS app's Info.plist. + /// + /// @return Whether or not automatic data collection is enabled for all + /// products. + bool IsDataCollectionDefaultEnabled() const; +#endif // INTERNAL_EXPERIMENTAL +#ifdef SWIG + void SetDataCollectionDefaultEnabled(bool enabled); + bool IsDataCollectionDefaultEnabled() const; +#endif // SWIG + +#ifdef INTERNAL_EXPERIMENTAL + // This is only visible to SWIG and internal users of firebase::App. + /// Get the initialization results of modules that were initialized when + /// creating this app. + /// + /// @return Initialization results of modules indexed by module name. + const std::map& init_results() const { + return init_results_; + } + + // Returns a pointer to the function registry, used by components to expose + // methods to one another without introducing linkage dependencies. + internal::FunctionRegistry* function_registry(); + + /// @brief Register a library which utilizes the Firebase C++ SDK. + /// + /// @param library Name of the library to register as a user of the Firebase + /// C++ SDK. + /// @param version Version of the library being registered. + static void RegisterLibrary(const char* library, const char* version); + + // Internal method to retrieve the combined string of registered libraries. + static const char* GetUserAgent(); + + // On desktop, when App.Create() is invoked without parameters, it looks for a + // file named 'google-services-desktop.json', to load parameters from. + // This function sets the location to search in. + // Note - when setting this, make sure to end the path with the appropriate + // path separator! + static void SetDefaultConfigPath(const char* path); +#endif // INTERNAL_EXPERIMENTAL + +#ifdef INTERNAL_EXPERIMENTAL +#if FIREBASE_PLATFORM_DESKTOP + // These methods are only visible to SWIG and internal users of firebase::App. + + /// Logs a heartbeat using the internal HeartbeatController. + void LogHeartbeat() const; + + /// Get a pointer to the HeartbeatController associated with this app. + std::shared_ptr GetHeartbeatController() + const; +#endif // FIREBASE_PLATFORM_DESKTOP +#endif // INTERNAL_EXPERIMENTAL + +#ifdef INTERNAL_EXPERIMENTAL +#if FIREBASE_PLATFORM_ANDROID + /// Get the platform specific app implementation referenced by this object. + /// + /// @return Global reference to the FirebaseApp. The returned reference + /// most be deleted after use. + jobject GetPlatformApp() const; +#elif FIREBASE_PLATFORM_IOS || FIREBASE_PLATFORM_TVOS +#ifdef __OBJC__ + /// Get the platform specific app implementation referenced by this object. + /// + /// @return Reference to the FIRApp object owned by this app. + FIRApp* GetPlatformApp() const; +#endif // __OBJC__ +#endif // FIREBASE_PLATFORM_ANDROID, FIREBASE_PLATFORM_IOS, + // FIREBASE_PLATFORM_TVOS +#endif // INTERNAL_EXPERIMENTAL + + private: + /// Construct the object. + App() + : +#if FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) + activity_(nullptr), +#endif + internal_(nullptr) { + Initialize(); + +#ifdef FIREBASE_LINUX_BUILD_CONFIG_STRING + CheckCompilerString(FIREBASE_LINUX_BUILD_CONFIG_STRING); +#endif // FIREBASE_LINUX_BUILD_CONFIG_STRING + } + + /// Initialize internal implementation + void Initialize(); + +#ifndef SWIG +// +// Unity doesn't need the JNI from here, it has its method to access JNI. +// +#if FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) + /// Android activity. + /// @note This is specific to Android. + jobject activity_; +#endif // FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) +#endif // SWIG + + /// Name of the App instance. + std::string name_; + /// Options used to create this App instance. + AppOptions options_; + /// Module initialization results. + std::map init_results_; + /// Pointer to other internal data used by this instance. + internal::AppInternal* internal_; + + /// @endcond +}; + +} // namespace firebase + +#endif // FIREBASE_APP_SRC_INCLUDE_FIREBASE_APP_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/auth.h b/packages/firebase_core/firebase_core/firebase_core/firebase/auth.h new file mode 100644 index 000000000000..408c34ea9006 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/auth.h @@ -0,0 +1,939 @@ +/* + * Copyright 2016 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_AUTH_SRC_INCLUDE_FIREBASE_AUTH_H_ +#define FIREBASE_AUTH_SRC_INCLUDE_FIREBASE_AUTH_H_ + +#include + +#include "firebase/app.h" +#include "firebase/auth/user.h" +#include "firebase/future.h" +#include "firebase/internal/common.h" + +#if !defined(DOXYGEN) +#ifndef SWIG +FIREBASE_APP_REGISTER_CALLBACKS_REFERENCE(auth) +#endif // SWIG +#endif // !defined(DOXYGEN) + +namespace firebase { + +/// @brief Firebase Authentication API. +/// +/// Firebase Authentication provides backend services to securely authenticate +/// users. It can authenticate users using passwords and federated identity +/// provider credentials, and it can integrate with a custom auth backend. +namespace auth { + +// Predeclarations. +struct AuthData; +class AuthStateListener; +class IdTokenListener; +class PhoneAuthProvider; +struct AuthCompletionHandle; +class FederatedAuthProvider; +class FederatedOAuthProvider; +struct SignInResult; + +/// @brief Firebase authentication object. +/// +/// +/// @if swig_examples +/// Firebase.Auth.FirebaseAuth is the gateway to the Firebase authentication +/// API. With it, you can reference @ref Firebase.Auth.FirebaseAuth objects to +/// manage user accounts and credentials. +/// +/// Each @ref Firebase.FirebaseApp has up to one Firebase.Auth.FirebaseAuth +/// class. You acquire the Firebase.Auth.FirebaseAuth class through the static +/// function @ref Firebase.Auth.FirebaseAuth.GetAuth. +/// +/// For example: +/// @code{.cs} +/// // Get the Auth class for your App. +/// Firebase.Auth.FirebaseAuth auth = Firebase.Auth.FirebaseAuth.GetAuth(app); +/// +/// // Request anonymous sign-in and wait until asynchronous call completes. +/// auth.SignInAnonymouslyAsync().ContinueWith((authTask) => { +/// // Print sign in results. +/// if (authTask.IsCanceled) { +/// DebugLog("Sign-in canceled."); +/// } else if (authTask.IsFaulted) { +/// DebugLog("Sign-in encountered an error."); +/// DebugLog(authTask.Exception.ToString()); +/// } else if (authTask.IsCompleted) { +/// Firebase.Auth.User user = authTask.Result; +/// DebugLog(String.Format("Signed in as {0} user.", +/// user.Anonymous ? "an anonymous" : "a non-anonymous")); +/// DebugLog("Signing out."); +/// auth.SignOut(); +/// }); +/// @endcode +/// @endif +/// +/// @if cpp_examples +/// +/// firebase::auth::Auth is the gateway to the Firebase authentication API. +/// With it, you can reference @ref firebase::auth::User objects to manage user +/// accounts and credentials. +/// +/// Each @ref firebase::App has up to one firebase::auth::Auth class. You +/// acquire the firebase::auth::Auth class through the static function +/// @ref firebase::auth::Auth::GetAuth. +/// +/// For example: +/// @code{.cpp} +/// +/// // Get the Auth class for your App. +/// firebase::auth::Auth* auth = firebase::auth::Auth::GetAuth(app); +/// +/// // Request anonymous sign-in and wait until asynchronous call completes. +/// firebase::Future sign_in_future = +/// auth->SignInAnonymously(); +/// while(sign_in_future.status() == firebase::kFutureStatusPending) { +/// // when polling, like this, make sure you service your platform's +/// // message loop +/// // see https://github.com/firebase/quickstart-cpp for a sample +/// ProcessEvents(300); +/// std::cout << "Signing in...\n"; +/// } +/// +/// const firebase::auth::AuthError error = +/// static_cast(sign_in_future.error()); +/// if (error != firebase::auth::kAuthErrorNone) { +/// std::cout << "Sign in failed with error '" +/// << sign_in_future.error_message() << "'\n"; +/// } else { +/// firebase::auth::User* user = *sign_in_future.result(); +/// // is_anonymous from Anonymous +/// std::cout << "Signed in as " +/// << (user->is_anonymous() ? "an anonymous" : "a non-anonymous") +/// << " user\n"; +/// } +/// @endcode +/// @endif +class Auth { + public: + /// @brief Results of calls @ref FetchProvidersForEmail. + /// + /// + /// @if swig_examples + /// @see FirebaseAuth.FetchProvidersForEmailAsync(). + /// @endif + /// + struct FetchProvidersResult { + /// The IDPs (identity providers) that can be used for `email`. + /// An array of length `num_providers` of null-terminated strings. + /// + /// The C# doc string is in the SWIG file because nested structs are + /// causing problems b/35780150 + /// + std::vector providers; + }; + + ~Auth(); + + /// Synchronously gets the cached current user, or nullptr if there is none. + /// @note This function may block and wait until the Auth instance finishes + /// loading the saved user's state. This should only happen for a short + /// period of time after the Auth instance is created. + /// + /// @xmlonly + /// + /// Synchronously gets the cached current user, or null if there is none. + /// @note This function may block and wait until the Auth instance finishes + /// loading the saved user's state. This should only happen for a short + /// period of time after the Auth instance is created. + /// + /// @endxmlonly + /// + User* current_user(); + + /// The current user language code. This can be set to the app’s current + /// language by calling set_language_code. The string must be a language code + /// that follows BCP 47. This will return an empty string if the app default + /// language code is being used. + std::string language_code() const; + + /// Sets the user-facing language code for auth operations that can be + /// internationalized, such as FirebaseUser.sendEmailVerification(). This + /// language code should follow the conventions defined by the IETF in BCP 47. + void set_language_code(const char* language_code); + + /// Sets the user-facing language code to be the default app language. This + /// uses a language associated with the device's locale data. On desktop + /// this will set the language code to the Firebase service's default. You + /// may subsequently customize the language code again by invoking + /// set_language_code(). + void UseAppLanguage(); + + // ----- Providers ------------------------------------------------------- + /// Asynchronously requests the IDPs (identity providers) that can be used + /// for the given email address. + /// + /// Useful for an "identifier-first" login flow. + /// + /// @if cpp_examples + /// The following sample code illustrates a possible login screen + /// that allows the user to pick an identity provider. + /// @code{.cpp} + /// // This function is called every frame to display the login screen. + /// // Returns the identity provider name, or "" if none selected. + /// const char* DisplayIdentityProviders(firebase::auth::Auth& auth, + /// const char* email) { + /// // Get results of most recent call to FetchProvidersForEmail(). + /// firebase::Future future = + /// auth.FetchProvidersForEmailLastResult(); + /// const firebase::auth::Auth::FetchProvidersResult* result = + /// future.result(); + /// + /// // Header. + /// ShowTextBox("Sign in %s", email); + /// + /// // Fetch providers from the server if we need to. + /// const bool refetch = + /// future.status() == firebase::kFutureStatusInvalid || + /// (result != nullptr && strcmp(email, result->email.c_str()) != 0); + /// if (refetch) { + /// auth.FetchProvidersForEmail(email); + /// } + /// + /// // Show a waiting icon if we're waiting for the asynchronous call to + /// // complete. + /// if (future.status() != firebase::kFutureStatusComplete) { + /// ShowImage("waiting icon"); + /// return ""; + /// } + /// + /// // Show error code if the call failed. + /// if (future.error() != firebase::auth::kAuthErrorNone) { + /// ShowTextBox("Error fetching providers: %s", future.error_message()); + /// } + /// + /// // Show a button for each provider available to this email. + /// // Return the provider for the button that's pressed. + /// for (size_t i = 0; i < result->providers.size(); ++i) { + /// const bool selected = ShowTextButton(result->providers[i].c_str()); + /// if (selected) return result->providers[i].c_str(); + /// } + /// return ""; + /// } + /// @endcode + /// @endif + Future FetchProvidersForEmail(const char* email); + + /// Get results of the most recent call to @ref FetchProvidersForEmail. + Future FetchProvidersForEmailLastResult() const; + + // ----- Sign In --------------------------------------------------------- + /// Asynchronously logs into Firebase with the given Auth token. + /// + /// An error is returned, if the token is invalid, expired or otherwise + /// not accepted by the server. + Future SignInWithCustomToken(const char* token); + + /// Get results of the most recent call to @ref SignInWithCustomToken. + Future SignInWithCustomTokenLastResult() const; + + /// Convenience method for @ref SignInAndRetrieveDataWithCredential that + /// doesn't return additional identity provider data. + Future SignInWithCredential(const Credential& credential); + + /// Get results of the most recent call to @ref SignInWithCredential. + Future SignInWithCredentialLastResult() const; + + /// Sign-in a user authenticated via a federated auth provider. + /// + /// @param[in] provider Contains information on the provider to authenticate + /// with. + /// + /// @return A Future with the result of the sign-in request. + /// + /// @note: This operation is supported only on iOS, tvOS and Android + /// platforms. On other platforms this method will return a Future with a + /// preset error code: kAuthErrorUnimplemented. + Future SignInWithProvider(FederatedAuthProvider* provider); + + /// Asynchronously logs into Firebase with the given credentials. + /// + /// For example, the credential could wrap a Facebook login access token or + /// a Twitter token/token-secret pair. + /// + /// The SignInResult contains both a reference to the User (which can be null + /// if the sign in failed), and AdditionalUserInfo, which holds details + /// specific to the Identity Provider used to sign in. + /// + /// An error is returned if the token is invalid, expired, or otherwise not + /// accepted by the server. + Future SignInAndRetrieveDataWithCredential( + const Credential& credential); + + /// Get results of the most recent call to + /// @ref SignInAndRetrieveDataWithCredential. + Future SignInAndRetrieveDataWithCredentialLastResult() const; + + /// Asynchronously creates and becomes an anonymous user. + /// If there is already an anonymous user signed in, that user will be + /// returned instead. + /// If there is any other existing user, that user will be signed out. + /// + /// + /// @if swig_examples + /// @code{.cs} + /// bool SignIn(Firebase.Auth.FirebaseAuth auth) { + /// auth.SignInAnonymouslyAsync().ContinueWith((authTask) => { + /// if (authTask.IsCanceled) { + /// DebugLog("Anonymous sign in canceled."); + /// } else if (authTask.IsFaulted) { + /// DebugLog("Anonymous sign in encountered an error."); + /// DebugLog(authTask.Exception.ToString()); + /// } else if (authTask.IsCompleted) { + /// DebugLog("Anonymous sign in successful!"); + /// } + /// }); + /// } + /// @endcode + /// @endif + /// + /// @if cpp_examples + /// The following sample code illustrates the sign-in flow that might be + /// used by a game or some other program with a regular (for example, 30Hz) + /// update loop. + /// + /// The sample calls SignIn() every frame. We don’t maintain our own + /// Futures but instead call SignInAnonymouslyLastResult() to get the Future + /// of our most recent call. + /// + /// @code{.cpp} + /// // Try to ensure that we get logged in. + /// // This function is called every frame. + /// bool SignIn(firebase::auth::Auth& auth) { + /// // Grab the result of the latest sign-in attempt. + /// firebase::Future future = + /// auth.SignInAnonymouslyLastResult(); + /// + /// // If we're in a state where we can try to sign in, do so. + /// if (future.status() == firebase::kFutureStatusInvalid || + /// (future.status() == firebase::kFutureStatusComplete && + /// future.error() != firebase::auth::kAuthErrorNone)) { + /// auth.SignInAnonymously(); + /// } + /// + /// // We're signed in if the most recent result was successful. + /// return future.status() == firebase::kFutureStatusComplete && + /// future.error() == firebase::auth::kAuthErrorNone; + /// } + /// @endcode + /// @endif + Future SignInAnonymously(); + + /// Get results of the most recent call to @ref SignInAnonymously. + Future SignInAnonymouslyLastResult() const; + + /// Signs in using provided email address and password. + /// An error is returned if the password is wrong or otherwise not accepted + /// by the server. + Future SignInWithEmailAndPassword(const char* email, + const char* password); + + /// Get results of the most recent call to @ref SignInWithEmailAndPassword. + Future SignInWithEmailAndPasswordLastResult() const; + + /// Creates, and on success, logs in a user with the given email address + /// and password. + /// + /// An error is returned when account creation is unsuccessful + /// (due to another existing account, invalid password, etc.). + Future CreateUserWithEmailAndPassword(const char* email, + const char* password); + + /// Get results of the most recent call to + /// @ref CreateUserWithEmailAndPassword. + Future CreateUserWithEmailAndPasswordLastResult() const; + + /// Removes any existing authentication credentials from this client. + /// This function always succeeds. + void SignOut(); + + // ----- Password Reset ------------------------------------------------- + /// Initiates a password reset for the given email address. + /// + /// If the email address is not registered, then the returned task has a + /// status of IsFaulted. + /// + /// + /// @if swig_examples + /// @code{.cs} + /// void ResetPassword(string email) { + /// auth.SendPasswordResetEmail(email).ContinueWith((authTask) => { + /// if (authTask.IsCanceled) { + /// DebugLog("Password reset was canceled."); + /// } else if (authTask.IsFaulted) { + /// DebugLog("Password reset encountered an error."); + /// DebugLog(authTask.Exception.ToString()); + /// } else if (authTask.IsCompleted) { + /// DebugLog("Password reset successful!"); + /// } + /// }); + /// } + /// @endcode + /// @endif + /// + /// @if cpp_examples + /// The following sample code illustrating a possible password reset flow. + /// Like in the Anonymous Sign-In example above, the ResetPasswordScreen() + /// function is called once per frame (say 30 times per second). + /// + /// No state is persisted by the caller in this example. The state of the + /// most recent calls are instead accessed through calls to functions like + /// auth.SendPasswordResetEmailLastResult(). + /// @code{.cpp} + /// const char* ImageNameForStatus(const firebase::FutureBase& future) { + /// assert(future.status() != firebase::kFutureStatusInvalid); + /// return future.status() == firebase::kFutureStatusPending + /// ? "waiting icon" + /// : future.error() == firebase::auth::kAuthErrorNone + /// ? "checkmark icon" + /// : "x mark icon"; + /// } + /// + /// // This function is called once per frame. + /// void ResetPasswordScreen(firebase::auth::Auth& auth) { + /// // Gather email address. + /// // ShowInputBox() returns a value when `enter` is pressed. + /// const std::string email = ShowInputBox("Enter e-mail"); + /// if (email != "") { + /// auth.SendPasswordResetEmail(email.c_str()); + /// } + /// + /// // Show checkmark, X-mark, or waiting icon beside the + /// // email input box, to indicate if email has been sent. + /// firebase::Future send_future = + /// auth.SendPasswordResetEmailLastResult(); + /// ShowImage(ImageNameForStatus(send_future)); + /// + /// // Display error message if the e-mail could not be sent. + /// if (send_future.status() == firebase::kFutureStatusComplete && + /// send_future.error() != firebase::auth::kAuthErrorNone) { + /// ShowTextBox(send_future.error_message()); + /// } + /// } + /// @endcode + /// @endif + Future SendPasswordResetEmail(const char* email); + + /// Get results of the most recent call to @ref SendPasswordResetEmail. + Future SendPasswordResetEmailLastResult() const; + +#ifndef SWIG + /// @brief Registers a listener to changes in the authentication state. + /// + /// There can be more than one listener registered at the same time. + /// The listeners are called asynchronously, possibly on a different thread. + /// + /// Authentication state changes are: + /// - Right after the listener has been registered + /// - When a user signs in + /// - When the current user signs out + /// - When the current user changes + /// + /// It is a recommended practice to always listen to sign-out events, as you + /// may want to prompt the user to sign in again and maybe restrict the + /// information or actions they have access to. + /// + /// Use RemoveAuthStateListener to unregister a listener. + /// + /// @note The caller owns `listener` and is responsible for destroying it. + /// When `listener` is destroyed, or when @ref Auth is destroyed, + /// RemoveAuthStateListener is called automatically. + void AddAuthStateListener(AuthStateListener* listener); + + /// @brief Unregisters a listener of authentication changes. + /// + /// Listener must previously been added with AddAuthStateListener. + /// + /// Note that listeners unregister themselves automatically when they + /// are destroyed, and the Auth class unregisters its listeners when the + /// Auth class itself is destroyed, so this function does not normally need + /// to be called explicitly. + void RemoveAuthStateListener(AuthStateListener* listener); + + /// @brief Registers a listener to changes in the ID token state. + /// + /// There can be more than one listener registered at the same time. + /// The listeners are called asynchronously, possibly on a different thread. + /// + /// Authentication state changes are: + /// - Right after the listener has been registered + /// - When a user signs in + /// - When the current user signs out + /// - When the current user changes + /// - When there is a change in the current user's token + /// + /// Use RemoveIdTokenListener to unregister a listener. + /// + /// @note The caller owns `listener` and is responsible for destroying it. + /// When `listener` is destroyed, or when @ref Auth is destroyed, + /// RemoveIdTokenListener is called automatically. + void AddIdTokenListener(IdTokenListener* listener); + + /// @brief Unregisters a listener of ID token changes. + /// + /// Listener must previously been added with AddIdTokenListener. + /// + /// Note that listeners unregister themselves automatically when they + /// are destroyed, and the Auth class unregisters its listeners when the + /// Auth class itself is destroyed, so this function does not normally need + /// to be called explicitly. + void RemoveIdTokenListener(IdTokenListener* listener); +#endif // not SWIG + + /// Gets the App this auth object is connected to. + App& app(); + + /// Returns the Auth object for an App. Creates the Auth if required. + /// + /// To get the Auth object for the default app, use, + /// GetAuth(GetDefaultFirebaseApp()); + /// + /// If the library Auth fails to initialize, init_result_out will be + /// written with the result status (if a pointer is given). + /// + /// @param[in] app The App to use for the Auth object. + /// @param[out] init_result_out Optional: If provided, write the init result + /// here. Will be set to kInitResultSuccess if initialization succeeded, or + /// kInitResultFailedMissingDependency on Android if Google Play services is + /// not available on the current device. + static Auth* GetAuth(App* app, InitResult* init_result_out = nullptr); + + private: + /// @cond FIREBASE_APP_INTERNAL + friend class ::firebase::App; + friend class ::firebase::auth::PhoneAuthProvider; + friend class IdTokenRefreshListener; + friend class IdTokenRefreshThread; + friend class UserDataPersist; + friend class UserDesktopTest; + friend class AuthDesktopTest; + + friend void EnableTokenAutoRefresh(AuthData* authData); + friend void DisableTokenAutoRefresh(AuthData* authData); + friend void ResetTokenRefreshCounter(AuthData* authData); + friend void LogHeartbeat(Auth* auth); + /// @endcond + + // Find Auth instance using App. Return null if the instance does not exist. + static Auth* FindAuth(App* app); + + // Provides access to the auth token for the current user. Returns the + // current user's auth token, or an empty string, if there isn't one. + // Note that this can potentially return an expired token from the cache. + static bool GetAuthTokenForRegistry(App* app, void* /*unused*/, void* out); + + // Provides asynchronous access to the auth token for the current user. Allow + // the caller to force-refresh the token. Even without force-refresh, this + // ensure the future contain a fresh current user's auth token. This function + // returns invalid future if user data is not available. + static bool GetAuthTokenAsyncForRegistry(App* app, void* force_refresh, + void* out_future); + + // Provides access to the current user's uid, equivalent to calling + // this->current_user()->uid(). Returns the current user's uid or an empty + // string, if there isn't one. The out pointer is expected to point to an + // instance of std::string. + static bool GetCurrentUserUidForRegistry(App* app, void* /*unused*/, + void* out); + + // Starts and stops a thread to ensure that the cached auth token is never + // kept long enough for it to expire. Refcounted, so multiple classes can + // register this without causing problems. + static bool StartTokenRefreshThreadForRegistry(App* app, void* /*unused*/, + void* /*unused*/); + static bool StopTokenRefreshThreadForRegistry(App* app, void* /*unused*/, + void* /*unused*/); + + // Adds an indirect auth state listener implemented as a callback and a + // context object. + // + // @param callback a function pointer that takes a single void* argument and + // returns void (i.e. it has type void (*)(void*)). + // @param context a pointer to an arbitrary object that Auth will pass to + // the callback when the auth state changes. + static bool AddAuthStateListenerForRegistry(App* app, void* callback, + void* context); + + // Removes the indirect auth state listener that was added with the same + // arguments. + static bool RemoveAuthStateListenerForRegistry(App* app, void* callback, + void* context); + + // Init and Destroy the platform specific auth data. + void InitPlatformAuth(AuthData* const auth_data); + void DestroyPlatformAuth(AuthData* const auth_data); + + // Call GetAuth() to create an Auth object. + // Constructors and destructors don't make any external calls. + // They just initialize and deinitialize internal variables. + Auth(App* app, void* auth_impl); + + // Delete the internal AuthData object. + void DeleteInternal(); + + // This class uses the pimpl mechanism to avoid exposing platform-dependent + // implementation. + AuthData* auth_data_; +}; + +#ifndef SWIG +/// @brief Listener called when there is a change in the authentication state. +/// +/// Override base class method to handle authentication state changes. +/// Methods are invoked asynchronously and may be invoked on other threads. +class AuthStateListener { + public: + /// @note: Destruction of the listener automatically calls + /// RemoveAuthStateListener() from the Auths this listener is registered with, + /// if those Auths have not yet been destroyed. + virtual ~AuthStateListener(); + + /// Called when the authentication state of `auth` changes. + /// - Right after the listener has been registered + /// - When a user is signed in + /// - When the current user is signed out + /// - When the current user changes + /// + /// @param[in] auth Disambiguates which @ref Auth instance the event + /// corresponds to, in the case where you are using more than one at the same + /// time. + virtual void OnAuthStateChanged(Auth* auth) = 0; + + private: + /// @cond FIREBASE_APP_INTERNAL + friend class Auth; + /// @endcond + + /// The Auths with which this listener has been registered. + std::vector auths_; +}; +#endif // not SWIG + +#ifndef SWIG +/// @brief Listener called when there is a change in the ID token. +/// +/// Override base class method to handle ID token changes. +/// Methods are invoked asynchronously and may be invoked on other threads. +class IdTokenListener { + public: + /// @note: Destruction of the listener automatically calls + /// RemoveIdTokenListener() from the Auths this listener is registered with, + /// if those Auths have not yet been destroyed. + virtual ~IdTokenListener(); + + /// Called when there is a change in the current user's token. + /// - Right after the listener has been registered + /// - When a user signs in + /// - When the current user signs out + /// - When the current user changes + /// - When there is a change in the current user's token + /// + /// @param[in] auth Disambiguates which @ref Auth instance the event + /// corresponds to, in the case where you are using more than one at the same + /// time. + virtual void OnIdTokenChanged(Auth* auth) = 0; + + private: + /// @cond FIREBASE_APP_INTERNAL + friend class Auth; + /// @endcond + + /// The Auths with which this listener has been registered. + std::vector auths_; +}; + +#endif // not SWIG + +/// @brief Used to authenticate with Federated Auth Providers. +/// +/// The federated auth provider implementation may facilitate multiple provider +/// types in the future, with support for OAuth to start. +class FederatedAuthProvider { + public: +#ifdef INTERNAL_EXPERIMENTAL +#ifndef SWIG + /// @brief Contains resulting information of a user authenticated by a + /// Federated Auth Provider. This information will be used by the internal + /// implementation to construct a corresponding User object. + struct AuthenticatedUserData { + /// The unique ID identifies the IdP account. + const char* uid; + + /// [opt] The email of the account. + const char* email; + + /// Whether the sign-in email is verified. + bool is_email_verified; + + /// [opt] The display name for the account. + const char* display_name; + + /// [opt] The username for the account. + const char* user_name; + + /// [opt] The photo Url for the account, if one exists. + const char* photo_url; + + /// The linked provider ID (e.g. "google.com" for the Google provider). + const char* provider_id; + + /// A Firebase Auth ID token for the authenticated user. + const char* access_token; + + /// A Firebase Auth refresh token for the authenticated user. + const char* refresh_token; + + /// [opt] IdP user profile data corresponding to the provided credential. + std::map raw_user_info; + + /// The number of seconds in which the ID token expires. + uint64_t token_expires_in_seconds; + }; + + /// @brief Handlers for client applications to facilitate federated auth + /// requests on non-mobile systems. + template + class Handler { + public: + virtual ~Handler() {} + + /// @brief Application sign-in handler. + /// + /// The application must implement this method to handle federated auth user + /// sign-in requests on non-mobile systems. + /// + /// @param[in] provider_data Contains information on the provider to + /// authenticate with. + /// @param[in] completion_handle Internal data pertaining to this operation + /// which must be passed to SignInComplete once the handler has completed + /// the sign in operation. + /// + /// @see Auth#SignInWithProvider + /// @see SignInComplete + virtual void OnSignIn(const T& provider_data, + AuthCompletionHandle* completion_handle) = 0; + + /// Completion for OnSignIn events. + /// + /// Invoke this method once the corresponding OnSignIn has been fulfilled. + /// This method will trigger the associated Future previously + /// returned from the Auth::SignInWithProvider method. + /// + /// @param[in] completion_handle The handle provided to the application's + /// FederatedAuthProvider::Handler::OnSignIn method. + /// @param[in] user_data The application's resulting Firebase user + /// values following the authorization request. + /// @param[in] auth_error The enumerated status code of the authorization + /// request. + /// @param[in] error_message An optional error message to be set in the + /// Future. + /// + /// @see OnSignIn + /// @see Auth::SignInWithProvider + void SignInComplete(AuthCompletionHandle* completion_handle, + const AuthenticatedUserData& user_data, + AuthError auth_error, const char* error_message); + + /// @brief Application user account link handler. + /// + /// The application must implement this method to handle federated auth user + /// link requests on non-mobile systems. + /// + /// @param[in] provider_data Contains information on the provider to + /// authenticate with. + /// @param[in] completion_handle Internal data pertaining to this operation + /// which must be passed to LinkComplete once the handler has completed the + /// user link operation. + /// + /// @see User#LinkWithProvider + virtual void OnLink(const T& provider_data, + AuthCompletionHandle* completion_handle) = 0; + + /// Completion for non-mobile user authorization handlers. + /// + /// Invoke this method once the OnLine process has been fulfilled. This + /// method will trigger the associated Future previously + /// returned from an invocation of User::LinkWithProvider. + /// + /// @param[in] completion_handle The handle provided to the + /// application's FederatedAuthProvider::Handler::OnLink method. + /// @param[in] user_data The application's resulting Firebase user + /// values following the user link request. + /// @param[in] auth_error The enumerated status code of the user link + /// request. + /// @param[in] error_message An optional error message to be set in the + /// Future. + /// + /// @see OnLink + /// @see User#LinkWithProvider + void LinkComplete(AuthCompletionHandle* completion_handle, + const AuthenticatedUserData& user_data, + AuthError auth_error, const char* error_message); + + /// @brief Application user re-authentication handler. + /// + /// The application must implement this method to handle federated auth user + /// re-authentication requests on non-mobile systems. + /// + /// @param[in] provider_data Contains information on the provider to + /// authenticate with. + /// @param[in] completion_handle Internal data pertaining to this operation + /// which must be passed to ReauthenticateComplete once the handler has + /// completed the reauthentication operation. + /// + /// @see User#ReauthenticateWithProviderComplete + virtual void OnReauthenticate(const T& provider_data, + AuthCompletionHandle* completion_handle) = 0; + + /// Completion for non-mobile user authorization handlers. + /// + /// Invoke this method once the OnReauthenticate process has been + /// fulfilled. This method will trigger the associated Future + /// previously returned from an invocation of + /// User::ReauthenticateWithProvider. + /// + /// @param[in] completion_handle The handle provided to the application's + /// FederatedAuthProvider::Handler::OnReauthenticate method. + /// @param[in] user_data The application's resulting Firebase user + /// values following the user re-authentication request. + /// @param[in] auth_error The enumerated status code of the reauthentication + /// request. + /// @param[in] error_message An optional error message to be set in the + /// Future. + /// + /// @see OnReauthenticate + /// @see User#ReuthenticateWithProvider + void ReauthenticateComplete(AuthCompletionHandle* completion_handle, + const AuthenticatedUserData& user_data, + AuthError auth_error, + const char* error_message); + }; +#endif // not SWIG +#endif // INTERNAL_EXPERIMENTAL + + FederatedAuthProvider() {} + virtual ~FederatedAuthProvider() {} + + private: + friend class ::firebase::auth::Auth; + friend class ::firebase::auth::User; + virtual Future SignIn(AuthData* auth_data) = 0; + virtual Future Link(AuthData* auth_data) = 0; + virtual Future Reauthenticate(AuthData* auth_data) = 0; +}; + +/// @brief Authenticates with Federated OAuth Providers via the +/// firebase::auth::Auth and firebase::auth::User classes. +/// +/// Once configured with a provider id, and with OAuth scope and OAuth custom +/// parameters via an FedeartedOAuthProviderData structure, an object of +/// this class may be used via Auth::SignInWithProvider to sign-in users, or via +/// User::LinkWithProvider and User::ReauthenticateWithProvider for cross +/// account linking and user reauthentication, respectively. +class FederatedOAuthProvider : public FederatedAuthProvider { + public: +#ifdef INTERNAL_EXPERIMENTAL +#ifndef SWIG + /// @brief A FederatedAuthProvider typed specifically for OAuth Authentication + /// handling. + /// + /// To be used on non-mobile environments for custom OAuth implementations and + /// UI flows. + typedef FederatedAuthProvider::Handler + AuthHandler; +#endif // !SWIG +#endif // INTERNAL_EXPERIMENTAL + + /// Constructs an unconfigured provider. + FederatedOAuthProvider(); + + /// Constructs a FederatedOAuthProvider preconfigured with provider data. + /// + /// @param[in] provider_data Contains the federated provider id and OAuth + /// scopes and OAuth custom parameters required for user authentication and + /// user linking. + explicit FederatedOAuthProvider( + const FederatedOAuthProviderData& provider_data); + +#ifdef INTERNAL_EXPERIMENTAL +#ifndef SWIG + /// @brief Constructs a provider with the required information to authenticate + /// using an OAuth Provider. + /// + /// An AuthHandler is required on desktop platforms to facilitate custom + /// implementations of OAuth authentication. The AuthHandler must outlive the + /// instance of this OAuthProvider on desktop systems and is ignored on iOS, + /// tvOS, and Android platforms. + /// + /// @param[in] provider_data Contains information on the provider to + /// authenticate with. + /// @param[in] handler An FederatedOAuthProviderData typed + /// FederatedAuthProvider::Handler which be invoked on non-mobile systems + /// to handle authentication requests. + FederatedOAuthProvider(const FederatedOAuthProviderData& provider_data, + AuthHandler* handler); +#endif // !SWIG +#endif // INTERNAL_EXPERIMENTAL + + ~FederatedOAuthProvider() override; + + /// @brief Configures the provider with OAuth provider information. + /// + /// @param[in] provider_data Contains the federated provider id and OAuth + /// scopes and OAuth custom parameters required for user authentication and + /// user linking. + void SetProviderData(const FederatedOAuthProviderData& provider_data); + +#ifdef INTERNAL_EXPERIMENTAL +#ifndef SWIG + /// @brief Configures the use of an AuthHandler for non-mobile systems. + /// + /// The existence of a handler is required for non-mobile systems, and is + /// ignored on iOS, tvOS and Android platforms. + /// + /// @param[in] handler An FederatedOAuthProviderData typed + /// FederatedAuthProvider::Handler which be invoked on non-mobile systems + /// to handle authentication requests. The handler must outlive the instance + /// of this FederatedOAuthProvider. + void SetAuthHandler(AuthHandler* handler); +#endif // !SWIG +#endif // INTERNAL_EXPERIMENTAL + + private: + friend class ::firebase::auth::Auth; + + Future SignIn(AuthData* auth_data) override; + Future Link(AuthData* auth_data) override; + Future Reauthenticate(AuthData* auth_data) override; + + FederatedOAuthProviderData provider_data_; +#ifdef INTERNAL_EXPERIMENTAL + AuthHandler* handler_; +#endif // INTERNAL_EXPERIMENTAL +}; + +} // namespace auth +} // namespace firebase + +#endif // FIREBASE_AUTH_SRC_INCLUDE_FIREBASE_AUTH_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/auth/credential.h b/packages/firebase_core/firebase_core/firebase_core/firebase/auth/credential.h new file mode 100644 index 000000000000..a179d199b67a --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/auth/credential.h @@ -0,0 +1,633 @@ +/* + * Copyright 2016 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_AUTH_SRC_INCLUDE_FIREBASE_AUTH_CREDENTIAL_H_ +#define FIREBASE_AUTH_SRC_INCLUDE_FIREBASE_AUTH_CREDENTIAL_H_ + +#include + +#include + +#include "firebase/auth/types.h" +#include "firebase/internal/common.h" + +namespace firebase { + +// Predeclarations. +class App; + +/// @cond FIREBASE_APP_INTERNAL +template +class Future; +/// @endcond + +namespace auth { + +// Predeclarations. +class Auth; +class User; + +// Opaque internal types. +struct AuthData; +class ForceResendingTokenData; +struct PhoneAuthProviderData; +struct PhoneListenerData; + +/// @brief Authentication credentials for an authentication provider. +/// +/// An authentication provider is a service that allows you to authenticate +/// a user. Firebase provides email/password authentication, but there are also +/// external authentication providers such as Facebook. +class Credential { +#ifndef SWIG + /// @cond FIREBASE_APP_INTERNAL + friend class EmailAuthProvider; + friend class FacebookAuthProvider; + friend class GameCenterAuthProvider; + friend class GitHubAuthProvider; + friend class GoogleAuthProvider; + friend class JniAuthPhoneListener; + friend class MicrosoftAuthProvider; + friend class OAuthProvider; + friend class PhoneAuthProvider; + friend class PlayGamesAuthProvider; + friend class TwitterAuthProvider; + friend class YahooAuthProvider; + friend class ServiceUpdatedCredentialProvider; + /// @endcond +#endif // !SWIG + + private: + /// Should only be created by `Provider` classes. + /// + /// @see EmailAuthProvider::GetCredential() + /// @see FacebookAuthProvider::GetCredential() + /// @see GoogleAuthProvider::GetCredential() + explicit Credential(void* impl) : impl_(impl), error_code_(kAuthErrorNone) {} + + public: + Credential() : impl_(nullptr), error_code_(kAuthErrorNone) {} + ~Credential(); + + /// Copy constructor. + Credential(const Credential& rhs); + + /// Copy a Credential. + Credential& operator=(const Credential& rhs); + + /// Gets the name of the Identification Provider (IDP) for the credential. + /// + /// + /// @xmlonly + /// + /// Gets the name of the Identification Provider (IDP) for the credential. + /// + /// @endxmlonly + /// + std::string provider() const; + + /// Get whether this credential is valid. A credential can be + /// invalid in an error condition, e.g. empty username/password. + /// + /// @returns True if the credential is valid, false otherwise. + bool is_valid() const; + + protected: + /// @cond FIREBASE_APP_INTERNAL + friend class Auth; + friend class User; + + /// Platform-specific implementation. + /// For example, FIRAuthCredential* on iOS. + void* impl_; + + // If not kAuthErrorNone, then use this error code and string to override + // whatever error we would normally return when trying to sign-in with this + // credential. + AuthError error_code_; + std::string error_message_; + /// @endcond +}; + +/// @brief Use email and password to authenticate. +/// +/// Allows developers to use the email and password credentials as they could +/// other auth providers. For example, this can be used to change passwords, +/// log in, etc. +class EmailAuthProvider { + public: + /// Generate a credential from the given email and password. + /// + /// @param email E-mail to generate the credential from. + /// @param password Password to use for the new credential. + /// + /// @returns New Credential. + static Credential GetCredential(const char* email, const char* password); + + /// The string used to identify this provider. + static const char* const kProviderId; +}; + +/// @brief Use an access token provided by Facebook to authenticate. +class FacebookAuthProvider { + public: + /// Generate a credential from the given Facebook token. + /// + /// @param access_token Facebook token to generate the credential from. + /// + /// @returns New Credential. + static Credential GetCredential(const char* access_token); + + /// The string used to identify this provider. + static const char* const kProviderId; +}; + +/// @brief GameCenter (Apple) auth provider +class GameCenterAuthProvider { + public: + /// Generate a credential from GameCenter for the current user. + /// + /// @return a Future that will be fulfilled with the resulting credential. + static Future GetCredential(); + + /// Get the result of the most recent GetCredential() call. + /// + /// @return an object which can be used to retrieve the Credential. + static Future GetCredentialLastResult(); + + /// Tests to see if the current user is signed in to GameCenter. + /// + /// @return true if the user is signed in, false otherwise. + static bool IsPlayerAuthenticated(); + + /// The string used to identify this provider. + static const char* const kProviderId; +}; + +/// @brief Use an access token provided by GitHub to authenticate. +class GitHubAuthProvider { + public: + /// Generate a credential from the given GitHub token. + /// + /// @param token The GitHub OAuth access token. + /// + /// @returns New Credential. + static Credential GetCredential(const char* token); + + /// The string used to identify this provider. + static const char* const kProviderId; +}; + +/// @brief Use an ID token and access token provided by Google to authenticate. +class GoogleAuthProvider { + public: + /// Generate a credential from the given Google ID token and/or access token. + /// + /// @param id_token Google Sign-In ID token. + /// @param access_token Google Sign-In access token. + /// + /// @returns New Credential. + static Credential GetCredential(const char* id_token, + const char* access_token); + + /// The string used to identify this provider. + static const char* const kProviderId; +}; + +/// @brief Use an access token provided by Microsoft to authenticate. +class MicrosoftAuthProvider { + public: + /// The string used to identify this provider. + static const char* const kProviderId; +}; + +/// @brief OAuth2.0+UserInfo auth provider (OIDC compliant and non-compliant). +class OAuthProvider { + public: + /// Generate a credential for an OAuth2 provider. + /// + /// @param provider_id Name of the OAuth2 provider + /// TODO(jsanmiya) add examples. + /// @param id_token The authentication token (OIDC only). + /// @param access_token TODO(jsanmiya) add explanation (currently missing + /// from Android and iOS implementations). + static Credential GetCredential(const char* provider_id, const char* id_token, + const char* access_token); + + /// Generate a credential for an OAuth2 provider. + /// + /// @param provider_id Name of the OAuth2 provider. + /// @param id_token The authentication token (OIDC only). + /// @param raw_nonce The raw nonce associated with the Auth credential being + /// created. + /// @param access_token The access token associated with the Auth credential + /// to be created, if available. This value may be null. + static Credential GetCredential(const char* provider_id, const char* id_token, + const char* raw_nonce, + const char* access_token); +}; + +/// @brief Use phone number text messages to authenticate. +/// +/// Allows developers to use the phone number and SMS verification codes +/// to authenticate a user on a mobile device. +/// +/// This class is not supported on tvOS and Desktop platforms. +/// +/// The verification flow results in a Credential that can be used to, +/// * Sign in to an existing phone number account/sign up with a new +/// phone number +/// * Link a phone number to a current user. This provider will be added to +/// the user. +/// * Update a phone number on an existing user. +/// * Re-authenticate an existing user. This may be needed when a sensitive +/// operation requires the user to be recently logged in. +/// +/// Possible verification flows: +/// (1) User manually enters verification code. +/// @if cpp_examples +/// - App calls @ref VerifyPhoneNumber. +/// - Web verification page is displayed to user where they may need to +/// solve a CAPTCHA. [iOS only]. +/// - Auth server sends the verification code via SMS to the provided +/// phone number. App receives verification id via Listener::OnCodeSent(). +/// - User receives SMS and enters verification code in app's GUI. +/// - App uses user's verification code to call +/// @ref PhoneAuthProvider::GetCredential. +/// @endif +/// +/// @if swig_examples +/// - App calls @ref VerifyPhoneNumber. +/// - Web verification page is displayed to user where they may need to +/// solve a CAPTCHA. [iOS only]. +/// - Auth server sends the verification code via SMS to the provided +/// phone number. App receives verification id via @ref CodeSent. +/// - User receives SMS and enters verification code in app's GUI. +/// - App uses user's verification code to call +/// @ref PhoneAuthProvider::GetCredential. +/// @endif +/// +/// +/// (2) SMS is automatically retrieved (Android only). +/// - App calls @ref VerifyPhoneNumber with `timeout_ms` > 0. +/// - Auth server sends the verification code via SMS to the provided +/// phone number. +/// - SMS arrives and is automatically retrieved by the operating system. +/// Credential is automatically created and passed to the app via +/// @if cpp_examples +/// Listener::OnVerificationCompleted(). +/// @endif +/// +/// @if swig_examples +/// @ref VerificationCompleted. +/// @endif +/// +/// +/// (3) Phone number is instantly verified (Android only). +/// - App calls @ref VerifyPhoneNumber. +/// - The operating system validates the phone number without having to +/// send an SMS. Credential is automatically created and passed to +/// the app via +/// @if cpp_examples +/// Listener::OnVerificationCompleted(). +/// @endif +/// +/// @if swig_examples +/// @ref VerificationCompleted. +/// @endif +/// +/// +/// @if cpp_examples +/// All three flows can be handled with the example code below. +/// The flow is complete when PhoneVerifier::credential() returns non-NULL. +/// +/// @code{.cpp} +/// class PhoneVerifier : public PhoneAuthProvider::Listener { +/// public: +/// PhoneVerifier(const char* phone_number, +/// PhoneAuthProvider* phone_auth_provider) +/// : display_message_("Sending SMS with verification code"), +/// display_verification_code_input_box_(false), +/// display_resend_sms_button_(false), +/// phone_auth_provider_(phone_auth_provider), +/// phone_number_(phone_number) { +/// SendSms(); +/// } +/// +/// ~PhoneVerifier() override {} +/// +/// void OnVerificationCompleted(Credential credential) override { +/// // Grab `mutex_` for the scope of `lock`. Callbacks can be called on +/// // other threads, so this mutex ensures data access is atomic. +/// MutexLock lock(mutex_); +/// credential_ = credential; +/// } +/// +/// void OnVerificationFailed(const std::string& error) override { +/// MutexLock lock(mutex_); +/// display_message_ = "Verification failed with error: " + error; +/// } +/// +/// void OnCodeSent(const std::string& verification_id, +/// const PhoneAuthProvider::ForceResendingToken& +/// force_resending_token) override { +/// MutexLock lock(mutex_); +/// verification_id_ = verification_id; +/// force_resending_token_ = force_resending_token; +/// +/// display_verification_code_input_box_ = true; +/// display_message_ = "Waiting for SMS"; +/// } +/// +/// void OnCodeAutoRetrievalTimeOut( +/// const std::string& verification_id) override { +/// MutexLock lock(mutex_); +/// display_resend_sms_button_ = true; +/// } +/// +/// // Draw the verification GUI on screen and process input events. +/// void Draw() { +/// MutexLock lock(mutex_); +/// +/// // Draw an informative message describing what's currently happening. +/// ShowTextBox(display_message_.c_str()); +/// +/// // Once the time out expires, display a button to resend the SMS. +/// // If the button is pressed, call VerifyPhoneNumber again using the +/// // force_resending_token_. +/// if (display_resend_sms_button_ && !verification_id_.empty()) { +/// const bool resend_sms = ShowTextButton("Resend SMS"); +/// if (resend_sms) { +/// SendSms(); +/// } +/// } +/// +/// // Once the SMS has been sent, allow the user to enter the SMS +/// // verification code into a text box. When the user has completed +/// // entering it, call GetCredential() to complete the flow. +/// if (display_verification_code_input_box_) { +/// const std::string verification_code = +/// ShowInputBox("Verification code"); +/// if (!verification_code.empty()) { +/// credential_ = phone_auth_provider_->GetCredential( +/// verification_id_.c_str(), verification_code.c_str()); +/// } +/// } +/// } +/// +/// // The phone number verification flow is complete when this returns +/// // non-NULL. +/// Credential* credential() { +/// MutexLock lock(mutex_); +/// return credential_.is_valid() ? &credential_ : nullptr; +/// } +/// +/// private: +/// void SendSms() { +/// static const uint32_t kAutoVerifyTimeOut = 2000; +/// MutexLock lock(mutex_); +/// phone_auth_provider_->VerifyPhoneNumber( +/// phone_number_.c_str(), kAutoVerifyTimeOut, &force_resending_token_, +/// this); +/// display_resend_sms_button_ = false; +/// } +/// +/// // GUI-related variables. +/// std::string display_message_; +/// bool display_verification_code_input_box_; +/// bool display_resend_sms_button_; +/// +/// // Phone flow related variables. +/// PhoneAuthProvider* phone_auth_provider_; +/// std::string phone_number_; +/// std::string verification_id_; +/// PhoneAuthProvider::ForceResendingToken force_resending_token_; +/// Credential credential_; +/// +/// // Callbacks can be called on other threads, so guard them with a mutex. +/// Mutex mutex_; +/// }; +/// @endcode +/// @endif +class PhoneAuthProvider { + public: + /// @brief Token to maintain current phone number verification session. + /// Acquired via @ref Listener::OnCodeSent. Used in @ref VerifyPhoneNumber. + class ForceResendingToken { + public: + /// This token will be invalid until it is assigned a value sent via + /// @ref Listener::OnCodeSent. It can still be passed into + /// @ref VerifyPhoneNumber, but it will be ignored. + ForceResendingToken(); + + /// Make `this` token refer to the same phone session as `rhs`. + ForceResendingToken(const ForceResendingToken& rhs); + + /// Releases internal resources when destructing. + ~ForceResendingToken(); + + /// Make `this` token refer to the same phone session as `rhs`. + ForceResendingToken& operator=(const ForceResendingToken& rhs); + + /// Return true if `rhs` is refers to the same phone number session as + /// `this`. + bool operator==(const ForceResendingToken& rhs) const; + + /// Return true if `rhs` is refers to a different phone number session as + /// `this`. + bool operator!=(const ForceResendingToken& rhs) const; + + private: + friend class JniAuthPhoneListener; + friend class PhoneAuthProvider; + ForceResendingTokenData* data_; + }; + + /// @brief Receive callbacks from @ref VerifyPhoneNumber events. + /// + /// Please see @ref PhoneAuthProvider for a sample implementation. + class Listener { + public: + Listener(); + virtual ~Listener(); + + /// @brief Phone number auto-verification succeeded. + /// + /// Called when, + /// - auto-sms-retrieval has succeeded--flow (2) in @ref PhoneAuthProvider + /// - instant validation has succeeded--flow (3) in @ref PhoneAuthProvider + /// + /// @note This callback is never called on iOS, since iOS does not have + /// auto-validation. It is always called immediately in the stub desktop + /// implementation, however, since it fakes immediate success. + /// + /// @param[in] credential The completed credential from the phone number + /// verification flow. + virtual void OnVerificationCompleted(Credential credential) = 0; + + /// @brief Phone number verification failed with an error. + /// + /// Called when and error occurred doing phone number authentication. + /// For example, + /// - quota exceeded + /// - unknown phone number format + /// + /// @param[in] error A description of the failure. + virtual void OnVerificationFailed(const std::string& error) = 0; + + /// @brief SMS message with verification code sent to phone number. + /// + /// Called immediately after Auth server sends a verification SMS. + /// Once receiving this, you can allow users to manually input the + /// verification code (even if you're also performing auto-verification). + /// For user manual input case, get the SMS verification code from the user + /// and then call @ref GetCredential with the user's code. + /// + /// @param[in] verification_id Pass to @ref GetCredential along with the + /// user-input verification code to complete the phone number verification + /// flow. + /// @param[in] force_resending_token If the user requests that another SMS + /// message be sent, use this when you recall @ref VerifyPhoneNumber. + virtual void OnCodeSent(const std::string& verification_id, + const ForceResendingToken& force_resending_token); + + /// @brief The timeout specified in @ref VerifyPhoneNumber has expired. + /// + /// Called once `auto_verify_time_out_ms` has passed. + /// If using auto SMS retrieval, you can choose to block the UI (do not + /// allow manual input of the verification code) until timeout is hit. + /// + /// @note This callback is called immediately on iOS, since iOS does not + /// have auto-validation. + /// + /// @param[in] verification_id Identify the transaction that has timed out. + virtual void OnCodeAutoRetrievalTimeOut(const std::string& verification_id); + + private: + friend class PhoneAuthProvider; + + /// Back-pointer to the data of the PhoneAuthProvider that + /// @ref VerifyPhoneNumber was called with. Used internally. + PhoneListenerData* data_; + }; + + /// Maximum value of `auto_verify_time_out_ms` in @ref VerifyPhoneNumber. + /// Larger values will be clamped. + /// + /// @deprecated This value is no longer used to clamp + /// `auto_verify_time_out_ms` in VerifyPhoneNumber. The range is + /// determined by the underlying SDK, ex. PhoneAuthOptions.Build + /// in Android SDK + static const uint32_t kMaxTimeoutMs; + + /// Start the phone number authentication operation. + /// + /// @param[in] phone_number The phone number identifier supplied by the user. + /// Its format is normalized on the server, so it can be in any format + /// here. + /// @param[in] auto_verify_time_out_ms The time out for SMS auto retrieval, in + /// miliseconds. Currently SMS auto retrieval is only supported on Android. + /// If 0, do not do SMS auto retrieval. + /// If positive, try to auto-retrieve the SMS verification code. + /// When the time out is exceeded, listener->OnCodeAutoRetrievalTimeOut() + /// is called. + /// @param[in] force_resending_token If NULL, assume this is a new phone + /// number to verify. If not-NULL, bypass the verification session deduping + /// and force resending a new SMS. + /// This token is received in @ref Listener::OnCodeSent. + /// This should only be used when the user presses a Resend SMS button. + /// @param[in,out] listener Class that receives notification whenever an SMS + /// verification event occurs. See sample code at top of class. + void VerifyPhoneNumber(const char* phone_number, + uint32_t auto_verify_time_out_ms, + const ForceResendingToken* force_resending_token, + Listener* listener); + + /// Generate a credential for the given phone number. + /// + /// @param[in] verification_id The id returned when sending the verification + /// code. Sent to the caller via @ref Listener::OnCodeSent. + /// @param[in] verification_code The verification code supplied by the user, + /// most likely by a GUI where the user manually enters the code + /// received in the SMS sent by @ref VerifyPhoneNumber. + /// + /// @returns New Credential. + Credential GetCredential(const char* verification_id, + const char* verification_code); + + /// Return the PhoneAuthProvider for the specified `auth`. + /// + /// @param[in] auth The Auth session for which we want to get a + /// PhoneAuthProvider. + static PhoneAuthProvider& GetInstance(Auth* auth); + + /// The string used to identify this provider. + static const char* const kProviderId; + + private: + friend struct AuthData; + friend class JniAuthPhoneListener; + + // Use @ref GetInstance to access the PhoneAuthProvider. + PhoneAuthProvider(); + + // The PhoneAuthProvider is owned by the Auth class. + ~PhoneAuthProvider(); + + PhoneAuthProviderData* data_; +}; + +/// @brief Use a server auth code provided by Google Play Games to authenticate. +class PlayGamesAuthProvider { + public: + /// Generate a credential from the given Server Auth Code. + /// + /// @param server_auth_code Play Games Sign in Server Auth Code. + /// + /// @return New Credential. + static Credential GetCredential(const char* server_auth_code); + + /// The string used to identify this provider. + static const char* const kProviderId; +}; + +/// @brief Use a token and secret provided by Twitter to authenticate. +class TwitterAuthProvider { + public: + /// Generate a credential from the given Twitter token and password. + /// + /// @param token The Twitter OAuth token. + /// @param secret The Twitter OAuth secret. + /// + /// @return New Credential. + static Credential GetCredential(const char* token, const char* secret); + + /// The string used to identify this provider. + static const char* const kProviderId; +}; + +/// @brief Use an access token provided by Yahoo to authenticate. +class YahooAuthProvider { + public: + /// The string used to identify this provider. + static const char* const kProviderId; +}; + +} // namespace auth +} // namespace firebase + +#endif // FIREBASE_AUTH_SRC_INCLUDE_FIREBASE_AUTH_CREDENTIAL_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/auth/types.h b/packages/firebase_core/firebase_core/firebase_core/firebase/auth/types.h new file mode 100644 index 000000000000..3f141ad3692c --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/auth/types.h @@ -0,0 +1,473 @@ +/* + * Copyright 2016 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_AUTH_SRC_INCLUDE_FIREBASE_AUTH_TYPES_H_ +#define FIREBASE_AUTH_SRC_INCLUDE_FIREBASE_AUTH_TYPES_H_ + +#include +#include +#include + +namespace firebase { +namespace auth { + +/// All possible error codes from asynchronous calls. +/// For error details, +/// @if cpp_examples +/// call Future::ErrorMessage(). +/// @endif +/// +/// @if swig_examples +/// use the FirebaseException.Message property. +/// @endif +/// +enum AuthError { + /// Success. + kAuthErrorNone = 0, + + /// Function will be implemented in a later revision of the API. + kAuthErrorUnimplemented = -1, + + /// This indicates an internal error. + /// Common error code for all API Methods. + kAuthErrorFailure = 1, + + /// Indicates a validation error with the custom token. + /// This error originates from "bring your own auth" methods. + kAuthErrorInvalidCustomToken, + + /// Indicates the service account and the API key belong to different + /// projects. + /// Caused by "Bring your own auth" methods. + kAuthErrorCustomTokenMismatch, + + /// Indicates the IDP token or requestUri is invalid. + /// Caused by "Sign in with credential" methods. + kAuthErrorInvalidCredential, + + /// Indicates the user’s account is disabled on the server. + /// Caused by "Sign in with credential" methods. + kAuthErrorUserDisabled, + + /// Indicates an account already exists with the same email address but using + /// different sign-in credentials. Account linking is required. + /// Caused by "Sign in with credential" methods. + kAuthErrorAccountExistsWithDifferentCredentials, + + /// Indicates the administrator disabled sign in with the specified identity + /// provider. + /// Caused by "Set account info" methods. + kAuthErrorOperationNotAllowed, + + /// Indicates the email used to attempt a sign up is already in use. + /// Caused by "Set account info" methods. + kAuthErrorEmailAlreadyInUse, + + /// Indicates the user has attemped to change email or password more than 5 + /// minutes after signing in, and will need to refresh the credentials. + /// Caused by "Set account info" methods. + kAuthErrorRequiresRecentLogin, + + /// Indicates an attempt to link with a credential that has already been + /// linked with a different Firebase account. + /// Caused by "Set account info" methods. + kAuthErrorCredentialAlreadyInUse, + + /// Indicates an invalid email address. + /// Caused by "Sign in with password" methods. + kAuthErrorInvalidEmail, + + /// Indicates the user attempted sign in with a wrong password. + /// Caused by "Sign in with password" methods. + kAuthErrorWrongPassword, + + /// Indicates that too many requests were made to a server method. + /// Common error code for all API methods. + kAuthErrorTooManyRequests, + + /// Indicates the user account was not found. + /// Send password request email error code. + /// Common error code for all API methods. + kAuthErrorUserNotFound, + + /// Indicates an attempt to link a provider to which the account is already + /// linked. + /// Caused by "Link credential" methods. + kAuthErrorProviderAlreadyLinked, + + /// Indicates an attempt to unlink a provider that is not linked. + /// Caused by "Link credential" methods. + kAuthErrorNoSuchProvider, + + /// Indicates user's saved auth credential is invalid, the user needs to sign + /// in again. + /// Caused by requests with an STS id token. + kAuthErrorInvalidUserToken, + + /// Indicates the saved token has expired. + /// For example, the user may have changed account password on another device. + /// The user needs to sign in again on the device that made this request. + /// Caused by requests with an STS id token. + kAuthErrorUserTokenExpired, + + /// Indicates a network error occurred (such as a timeout, interrupted + /// connection, or unreachable host). These types of errors are often + /// recoverable with a retry. + /// Common error code for all API Methods. + kAuthErrorNetworkRequestFailed, + + /// Indicates an invalid API key was supplied in the request. + /// For Android these should no longer occur (as of 2016 v3). + /// Common error code for all API Methods. + kAuthErrorInvalidApiKey, + + /// Indicates the App is not authorized to use Firebase Authentication with + /// the provided API Key. + /// Common error code for all API Methods. + /// On Android this error should no longer occur (as of 2016 v3). + /// Common error code for all API Methods. + kAuthErrorAppNotAuthorized, + + /// Indicates that an attempt was made to reauthenticate with a user which is + /// not the current user. + kAuthErrorUserMismatch, + + /// Indicates an attempt to set a password that is considered too weak. + kAuthErrorWeakPassword, + + /// Internal api usage error code when there is no signed-in user + /// and getAccessToken is called. + /// + /// @note This error is only reported on Android. + kAuthErrorNoSignedInUser, + + /// This can happen when certain methods on App are performed, when the auth + /// API is not loaded. + /// + /// @note This error is only reported on Android. + kAuthErrorApiNotAvailable, + + /// Indicates the out-of-band authentication code is expired. + kAuthErrorExpiredActionCode, + + /// Indicates the out-of-band authentication code is invalid. + kAuthErrorInvalidActionCode, + + /// Indicates that there are invalid parameters in the payload during a + /// "send password reset email" attempt. + kAuthErrorInvalidMessagePayload, + + /// Indicates that an invalid phone number was provided. + /// This is caused when the user is entering a phone number for verification. + kAuthErrorInvalidPhoneNumber, + + /// Indicates that a phone number was not provided during phone number + /// verification. + /// + /// @note This error is iOS-specific. + kAuthErrorMissingPhoneNumber, + + /// Indicates that the recipient email is invalid. + kAuthErrorInvalidRecipientEmail, + + /// Indicates that the sender email is invalid during a "send password reset + /// email" attempt. + kAuthErrorInvalidSender, + + /// Indicates that an invalid verification code was used in the + /// verifyPhoneNumber request. + kAuthErrorInvalidVerificationCode, + + /// Indicates that an invalid verification ID was used in the + /// verifyPhoneNumber request. + kAuthErrorInvalidVerificationId, + + /// Indicates that the phone auth credential was created with an empty + /// verification code. + kAuthErrorMissingVerificationCode, + + /// Indicates that the phone auth credential was created with an empty + /// verification ID. + kAuthErrorMissingVerificationId, + + /// Indicates that an email address was expected but one was not provided. + kAuthErrorMissingEmail, + + /// Represents the error code for when an application attempts to create an + /// email/password account with an empty/null password field. + /// + /// @note This error is only reported on Android. + kAuthErrorMissingPassword, + + /// Indicates that the project's quota for this operation (SMS messages, + /// sign-ins, account creation) has been exceeded. Try again later. + kAuthErrorQuotaExceeded, + + /// Thrown when one or more of the credentials passed to a method fail to + /// identify and/or authenticate the user subject of that operation. Inspect + /// the error message to find out the specific cause. + /// @note This error is only reported on Android. + kAuthErrorRetryPhoneAuth, + + /// Indicates that the SMS code has expired. + kAuthErrorSessionExpired, + + /// Indicates that the app could not be verified by Firebase during phone + /// number authentication. + /// + /// @note This error is iOS-specific. + kAuthErrorAppNotVerified, + + /// Indicates a general failure during the app verification flow. + /// + /// @note This error is iOS-specific. + kAuthErrorAppVerificationFailed, + + /// Indicates that the reCAPTCHA token is not valid. + /// + /// @note This error is iOS and tvOS-specific. + kAuthErrorCaptchaCheckFailed, + + /// Indicates that an invalid APNS device token was used in the verifyClient + /// request. + /// + /// @note This error is iOS and tvOS-specific. + kAuthErrorInvalidAppCredential, + + /// Indicates that the APNS device token is missing in the verifyClient + /// request. + /// + /// @note This error is iOS and tvOS-specific. + kAuthErrorMissingAppCredential, + + /// Indicates that the clientID used to invoke a web flow is invalid. + /// + /// @note This error is iOS and tvOS-specific. + kAuthErrorInvalidClientId, + + /// Indicates that the domain specified in the continue URI is not valid. + /// + /// @note This error is iOS and tvOS-specific. + kAuthErrorInvalidContinueUri, + + /// Indicates that a continue URI was not provided in a request to the backend + /// which requires one. + kAuthErrorMissingContinueUri, + + /// Indicates an error occurred while attempting to access the keychain. + /// Common error code for all API Methods. + /// + /// @note This error is iOS and tvOS-specific. + kAuthErrorKeychainError, + + /// Indicates that the APNs device token could not be obtained. The app may + /// not have set up remote notification correctly, or may have failed to + /// forward the APNs device token to FIRAuth if app delegate swizzling is + /// disabled. + /// + /// @note This error is iOS and tvOS-specific. + kAuthErrorMissingAppToken, + + /// Indicates that the iOS bundle ID is missing when an iOS App Store ID is + /// provided. + /// + /// @note This error is iOS and tvOS-specific. + kAuthErrorMissingIosBundleId, + + /// Indicates that the app fails to forward remote notification to FIRAuth. + /// + /// @note This error is iOS and tvOS-specific. + kAuthErrorNotificationNotForwarded, + + /// Indicates that the domain specified in the continue URL is not white- + /// listed in the Firebase console. + /// + /// @note This error is iOS and tvOS-specific. + kAuthErrorUnauthorizedDomain, + + /// Indicates that an attempt was made to present a new web context while one + /// was already being presented. + kAuthErrorWebContextAlreadyPresented, + + /// Indicates that the URL presentation was cancelled prematurely by the user. + kAuthErrorWebContextCancelled, + + /// Indicates that Dynamic Links in the Firebase Console is not activated. + kAuthErrorDynamicLinkNotActivated, + + /// Indicates that the operation was cancelled. + kAuthErrorCancelled, + + /// Indicates that the provider id given for the web operation is invalid. + kAuthErrorInvalidProviderId, + + /// Indicates that an internal error occurred during a web operation. + kAuthErrorWebInternalError, + + /// Indicates that 3rd party cookies or data are disabled, or that there was + /// a problem with the browser. + kAuthErrorWebStorateUnsupported, + + /// Indicates that the provided tenant ID does not match the Auth instance's + /// tenant ID. + kAuthErrorTenantIdMismatch, + + /// Indicates that a request was made to the backend with an associated tenant + /// ID for an operation that does not support multi-tenancy. + kAuthErrorUnsupportedTenantOperation, + + /// Indicates that an FDL domain used for an out of band code flow is either + /// not configured or is unauthorized for the current project. + kAuthErrorInvalidLinkDomain, + + /// Indicates that credential related request data is invalid. This can occur + /// when there is a project number mismatch (sessionInfo, spatula header, + /// temporary proof), + /// an incorrect temporary proof phone number, or during game center sign in + /// when the user is + /// already signed into a different game center account. + kAuthErrorRejectedCredential, + + /// Indicates that the phone number provided in the MFA sign in flow to be + /// verified does not correspond to a phone second factor for the user. + kAuthErrorPhoneNumberNotFound, + + /// Indicates that a request was made to the backend with an invalid tenant + /// ID. + kAuthErrorInvalidTenantId, + + /// Indicates that a request was made to the backend without a valid client + /// identifier. + kAuthErrorMissingClientIdentifier, + + /// Indicates that a second factor challenge request was made without proof of + /// a successful first factor sign-in. + kAuthErrorMissingMultiFactorSession, + + /// Indicates that a second factor challenge request was made where a second + /// factor identifier was not provided. + kAuthErrorMissingMultiFactorInfo, + + /// Indicates that a second factor challenge request was made containing an + /// invalid proof of first factor sign-in. + kAuthErrorInvalidMultiFactorSession, + + /// Indicates that the user does not have a second factor matching the + /// provided identifier. + kAuthErrorMultiFactorInfoNotFound, + + /// Indicates that a request was made that is restricted to administrators + /// only. + kAuthErrorAdminRestrictedOperation, + + /// Indicates that the user's email must be verified to perform that request. + kAuthErrorUnverifiedEmail, + + /// Indicates that the user is trying to enroll a second factor that already + /// exists on their account. + kAuthErrorSecondFactorAlreadyEnrolled, + + /// Indicates that the user has reached the maximum number of allowed second + /// factors and is attempting to enroll another one. + kAuthErrorMaximumSecondFactorCountExceeded, + + /// Indicates that a user either attempted to enroll in 2FA with an + /// unsupported first factor or is enrolled and attempts a first factor sign + /// in that is not supported for 2FA users. + kAuthErrorUnsupportedFirstFactor, + + /// Indicates that a second factor users attempted to change their email with + /// updateEmail instead of verifyBeforeUpdateEmail. + kAuthErrorEmailChangeNeedsVerification, + +#ifdef INTERNAL_EXPERIMENTAL + /// Indicates that the provided event handler is null or invalid. + kAuthErrorInvalidEventHandler, + + /// Indicates that the federated provider is busy with a previous + /// authorization request. Try again when the previous authorization request + /// completes. + kAuthErrorFederatedProviderAreadyInUse, + + /// Indicates that one or more fields of the provided AuthenticatedUserData + /// are invalid. + kAuthErrorInvalidAuthenticatedUserData, + + /// Indicates that an error occurred during a Federated Auth UI Flow when the + /// user was prompted to enter their credentials. + kAuthErrorFederatedSignInUserInteractionFailure, + + /// Indicates that a request was made with a missing or invalid nonce. + /// This can happen if the hash of the provided raw nonce did not match the + /// hashed nonce in the OIDC ID token payload. + kAuthErrorMissingOrInvalidNonce, + + /// Indicates that the user did not authorize the application during Generic + /// IDP sign-in. + kAuthErrorUserCancelled, + + /// Indicates that a request was made to an unsupported backend endpoint in + /// passthrough mode. + kAuthErrorUnsupportedPassthroughOperation, + + /// Indicates that a token refresh was requested, but neither a refresh token + /// nor a custom token provider is available. + kAuthErrorTokenRefreshUnavailable, + +#endif // INTERNAL_EXEPERIMENTAL +}; + +/// @brief Contains information required to authenticate with a third party +/// provider. +struct FederatedProviderData { + /// @brief contains the id of the provider to be used during sign-in, link, or + /// reauthentication requests. + std::string provider_id; +}; + +/// @brief Contains information to identify an OAuth povider. +struct FederatedOAuthProviderData : FederatedProviderData { + /// Initailizes an empty provider data structure. + FederatedOAuthProviderData() {} + + /// Initializes the provider data structure with a provider id. + explicit FederatedOAuthProviderData(const std::string& provider) { + this->provider_id = provider; + } + +#ifndef SWIG + /// @brief Initializes the provider data structure with the specified provider + /// id, scopes and custom parameters. + FederatedOAuthProviderData( + const std::string& provider, std::vector scopes, + std::map custom_parameters) { + this->provider_id = provider; + this->scopes = scopes; + this->custom_parameters = custom_parameters; + } +#endif + + /// OAuth parmeters which specify which rights of access are being requested. + std::vector scopes; + + /// OAuth parameters which are provided to the federated provider service. + std::map custom_parameters; +}; + +} // namespace auth +} // namespace firebase + +#endif // FIREBASE_AUTH_SRC_INCLUDE_FIREBASE_AUTH_TYPES_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/auth/user.h b/packages/firebase_core/firebase_core/firebase_core/firebase/auth/user.h new file mode 100644 index 000000000000..ddd1ba890687 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/auth/user.h @@ -0,0 +1,501 @@ +/* + * Copyright 2016 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_AUTH_SRC_INCLUDE_FIREBASE_AUTH_USER_H_ +#define FIREBASE_AUTH_SRC_INCLUDE_FIREBASE_AUTH_USER_H_ + +#include +#include + +#include "firebase/auth/credential.h" +#include "firebase/auth/types.h" +#include "firebase/future.h" +#include "firebase/internal/common.h" +#include "firebase/variant.h" + +namespace firebase { +namespace auth { + +// Predeclarations. +class Auth; +struct AuthData; + +class FederatedAuthProvider; + +/// @brief Interface implemented by each identity provider. +class UserInfoInterface { + public: + virtual ~UserInfoInterface(); + + /// Gets the unique Firebase user ID for the user. + /// + /// @note The user's ID, unique to the Firebase project. + /// Do NOT use this value to authenticate with your backend server, if you + /// have one. + /// @if cpp_examples + /// Use User::GetToken() instead. + /// @endif + /// + /// @if swig_examples + /// Use User.Token instead. + /// @endif + /// @xmlonly + /// + /// Gets the unique Firebase user ID for the user. + /// + /// @note The user's ID, unique to the Firebase project. + /// Do NOT use this value to authenticate with your backend server, if you + /// have one. Use User.Token instead. + /// + /// @endxmlonly + /// + virtual std::string uid() const = 0; + + /// Gets email associated with the user, if any. + /// + /// @xmlonly + /// + /// Gets email associated with the user, if any. + /// + /// @endxmlonly + /// + virtual std::string email() const = 0; + + /// Gets the display name associated with the user, if any. + /// + /// @xmlonly + /// + /// Gets the display name associated with the user, if any. + /// + /// @endxmlonly + /// + virtual std::string display_name() const = 0; + + /// Gets the photo url associated with the user, if any. + /// + /// @xmlonly + /// + /// Gets the photo url associated with the user, if any. + /// + /// @endxmlonly + /// + virtual std::string photo_url() const = 0; + + /// Gets the provider ID for the user (For example, "Facebook"). + /// + /// @xmlonly + /// + /// Gets the provider ID for the user (For example, \"Facebook\"). + /// + /// @endxmlonly + /// + virtual std::string provider_id() const = 0; + + /// Gets the phone number for the user, in E.164 format. + virtual std::string phone_number() const = 0; +}; + +/// @brief Additional user data returned from an identity provider. +struct AdditionalUserInfo { + /// The provider identifier. + std::string provider_id; + + /// The name of the user. + std::string user_name; + + /// Additional identity-provider specific information. + /// Most likely a hierarchical key-value mapping, like a parsed JSON file. + /// Note we use map instead of unordered_map to support older compilers. + std::map profile; + + /// On a nonce-based credential link failure where the user has already linked + /// to the provider, the Firebase auth service may provide an updated + /// Credential. If is_valid returns true on this credential, then it may be + /// passed to a new firebase::auth::Auth::SignInWithCredential request to sign + /// the user in with the provider. + Credential updated_credential; +}; + +/// @brief Metadata corresponding to a Firebase user. +struct UserMetadata { + UserMetadata() : last_sign_in_timestamp(0), creation_timestamp(0) {} + + /// The last sign in UTC timestamp in milliseconds. + /// See https://en.wikipedia.org/wiki/Unix_time for details of UTC. + uint64_t last_sign_in_timestamp; + + /// The Firebase user creation UTC timestamp in milliseconds. + uint64_t creation_timestamp; +}; + +/// @brief Result of operations that can affect authentication state. +struct SignInResult { + SignInResult() : user(NULL) {} + + /// The currently signed-in @ref User, or NULL if there isn't any (i.e. the + /// user is signed out). + User* user; + + /// Identity-provider specific information for the user, if the provider is + /// one of Facebook, GitHub, Google, or Twitter. + AdditionalUserInfo info; + + /// Metadata associated with the Firebase user. + UserMetadata meta; +}; + +/// @brief Firebase user account object. +/// +/// This class allows you to manipulate the profile of a user, link to and +/// unlink from authentication providers, and refresh authentication tokens. +class User : public UserInfoInterface { + public: + /// Parameters to the UpdateUserProfile() function. + /// + /// For fields you don't want to update, pass NULL. + /// For fields you want to reset, pass "". + struct UserProfile { + /// Construct a UserProfile with no display name or photo URL. + UserProfile() : display_name(NULL), photo_url(NULL) {} + + /// User display name. + const char* display_name; + + /// User photo URI. + const char* photo_url; + }; + + ~User(); + + /// The Java Web Token (JWT) that can be used to identify the user to + /// the backend. + /// + /// If a current ID token is still believed to be valid (i.e. it has not yet + /// expired), that token will be returned immediately. + /// A developer may set the optional force_refresh flag to get a new ID token, + /// whether or not the existing token has expired. For example, a developer + /// may use this when they have discovered that the token is invalid for some + /// other reason. + Future GetToken(bool force_refresh); + +#if defined(INTERNAL_EXPERIMENTAL) || defined(SWIG) + /// A "thread safer" version of GetToken. + /// If called by two threads simultaneously, GetToken can return the same + /// pending Future twice. This creates problems if both threads try to set + /// the OnCompletion callback, unaware that there's another copy. + /// GetTokenThreadSafe returns a proxy to the Future if it's still pending, + /// allowing each proxy to have their own callback. + Future GetTokenThreadSafe(bool force_refresh); +#endif // defined(INTERNAL_EXPERIMENTAL) || defined(SWIG) + + /// Get results of the most recent call to @ref GetToken. + Future GetTokenLastResult() const; + + /// Gets the third party profile data associated with this user returned by + /// the authentication server, if any. + /// + /// @xmlonly + /// + /// Gets the third party profile data associated with this user returned by + /// the authentication server, if any. + /// + /// @endxmlonly + /// + const std::vector& provider_data() const; + + /// Sets the email address for the user. + /// + /// May fail if there is already an email/password-based account for the same + /// email address. + Future UpdateEmail(const char* email); + + /// Get results of the most recent call to @ref UpdateEmail. + Future UpdateEmailLastResult() const; + + /// Attempts to change the password for the current user. + /// + /// For an account linked to an Identity Provider (IDP) with no password, + /// this will result in the account becoming an email/password-based account + /// while maintaining the IDP link. May fail if the password is invalid, + /// if there is a conflicting email/password-based account, or if the token + /// has expired. + /// To retrieve fresh tokens, + /// @if cpp_examples + /// call @ref Reauthenticate. + /// @endif + /// + /// @if swig_examples + /// call @ref ReauthenticateAsync. + /// @endif + /// + Future UpdatePassword(const char* password); + + /// Get results of the most recent call to @ref UpdatePassword. + Future UpdatePasswordLastResult() const; + + /// Convenience function for @ref ReauthenticateAndRetrieveData that discards + /// the returned AdditionalUserInfo data. + Future Reauthenticate(const Credential& credential); + + /// Get results of the most recent call to @ref Reauthenticate. + Future ReauthenticateLastResult() const; + + /// Reauthenticate using a credential. + /// + /// @if cpp_examples + /// Some APIs (for example, @ref UpdatePassword, @ref Delete) require that + /// the token used to invoke them be from a recent login attempt. + /// This API takes an existing credential for the user and retrieves fresh + /// tokens, ensuring that the operation can proceed. Developers can call + /// this method prior to calling @ref UpdatePassword() to ensure success. + /// @endif + /// + /// @if swig_examples + /// Some APIs (for example, @ref UpdatePasswordAsync, @ref DeleteAsync) + /// require that the token used to invoke them be from a recent login attempt. + /// This API takes an existing credential for the user and retrieves fresh + /// tokens, ensuring that the operation can proceed. Developers can call + /// this method prior to calling @ref UpdatePasswordAsync() to ensure success. + /// @endif + /// + /// + /// Data from the Identity Provider used to sign-in is returned in the + /// AdditionalUserInfo inside the returned SignInResult. + /// + /// Returns an error if the existing credential is not for this user + /// or if sign-in with that credential failed. + /// @note: The current user may be signed out if this operation fails on + /// Android and desktop platforms. + Future ReauthenticateAndRetrieveData( + const Credential& credential); + + /// Get results of the most recent call to @ref ReauthenticateAndRetrieveData. + Future ReauthenticateAndRetrieveDataLastResult() const; + + /// @brief Re-authenticates the user with a federated auth provider. + /// + /// @param[in] provider Contains information on the auth provider to + /// authenticate with. + /// @return A Future with the result of the re-authentication + /// request. + /// @note: This operation is supported only on iOS, tvOS and Android + /// platforms. On other platforms this method will return a Future with a + /// preset error code: kAuthErrorUnimplemented. + Future ReauthenticateWithProvider( + FederatedAuthProvider* provider) const; + + /// Initiates email verification for the user. + Future SendEmailVerification(); + + /// Get results of the most recent call to @ref SendEmailVerification. + Future SendEmailVerificationLastResult() const; + + /// Updates a subset of user profile information. + Future UpdateUserProfile(const UserProfile& profile); + + /// Get results of the most recent call to @ref UpdateUserProfile. + Future UpdateUserProfileLastResult() const; + + /// Convenience function for @ref ReauthenticateAndRetrieveData that discards + /// the returned @ref AdditionalUserInfo in @ref SignInResult. + Future LinkWithCredential(const Credential& credential); + + /// Get results of the most recent call to @ref LinkWithCredential. + Future LinkWithCredentialLastResult() const; + + /// Links the user with the given 3rd party credentials. + /// + /// For example, a Facebook login access token, a Twitter token/token-secret + /// pair. + /// Status will be an error if the token is invalid, expired, or otherwise + /// not accepted by the server as well as if the given 3rd party + /// user id is already linked with another user account or if the current user + /// is already linked with another id from the same provider. + /// + /// Data from the Identity Provider used to sign-in is returned in the + /// @ref AdditionalUserInfo inside @ref SignInResult. + Future LinkAndRetrieveDataWithCredential( + const Credential& credential); + + /// Get results of the most recent call to + /// @ref LinkAndRetrieveDataWithCredential. + Future LinkAndRetrieveDataWithCredentialLastResult() const; + + /// Links this user with a federated auth provider. + /// + /// @param[in] provider Contains information on the auth provider to link + /// with. + /// @return A Future with the user data result of the link + /// request. + /// + /// @note: This operation is supported only on iOS, tvOS and Android + /// platforms. On other platforms this method will return a Future with a + /// preset error code: kAuthErrorUnimplemented. + Future LinkWithProvider(FederatedAuthProvider* provider) const; + + /// Unlinks the current user from the provider specified. + /// Status will be an error if the user is not linked to the given provider. + Future Unlink(const char* provider); + + /// Get results of the most recent call to @ref Unlink. + Future UnlinkLastResult() const; + + /// Updates the currently linked phone number on the user. + /// This is useful when a user wants to change their phone number. It is a + /// shortcut to calling Unlink(phone_credential.provider().c_str()) and then + /// LinkWithCredential(phone_credential). + /// `credential` must have been created with @ref PhoneAuthProvider. + Future UpdatePhoneNumberCredential(const Credential& credential); + + /// Get results of the most recent call to @ref UpdatePhoneNumberCredential. + Future UpdatePhoneNumberCredentialLastResult() const; + + /// Refreshes the data for this user. + /// + /// For example, the attached providers, email address, display name, etc. + Future Reload(); + + /// Get results of the most recent call to @ref Reload. + Future ReloadLastResult() const; + + /// Deletes the user account. + Future Delete(); + + /// Get results of the most recent call to @ref Delete. + Future DeleteLastResult() const; + + /// Gets the metadata for this user account. + UserMetadata metadata() const; + + /// Returns true if the email address associated with this user has been + /// verified. + /// + /// @xmlonly + /// + /// True if the email address associated with this user has been verified. + /// + /// @endxmlonly + /// + bool is_email_verified() const; + + /// Returns true if user signed in anonymously. + /// + /// @xmlonly + /// + /// True if user signed in anonymously. + /// + /// @endxmlonly + /// + bool is_anonymous() const; + + /// Gets the unique Firebase user ID for the user. + /// + /// @note The user's ID, unique to the Firebase project. + /// Do NOT use this value to authenticate with your backend server, if you + /// have one. + /// @if cpp_examples + /// Use User::GetToken() instead. + /// @endif + /// + /// @if swig_examples + /// Use User.Token instead. + /// @endif + /// @xmlonly + /// + /// Gets the unique Firebase user ID for the user. + /// + /// @note The user's ID, unique to the Firebase project. + /// Do NOT use this value to authenticate with your backend server, if you + /// have one. Use User.Token instead. + /// + /// @endxmlonly + /// + virtual std::string uid() const; + + /// Gets email associated with the user, if any. + /// + /// @xmlonly + /// + /// Gets email associated with the user, if any. + /// + /// @endxmlonly + /// + virtual std::string email() const; + + /// Gets the display name associated with the user, if any. + /// + /// @xmlonly + /// + /// Gets the display name associated with the user, if any. + /// + /// @endxmlonly + /// + virtual std::string display_name() const; + + /// Gets the photo url associated with the user, if any. + /// + /// @xmlonly + /// + /// Gets the photo url associated with the user, if any. + /// + /// @endxmlonly + /// + virtual std::string photo_url() const; + + /// Gets the provider ID for the user (For example, "Facebook"). + /// + /// @xmlonly + /// + /// Gets the provider ID for the user (For example, \"Facebook\"). + /// + /// @endxmlonly + /// + virtual std::string provider_id() const; + + /// Gets the phone number for the user, in E.164 format. + virtual std::string phone_number() const; + + private: + /// @cond FIREBASE_APP_INTERNAL + friend struct AuthData; + // Only exists in AuthData. Access via @ref Auth::CurrentUser(). + explicit User(AuthData* auth_data) : auth_data_(auth_data) {} + + // Disable copy constructor. + User(const User&) = delete; + // Disable copy operator. + User& operator=(const User&) = delete; + /// @endcond + +#if defined(INTERNAL_EXPERIMENTAL) + // Doxygen should not make docs for this function. + /// @cond FIREBASE_APP_INTERNAL + friend class IdTokenRefreshThread; + friend class IdTokenRefreshListener; + friend class Auth; + Future GetTokenInternal(const bool force_refresh, + const int future_identifier); + /// @endcond +#endif // defined(INTERNAL_EXPERIMENTAL) + + // Use the pimpl mechanism to hide data details in the cpp files. + AuthData* auth_data_; +}; + +} // namespace auth +} // namespace firebase + +#endif // FIREBASE_AUTH_SRC_INCLUDE_FIREBASE_AUTH_USER_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/database.h b/packages/firebase_core/firebase_core/firebase_core/firebase/database.h new file mode 100644 index 000000000000..d0dc904c107b --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/database.h @@ -0,0 +1,199 @@ +// Copyright 2016 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_H_ +#define FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_H_ + +#include "firebase/app.h" +#include "firebase/database/common.h" +#include "firebase/database/data_snapshot.h" +#include "firebase/database/database_reference.h" +#include "firebase/database/disconnection.h" +#include "firebase/database/listener.h" +#include "firebase/database/mutable_data.h" +#include "firebase/database/query.h" +#include "firebase/database/transaction.h" +#include "firebase/internal/common.h" +#include "firebase/log.h" + +namespace firebase { + +/// Namespace for the Firebase Realtime Database C++ SDK. +namespace database { + +namespace internal { +class DatabaseInternal; +} // namespace internal + +class DatabaseReference; + +#ifndef SWIG +/// @brief Entry point for the Firebase Realtime Database C++ SDK. +/// +/// To use the SDK, call firebase::database::Database::GetInstance() to obtain +/// an instance of Database, then use GetReference() to obtain references to +/// child paths within the database. From there you can set data via +/// Query::SetValue(), get data via Query::GetValue(), attach listeners, and +/// more. +#endif // SWIG +class Database { + public: + /// @brief Get an instance of Database corresponding to the given App. + /// + /// Firebase Realtime Database uses firebase::App to communicate with Firebase + /// Authentication to authenticate users to the Database server backend. + /// + /// If you call GetInstance() multiple times with the same App, you will get + /// the same instance of Database. + /// + /// @param[in] app Your instance of firebase::App. Firebase Realtime Database + /// will use this to communicate with Firebase Authentication. + /// @param[out] init_result_out Optional: If provided, write the init result + /// here. Will be set to kInitResultSuccess if initialization succeeded, or + /// kInitResultFailedMissingDependency on Android if Google Play services is + /// not available on the current device. + /// + /// @returns An instance of Database corresponding to the given App. + static Database* GetInstance(::firebase::App* app, + InitResult* init_result_out = nullptr); + + /// @brief Gets an instance of FirebaseDatabase for the specified URL. + /// + /// If you call GetInstance() multiple times with the same App and URL, you + /// will get the same instance of Database. + /// + /// @param[in] app Your instance of firebase::App. Firebase Realtime Database + /// will use this to communicate with Firebase Authentication. + /// @param[in] url The URL of your Firebase Realtime Database. This overrides + /// any url specified in the App options. + /// @param[out] init_result_out Optional: If provided, write the init result + /// here. Will be set to kInitResultSuccess if initialization succeeded, or + /// kInitResultFailedMissingDependency on Android if Google Play services is + /// not available on the current device. + /// + /// @returns An instance of Database corresponding to the given App and URL. + static Database* GetInstance(::firebase::App* app, const char* url, + InitResult* init_result_out = nullptr); + + /// @brief Destructor for the Database object. + /// + /// When deleted, this instance will be removed from the cache of Database + /// objects. If you call GetInstance() in the future with the same App, a new + /// Database instance will be created. + ~Database(); + + /// @brief Get the firebase::App that this Database was created with. + /// + /// @returns The firebase::App this Database was created with. + App* app() const; + + /// @brief Get the URL that this Database was created with. + /// + /// @returns The URL this Database was created with, or an empty string if + /// this Database was created with default parameters. This string will remain + /// valid in memory for the lifetime of this Database. + const char* url() const; + + /// @brief Get a DatabaseReference to the root of the database. + /// + /// @returns A DatabaseReference to the root of the database. + DatabaseReference GetReference() const; + /// @brief Get a DatabaseReference for the specified path. + /// + /// @returns A DatabaseReference to the specified path in the database. + /// If you specified an invalid path, the reference's + /// DatabaseReference::IsValid() will return false. + DatabaseReference GetReference(const char* path) const; + /// @brief Get a DatabaseReference for the provided URL, which must belong to + /// the database URL this instance is already connected to. + /// + /// @returns A DatabaseReference to the specified path in the database. + /// If you specified an invalid path, the reference's + /// DatabaseReference::IsValid() will return false. + DatabaseReference GetReferenceFromUrl(const char* url) const; + + /// @brief Shuts down the connection to the Firebase Realtime Database + /// backend until GoOnline() is called. + void GoOffline(); + + /// @brief Resumes the connection to the Firebase Realtime Database backend + /// after a previous GoOffline() call. + void GoOnline(); + + /// @brief Purge all pending writes to the Firebase Realtime Database server. + /// + /// The Firebase Realtime Database client automatically queues writes and + /// sends them to the server at the earliest opportunity, depending on network + /// connectivity. In some cases (e.g. offline usage) there may be a large + /// number of writes waiting to be sent. Calling this method will purge all + /// outstanding writes so they are abandoned. All writes will be purged, + /// including transactions and onDisconnect() writes. The writes will be + /// rolled back locally, perhaps triggering events for affected event + /// listeners, and the client will not (re-)send them to the Firebase backend. + void PurgeOutstandingWrites(); + + /// @brief Sets whether pending write data will persist between application + /// exits. + /// + /// The Firebase Database client will cache synchronized data and keep track + /// of all writes you've initiated while your application is running. It + /// seamlessly handles intermittent network connections and re-sends write + /// operations when the network connection is restored. However by default + /// your write operations and cached data are only stored in-memory and will + /// be lost when your app restarts. By setting this value to `true`, the data + /// will be persisted to on-device (disk) storage and will thus be available + /// again when the app is restarted (even when there is no network + /// connectivity at that time). + /// + /// @note SetPersistenceEnabled should be called before creating any instances + /// of DatabaseReference, and only needs to be called once per application. + /// + /// @param[in] enabled Set this to true to persist write data to on-device + /// (disk) storage, or false to discard pending writes when the app exists. + void set_persistence_enabled(bool enabled); + + /// Set the log verbosity of this Database instance. + /// + /// The log filtering is cumulative with Firebase App. That is, this library's + /// log messages will only be displayed if they are not filtered out by this + /// library's log level setting and by Firebase App's log level setting. + /// + /// @note On Android this can only be set before any operations have been + /// performed with the object. + /// + /// @param[in] log_level Log level, by default this is set to kLogLevelInfo. + void set_log_level(LogLevel log_level); + + /// Get the log verbosity of this Database instance. + /// + /// @return Get the currently configured logging verbosity. + LogLevel log_level() const; + + private: + friend Database* GetDatabaseInstance(::firebase::App* app, const char* url, + InitResult* init_result_out); + Database(::firebase::App* app, internal::DatabaseInternal* internal); + Database(const Database& src); + Database& operator=(const Database& src); + + // Delete the internal_ data. + void DeleteInternal(); + + internal::DatabaseInternal* internal_; +}; + +} // namespace database +} // namespace firebase + +#endif // FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/database/common.h b/packages/firebase_core/firebase_core/firebase_core/firebase/database/common.h new file mode 100644 index 000000000000..298972784631 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/database/common.h @@ -0,0 +1,83 @@ +// Copyright 2016 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_COMMON_H_ +#define FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_COMMON_H_ + +#include "firebase/variant.h" + +namespace firebase { +namespace database { + +/// Error code returned by Firebase Realtime Database C++ functions. +enum Error { + /// The operation was a success, no error occurred. + kErrorNone = 0, + /// The operation had to be aborted due to a network disconnect. + kErrorDisconnected, + /// The supplied auth token has expired. + kErrorExpiredToken, + /// The specified authentication token is invalid. + kErrorInvalidToken, + /// The transaction had too many retries. + kErrorMaxRetries, + /// The operation could not be performed due to a network error. + kErrorNetworkError, + /// The server indicated that this operation failed. + kErrorOperationFailed, + /// The transaction was overridden by a subsequent set. + kErrorOverriddenBySet, + /// This client does not have permission to perform this operation. + kErrorPermissionDenied, + /// The service is unavailable. + kErrorUnavailable, + /// An unknown error occurred. + kErrorUnknownError, + /// The write was canceled locally. + kErrorWriteCanceled, + /// You specified an invalid Variant type for a field. For example, + /// a DatabaseReference's Priority and the keys of a Map must be of + /// scalar type (MutableString, StaticString, Int64, Double). + kErrorInvalidVariantType, + /// An operation that conflicts with this one is already in progress. For + /// example, calling SetValue and SetValueAndPriority on a DatabaseReference + /// is not allowed. + kErrorConflictingOperationInProgress, + /// The transaction was aborted, because the user's DoTransaction function + /// returned kTransactionResultAbort instead of kTransactionResultSuccess. + kErrorTransactionAbortedByUser, +}; + +/// @brief Get the human-readable error message corresponding to an error code. +/// +/// @param[in] error Error code to get the error message for. +/// +/// @returns Statically-allocated string describing the error. +extern const char* GetErrorMessage(Error error); + +/// @brief Get a server-populated value corresponding to the current +/// timestamp. +/// +/// When inserting values into the database, you can use the special value +/// firebase::database::ServerTimestamp() to have the server auto-populate the +/// current timestamp, which is represented as millieconds since the Unix epoch, +/// into the field. +/// +/// @returns A special value that tells the server to use the current timestamp. +const Variant& ServerTimestamp(); + +} // namespace database +} // namespace firebase + +#endif // FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_COMMON_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/database/data_snapshot.h b/packages/firebase_core/firebase_core/firebase_core/firebase/database/data_snapshot.h new file mode 100644 index 000000000000..cb83292a792b --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/database/data_snapshot.h @@ -0,0 +1,205 @@ +// Copyright 2016 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_DATA_SNAPSHOT_H_ +#define FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_DATA_SNAPSHOT_H_ + +#include + +#include + +#include "firebase/internal/common.h" +#include "firebase/variant.h" + +namespace firebase { +namespace database { +namespace internal { +class Callbacks; +class ChildEventRegistration; +class DataSnapshotInternal; +class DatabaseInternal; +class DatabaseInternalTestMatcherTest; +class DatabaseReferenceInternal; +class QueryInternal; +class Repo; +class ValueEventRegistration; +} // namespace internal + +class Database; +class DatabaseReference; + +#ifndef SWIG +/// A DataSnapshot instance contains data from a Firebase Database location. Any +/// time you read Database data, you receive the data as a DataSnapshot. These +/// are efficiently-generated and cannot be changed. To modify data, +/// use DatabaseReference::SetValue() or DatabaseReference::RunTransaction(). +#endif // SWIG +class DataSnapshot { + public: + /// @brief Default constructor. + /// + /// This DataSnapshot contains nothing and is considered invalid (i.e. + /// is_valid() == false). Use this to construct an empty DataSnapshot that you + /// will later populate with data from a database callback. + DataSnapshot() : internal_(nullptr) {} + +#ifdef INTERNAL_EXPERIMENTAL + explicit DataSnapshot(internal::DataSnapshotInternal* internal); +#endif + + /// @brief Copy constructor. DataSnapshots are immutable, so they can be + /// efficiently copied. + /// + /// @param[in] snapshot DataSnapshot to copy. + DataSnapshot(const DataSnapshot& snapshot); + + /// @brief Copy assignment operator. DataSnapshots are immutable, so they can + /// be efficiently copied. + /// + /// @param[in] snapshot DataSnapshot to copy. + /// + /// @returns Reference to the destination DataSnapshot. + DataSnapshot& operator=(const DataSnapshot& snapshot); + +#if defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) + /// @brief Move constructor. DataSnapshots are immutable, so they can be + /// efficiently moved. + /// + /// @param[in] snapshot DataSnapshot to move into this one. + DataSnapshot(DataSnapshot&& snapshot); + + /// @brief Move assignment operator. DataSnapshots are immutable, so they can + /// be efficiently moved. + /// + /// @param[in] snapshot DataSnapshot to move into this one. + /// + /// @returns Reference to this destination DataSnapshot. + DataSnapshot& operator=(DataSnapshot&& snapshot); +#endif // defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) + + /// Destructor. + ~DataSnapshot(); + + /// @brief Returns true if the data is non-empty. + bool exists() const; + + /// @brief Get a DataSnapshot for the location at the specified relative path. + /// + /// @param[in] path Path relative to this snapshot's location. + /// It only needs to be valid during this call. + /// + /// @returns A DataSnapshot corresponding to specified child location. + DataSnapshot Child(const char* path) const; + + /// @brief Get a DataSnapshot for the location at the specified relative path. + /// + /// @param[in] path Path relative to this snapshot's location. + /// + /// @returns A DataSnapshot corresponding to specified child location. + DataSnapshot Child(const std::string& path) const; + + /// @brief Get all the immediate children of this location. + /// + /// @returns The immediate children of this snapshot. + std::vector children() const; + + /// @brief Get the number of children of this location. + /// + /// @returns The number of immediate children of this snapshot. + size_t children_count() const; + + /// @brief Does this DataSnapshot have any children at all? + /// + /// @returns True if the snapshot has any children, false otherwise. + bool has_children() const; + + /// @brief Get the key name of the source location of this snapshot. + /// + /// @note The returned pointer is only guaranteed to be valid while the + /// DataSnapshot is still in memory. + /// + /// @returns Key name of the source location of this snapshot. + const char* key() const; + + /// @brief Get the key name of the source location of this snapshot. + /// + /// @returns Key name of the source location of this snapshot. + std::string key_string() const; + + /// @brief Get the value of the data contained in this snapshot. + /// + /// @returns The value of the data contained in this location. + Variant value() const; + + /// @brief Get the priority of the data contained in this snapshot. + /// + /// @returns The value of this location's Priority relative to its siblings. + Variant priority() const; + + /// @brief Obtain a DatabaseReference to the source location for this + /// snapshot. + /// + /// @returns A DatabaseReference corresponding to same location as + /// this snapshot. + DatabaseReference GetReference() const; + + /// @brief Does this DataSnapshot have data at a particular location? + /// + /// @param[in] path Path relative to this snapshot's location. + /// The pointer only needs to be valid during this call. + /// + /// @returns True if the snapshot has data at the specified location, false if + /// not. + bool HasChild(const char* path) const; + + /// @brief Does this DataSnapshot have data at a particular location? + /// + /// @param[in] path Path relative to this snapshot's location. + /// + /// @returns True if the snapshot has data at the specified location, false if + /// not. + bool HasChild(const std::string& path) const; + + /// @brief Returns true if this snapshot is valid, false if it is not + /// valid. An invalid snapshot could be returned by a transaction where an + /// error has occurred. + /// + /// @returns true if this snapshot is valid, false if this snapshot is + /// invalid. + bool is_valid() const; + + private: + /// @cond FIREBASE_APP_INTERNAL + friend class internal::Callbacks; + friend class internal::ChildEventRegistration; + friend class internal::DataSnapshotInternal; + friend class internal::DatabaseInternal; + friend class internal::DatabaseInternalTestMatcherTest; + friend class internal::DatabaseReferenceInternal; + friend class internal::QueryInternal; + friend class internal::Repo; + friend class internal::ValueEventRegistration; + /// @endcond + +#ifndef INTERNAL_EXPERIMENTAL + explicit DataSnapshot(internal::DataSnapshotInternal* internal); +#endif + + internal::DataSnapshotInternal* internal_; +}; + +} // namespace database +} // namespace firebase + +#endif // FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_DATA_SNAPSHOT_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/database/database_reference.h b/packages/firebase_core/firebase_core/firebase_core/firebase/database/database_reference.h new file mode 100644 index 000000000000..3e746541a1d5 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/database/database_reference.h @@ -0,0 +1,477 @@ +// Copyright 2016 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_DATABASE_REFERENCE_H_ +#define FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_DATABASE_REFERENCE_H_ + +#include +#include + +#include "firebase/database/disconnection.h" +#include "firebase/database/query.h" +#include "firebase/database/transaction.h" +#include "firebase/future.h" +#include "firebase/internal/common.h" +#include "firebase/variant.h" + +namespace firebase { +namespace database { +namespace internal { +class DatabaseInternal; +class DatabaseReferenceInternal; +class Repo; +} // namespace internal + +class DataSnapshot; + +#ifndef SWIG +/// DatabaseReference represents a particular location in your Database and can +/// be used for reading or writing data to that Database location. +/// +/// This class is the starting point for all Database operations. After you've +/// initialized it with a URL, you can use it to read data, write data, and to +/// create new DatabaseReference instances. +#endif // SWIG +class DatabaseReference : public Query { + public: + /// @brief Default constructor. This creates an invalid DatabaseReference. + /// Attempting to perform any operations on this reference will fail unless a + /// valid DatabaseReference has been assigned to it. + DatabaseReference() : Query(), internal_(nullptr) {} + + /// @brief Required virtual destructor. + virtual ~DatabaseReference(); + + /// @brief Copy constructor. It's totally okay (and efficient) to copy + /// DatabaseReference instances, as they simply point to the same location in + /// the database. + /// + /// @param[in] reference DatabaseReference to copy from. + DatabaseReference(const DatabaseReference& reference); + + /// @brief Copy assignment operator. It's totally okay (and efficient) to copy + /// DatabaseReference instances, as they simply point to the same location in + /// the database. + /// + /// @param[in] reference DatabaseReference to copy from. + /// + /// @returns Reference to the destination DatabaseReference. + DatabaseReference& operator=(const DatabaseReference& reference); + +#if defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) + /// @brief Move constructor. Moving is an efficient operation for + /// DatabaseReference instances. + /// + /// @param[in] reference DatabaseReference to move data from. + DatabaseReference(DatabaseReference&& reference); + + /// @brief Move assignment operator. Moving is an efficient operation for + /// DatabaseReference instances. + /// + /// @param[in] reference DatabaseReference to move data from. + /// + /// @returns Reference to the destination DatabaseReference. + DatabaseReference& operator=(DatabaseReference&& reference); +#endif // defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) + + /// @brief Gets the database to which we refer. + /// + /// The pointer will remain valid indefinitely. + /// + /// @returns Firebase Database instance that this DatabaseReference refers to. + Database* database() const; + + /// @brief Gets the string key of this database location. + /// + /// The pointer is only valid while the DatabaseReference remains in memory. + /// + /// @returns String key of this database location, which will remain valid in + /// memory until the DatabaseReference itself goes away. + const char* key() const; + + /// @brief Gets the string key of this database location. + /// + /// @returns String key of this database location. + std::string key_string() const; + + /// @brief Returns true if this reference refers to the root of the database. + /// + /// @returns true if this reference refers to the root of the database, false + /// otherwise. + bool is_root() const; + + /// @brief Returns true if this reference is valid, false if it is not + /// valid. DatabaseReferences constructed with the default constructor + /// are considered invalid. An invalid reference could be returned by + /// Database::GetReference() or Database::GetReferenceFromUrl() if you specify + /// an incorrect location, or calling Query::GetReference() on an invalid + /// query. + /// + /// @returns true if this reference is valid, false if this reference is + /// invalid. + bool is_valid() const override; + + /// @brief Gets the parent of this location, or get this location again if + /// IsRoot(). + /// + /// @returns Parent of this location in the database, unless this location is + /// the root, in which case it returns this same location again. + DatabaseReference GetParent() const; + + /// @brief Gets the root of the database. + /// + /// @returns Root of the database. + DatabaseReference GetRoot() const; + + /// @brief Gets a reference to a location relative to this one. + /// + /// @param[in] path Path relative to this snapshot's location. + /// The pointer only needs to be valid during this call. + /// + /// @returns Child relative to this location. + DatabaseReference Child(const char* path) const; + + /// @brief Gets a reference to a location relative to this one. + /// + /// @param[in] path Path relative to this snapshot's location. + /// + /// @returns Child relative to this location. + DatabaseReference Child(const std::string& path) const; + + /// @brief Automatically generates a child location, create a reference to it, + /// and returns that reference to it. + /// + /// @returns A newly created child, with a unique key. + DatabaseReference PushChild() const; + + /// @brief Removes the value at this location from the database. + /// + /// This is an asynchronous operation which takes time to execute, and uses + /// firebase::Future to return its result. + /// + /// @returns A Future result, which will complete when the operation either + /// succeeds or fails. When the Future is completed, if its Error is + /// kErrorNone, the operation succeeded. + /// + /// @note Only one RemoveValue() should be running on a given database + /// location at the same time. If you need to run multiple operations at once, + /// use RunTransaction(). + Future RemoveValue(); + + /// @brief Gets the result of the most recent call to RemoveValue(); + /// + /// @returns Result of the most recent call to RemoveValue(). + Future RemoveValueLastResult(); + + /// @brief Run a user-supplied callback function (passing in a context), + /// possibly multiple times, to perform an atomic transaction on the database. + /// + /// @see firebase::database::DoTransactionWithContext for more information. + /// + /// @param[in] transaction_function The user-supplied function that will be + /// called, possibly multiple times, to perform the database transaction. + /// @param[in] context User-supplied context that will be passed to the + /// transaction function. + /// @param[in] trigger_local_events If true, events will be triggered for + /// intermediate state changes during the transaction. If false, only the + /// final state will cause events to be triggered. + /// + /// @returns A Future result, which will complete when the transaction either + /// succeeds or fails. When the Future is completed, if its Error is + /// kErrorNone, the operation succeeded and the transaction was committed, and + /// the new value of the data will be returned in the DataSnapshot result. If + /// the Error is kErrorTransactionAbortedByUser, the transaction was aborted + /// because the transaction function returned kTransactionResultAbort, and the + /// old value will be returned in DataSnapshot. Otherwise, if some other error + /// occurred, Error and ErrorMessage will be set and DataSnapshot will be + /// invalid. + /// + /// @note Only one RunTransaction() should be running on a given database + /// location at the same time. + Future RunTransaction( + DoTransactionWithContext transaction_function, void* context, + bool trigger_local_events = true); + +#if defined(FIREBASE_USE_STD_FUNCTION) || defined(DOXYGEN) + /// @brief Run a user-supplied callback, possibly multiple times, to perform + /// an atomic transaction on the database. + /// + /// @see firebase::database::DoTransactionFunction for more information. + /// + /// @param[in] transaction_function The user-supplied function or lambda that + /// will be called, possibly multiple times, to perform the database + /// transaction. + /// @param[in] trigger_local_events If true, events will be triggered for + /// intermediate state changes during the transaction. If false, only the + /// final state will cause events to be triggered. + /// + /// @returns A Future result, which will complete when the transaction either + /// succeeds or fails. When the Future is completed, if its Error is + /// kErrorNone, the operation succeeded and the transaction was committed, and + /// the new value of the data will be returned in the DataSnapshot result. If + /// the Error is kErrorTransactionAbortedByUser, the transaction was aborted + /// because the transaction function returned kTransactionResultAbort, and the + /// old value will be returned in DataSnapshot. Otherwise, if some other error + /// occurred, Error and ErrorMessage will be set and DataSnapshot will be + /// invalid. + /// + /// @note Only one RunTransaction() should be running on a given database + /// location at the same time. + /// + /// @note This version (that accepts an std::function) is not available when + /// using stlport on Android. If you don't wish to use std::function, use the + /// overloaded method that accepts a simple function pointer with a context. + Future RunTransaction( + DoTransactionFunction transaction_function, + bool trigger_local_events = true); +#endif // defined(FIREBASE_USE_STD_FUNCTION) || defined(DOXYGEN) + +#if !defined(FIREBASE_USE_STD_FUNCTION) || defined(DOXYGEN) + /// @brief Run a user-supplied callback function, possibly multiple times, to + /// perform an atomic transaction on the database. + /// + /// @see firebase::database::DoTransaction for more information. + /// + /// @param[in] transaction_function The user-supplied function that will be + /// called, possibly multiple times, to perform the database transaction. + /// @param[in] trigger_local_events If true, events will be triggered for + /// intermediate state changes during the transaction. If false, only the + /// final state will cause events to be triggered. + /// + /// @returns A Future result, which will complete when the transaction either + /// succeeds or fails. When the Future is completed, if its Error is + /// kErrorNone, the operation succeeded and the transaction was committed, and + /// the new value of the data will be returned in the DataSnapshot result. If + /// the Error is kErrorTransactionAbortedByUser, the transaction was aborted + /// because the transaction function returned kTransactionResultAbort, and the + /// old value will be returned in DataSnapshot. Otherwise, if some other error + /// occurred, Error and ErrorMessage will be set and DataSnapshot will be + /// invalid. + /// + /// @note Only one RunTransaction() should be running on a given database + /// location at the same time. + /// + /// @note This version (that accepts a simple function pointer) is only + /// available when using stlport and std::function is not available. + Future RunTransaction(DoTransaction transaction_function, + bool trigger_local_events = true); +#endif // !defined(FIREBASE_USE_STD_FUNCTION) || defined(DOXYGEN) + + /// @brief Get the result of the most recent call to RunTransaction(). + /// + /// @returns Results of the most recent call to RunTransaction(). + Future RunTransactionLastResult(); + + /// @brief Sets the priority of this field, which controls its sort + /// order relative to its siblings. + /// + /// In Firebase, children are sorted in the following order: + /// 1. First, children with no priority. + /// 2. Then, children with numerical priority, sorted numerically in + /// ascending order. + /// 3. Then, remaining children, sorted lexicographically in ascending order + /// of their text priority. + /// + /// Children with the same priority (including no priority) are sorted by + /// key: + /// A. First, children with keys that can be parsed as 32-bit integers, + /// sorted in ascending numerical order of their keys. + /// B. Then, remaining children, sorted in ascending lexicographical order + /// of their keys. + /// + /// This is an asynchronous operation which takes time to execute, and uses + /// firebase::Future to return its result. + /// + /// @param[in] priority Sort priority for this child relative to its siblings. + /// The Variant types accepted are Null, Int64, Double, and String. Other + /// types will return kErrorInvalidVariantType. + /// + /// @returns A Future result, which will complete when the operation either + /// succeeds or fails. When the Future is completed, if its Error is + /// kErrorNone, the operation succeeded. + /// + /// @note Only one SetPriority() should be running on a given database + /// location + /// at the same time. If you need to run multiple operations at once, use + /// RunTransaction(). + Future SetPriority(Variant priority); + + /// @brief Gets the result of the most recent call to SetPriority(). + /// + /// @returns Result of the most recent call to SetPriority(). + Future SetPriorityLastResult(); + + /// @brief Sets the data at this location to the given value. + /// + /// This is an asynchronous operation which takes time to execute, and uses + /// firebase::Future to return its result. + /// + /// @param[in] value The value to set this location to. The Variant's type + /// corresponds to the types accepted by the database JSON: + /// Null: Deletes this location from the database. + /// Int64: Inserts an integer value into this location. + /// Double: Inserts a floating point value into this location. + /// String: Inserts a string into this location. + /// (Accepts both Mutable and Static strings) + /// Vector: Inserts a JSON array into this location. The elements can be any + /// Variant type, including Vector and Map. + /// Map: Inserts a JSON associative array into this location. The keys must + /// be of type String (or Int64/Double which are converted to String). + /// The values can be any Variant type, including Vector and Map. + /// + /// @returns A Future result, which will complete when the operation either + /// succeeds or fails. When the Future is completed, if its Error is + /// kErrorNone, the operation succeeded. + /// + /// @note Only one SetValue() should be running on a given database location + /// at the same time. If you need to run multiple operations at once, use + /// RunTransaction(). + Future SetValue(Variant value); + + /// @brief Gets the result of the most recent call to SetValue(). + /// + /// @returns Result of the most recent call to SetValue(). + Future SetValueLastResult(); + + /// @brief Sets both the data and priority of this location. See SetValue() + /// and SetPriority() for context on the parameters. + /// + /// This is an asynchronous operation which takes time to execute, and uses + /// firebase::Future to return its result. + /// + /// @param[in] value The value to set this location to. See SetValue() for + /// information on the types accepted. + /// @param[in] priority The priority to set this location to. See + /// SetPriority() for information on the types accepted. + /// + /// @returns A Future result, which will complete when the operation either + /// succeeds or fails. When the Future is completed, if its Error is + /// kErrorNone, the operation succeeded. + /// + /// @note Only one SetValueAndPriority() should be running on a given database + /// location at the same time. SetValueAndPriority() can't be used on the same + /// location at the same time as either SetValue() or SetPriority(), and will + /// return kErrorConflictingOperationInProgress if you try. If you need to run + /// multiple operations at once, use RunTransaction(). + Future SetValueAndPriority(Variant value, Variant priority); + + /// @brief Get the result of the most recent call to SetValueAndPriority(). + /// + /// @returns Result of the most recent call to SetValueAndPriority(). + Future SetValueAndPriorityLastResult(); + + /// @brief Updates the specified child keys to the given values. + /// + /// @param[in] values A variant of type Map. The keys are the paths to update + /// and must be of type String (or Int64/Double which are converted to + /// String). The values can be any Variant type. A value of Variant type Null + /// will delete the child. + /// + /// @returns A Future result, which will complete when the operation either + /// succeeds or fails. When the Future is completed, if its Error is + /// kErrorNone, the operation succeeded. + /// + /// @note This method will return kErrorConflictingOperationInProgress if it + /// is run at the same time as SetValue(), SetValueAndPriority(), or + /// RemoveValue() in the same location. + Future UpdateChildren(Variant values); + + /// @brief Updates the specified child keys to the given values. + /// + /// This is an asynchronous operation which takes time to execute, and uses + /// firebase::Future to return its result. + /// + /// @param[in] values The paths to update, and their new child values. A value + /// of type Null will delete that particular child. + /// + /// @returns A Future result, which will complete when the operation either + /// succeeds or fails. When the Future is completed, if its Error is + /// kErrorNone, the operation succeeded. + inline Future UpdateChildren( + const std::map& values) { + return UpdateChildren(Variant(values)); + } + + /// @brief Gets the result of the most recent call to either version of + /// UpdateChildren(). + /// + /// @returns Result of the most recent call to UpdateChildren(). + Future UpdateChildrenLastResult(); + + /// @brief Get the absolute URL of this reference. + /// + /// @returns The absolute URL of the location this reference refers to. + std::string url() const; + + /// @brief Get the disconnect handler, which controls what actions the server + /// will perform to this location's data when this client disconnects. + /// + /// @returns Disconnection handler for this location. You can use this to + /// queue up operations on the server to be performed when the client + /// disconnects. + DisconnectionHandler* OnDisconnect(); + + /// @brief Manually disconnect Firebase Realtime Database from the server, and + /// disable automatic reconnection. This will affect all other instances of + /// DatabaseReference as well. + void GoOffline(); + + /// @brief Manually reestablish connection to the Firebase Realtime Database + /// server and enable automatic reconnection. This will affect all other + /// instances of DatabaseReference as well. + void GoOnline(); + + protected: + /// @cond FIREBASE_APP_INTERNAL + explicit DatabaseReference(internal::DatabaseReferenceInternal* internal); + /// @endcond + + private: + /// @cond FIREBASE_APP_INTERNAL + + // Remove the "Query" cleanup registration (which the base class constructor + // already registered) and replace it with a "DatabaseReference" registration. + // + // This is necessary so that if the instance needs to be cleaned up, the + // correct pointer type will be used to access it. + void SwitchCleanupRegistrationToDatabaseReference(); + + // Remove the "DatabaseReference" cleanup registration and replace it with a + // "Query" one. ~Query() will unregister that one. + void SwitchCleanupRegistrationBackToQuery(); + + friend class DataSnapshot; + friend class Query; + friend class internal::DatabaseInternal; + friend class internal::Repo; + friend bool operator==(const DatabaseReference& lhs, + const DatabaseReference& rhs); + /// @endcond + + internal::DatabaseReferenceInternal* internal_; +}; + +/// @brief Compares two DatabaseReference instances. +/// +/// @param[in] lhs A DatabaseReference. +/// @param[in] rhs A DatabaseReference to compare against. +/// +/// @returns True if the DatabaseReference instances have the same URL. False +/// otherwise. +bool operator==(const DatabaseReference& lhs, const DatabaseReference& rhs); + +} // namespace database +} // namespace firebase + +#endif // FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_DATABASE_REFERENCE_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/database/disconnection.h b/packages/firebase_core/firebase_core/firebase_core/firebase/database/disconnection.h new file mode 100644 index 000000000000..b21fa472e629 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/database/disconnection.h @@ -0,0 +1,156 @@ +// Copyright 2016 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_DISCONNECTION_H_ +#define FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_DISCONNECTION_H_ + +#include "firebase/future.h" +#include "firebase/internal/common.h" +#include "firebase/variant.h" + +namespace firebase { +namespace database { +namespace internal { +class DatabaseReferenceInternal; +class DisconnectionHandlerInternal; +} // namespace internal + +/// Allows you to register server-side actions to occur when the client +/// disconnects. Each method you call (with the exception of Cancel) will queue +/// up an action on the data that will be performed by the server in the event +/// the client disconnects. To reset this queue, call Cancel(). +/// +/// A DisconnectionHandler is associated with a specific location in the +/// database, as they are obtained by calling DatabaseReference::OnDisconnect(). +class DisconnectionHandler { + public: + ~DisconnectionHandler(); + + /// @brief Cancel any Disconnection operations that are queued up by this + /// handler. When the Future returns, if its Error is kErrorNone, the queue + /// has been cleared on the server. + /// + /// @returns A Future result, which will complete when the operation either + /// succeeds or fails. When the Future is completed, if its Error is + /// kErrorNone, the operation succeeded. + Future Cancel(); + /// @brief Get the result of the most recent call to Cancel(). + /// + /// @returns Result of the most recent call to Cancel(). + Future CancelLastResult(); + + /// @brief Remove the value at the current location when the client + /// disconnects. When the Future returns, if its Error is kErrorNone, the + /// RemoveValue operation has been successfully queued up on the server. + /// + /// @returns A Future result, which will complete when the operation either + /// succeeds or fails. When the Future is completed, if its Error is + /// kErrorNone, the operation succeeded. + Future RemoveValue(); + /// @brief Get the result of the most recent call to RemoveValue(). + /// + /// @returns Result of the most recent call to RemoveValue(). + Future RemoveValueLastResult(); + + /// @brief Set the value of the data at the current location when the client + /// disconnects. When the Future returns, if its Error is kErrorNone, the + /// SetValue operation has been successfully queued up on the server. + /// + /// @param[in] value The value to set this location to when the client + /// disconnects. For information on how the Variant types are used, + /// see firebase::database::DatabaseReference::SetValue(). + /// + /// @returns A Future result, which will complete when the operation either + /// succeeds or fails. When the Future is completed, if its Error is + /// kErrorNone, the operation succeeded. + Future SetValue(Variant value); + /// Get the result of the most recent call to SetValue(). + /// + /// @returns Result of the most recent call to SetValue(). + Future SetValueLastResult(); + + /// @brief Set the value and priority of the data at the current location when + /// the client disconnects. When the Future returns, if its Error is + /// kErrorNone, the SetValue operation has been successfully queued up on the + /// server. + /// + /// @param[in] value The value to set this location to when the client + /// disconnects. For information on how the Variant types are used, + /// see firebase::database::DatabaseReference::SetValue(). + /// @param[in] priority The priority to set this location to when the client + /// disconnects. The Variant types accepted are Null, Int64, Double, and + /// String. For information about how priority is used, see + /// firebase::database::DatabaseReference::SetPriority(). + /// + /// @returns A Future result, which will complete when the operation either + /// succeeds or fails. When the Future is completed, if its Error is + /// kErrorNone, the operation succeeded. + Future SetValueAndPriority(Variant value, Variant priority); + /// @brief Get the result of the most recent call to SetValueAndPriority(). + /// + /// @returns Result of the most recent call to SetValueAndPriority(). + Future SetValueAndPriorityLastResult(); + + /// @brief Updates the specified child keys to the given values when the + /// client disconnects. When the Future returns, if its Error is kErrorNone, + /// the UpdateChildren operation has been successfully queued up by the + /// server. + /// + /// @param[in] values A variant of type Map. The keys are the paths to update + /// and must be of type String (or Int64/Double which are converted to + /// String). The values can be any Variant type. A value of Variant type Null + /// will delete the child. + /// + /// @returns A Future result, which will complete when the operation either + /// succeeds or fails. When the Future is completed, if its Error is + /// kErrorNone, the operation succeeded. + Future UpdateChildren(Variant values); + /// @brief Updates the specified child keys to the given values when the + /// client disconnects. When the Future returns, if its Error is kErrorNone, + /// the UpdateChildren operation has been successfully queued up by the + /// server. + /// + /// @param[in] values The paths to update, and their new child values. A value + /// of type Null will delete that particular child. + /// + /// @returns A Future result, which will complete when the operation either + /// succeeds or fails. When the Future is completed, if its Error is + /// kErrorNone, the operation succeeded. + Future UpdateChildren(const std::map& values) { + return UpdateChildren(Variant(values)); + } + /// @brief Gets the result of the most recent call to either version of + /// UpdateChildren(). + /// + /// @returns Result of the most recent call to UpdateChildren(). + Future UpdateChildrenLastResult(); + + private: + /// @cond FIREBASE_APP_INTERNAL + friend class internal::DatabaseReferenceInternal; + friend class internal::DisconnectionHandlerInternal; + /// @endcond + + /// Call DatabaseReference::OnDisconnect() to get an instance of this class. + explicit DisconnectionHandler( + internal::DisconnectionHandlerInternal* internal); + + /// You can only get the DisconnectHandler for a given reference. + internal::DisconnectionHandlerInternal* internal_; +}; + +} // namespace database +} // namespace firebase + +#endif // FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_DISCONNECTION_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/database/listener.h b/packages/firebase_core/firebase_core/firebase_core/firebase/database/listener.h new file mode 100644 index 000000000000..fe13d9299003 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/database/listener.h @@ -0,0 +1,112 @@ +// Copyright 2016 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_LISTENER_H_ +#define FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_LISTENER_H_ + +#include "firebase/database/common.h" + +namespace firebase { +namespace database { + +class DataSnapshot; + +/// Value listener interface. Subclasses of this listener class can be +/// used to receive events about data changes at a location. Attach +/// the listener to a location using +/// DatabaseReference::AddValueListener() or +/// Query::AddValueListener(), and OnValueChanged() will be called +/// once immediately, and again when the value changes. +class ValueListener { + public: + virtual ~ValueListener(); + + /// This method will be called with a snapshot of the data at this + /// location each time that data changes. + /// + /// @param[in] snapshot The current data at the location. + virtual void OnValueChanged(const DataSnapshot& snapshot) = 0; + + /// @brief This method will be triggered in the event that this listener + /// either failed at the server, or is removed as a result of the security and + /// Firebase rules. + /// + /// @param[in] error A code corresponding to the error that occurred. + /// @param[in] error_message A description of the error that occurred. + virtual void OnCancelled(const Error& error, const char* error_message) = 0; +}; + +/// Child listener interface. Subclasses of this listener class can be +/// used to receive events about changes in the child locations of a +/// firebase::database::Query or +/// firebase::database::DatabaseReference. Attach the listener to a +/// location with Query::AddChildListener() or +/// DatabaseReference::AddChildListener() and the appropriate method +/// will be triggered when changes occur. +class ChildListener { + public: + virtual ~ChildListener(); + + /// @brief This method is triggered when a new child is added to the location + /// to which this listener was added. + /// + /// @param[in] snapshot An immutable snapshot of the data at the new data at + /// the child location. + /// @param[in] previous_sibling_key The key name of sibling location ordered + /// before the child. This will be nullptr for the first child node of a + /// location. + virtual void OnChildAdded(const DataSnapshot& snapshot, + const char* previous_sibling_key) = 0; + /// @brief This method is triggered when the data at a child location has + /// changed. + /// + /// @param[in] snapshot An immutable snapshot of the data at the new data at + /// the child location. + /// @param[in] previous_sibling_key The key name of sibling location ordered + /// before the child. This will be nullptr for the first child node of a + /// location. + virtual void OnChildChanged(const DataSnapshot& snapshot, + const char* previous_sibling_key) = 0; + /// @brief This method is triggered when a child location's priority changes. + /// See DatabaseReference::SetPriority() for more information on priorities + /// and + /// ordering data. + /// + /// @param[in] snapshot An immutable snapshot of the data at the new data at + /// the child location. + /// @param[in] previous_sibling_key The key name of sibling location ordered + /// before the child. This will be nullptr for the first child node of a + /// location. + virtual void OnChildMoved(const DataSnapshot& snapshot, + const char* previous_sibling_key) = 0; + /// @brief This method is triggered when a child is removed from the location + /// to which this listener was added. + /// + /// @param[in] snapshot An immutable snapshot of the data at the new data at + /// the child location. + virtual void OnChildRemoved(const DataSnapshot& snapshot) = 0; + + /// @brief This method will be triggered in the event that this listener + /// either failed at the server, or is removed as a result of the security and + /// Firebase rules. + /// + /// @param[in] error A code corresponding to the error that occurred. + /// @param[in] error_message A description of the error that occurred. + virtual void OnCancelled(const Error& error, const char* error_message) = 0; +}; + +} // namespace database +} // namespace firebase + +#endif // FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_LISTENER_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/database/mutable_data.h b/packages/firebase_core/firebase_core/firebase_core/firebase/database/mutable_data.h new file mode 100644 index 000000000000..cedfa159cca6 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/database/mutable_data.h @@ -0,0 +1,165 @@ +// Copyright 2016 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_MUTABLE_DATA_H_ +#define FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_MUTABLE_DATA_H_ + +#include "firebase/internal/common.h" +#include "firebase/variant.h" + +namespace firebase { +namespace database { +namespace internal { +class DatabaseInternal; +class DatabaseReferenceInternal; +class MutableDataInternal; +class Repo; +} // namespace internal + +#ifndef SWIG +/// Instances of this class encapsulate the data and priority at a location. It +/// is used in transactions, and it is intended to be inspected and then updated +/// to the desired data at that location. +#endif // SWIG +class MutableData { + public: +#if defined(FIREBASE_USE_MOVE_OPERATORS) + /// Move constructor + /// Move is more efficient than copy and delete. + MutableData(MutableData&& rhs); + + // MutableData may be moved. + MutableData& operator=(MutableData&& rhs); +#endif // defined(FIREBASE_USE_MOVE_OPERATORS) + + /// Destructor. + ~MutableData(); + + /// @brief Used to obtain a MutableData instance that encapsulates + /// the data and priority at the given relative path. + /// + /// Note that changes made to a child MutableData instance will be visible + /// to the parent and vice versa. + /// + /// @param[in] path Path relative to this snapshot's location. + /// The pointer only needs to be valid during this call. + /// + /// @returns MutableData for the Child relative to this location. The memory + /// will be freed when the Transaction is finished. + MutableData Child(const char* path); + + /// @brief Used to obtain a MutableData instance that encapsulates + /// the data and priority at the given relative path. + /// + /// @param[in] path Path relative to this snapshot's location. + /// + /// @returns MutableData for the Child relative to this location. The memory + /// will be freed when the Transaction is finished. + MutableData Child(const std::string& path); + + /// @brief Get all the immediate children of this location. + /// + /// @returns The immediate children of this location. + std::vector children(); + + /// @brief Get the number of children of this location. + /// + /// @returns The number of immediate children of this location. + size_t children_count(); + + /// @brief Get the key name of the source location of this data. + /// + /// @note The returned pointer is only guaranteed to be valid during the + /// transaction. + /// + /// @returns Key name of the source location of this data. + const char* key() const; + + /// @brief Get the key name of the source location of this data. + /// + /// @returns Key name of the source location of this data. + std::string key_string() const; + + /// @brief Get the value of the data contained at this location. + /// + /// @returns The value of the data contained at this location. + Variant value() const; + + /// @brief Get the priority of the data contained at this snapshot. + /// + /// @returns The value of this location's Priority relative to its siblings. + Variant priority(); + + /// @brief Does this MutableData have data at a particular location? + /// + /// @param[in] path Path relative to this data's location. + /// The pointer only needs to be valid during this call. + /// + /// @returns True if there is data at the specified location, false if not. + bool HasChild(const char* path) const; + + /// @brief Does this MutableData have data at a particular location? + /// + /// @param[in] path Path relative to this data's location. + /// @returns True if there is data at the specified location, false if not. + bool HasChild(const std::string& path) const; + + /// @brief Sets the data at this location to the given value. + /// + /// @param[in] value The value to set this location to. The Variant's type + /// corresponds to the types accepted by the database JSON: + /// Null: Deletes this location from the database. + /// Int64: Inserts an integer value into this location. + /// Double: Inserts a floating point value into this location. + /// String: Inserts a string into this location. + /// (Accepts both Mutable and Static strings) + /// Vector: Inserts a JSON array into this location. The elements can be any + /// Variant type, including Vector and Map. + /// Map: Inserts a JSON associative array into this location. The keys must + /// be of type String (or Int64/Double which are converted to String). + /// The values can be any Variant type, including Vector and Map. + void set_value(const Variant& value); + + /// @brief Sets the priority of this field, which controls its sort + /// order relative to its siblings. + /// + /// @see firebase::database::DatabaseReference::SetPriority() for information + /// on how Priority affects the ordering of a node's children. + /// + /// @param[in] priority Sort priority for this child relative to its siblings. + /// The Variant types accepted are Null, Int64, Double, and String. Other + /// types will return kErrorInvalidVariantType. + void set_priority(const Variant& priority); + + private: + /// @cond FIREBASE_APP_INTERNAL + friend class internal::DatabaseReferenceInternal; + friend class internal::DatabaseInternal; + friend class internal::MutableDataInternal; + friend class internal::Repo; + friend MutableData GetInvalidMutableData(); + /// @endcond + + explicit MutableData(internal::MutableDataInternal* internal); + + MutableData(const MutableData& rhs) = delete; + MutableData& operator=(const MutableData& rhs) = delete; + + internal::MutableDataInternal* internal_; +}; + +} // namespace database +} // namespace firebase + +#endif // FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_MUTABLE_DATA_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/database/query.h b/packages/firebase_core/firebase_core/firebase_core/firebase/database/query.h new file mode 100644 index 000000000000..c60707a7ee65 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/database/query.h @@ -0,0 +1,358 @@ +// Copyright 2016 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_QUERY_H_ +#define FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_QUERY_H_ + +#include + +#include "firebase/database/listener.h" +#include "firebase/future.h" +#include "firebase/internal/common.h" + +namespace firebase { +namespace database { +namespace internal { +class QueryInternal; +} // namespace internal + +class DatabaseReference; + +#ifndef SWIG +/// The Query class is used for reading data. Listeners can be attached, which +/// will be triggered when the data changes. +#endif // SWIG +class Query { + public: + /// Default constructor. This creates an invalid Query. Attempting to perform + /// any operations on this reference will fail unless a valid Query has been + /// assigned to it. + Query() : internal_(nullptr) {} + + /// Copy constructor. Queries can be copied. Copies exist independently of + /// each other. + Query(const Query& query); + + /// Copy assignment operator. Queries can be copied. Copies exist + /// independently of each other. + Query& operator=(const Query& query); + +#if defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) + /// Move constructor. + Query(Query&& query); + /// Move assignment operator. + Query& operator=(Query&& query); +#endif // defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) + + /// @brief Required virtual destructor. + virtual ~Query(); + + /// @brief Gets the value of the query for the given location a single time. + /// + /// This is an asynchronous operation which takes time to execute, and uses + /// firebase::Future to return its result. + /// + /// @returns A Future result, which will complete when the operation either + /// succeeds or fails. On this Future's completion, if its Error is + /// kErrorNone, the operation succeeded, and the DataSnapshot contains the + /// data in this location. + Future GetValue(); + /// @brief Gets the result of the most recent call to GetValue(). + /// + /// @returns Result of the most recent call to GetValue(). + Future GetValueLastResult(); + + /// @brief Adds a listener that will be called immediately and then again any + /// time the data changes. + /// + /// @param[in] listener A ValueListener instance, which must remain in memory + /// until you remove the listener from the Query. + void AddValueListener(ValueListener* listener); + + /// @brief Removes a listener that was previously added with + /// AddValueListener(). + /// + /// @param[in] listener A ValueListener instance to remove from the + /// Query. After it is removed, you can delete it or attach it to a new + /// location. + /// + /// @note You can remove a ValueListener from a different Query than you added + /// it to, as long as the two Query instances are equivalent. + void RemoveValueListener(ValueListener* listener); + + /// @brief Removes all value listeners that were added with + /// AddValueListener(). + /// + /// @note You can remove ValueListeners from a different Query than you added + /// them to, as long as the two Query instances are equivalent. + void RemoveAllValueListeners(); + + /// @brief Adds a listener that will be called any time a child is added, + /// removed, modified, or reordered. + /// + /// @param[in] listener A ChildListener instance, which must remain in memory + /// until you remove the listener from the Query. + void AddChildListener(ChildListener* listener); + + /// @brief Removes a listener that was previously added with + /// AddChildListener(). + /// + /// @param[in] listener A ChildListener instance to remove from the + /// Query. After it is removed, you can delete it or attach it to a new + /// location. + /// + /// @note You can remove a ChildListener from a different Query than you added + /// it to, as long as the two Query instances are equivalent. + void RemoveChildListener(ChildListener* listener); + + /// @brief Removes all child listeners that were added by AddChildListener(). + /// + /// @note You can remove ChildListeners from a different Query than you added + /// them to, as long as the two Query instances are equivalent. + void RemoveAllChildListeners(); + + /// @brief Gets a DatabaseReference corresponding to the given location. + /// + /// @returns A DatabaseReference corresponding to the same location as the + /// Query, but without any of the ordering or filtering parameters. + DatabaseReference GetReference() const; + + /// @brief Sets whether this location's data should be kept in sync even if + /// there are no active Listeners. + /// + /// By calling SetKeepSynchronized(true) on a given database location, the + /// data for that location will automatically be downloaded and kept in sync, + /// even when no listeners are attached for that location. Additionally, while + /// a location is kept synced, it will not be evicted from the persistent disk + /// cache. + /// + /// @param[in] keep_sync If true, set this location to be synchronized. If + /// false, set it to not be synchronized. + void SetKeepSynchronized(bool keep_sync); + + // The OrderBy* functions are used for two purposes: + // 1. Order the data when getting the list of children. + // 2. When filtering the data using the StartAt* and EndAt* functions further + // below, use the specified ordering. + + /// @brief Gets a query in which child nodes are ordered by the values of the + /// specified path. Any previous OrderBy directive will be replaced in the + /// returned Query. + /// + /// @param[in] path Path to a child node. The value of this node will be used + /// for sorting this query. The pointer you pass in need not remain valid + /// after the call completes. + /// + /// @returns A Query in this same location, with the children are sorted by + /// the value of their own child specified here. + Query OrderByChild(const char* path); + /// @brief Gets a query in which child nodes are ordered by the values of the + /// specified path. Any previous OrderBy directive will be replaced in the + /// returned Query. + /// + /// @param[in] path Path to a child node. The value of this node will be used + /// for sorting this query. + /// + /// @returns A Query in this same location, with the children are sorted by + /// the value of their own child specified here. + Query OrderByChild(const std::string& path); + /// @brief Gets a query in which child nodes are ordered by their keys. Any + /// previous OrderBy directive will be replaced in the returned Query. + /// + /// @returns A Query in this same location, with the children are sorted by + /// their key. + Query OrderByKey(); + /// @brief Gets a query in which child nodes are ordered by their priority. + /// Any previous OrderBy directive will be replaced in the returned Query. + /// + /// @returns A Query in this same location, with the children are sorted by + /// their priority. + Query OrderByPriority(); + /// @brief Create a query in which nodes are ordered by their value. + /// + /// @returns A Query in this same location, with the children are sorted by + /// their value. + Query OrderByValue(); + + // The StartAt, EndAt, and EqualTo functions are used to limit which child + // nodes are returned when iterating through the current location. + + /// @brief Get a Query constrained to nodes with the given sort value or + /// higher. + /// + /// This method is used to generate a reference to a limited view of the data + /// at this location. The Query returned will only refer to child nodes with a + /// value greater than or equal to the given value, using the given OrderBy + /// directive (or priority as the default). + /// + /// @param[in] order_value The lowest sort value the Query should include. + /// + /// @returns A Query in this same location, filtering out child nodes that + /// have a lower sort value than the sort value specified. + Query StartAt(Variant order_value); + /// @brief Get a Query constrained to nodes with the given sort value or + /// higher, and the given key or higher. + /// + /// This method is used to generate a reference to a limited view of the data + /// at this location. The Query returned will only refer to child nodes with a + /// value greater than or equal to the given value, using the given OrderBy + /// directive (or priority as default), and additionally only child nodes with + /// a key greater than or equal to the given key. + /// + /// Known issue This currently does not work properly on all platforms. + /// Please use StartAt(Variant order_value) instead. + /// + /// @param[in] order_value The lowest sort value the Query should include. + /// @param[in] child_key The lowest key the Query should include. + /// + /// @returns A Query in this same location, filtering out child nodes that + /// have a lower sort value than the sort value specified, or a lower key than + /// the key specified. + Query StartAt(Variant order_value, const char* child_key); + + /// @brief Get a Query constrained to nodes with the given sort value or + /// lower. + /// + /// This method is used to generate a reference to a limited view of the data + /// at this location. The Query returned will only refer to child nodes with a + /// value less than or equal to the given value, using the given OrderBy + /// directive (or priority as default). + /// + /// @param[in] order_value The highest sort value the Query should refer + /// to. + /// + /// @returns A Query in this same location, filtering out child nodes that + /// have a higher sort value or key than the sort value or key specified. + Query EndAt(Variant order_value); + /// @brief Get a Query constrained to nodes with the given sort value or + /// lower, and the given key or lower. + /// + /// This method is used to generate a reference to a limited view of + /// the data at this location. The Query returned will only refer to child + /// nodes with a value less than or equal to the given value, using the given + /// OrderBy directive (or priority as default), and additionally only child + /// nodes with a key less than or equal to the given key. + /// + /// Known issue This currently does not work properly on all platforms. + /// Please use EndAt(Variant order_value) instead. + /// + /// @param[in] order_value The highest sort value the Query should include. + /// @param[in] child_key The highest key the Query should include. + /// + /// @returns A Query in this same location, filtering out child nodes that + /// have a higher sort value than the sort value specified, or a higher key + /// than the key specified. + Query EndAt(Variant order_value, const char* child_key); + + /// @brief Get a Query constrained to nodes with the exact given sort value. + /// + /// This method is used to create a query constrained to only return child + /// nodes with the given value, using the given OrderBy directive (or priority + /// as default). + /// + /// @param[in] order_value The exact sort value the Query should include. + /// + /// @returns A Query in this same location, filtering out child nodes that + /// have a different sort value than the sort value specified. + Query EqualTo(Variant order_value); + + /// @brief Get a Query constrained to nodes with the exact given sort value, + /// and the exact given key. + /// + /// This method is used to create a query constrained to only return the child + /// node with the given value, using the given OrderBy directive (or priority + /// as default), and the given key. Note that there is at most one such child + /// as child key names are unique. + /// + /// Known issue This currently does not work properly on iOS, tvOS and + /// desktop. Please use EqualTo(Variant order_value) instead. + /// + /// @param[in] order_value The exact sort value the Query should include. + /// @param[in] child_key The exact key the Query should include. + /// + /// @returns A Query in this same location, filtering out child nodes that + /// have a different sort value than the sort value specified, and containing + /// at most one child with the exact key specified. + Query EqualTo(Variant order_value, const char* child_key); + + // The LimitTo* functions are used to limit how many child nodes are returned + // when iterating through the current location. + + /// @brief Gets a Query limited to only the first results. + /// + /// Limits the query to reference only the first N child nodes, using the + /// given OrderBy directive (or priority as default). + /// + /// @param[in] limit Number of children to limit the Query to. + /// + /// @returns A Query in this same location, limited to the specified number of + /// children (taken from the beginning of the sorted list). + Query LimitToFirst(size_t limit); + /// @brief Gets a Query limited to only the last results. + /// + /// @param[in] limit Number of children to limit the Query to. + /// + /// @returns A Query in this same location, limited to the specified number of + /// children (taken from the end of the sorted list). + Query LimitToLast(size_t limit); + + /// @brief Returns true if this query is valid, false if it is not valid. An + /// invalid query could be returned by, say, attempting to OrderBy two + /// different items, or calling OrderByChild() with an empty path, or by + /// constructing a Query with the default constructor. If a Query + /// is invalid, attempting to add more constraints will also result in an + /// invalid Query. + /// + /// @returns true if this query is valid, false if this query is + /// invalid. + virtual bool is_valid() const; + + protected: + /// @cond FIREBASE_APP_INTERNAL + explicit Query(internal::QueryInternal* internal); + void SetInternal(internal::QueryInternal* internal); + void RegisterCleanup(); + void UnregisterCleanup(); + /// @endcond + + private: + /// @cond FIREBASE_APP_INTERNAL + friend bool operator==(const Query& lhs, const Query& rhs); + /// @endcond + + internal::QueryInternal* internal_; +}; + +/// @brief Compares two Query instances. +/// +/// Two Query instances on the same database, in the same location, with the +/// same parameters (OrderBy*, StartAt, EndAt, EqualTo, Limit*) are considered +/// equivalent. +/// +/// Equivalent Queries have a shared pool of ValueListeners and +/// ChildListeners. When listeners are added or removed from one Query +/// instance, it affects all equivalent Query instances. +/// +/// @param[in] lhs The Query to compare against. +/// @param[in] rhs The Query to compare against. +/// +/// @returns True if the Query instances have the same database, the same +/// path, and the same parameters, determined by StartAt(), EndAt(), +/// EqualTo(), and the OrderBy and LimitTo methods. False otherwise. +bool operator==(const Query& lhs, const Query& rhs); + +} // namespace database +} // namespace firebase + +#endif // FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_QUERY_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/database/transaction.h b/packages/firebase_core/firebase_core/firebase_core/firebase/database/transaction.h new file mode 100644 index 000000000000..cb2dd33c59e2 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/database/transaction.h @@ -0,0 +1,102 @@ +// Copyright 2016 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_TRANSACTION_H_ +#define FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_TRANSACTION_H_ + +#include "firebase/database/common.h" +#include "firebase/database/data_snapshot.h" +#include "firebase/database/mutable_data.h" +#include "firebase/internal/common.h" +#include "firebase/variant.h" + +#if defined(FIREBASE_USE_STD_FUNCTION) +#include +#endif // defined(FIREBASE_USE_STD_FUNCTION) + +namespace firebase { +namespace database { + +/// Specifies whether the transaction succeeded or not. +enum TransactionResult { + /// The transaction was successful, the MutableData was updated. + kTransactionResultSuccess, + /// The transaction did not succeed. Any changes to the MutableData + /// will be discarded. + kTransactionResultAbort, +}; + +/// Your own transaction handler, which the Firebase Realtime Database library +/// may call multiple times to apply changes to the data, and should return +/// success or failure depending on whether it succeeds. + +/// @note This version of the callback is no longer supported (unless you are +/// building for Android with stlport). You should use either one of +/// DoTransactionWithContext (a simple function pointer that accepts context +/// data) or DoTransactionFunction (based on std::function). +/// +/// @see DoTransactionWithContext for more information. +typedef TransactionResult (*DoTransaction)(MutableData* data); + +/// Your own transaction handler, which the Firebase Realtime Database library +/// may call multiple times to apply changes to the data, and should return +/// success or failure depending on whether it succeeds. The context you +/// specified to RunTransaction will be passed into this call. +/// +/// This function will be called, _possibly multiple times_, with the current +/// data at this location. The function is responsible for inspecting that data +/// and modifying it as desired, then returning a TransactionResult specifying +/// either that the MutableData was modified to a desired new state, or that the +/// transaction should be aborted. Whenever this function is called, the +/// MutableData passed in must be modified from scratch. +/// +/// Since this function may be called repeatedly for the same transaction, be +/// extremely careful of any side effects that may be triggered by this +/// function. In addition, this function is called from within the Firebase +/// Realtime Database library's run loop, so care is also required when +/// accessing data that may be in use by other threads in your application. +/// +/// Best practices for this function are to ONLY rely on the data passed in. +/// +/// @param[in] data Mutable data, which the callback can edit. +/// @param[in] context Context pointer, passed verbatim to the callback. +/// +/// @returns The callback should return kTransactionResultSuccess if the data +/// was modified, or kTransactionResultAbort if it was unable to modify the +/// data. If the callback returns kTransactionResultAbort, the RunTransaction() +/// call will return the kErrorTransactionAbortedByUser error code. +/// +/// @note If you want a callback to be triggered when the transaction is +/// finished, you can use the Future value returned by the method +/// running the transaction, and call Future::OnCompletion() to register a +/// callback to be called when the transaction either succeeds or fails. +/// +/// @see DoTransaction for more information. +typedef TransactionResult (*DoTransactionWithContext)(MutableData* data, + void* context); + +#if defined(FIREBASE_USE_STD_FUNCTION) || defined(DOXYGEN) +/// Your own transaction handler function or lambda, which the Firebase Realtime +/// Database library may call multiple times to apply changes to the data, and +/// should return success or failure depending on whether it succeeds. +/// +/// @see DoTransactionWithContext for more information. +typedef std::function + DoTransactionFunction; +#endif // defined(FIREBASE_USE_STD_FUNCTION) || defined(DOXYGEN) + +} // namespace database +} // namespace firebase + +#endif // FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_TRANSACTION_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/dynamic_links.h b/packages/firebase_core/firebase_core/firebase_core/firebase/dynamic_links.h new file mode 100644 index 000000000000..7a96de679f62 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/dynamic_links.h @@ -0,0 +1,117 @@ +// Copyright 2017 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef FIREBASE_DYNAMIC_LINKS_SRC_INCLUDE_FIREBASE_DYNAMIC_LINKS_H_ +#define FIREBASE_DYNAMIC_LINKS_SRC_INCLUDE_FIREBASE_DYNAMIC_LINKS_H_ + +#include + +#include "firebase/app.h" +#include "firebase/internal/common.h" + +#if !defined(DOXYGEN) && !defined(SWIG) +FIREBASE_APP_REGISTER_CALLBACKS_REFERENCE(dynamic_links) +#endif // !defined(DOXYGEN) && !defined(SWIG) + +namespace firebase { + +/// @brief Firebase Dynamic Links API. +/// +/// Firebase Dynamic Links is a cross-platform solution for generating and +/// receiving links, whether or not the app is already installed. +namespace dynamic_links { + +#ifndef SWIG +/// @brief Error code used by Futures returned by this API. +enum ErrorCode { + kErrorCodeSuccess = 0, + kErrorCodeFailed, +}; +#endif // SWIG + +/// @brief Enum describing the strength of a dynamic links match. +/// +/// This version is local to dynamic links; there is a similar enum in invites +/// and another internal version in app. +enum LinkMatchStrength { + /// No match has been achieved + kLinkMatchStrengthNoMatch = 0, + + /// The match between the Dynamic Link and device is not perfect. You should + /// not reveal any personal information related to the Dynamic Link. + kLinkMatchStrengthWeakMatch, + + /// The match between the Dynamic Link and this device has a high confidence, + /// but there is a small possibility of error. + kLinkMatchStrengthStrongMatch, + + /// The match between the Dynamic Link and the device is exact. You may + /// safely reveal any personal information related to this Dynamic Link. + kLinkMatchStrengthPerfectMatch +}; + +/// @brief The received Dynamic Link. +struct DynamicLink { + /// The URL that was passed to the app. + std::string url; + /// The match strength of the dynamic link. + LinkMatchStrength match_strength; +}; + +/// @brief Base class used to receive Dynamic Links. +class Listener { + public: + virtual ~Listener(); + + /// Called on the client when a dynamic link arrives. + /// + /// @param[in] dynamic_link The data describing the Dynamic Link. + virtual void OnDynamicLinkReceived(const DynamicLink* dynamic_link) = 0; +}; + +/// @brief Initialize Firebase Dynamic Links. +/// +/// After Initialize is called, the implementation may call functions on the +/// Listener provided at any time. +/// +/// @param[in] app The Firebase App object for this application. +/// @param[in] listener A Listener object that receives Dynamic Links. +/// +/// @return kInitResultSuccess if initialization succeeded, or +/// kInitResultFailedMissingDependency on Android if Google Play services is +/// not available on the current device. +InitResult Initialize(const App& app, Listener* listener); + +/// @brief Terminate Firebase Dynamic Links. +void Terminate(); + +/// @brief Set the listener for receiving Dynamic Links. +/// +/// @param[in] listener A Listener object that receives Dynamic Links. +/// +/// @return Pointer to the previously set listener. +Listener* SetListener(Listener* listener); + +/// Fetch any pending dynamic links. Each pending link will trigger a call to +/// the registered Listener class. +/// +/// This function is implicitly called on initialization. On iOS this is called +/// automatically when the app gains focus, but on Android this needs to be +/// called manually. +void Fetch(); + +} // namespace dynamic_links +} // namespace firebase + +#endif // FIREBASE_DYNAMIC_LINKS_SRC_INCLUDE_FIREBASE_DYNAMIC_LINKS_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/dynamic_links/components.h b/packages/firebase_core/firebase_core/firebase_core/firebase/dynamic_links/components.h new file mode 100644 index 000000000000..7a8e8fa1a44b --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/dynamic_links/components.h @@ -0,0 +1,336 @@ +// Copyright 2017 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef FIREBASE_DYNAMIC_LINKS_SRC_INCLUDE_FIREBASE_DYNAMIC_LINKS_COMPONENTS_H_ +#define FIREBASE_DYNAMIC_LINKS_SRC_INCLUDE_FIREBASE_DYNAMIC_LINKS_COMPONENTS_H_ + +#include +#include +#include + +#include "firebase/future.h" + +namespace firebase { + +namespace dynamic_links { + +/// @brief Google Analytics Parameters. +/// +/// Note that the strings used by the struct are not copied, as so must +/// either be statically allocated, or must persist in memory until the +/// DynamicLinkComponents that uses them goes out of scope. +struct GoogleAnalyticsParameters { + /// Constructs an empty set of Google Analytics parameters. + GoogleAnalyticsParameters() + : source(nullptr), + medium(nullptr), + campaign(nullptr), + term(nullptr), + content(nullptr) {} + + /// The campaign source; used to identify a search engine, newsletter, + /// or other source. + const char* source; + /// The campaign medium; used to identify a medium such as email or + /// cost-per-click (cpc). + const char* medium; + /// The campaign name; The individual campaign name, slogan, promo code, etc. + /// for a product. + const char* campaign; + /// The campaign term; used with paid search to supply the keywords for ads. + const char* term; + /// The campaign content; used for A/B testing and content-targeted ads to + /// differentiate ads or links that point to the same URL. + const char* content; +}; + +/// @brief iOS Parameters. +/// +/// Note that the strings used by the struct are not copied, as so must +/// either be statically allocated, or must persist in memory until the +/// DynamicLinkComponents that uses them goes out of scope. +struct IOSParameters { + /// Constructs a set of IOS parameters with the given bundle id. + /// + /// @param bundle_id_ The parameters ID of the iOS app to use to open the + /// link. + IOSParameters(const char* bundle_id_) + : bundle_id(bundle_id_), + fallback_url(nullptr), + custom_scheme(nullptr), + ipad_fallback_url(nullptr), + ipad_bundle_id(nullptr), + app_store_id(nullptr), + minimum_version(nullptr) {} + + /// Constructs an empty set of IOS parameters. + IOSParameters() + : bundle_id(nullptr), + fallback_url(nullptr), + custom_scheme(nullptr), + ipad_fallback_url(nullptr), + ipad_bundle_id(nullptr), + app_store_id(nullptr), + minimum_version(nullptr) {} + + /// The parameters ID of the iOS app to use to open the link. The app must be + /// connected to your project from the Overview page of the Firebase console. + /// Note this field is required. + const char* bundle_id; + /// The link to open on iOS if the app is not installed. + /// + /// Specify this to do something other than install your app from the + /// App Store when the app isn't installed, such as open the mobile + /// web version of the content, or display a promotional page for your app. + const char* fallback_url; + /// The app's custom URL scheme, if defined to be something other than your + /// app's parameters ID. + const char* custom_scheme; + /// The link to open on iPad if the app is not installed. + /// + /// Overrides fallback_url when on iPad. + const char* ipad_fallback_url; + /// The iPad parameters ID of the app. + const char* ipad_bundle_id; + /// The App Store ID, used to send users to the App Store when the app isn't + /// installed. + const char* app_store_id; + /// The minimum version of your app that can open the link. + const char* minimum_version; +}; + +/// @brief iTunes Connect App Analytics Parameters. +/// +/// Note that the strings used by the struct are not copied, as so must +/// either be statically allocated, or must persist in memory until the +/// DynamicLinkComponents that uses them goes out of scope. +struct ITunesConnectAnalyticsParameters { + /// Constructs an empty set of ITunes Connect Analytics parameters. + ITunesConnectAnalyticsParameters() + : provider_token(nullptr), + affiliate_token(nullptr), + campaign_token(nullptr) {} + + /// The provider token that enables analytics for Dynamic Links from + /// within iTunes Connect. + const char* provider_token; + /// The affiliate token used to create affiliate-coded links. + const char* affiliate_token; + /// The campaign token that developers can add to any link in order to + /// track sales from a specific marketing campaign. + const char* campaign_token; +}; + +/// @brief Android Parameters. +/// +/// Note that the strings used by the struct are not copied, as so must +/// either be statically allocated, or must persist in memory until the +/// DynamicLinkComponents that uses them goes out of scope. +struct AndroidParameters { + /// Constructs a set of Android parameters with the given package name. + /// + /// The package name of the Android app to use to open the link. + AndroidParameters(const char* package_name_) + : package_name(package_name_), + fallback_url(nullptr), + minimum_version(0) {} + + /// Constructs an empty set of Android parameters. + AndroidParameters() + : package_name(nullptr), fallback_url(nullptr), minimum_version(0) {} + + /// The package name of the Android app to use to open the link. The app + /// must be connected to your project from the Overview page of the Firebase + /// console. + /// Note this field is required. + const char* package_name; + /// The link to open when the app isn't installed. + /// + /// Specify this to do something other than install your app from the + /// Play Store when the app isn't installed, such as open the mobile web + /// version of the content, or display a promotional page for your app. + const char* fallback_url; + /// The versionCode of the minimum version of your app that can open the link. + int minimum_version; +}; + +/// @brief Social meta-tag Parameters. +/// +/// Note that the strings used by the struct are not copied, as so must +/// either be statically allocated, or must persist in memory until the +/// DynamicLinkComponents that uses them goes out of scope. +struct SocialMetaTagParameters { + /// Constructs an empty set of Social meta-tag parameters. + SocialMetaTagParameters() + : title(nullptr), description(nullptr), image_url(nullptr) {} + + /// The title to use when the Dynamic Link is shared in a social post. + const char* title; + /// The description to use when the Dynamic Link is shared in a social post. + const char* description; + /// The URL to an image related to this link. + const char* image_url; +}; + +/// @brief The desired path length for shortened Dynamic Link URLs. +enum PathLength { + /// Uses the server-default for the path length. + /// See https://goo.gl/8yDAqC for more information. + kPathLengthDefault = 0, + /// Typical short link for non-sensitive links. + kPathLengthShort, + /// Short link that uses a very long path to make it more difficult to + /// guess. Useful for sensitive links. + kPathLengthUnguessable, +}; + +/// @brief Additional options for Dynamic Link creation. +struct DynamicLinkOptions { + /// Constructs an empty set of Dynamic Link options. + DynamicLinkOptions() : path_length(kPathLengthDefault) {} + + /// The desired path length for shortened Dynamic Link URLs. + PathLength path_length; +}; + +/// @brief The returned value from creating a Dynamic Link. +struct GeneratedDynamicLink { + /// The Dynamic Link value. + std::string url; + /// Information about potential warnings on link creation. + /// + /// Usually presence of warnings means parameter format errors, parameter + /// value errors, or missing parameters. + std::vector warnings; + /// If non-empty, the cause of the Dynamic Link generation failure. + std::string error; +}; + +/// @brief The information needed to generate a Dynamic Link. +/// +/// Note that the strings used by the struct are not copied, as so must +/// either be statically allocated, or must persist in memory until this +/// struct goes out of scope. +struct DynamicLinkComponents { + /// The link your app will open. + /// You can specify any URL your app can handle, such as a link to your + /// app's content, or a URL that initiates some + /// app-specific logic such as crediting the user with a coupon, or + /// displaying a specific welcome screen. This link must be a well-formatted + /// URL, be properly URL-encoded, and use the HTTP or HTTPS scheme. + /// Note, this field is required. + const char* link; + /// The domain (of the form "https://xyz.app.goo.gl") to use for this Dynamic + /// Link. You can find this value in the Dynamic Links section of the Firebase + /// console. + /// + /// If you have set up custom domains on your project, set this to your + /// project's custom domain as listed in the Firebase console. + /// + /// Only https:// links are supported. + /// + /// Note, this field is required. + const char* domain_uri_prefix; + /// The Google Analytics parameters. + GoogleAnalyticsParameters* google_analytics_parameters; + /// The iOS parameters. + IOSParameters* ios_parameters; + /// The iTunes Connect App Analytics parameters. + ITunesConnectAnalyticsParameters* itunes_connect_analytics_parameters; + /// The Android parameters. + AndroidParameters* android_parameters; + /// The social meta-tag parameters. + SocialMetaTagParameters* social_meta_tag_parameters; + + /// Default constructor, initializes all fields to null. + DynamicLinkComponents() + : link(nullptr), + domain_uri_prefix(nullptr), + google_analytics_parameters(nullptr), + ios_parameters(nullptr), + itunes_connect_analytics_parameters(nullptr), + android_parameters(nullptr), + social_meta_tag_parameters(nullptr) {} + + /// Constructor that initializes with the given link and domain. + /// + /// @param link_ The link your app will open. + /// @param domain_uri_prefix_ The domain (of the form + /// "https://xyz.app.goo.gl") to use for this Dynamic Link. You can find this + /// value in the Dynamic Links section of the Firebase console. If you have + /// set up custom domains on your project, set this to your project's custom + /// domain as listed in the Firebase console. Note: If you do not specify + /// "https://" as the URI scheme, it will be added. + DynamicLinkComponents(const char* link_, const char* domain_uri_prefix_) + : link(link_), + domain_uri_prefix(domain_uri_prefix_), + google_analytics_parameters(nullptr), + ios_parameters(nullptr), + itunes_connect_analytics_parameters(nullptr), + android_parameters(nullptr), + social_meta_tag_parameters(nullptr) { + // For backwards compatibility with dynamic_link_domain, if + // domain_uri_prefix doesn't start with "https://", add it. + static const char kHttpsPrefix[] = "https://"; + static const size_t kHttpsPrefixLength = sizeof(kHttpsPrefix) - 1; + if (strncmp(domain_uri_prefix, kHttpsPrefix, kHttpsPrefixLength) != 0) { + domain_uri_prefix_with_scheme = + std::string(kHttpsPrefix) + domain_uri_prefix; + domain_uri_prefix = domain_uri_prefix_with_scheme.c_str(); + } + } + +#ifndef INTERNAL_EXPERIMENTAL + + private: +#endif // INTERNAL_EXPERIMENTAL + std::string domain_uri_prefix_with_scheme; +}; + +/// Creates a long Dynamic Link from the given parameters. +GeneratedDynamicLink GetLongLink(const DynamicLinkComponents& components); + +/// Creates a shortened Dynamic Link from the given parameters. +/// @param components: Settings used to configure the behavior for the link. +Future GetShortLink( + const DynamicLinkComponents& components); + +/// Creates a shortened Dynamic Link from the given parameters. +/// @param components: Settings used to configure the behavior for the link. +/// @param options: Additional options for Dynamic Link shortening, indicating +/// whether or not to produce an unguessable or shortest possible link. +/// No references to the options object will be retained after the call. +Future GetShortLink( + const DynamicLinkComponents& components, const DynamicLinkOptions& options); + +/// Creates a shortened Dynamic Link from a given long Dynamic Link. +/// @param long_dynamic_link A link previously generated from GetLongLink. +Future GetShortLink(const char* long_dynamic_link); + +/// Creates a shortened Dynamic Link from a given long Dynamic Link. +/// @param long_dynamic_link: A link previously generated from GetLongLink. +/// @param options: Additional options for Dynamic Link shortening, indicating +/// whether or not to produce an unguessable or shortest possible link. +/// No references to the options object will be retained after the call. +Future GetShortLink(const char* long_dynamic_link, + const DynamicLinkOptions& options); + +/// Get the (possibly still pending) results of the most recent GetShortUrl +/// call. +Future GetShortLinkLastResult(); + +} // namespace dynamic_links +} // namespace firebase + +#endif // FIREBASE_DYNAMIC_LINKS_SRC_INCLUDE_FIREBASE_DYNAMIC_LINKS_COMPONENTS_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore.h new file mode 100644 index 000000000000..c35de11b4d1a --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore.h @@ -0,0 +1,458 @@ +/* + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_H_ +#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_H_ + +#include +#include + +#include "firebase/internal/common.h" + +#include "firebase/app.h" +#include "firebase/future.h" +#include "firebase/log.h" +// Include *all* the public headers to make sure including just "firestore.h" is +// sufficient for users. +#include "firebase/firestore/collection_reference.h" +#include "firebase/firestore/document_change.h" +#include "firebase/firestore/document_reference.h" +#include "firebase/firestore/document_snapshot.h" +#include "firebase/firestore/field_path.h" +#include "firebase/firestore/field_value.h" +#include "firebase/firestore/firestore_errors.h" +#include "firebase/firestore/geo_point.h" +#include "firebase/firestore/listener_registration.h" +#include "firebase/firestore/load_bundle_task_progress.h" +#include "firebase/firestore/map_field_value.h" +#include "firebase/firestore/metadata_changes.h" +#include "firebase/firestore/query.h" +#include "firebase/firestore/query_snapshot.h" +#include "firebase/firestore/set_options.h" +#include "firebase/firestore/settings.h" +#include "firebase/firestore/snapshot_metadata.h" +#include "firebase/firestore/source.h" +#include "firebase/firestore/timestamp.h" +#include "firebase/firestore/transaction.h" +#include "firebase/firestore/transaction_options.h" +#include "firebase/firestore/write_batch.h" + +namespace firebase { +/** + * @brief Cloud Firestore API. + * + * Cloud Firestore is a flexible, scalable database for mobile, web, and server + * development from Firebase and Google Cloud Platform. + */ +namespace firestore { + +class FirestoreInternal; + +namespace csharp { + +class ApiHeaders; +class TransactionManager; + +} // namespace csharp + +/** + * @brief Entry point for the Firebase Firestore C++ SDK. + * + * To use the SDK, call firebase::firestore::Firestore::GetInstance() to obtain + * an instance of Firestore, then use Collection() or Document() to obtain + * references to child paths within the database. From there, you can set data + * via CollectionReference::Add() and DocumentReference::Set(), or get data via + * CollectionReference::Get() and DocumentReference::Get(), attach listeners, + * and more. + * + * @note Firestore classes are not meant to be subclassed except for use in test + * mocks. Subclassing is not supported in production code and new SDK releases + * may break code that does so. + */ +class Firestore { + public: + /** + * @brief Returns an instance of Firestore corresponding to the given App. + * + * Firebase Firestore uses firebase::App to communicate with Firebase + * Authentication to authenticate users to the Firestore server backend. + * + * If you call GetInstance() multiple times with the same App, you will get + * the same instance of Firestore. + * + * @param[in] app Your instance of firebase::App. Firebase Firestore will use + * this to communicate with Firebase Authentication. + * @param[out] init_result_out If provided, the initialization result will be + * written here. Will be set to firebase::kInitResultSuccess if initialization + * succeeded, or firebase::kInitResultFailedMissingDependency on Android if + * Google Play services is not available on the current device. + * + * @return An instance of Firestore corresponding to the given App. + */ + static Firestore* GetInstance(::firebase::App* app, + InitResult* init_result_out = nullptr); + + /** + * @brief Returns an instance of Firestore corresponding to the default App. + * + * Firebase Firestore uses the default App to communicate with Firebase + * Authentication to authenticate users to the Firestore server backend. + * + * If you call GetInstance() multiple times, you will get the same instance. + * + * @param[out] init_result_out If provided, the initialization result will be + * written here. Will be set to firebase::kInitResultSuccess if initialization + * succeeded, or firebase::kInitResultFailedMissingDependency on Android if + * Google Play services is not available on the current device. + * + * @return An instance of Firestore corresponding to the default App. + */ + static Firestore* GetInstance(InitResult* init_result_out = nullptr); + + /** + * @brief Destructor for the Firestore object. + * + * When deleted, this instance will be removed from the cache of Firestore + * objects. If you call GetInstance() in the future with the same App, a new + * Firestore instance will be created. + */ + virtual ~Firestore(); + + /** + * Deleted copy constructor; Firestore must be created with + * Firestore::GetInstance(). + */ + Firestore(const Firestore& src) = delete; + + /** + * Deleted copy assignment operator; Firestore must be created with + * Firestore::GetInstance(). + */ + Firestore& operator=(const Firestore& src) = delete; + + /** + * @brief Returns the firebase::App that this Firestore was created with. + * + * @return The firebase::App this Firestore was created with. + */ + virtual const App* app() const; + + /** + * @brief Returns the firebase::App that this Firestore was created with. + * + * @return The firebase::App this Firestore was created with. + */ + virtual App* app(); + + /** + * @brief Returns a CollectionReference instance that refers to the + * collection at the specified path within the database. + * + * @param[in] collection_path A slash-separated path to a collection. + * + * @return The CollectionReference instance. + */ + virtual CollectionReference Collection(const char* collection_path) const; + + /** + * @brief Returns a CollectionReference instance that refers to the + * collection at the specified path within the database. + * + * @param[in] collection_path A slash-separated path to a collection. + * + * @return The CollectionReference instance. + */ + virtual CollectionReference Collection( + const std::string& collection_path) const; + + /** + * @brief Returns a DocumentReference instance that refers to the document at + * the specified path within the database. + * + * @param[in] document_path A slash-separated path to a document. + * @return The DocumentReference instance. + */ + virtual DocumentReference Document(const char* document_path) const; + + /** + * @brief Returns a DocumentReference instance that refers to the document at + * the specified path within the database. + * + * @param[in] document_path A slash-separated path to a document. + * + * @return The DocumentReference instance. + */ + virtual DocumentReference Document(const std::string& document_path) const; + + /** + * @brief Returns a Query instance that includes all documents in the + * database that are contained in a collection or subcollection with the + * given collection_id. + * + * @param[in] collection_id Identifies the collections to query over. Every + * collection or subcollection with this ID as the last segment of its path + * will be included. Cannot contain a slash. + * + * @return The Query instance. + */ + virtual Query CollectionGroup(const char* collection_id) const; + + /** + * @brief Returns a Query instance that includes all documents in the + * database that are contained in a collection or subcollection with the + * given collection_id. + * + * @param[in] collection_id Identifies the collections to query over. Every + * collection or subcollection with this ID as the last segment of its path + * will be included. Cannot contain a slash. + * + * @return The Query instance. + */ + virtual Query CollectionGroup(const std::string& collection_id) const; + + /** Returns the settings used by this Firestore object. */ + virtual Settings settings() const; + + /** Sets any custom settings used to configure this Firestore object. */ + virtual void set_settings(Settings settings); + + /** + * Creates a write batch, used for performing multiple writes as a single + * atomic operation. + * + * Unlike transactions, write batches are persisted offline and therefore are + * preferable when you don't need to condition your writes on read data. + * + * @return The created WriteBatch object. + */ + virtual WriteBatch batch() const; + + /** + * Executes the given update and then attempts to commit the changes applied + * within the transaction. If any document read within the transaction has + * changed, the update function will be retried. If it fails to commit after + * 5 attempts, the transaction will fail. + * + * @param update function or lambda to execute within the transaction context. + * The string reference parameter can be used to set the error message. + * + * @return A Future that will be resolved when the transaction finishes. + */ + virtual Future RunTransaction( + std::function update); + + /** + * Executes the given update and then attempts to commit the changes applied + * within the transaction. If any document read within the transaction has + * changed, the update function will be retried. If it fails to commit after + * the `max_attempts` specified in the given `TransactionOptions`, the + * transaction will fail. + * + * @param options The transaction options for controlling execution. + * @param update function or lambda to execute within the transaction context. + * The string reference parameter can be used to set the error message. + * + * @return A Future that will be resolved when the transaction finishes. + */ + virtual Future RunTransaction( + TransactionOptions options, + std::function update); + + /** + * Sets the log verbosity of all Firestore instances. + * + * The default verbosity level is `kLogLevelInfo`. + * + * @param[in] log_level The desired verbosity. + */ + static void set_log_level(LogLevel log_level); + + /** + * Disables network access for this instance. While the network is disabled, + * any snapshot listeners or Get() calls will return results from cache, and + * any write operations will be queued until network usage is re-enabled via a + * call to EnableNetwork(). + * + * If the network was already disabled, calling `DisableNetwork()` again is + * a no-op. + */ + virtual Future DisableNetwork(); + + /** + * Re-enables network usage for this instance after a prior call to + * DisableNetwork(). + * + * If the network is currently enabled, calling `EnableNetwork()` is a no-op. + */ + virtual Future EnableNetwork(); + + /** + * Terminates this `Firestore` instance. + * + * After calling `Terminate()`, only the `ClearPersistence()` method may be + * used. Calling any other methods will result in an error. + * + * To restart after termination, simply create a new instance of `Firestore` + * with `Firestore::GetInstance()`. + * + * `Terminate()` does not cancel any pending writes and any tasks that are + * awaiting a response from the server will not be resolved. The next time you + * start this instance, it will resume attempting to send these writes to the + * server. + * + * Note: under normal circumstances, calling `Terminate()` is not required. + * This method is useful only when you want to force this instance to release + * all of its resources or in combination with `ClearPersistence()` to ensure + * that all local state is destroyed between test runs. + * + * @return A `Future` that is resolved when the instance has been successfully + * terminated. + */ + virtual Future Terminate(); + + /** + * Waits until all currently pending writes for the active user have been + * acknowledged by the backend. + * + * The returned future is resolved immediately without error if there are no + * outstanding writes. Otherwise, the future is resolved when all previously + * issued writes (including those written in a previous app session) have been + * acknowledged by the backend. The future does not wait for writes that were + * added after the method is called. If you wish to wait for additional + * writes, you have to call `WaitForPendingWrites` again. + * + * Any outstanding `WaitForPendingWrites` futures are resolved with an + * error during user change. + */ + virtual Future WaitForPendingWrites(); + + /** + * Clears the persistent storage. This includes pending writes and cached + * documents. + * + * Must be called while the Firestore instance is not started (after the app + * is shut down or when the app is first initialized). On startup, this method + * must be called before other methods (other than `settings()` and + * `set_settings()`). If the Firestore instance is still running, the function + * will complete with an error code of `FailedPrecondition`. + * + * Note: `ClearPersistence()` is primarily intended to help write + * reliable tests that use Firestore. It uses the most efficient mechanism + * possible for dropping existing data but does not attempt to securely + * overwrite or otherwise make cached data unrecoverable. For applications + * that are sensitive to the disclosure of cache data in between user sessions + * we strongly recommend not to enable persistence in the first place. + */ + virtual Future ClearPersistence(); + + /** + * Attaches a listener for a snapshots-in-sync event. Server-generated + * updates and local changes can affect multiple snapshot listeners. + * The snapshots-in-sync event indicates that all listeners affected by + * a given change have fired. + * + * NOTE: The snapshots-in-sync event only indicates that listeners are + * in sync with each other, but does not relate to whether those + * snapshots are in sync with the server. Use `SnapshotMetadata` in the + * individual listeners to determine if a snapshot is from the cache or + * the server. + * + * @param callback A callback to be called every time all snapshot + * listeners are in sync with each other. + * @return A `ListenerRegistration` object that can be used to remove the + * listener. + */ + virtual ListenerRegistration AddSnapshotsInSyncListener( + std::function callback); + + /** + * Loads a Firestore bundle into the local cache. + * + * @param bundle A string containing the bundle to be loaded. + * @return A `Future` that is resolved when the loading is either completed + * or aborted due to an error. + */ + virtual Future LoadBundle(const std::string& bundle); + + /** + * Loads a Firestore bundle into the local cache, with the provided callback + * executed for progress updates. + * + * @param bundle A string containing the bundle to be loaded. + * @param progress_callback A callback that is called with progress + * updates, and completion or error updates. + * @return A `Future` that is resolved when the loading is either completed + * or aborted due to an error. + */ + virtual Future LoadBundle( + const std::string& bundle, + std::function progress_callback); + + /** + * Reads a Firestore `Query` from the local cache, identified by the given + * name. + * + * Named queries are packaged into bundles on the server side (along with the + * resulting documents) and loaded into local cache using `LoadBundle`. Once + * in the local cache, you can use this method to extract a query by name. + * + * If a query cannot be found, the returned future will complete with its + * `error()` set to a non-zero error code. + * + * @param query_name The name of the query to read from saved bundles. + */ + virtual Future NamedQuery(const std::string& query_name); + + protected: + /** + * Default constructor, to be used only for mocking `Firestore`. + */ + Firestore() = default; + + private: + friend class FieldValueInternal; + friend class FirestoreInternal; + friend class Wrapper; + friend struct ConverterImpl; + friend class FirestoreIntegrationTest; + friend class IncludesTest; + template + friend struct CleanupFn; + + friend class csharp::ApiHeaders; + friend class csharp::TransactionManager; + + explicit Firestore(::firebase::App* app); + explicit Firestore(FirestoreInternal* internal); + + static Firestore* CreateFirestore(::firebase::App* app, + FirestoreInternal* internal, + InitResult* init_result_out); + static Firestore* AddFirestoreToCache(Firestore* firestore, + InitResult* init_result_out); + + static void SetClientLanguage(const std::string& language_token); + + // Delete the internal_ data. + void DeleteInternal(); + + mutable FirestoreInternal* internal_ = nullptr; +}; + +} // namespace firestore +} // namespace firebase + +#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/collection_reference.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/collection_reference.h new file mode 100644 index 000000000000..3d9d4de2ee7f --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/collection_reference.h @@ -0,0 +1,183 @@ +/* + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_COLLECTION_REFERENCE_H_ +#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_COLLECTION_REFERENCE_H_ + +#include + +#include "firebase/firestore/map_field_value.h" +#include "firebase/firestore/query.h" + +namespace firebase { + +/// @cond FIREBASE_APP_INTERNAL +template +class Future; +/// @endcond + +namespace firestore { + +class CollectionReferenceInternal; +class DocumentReference; + +/** + * @brief A CollectionReference can be used for adding documents, getting + * document references, and querying for documents (using the methods inherited + * from `Query`). + * + * @note Firestore classes are not meant to be subclassed except for use in test + * mocks. Subclassing is not supported in production code and new SDK releases + * may break code that does so. + */ +class CollectionReference : public Query { + public: + /** + * @brief Creates an invalid CollectionReference that has to be reassigned + * before it can be used. + * + * Calling any member function on an invalid CollectionReference will be + * a no-op. If the function returns a value, it will return a zero, empty, or + * invalid value, depending on the type of the value. + */ + CollectionReference(); + + /** + * @brief Copy constructor. + * + * `CollectionReference` can be efficiently copied because it simply refers to + * a location in the database. + * + * @param[in] other `CollectionReference` to copy from. + */ + CollectionReference(const CollectionReference& other); + + /** + * @brief Move constructor. + * + * Moving is more efficient than copying for a `CollectionReference`. After + * being moved from, a `CollectionReference` is equivalent to its + * default-constructed state. + * + * @param[in] other `CollectionReference` to move data from. + */ + CollectionReference(CollectionReference&& other); + + /** + * @brief Copy assignment operator. + * + * `CollectionReference` can be efficiently copied because it simply refers to + * a location in the database. + * + * @param[in] other `CollectionReference` to copy from. + * + * @return Reference to the destination `CollectionReference`. + */ + CollectionReference& operator=(const CollectionReference& other); + + /** + * @brief Move assignment operator. + * + * Moving is more efficient than copying for a `CollectionReference`. After + * being moved from, a `CollectionReference` is equivalent to its + * default-constructed state. + * + * @param[in] other `CollectionReference` to move data from. + * + * @return Reference to the destination `CollectionReference`. + */ + CollectionReference& operator=(CollectionReference&& other); + + /** + * @brief Gets the ID of the referenced collection. + * + * @return The ID as a std::string. + */ + virtual const std::string& id() const; + + /** + * @brief Returns the path of this collection (relative to the root of the + * database) as a slash-separated string. + * + * @return The path as a std::string. + */ + virtual std::string path() const; + + /** + * @brief Gets a DocumentReference to the document that contains this + * collection. + * + * @return The DocumentReference that contains this collection if this is a + * subcollection. If this is a root collection, returns an invalid + * DocumentReference (`DocumentReference::is_valid()` will return false). + */ + virtual DocumentReference Parent() const; + + /** + * @brief Returns a DocumentReference that points to a new document with an + * auto-generated ID within this collection. + * + * @return A DocumentReference pointing to the new document. + */ + virtual DocumentReference Document() const; + + /** + * @brief Gets a DocumentReference instance that refers to the document at the + * specified path within this collection. + * + * @param[in] document_path A slash-separated relative path to a document. + * The pointer only needs to be valid during this call. + * + * @return The DocumentReference instance. + */ + virtual DocumentReference Document(const char* document_path) const; + + /** + * @brief Gets a DocumentReference instance that refers to the document at the + * specified path within this collection. + * + * @param[in] document_path A slash-separated relative path to a document. + * + * @return The DocumentReference instance. + */ + virtual DocumentReference Document(const std::string& document_path) const; + + /** + * @brief Adds a new document to this collection with the specified data, + * assigning it a document ID automatically. + * + * @param data A map containing the data for the new document. + * + * @return A Future that will be resolved with the DocumentReference of the + * newly created document. + */ + virtual Future Add(const MapFieldValue& data); + + private: + friend class DocumentReference; + friend class DocumentReferenceInternal; + friend class FirestoreInternal; + friend struct ConverterImpl; + + explicit CollectionReference(CollectionReferenceInternal* internal); + + CollectionReferenceInternal* internal() const; +}; + +} // namespace firestore +} // namespace firebase + +#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_COLLECTION_REFERENCE_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/document_change.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/document_change.h new file mode 100644 index 000000000000..fbef011d290f --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/document_change.h @@ -0,0 +1,203 @@ +/* + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_DOCUMENT_CHANGE_H_ +#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_DOCUMENT_CHANGE_H_ + +#include + +namespace firebase { +namespace firestore { + +class DocumentChangeInternal; +class DocumentSnapshot; + +/** + * @brief A DocumentChange represents a change to the documents matching + * a query. + * + * DocumentChange contains the document affected and the type of change that + * occurred (added, modified, or removed). + * + * @note Firestore classes are not meant to be subclassed except for use in test + * mocks. Subclassing is not supported in production code and new SDK releases + * may break code that does so. + */ +class DocumentChange { + public: + /** + * An enumeration of snapshot diff types. + */ + enum class Type { + /** + * Indicates a new document was added to the set of documents matching the + * query. + */ + kAdded, + + /** + * Indicates a document within the query was modified. + */ + kModified, + + /** + * Indicates a document within the query was removed (either deleted or no + * longer matches the query). + */ + kRemoved, + }; + + /** + * The sentinel index used as a return value to indicate no matches. + */ +#if defined(ANDROID) + // Older NDK (r16b) fails to define this properly. Fix this when support for + // the older NDK is removed. + static const std::size_t npos; +#else + static constexpr std::size_t npos = static_cast(-1); +#endif // defined(ANDROID) + + /** + * @brief Creates an invalid DocumentChange that has to be reassigned before + * it can be used. + * + * Calling any member function on an invalid DocumentChange will be a no-op. + * If the function returns a value, it will return a zero, empty, or invalid + * value, depending on the type of the value. + */ + DocumentChange(); + + /** + * @brief Copy constructor. + * + * `DocumentChange` is immutable and can be efficiently copied (no deep copy + * is performed). + * + * @param[in] other `DocumentChange` to copy from. + */ + DocumentChange(const DocumentChange& other); + + /** + * @brief Move constructor. + * + * Moving is more efficient than copying for a `DocumentChange`. After being + * moved from, a `DocumentChange` is equivalent to its default-constructed + * state. + * + * @param[in] other `DocumentChange` to move data from. + */ + DocumentChange(DocumentChange&& other); + + virtual ~DocumentChange(); + + /** + * @brief Copy assignment operator. + * + * `DocumentChange` is immutable and can be efficiently copied (no deep copy + * is performed). + * + * @param[in] other `DocumentChange` to copy from. + * + * @return Reference to the destination `DocumentChange`. + */ + DocumentChange& operator=(const DocumentChange& other); + + /** + * @brief Move assignment operator. + * + * Moving is more efficient than copying for a `DocumentChange`. After being + * moved from, a `DocumentChange` is equivalent to its default-constructed + * state. + * + * @param[in] other `DocumentChange` to move data from. + * + * @return Reference to the destination `DocumentChange`. + */ + DocumentChange& operator=(DocumentChange&& other); + + /** + * Returns the type of change that occurred (added, modified, or removed). + */ + virtual Type type() const; + + /** + * @brief The document affected by this change. + * + * Returns the newly added or modified document if this DocumentChange is for + * an updated document. Returns the deleted document if this document change + * represents a removal. + */ + virtual DocumentSnapshot document() const; + + /** + * The index of the changed document in the result set immediately prior to + * this DocumentChange (that is, supposing that all prior DocumentChange + * objects have been applied). Returns DocumentChange::npos for 'added' + * events. + */ + virtual std::size_t old_index() const; + + /** + * The index of the changed document in the result set immediately after this + * DocumentChange (that is, supposing that all prior DocumentChange objects + * and the current DocumentChange object have been applied). Returns + * DocumentChange::npos for 'removed' events. + */ + virtual std::size_t new_index() const; + + /** + * @brief Returns true if this `DocumentChange` is valid, false if it is + * not valid. An invalid `DocumentChange` could be the result of: + * - Creating a `DocumentChange` using the default constructor. + * - Moving from the `DocumentChange`. + * - Deleting your Firestore instance, which will invalidate all the + * `DocumentChange` instances associated with it. + * + * @return true if this `DocumentChange` is valid, false if this + * `DocumentChange` is invalid. + */ + bool is_valid() const { return internal_ != nullptr; } + + private: + std::size_t Hash() const; + + friend bool operator==(const DocumentChange& lhs, const DocumentChange& rhs); + friend std::size_t DocumentChangeHash(const DocumentChange& change); + + friend class FirestoreInternal; + friend class Wrapper; + friend struct ConverterImpl; + template + friend struct CleanupFn; + + explicit DocumentChange(DocumentChangeInternal* internal); + + mutable DocumentChangeInternal* internal_ = nullptr; +}; + +/** Checks `lhs` and `rhs` for equality. */ +bool operator==(const DocumentChange& lhs, const DocumentChange& rhs); + +/** Checks `lhs` and `rhs` for inequality. */ +inline bool operator!=(const DocumentChange& lhs, const DocumentChange& rhs) { + return !(lhs == rhs); +} + +} // namespace firestore +} // namespace firebase + +#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_DOCUMENT_CHANGE_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/document_reference.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/document_reference.h new file mode 100644 index 000000000000..d0f82cf42d73 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/document_reference.h @@ -0,0 +1,351 @@ +/* + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_DOCUMENT_REFERENCE_H_ +#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_DOCUMENT_REFERENCE_H_ + +#include +#include +#include + +#include "firebase/internal/common.h" + +#include "firebase/firestore/firestore_errors.h" +#include "firebase/firestore/map_field_value.h" +#include "firebase/firestore/metadata_changes.h" +#include "firebase/firestore/set_options.h" +#include "firebase/firestore/source.h" + +namespace firebase { + +/// @cond FIREBASE_APP_INTERNAL +template +class Future; +/// @endcond + +namespace firestore { + +class CollectionReference; +class DocumentReferenceInternal; +class DocumentSnapshot; +template +class EventListener; +class Firestore; +class ListenerRegistration; + +/** + * @brief A DocumentReference refers to a document location in a Firestore + * database and can be used to write, read, or listen to the location. + * + * There may or may not exist a document at the referenced location. + * A DocumentReference can also be used to create a CollectionReference to + * a subcollection. + * + * Create a DocumentReference via `Firestore::Document(const std::string& + * path)`. + * + * @note Firestore classes are not meant to be subclassed except for use in test + * mocks. Subclassing is not supported in production code and new SDK releases + * may break code that does so. + */ +class DocumentReference { + public: + /** + * @brief Creates an invalid DocumentReference that has to be reassigned + * before it can be used. + * + * Calling any member function on an invalid DocumentReference will be + * a no-op. If the function returns a value, it will return a zero, empty, or + * invalid value, depending on the type of the value. + */ + DocumentReference(); + + /** + * @brief Copy constructor. + * + * `DocumentReference` can be efficiently copied because it simply refers to + * a location in the database. + * + * @param[in] other `DocumentReference` to copy from. + */ + DocumentReference(const DocumentReference& other); + + /** + * @brief Move constructor. + * + * Moving is more efficient than copying for a `DocumentReference`. After + * being moved from, a `DocumentReference` is equivalent to its + * default-constructed state. + * + * @param[in] other `DocumentReference` to move data from. + */ + DocumentReference(DocumentReference&& other); + + virtual ~DocumentReference(); + + /** + * @brief Copy assignment operator. + * + * `DocumentReference` can be efficiently copied because it simply refers to + * a location in the database. + * + * @param[in] other `DocumentReference` to copy from. + * + * @return Reference to the destination `DocumentReference`. + */ + DocumentReference& operator=(const DocumentReference& other); + + /** + * @brief Move assignment operator. + * + * Moving is more efficient than copying for a `DocumentReference`. After + * being moved from, a `DocumentReference` is equivalent to its + * default-constructed state. + * + * @param[in] other `DocumentReference` to move data from. + * + * @return Reference to the destination `DocumentReference`. + */ + DocumentReference& operator=(DocumentReference&& other); + + /** + * @brief Returns the Firestore instance associated with this document + * reference. + * + * The pointer will remain valid indefinitely. + * + * @return Firebase Firestore instance that this DocumentReference refers to. + */ + virtual const Firestore* firestore() const; + + /** + * @brief Returns the Firestore instance associated with this document + * reference. + * + * The pointer will remain valid indefinitely. + * + * @return Firebase Firestore instance that this DocumentReference refers to. + */ + virtual Firestore* firestore(); + + /** + * @brief Returns the string ID of this document location. + * + * @return String ID of this document location. + */ + virtual const std::string& id() const; + + /** + * @brief Returns the path of this document (relative to the root of the + * database) as a slash-separated string. + * + * @return String path of this document location. + */ + virtual std::string path() const; + + /** + * @brief Returns a CollectionReference to the collection that contains this + * document. + */ + virtual CollectionReference Parent() const; + + /** + * @brief Returns a CollectionReference instance that refers to the + * subcollection at the specified path relative to this document. + * + * @param[in] collection_path A slash-separated relative path to a + * subcollection. The pointer only needs to be valid during this call. + * + * @return The CollectionReference instance. + */ + virtual CollectionReference Collection(const char* collection_path) const; + + /** + * @brief Returns a CollectionReference instance that refers to the + * subcollection at the specified path relative to this document. + * + * @param[in] collection_path A slash-separated relative path to a + * subcollection. + * + * @return The CollectionReference instance. + */ + virtual CollectionReference Collection( + const std::string& collection_path) const; + + /** + * @brief Reads the document referenced by this DocumentReference. + * + * By default, Get() attempts to provide up-to-date data when possible by + * waiting for data from the server, but it may return cached data or fail if + * you are offline and the server cannot be reached. This behavior can be + * altered via the Source parameter. + * + * @param[in] source A value to configure the get behavior (optional). + * + * @return A Future that will be resolved with the contents of the Document at + * this DocumentReference. + */ + virtual Future Get(Source source = Source::kDefault) const; + + /** + * @brief Writes to the document referred to by this DocumentReference. + * + * If the document does not yet exist, it will be created. If you pass + * SetOptions, the provided data can be merged into an existing document. + * + * @param[in] data A map of the fields and values to write to the document. + * @param[in] options An object to configure the Set() behavior (optional). + * + * @return A Future that will be resolved when the write finishes. + */ + virtual Future Set(const MapFieldValue& data, + const SetOptions& options = SetOptions()); + + /** + * @brief Updates fields in the document referred to by this + * DocumentReference. + * + * If no document exists yet, the update will fail. + * + * @param[in] data A map of field / value pairs to update. Fields can contain + * dots to reference nested fields within the document. + * + * @return A Future that will be resolved when the client is online and the + * commit has completed against the server. The future will not resolve when + * the device is offline, though local changes will be visible immediately. + */ + virtual Future Update(const MapFieldValue& data); + + /** + * @brief Updates fields in the document referred to by this + * DocumentReference. + * + * If no document exists yet, the update will fail. + * + * @param[in] data A map from FieldPath to FieldValue to update. + * + * @return A Future that will be resolved when the client is online and the + * commit has completed against the server. The future will not resolve when + * the device is offline, though local changes will be visible immediately. + */ + virtual Future Update(const MapFieldPathValue& data); + + /** + * @brief Removes the document referred to by this DocumentReference. + * + * @return A Future that will be resolved when the delete completes. + */ + virtual Future Delete(); + + /** + * @brief Starts listening to the document referenced by this + * DocumentReference. + * + * @param[in] callback The std::function to call. When this function is + * called, snapshot value is valid if and only if error is Error::kErrorOk. + * The std::string is an error message; the value may be empty if an error + * message is not available. + * + * @return A registration object that can be used to remove the listener. + */ + virtual ListenerRegistration AddSnapshotListener( + std::function + callback); + + /** + * @brief Starts listening to the document referenced by this + * DocumentReference. + * + * @param[in] metadata_changes Indicates whether metadata-only changes (that + * is, only DocumentSnapshot::metadata() changed) should trigger snapshot + * events. + * @param[in] callback The std::function to call. When this function is + * called, snapshot value is valid if and only if error is Error::kErrorOk. + * The std::string is an error message; the value may be empty if an error + * message is not available. + * + * @return A registration object that can be used to remove the listener. + */ + virtual ListenerRegistration AddSnapshotListener( + MetadataChanges metadata_changes, + std::function + callback); + + /** + * @brief Returns true if this `DocumentReference` is valid, false if it is + * not valid. An invalid `DocumentReference` could be the result of: + * - Creating a `DocumentReference` using the default constructor. + * - Moving from the `DocumentReference`. + * - Calling `CollectionReference::Parent()` on a `CollectionReference` that + * is not a subcollection. + * - Deleting your Firestore instance, which will invalidate all the + * `DocumentReference` instances associated with it. + * + * @return true if this `DocumentReference` is valid, false if this + * `DocumentReference` is invalid. + */ + bool is_valid() const { return internal_ != nullptr; } + + /** + * Returns a string representation of this `DocumentReference` for + * logging/debugging purposes. + * + * @note the exact string representation is unspecified and subject to + * change; don't rely on the format of the string. + */ + std::string ToString() const; + + /** + * Outputs the string representation of this `DocumentReference` to the given + * stream. + * + * @see `ToString()` for comments on the representation format. + */ + friend std::ostream& operator<<(std::ostream& out, + const DocumentReference& reference); + + private: + friend bool operator==(const DocumentReference& lhs, + const DocumentReference& rhs); + + friend class CollectionReferenceInternal; + friend class DocumentSnapshotInternal; + friend class FieldValueInternal; + friend class FirestoreInternal; + friend class TransactionInternal; + friend class WriteBatchInternal; + friend struct ConverterImpl; + template + friend struct CleanupFn; + + explicit DocumentReference(DocumentReferenceInternal* internal); + + mutable DocumentReferenceInternal* internal_ = nullptr; +}; + +/** Checks `lhs` and `rhs` for equality. */ +bool operator==(const DocumentReference& lhs, const DocumentReference& rhs); + +/** Checks `lhs` and `rhs` for inequality. */ +inline bool operator!=(const DocumentReference& lhs, + const DocumentReference& rhs) { + return !(lhs == rhs); +} + +} // namespace firestore +} // namespace firebase + +#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_DOCUMENT_REFERENCE_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/document_snapshot.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/document_snapshot.h new file mode 100644 index 000000000000..7617eb5d1412 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/document_snapshot.h @@ -0,0 +1,297 @@ +/* + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_DOCUMENT_SNAPSHOT_H_ +#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_DOCUMENT_SNAPSHOT_H_ + +#include +#include + +#include "firebase/firestore/map_field_value.h" +#include "firebase/firestore/snapshot_metadata.h" + +namespace firebase { +namespace firestore { + +class DocumentReference; +class DocumentSnapshotInternal; +class FieldPath; +class FieldValue; +class Firestore; + +/** + * @brief A DocumentSnapshot contains data read from a document in your + * Firestore database. + * + * The data can be extracted with the GetData() method, or by using + * Get() to access a specific field. For a DocumentSnapshot that points to + * a non-existing document, any data access will cause a failed assertion. You + * can use the exists() method to explicitly verify a document's existence. + * + * @note Firestore classes are not meant to be subclassed except for use in test + * mocks. Subclassing is not supported in production code and new SDK releases + * may break code that does so. + */ +class DocumentSnapshot { + public: + /** + * Controls the return value for server timestamps that have not yet been set + * to their final value. + */ + enum class ServerTimestampBehavior { + /** + * Return Null for server timestamps that have not yet been set to their + * final value. + */ + kNone = 0, + + /** + * Return local estimates for server timestamps that have not yet been set + * to their final value. This estimate will likely differ from the final + * value and may cause these pending values to change once the server result + * becomes available. + */ + kEstimate, + + /** + * Return the previous value for server timestamps that have not yet been + * set to their final value. + */ + kPrevious, + + /** The default behavior, which is equivalent to specifying kNone. */ + // + // Note, SWIG renaming mechanism doesn't properly handle initializing an + // enum constant with another enum constant (e.g., in expression `kFoo = + // kBar` only `kFoo` will be renamed, leaving `kBar` as is, leading to + // compilation errors). + // + kDefault = 0, + }; + + /** + * @brief Creates an invalid DocumentSnapshot that has to be reassigned before + * it can be used. + * + * Calling any member function on an invalid DocumentSnapshot will be a no-op. + * If the function returns a value, it will return a zero, empty, or invalid + * value, depending on the type of the value. + */ + DocumentSnapshot(); + + /** + * @brief Copy constructor. + * + * `DocumentSnapshot` is immutable and can be efficiently copied (no deep copy + * is performed). + * + * @param[in] other `DocumentSnapshot` to copy from. + */ + DocumentSnapshot(const DocumentSnapshot& other); + + /** + * @brief Move constructor. + * + * Moving is more efficient than copying for a `DocumentSnapshot`. After being + * moved from, a `DocumentSnapshot` is equivalent to its default-constructed + * state. + * + * @param[in] other `DocumentSnapshot` to move data from. + */ + DocumentSnapshot(DocumentSnapshot&& other); + + virtual ~DocumentSnapshot(); + + /** + * @brief Copy assignment operator. + * + * `DocumentSnapshot` is immutable and can be efficiently copied (no deep copy + * is performed). + * + * @param[in] other `DocumentSnapshot` to copy from. + * + * @return Reference to the destination `DocumentSnapshot`. + */ + DocumentSnapshot& operator=(const DocumentSnapshot& other); + + /** + * @brief Move assignment operator. + * + * Moving is more efficient than copying for a `DocumentSnapshot`. After being + * moved from, a `DocumentSnapshot` is equivalent to its default-constructed + * state. + * + * @param[in] other `DocumentSnapshot` to move data from. + * + * @return Reference to the destination `DocumentSnapshot`. + */ + DocumentSnapshot& operator=(DocumentSnapshot&& other); + + /** + * @brief Returns the string ID of the document for which this + * DocumentSnapshot contains data. + * + * @return String ID of this document location. + */ + virtual const std::string& id() const; + + /** + * @brief Returns the document location for which this DocumentSnapshot + * contains data. + * + * @return DocumentReference of this document location. + */ + virtual DocumentReference reference() const; + + /** + * @brief Returns the metadata about this snapshot concerning its source and + * if it has local modifications. + * + * @return SnapshotMetadata about this snapshot. + */ + virtual SnapshotMetadata metadata() const; + + /** + * @brief Explicitly verify a document's existence. + * + * @return True if the document exists in this snapshot. + */ + virtual bool exists() const; + + /** + * @brief Retrieves all fields in the document as a map of FieldValues. + * + * @param stb Configures how server timestamps that have not yet + * been set to their final value are returned from the snapshot (optional). + * + * @return A map containing all fields in the document, or an empty map if the + * document doesn't exist. + */ + virtual MapFieldValue GetData( + ServerTimestampBehavior stb = ServerTimestampBehavior::kDefault) const; + + /** + * @brief Retrieves a specific field from the document. + * + * @param field String ID of the field to retrieve. The pointer only needs to + * be valid during this call. + * @param stb Configures how server timestamps that have not yet been set to + * their final value are returned from the snapshot (optional). + * + * @return The value contained in the field. If the field does not exist in + * the document, then a `FieldValue` instance with `is_valid() == false` will + * be returned. + */ + virtual FieldValue Get( + const char* field, + ServerTimestampBehavior stb = ServerTimestampBehavior::kDefault) const; + + /** + * @brief Retrieves a specific field from the document. + * + * @param field String ID of the field to retrieve. + * @param stb Configures how server timestamps that have not yet been set to + * their final value are returned from the snapshot (optional). + * + * @return The value contained in the field. If the field does not exist in + * the document, then a `FieldValue` instance with `is_valid() == false` will + * be returned. + */ + virtual FieldValue Get( + const std::string& field, + ServerTimestampBehavior stb = ServerTimestampBehavior::kDefault) const; + + /** + * @brief Retrieves a specific field from the document. + * + * @param field Path of the field to retrieve. + * @param stb Configures how server timestamps that have not yet been set to + * their final value are returned from the snapshot (optional). + * + * @return The value contained in the field. If the field does not exist in + * the document, then a `FieldValue` instance with `is_valid() == false` will + * be returned. + */ + virtual FieldValue Get( + const FieldPath& field, + ServerTimestampBehavior stb = ServerTimestampBehavior::kDefault) const; + + /** + * @brief Returns true if this `DocumentSnapshot` is valid, false if it is + * not valid. An invalid `DocumentSnapshot` could be the result of: + * - Creating a `DocumentSnapshot` with the default constructor. + * - Moving from the `DocumentSnapshot`. + * - Deleting your Firestore instance, which will invalidate all the + * `DocumentSnapshot` instances associated with it. + * + * @return true if this `DocumentSnapshot` is valid, false if this + * `DocumentSnapshot` is invalid. + */ + bool is_valid() const { return internal_ != nullptr; } + + /** + * Returns a string representation of this `DocumentSnapshot` for + * logging/debugging purposes. + * + * @note the exact string representation is unspecified and subject to + * change; don't rely on the format of the string. + */ + std::string ToString() const; + + /** + * Outputs the string representation of this `DocumentSnapshot` to the given + * stream. + * + * @see `ToString()` for comments on the representation format. + */ + friend std::ostream& operator<<(std::ostream& out, + const DocumentSnapshot& document); + + private: + std::size_t Hash() const; + + friend bool operator==(const DocumentSnapshot& lhs, + const DocumentSnapshot& rhs); + friend std::size_t DocumentSnapshotHash(const DocumentSnapshot& snapshot); + + friend class DocumentChangeInternal; + friend class EventListenerInternal; + friend class FirestoreInternal; + friend class QueryInternal; + friend class TransactionInternal; + friend class Wrapper; + friend struct ConverterImpl; + template + friend struct CleanupFn; + + explicit DocumentSnapshot(DocumentSnapshotInternal* internal); + + mutable DocumentSnapshotInternal* internal_ = nullptr; +}; + +/** Checks `lhs` and `rhs` for equality. */ +bool operator==(const DocumentSnapshot& lhs, const DocumentSnapshot& rhs); + +/** Checks `lhs` and `rhs` for inequality. */ +inline bool operator!=(const DocumentSnapshot& lhs, + const DocumentSnapshot& rhs) { + return !(lhs == rhs); +} + +} // namespace firestore +} // namespace firebase + +#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_DOCUMENT_SNAPSHOT_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/field_path.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/field_path.h new file mode 100644 index 000000000000..d09dec641140 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/field_path.h @@ -0,0 +1,205 @@ +/* + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_FIELD_PATH_H_ +#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_FIELD_PATH_H_ + +#include +#include +#include +#include + +namespace firebase { +namespace firestore { + +#if !defined(__ANDROID__) + +namespace model { +class FieldPath; +} // namespace model + +#else + +class FieldPathPortable; + +#endif // !defined(__ANDROID__) + +/** + * @brief A FieldPath refers to a field in a document. + * + * The path may consist of a single field name (referring to a top level field + * in the document) or a list of field names (referring to a nested field in the + * document). + */ +class FieldPath final { + public: + /** + * @brief Creates an invalid FieldPath that has to be reassigned before it can + * be used. + * + * Calling any member function on an invalid FieldPath will be a no-op. If the + * function returns a value, it will return a zero, empty, or invalid value, + * depending on the type of the value. + */ + FieldPath(); + + /** + * Creates a FieldPath from the provided field names. If more than one field + * name is provided, the path will point to a nested field in a document. + * + * @param field_names A list of field names. + */ + FieldPath(std::initializer_list field_names); + + /** + * Creates a FieldPath from the provided field names. If more than one field + * name is provided, the path will point to a nested field in a document. + * + * @param field_names A vector of field names. + */ + FieldPath(const std::vector& field_names); + + /** + * @brief Copy constructor. + * + * This performs a deep copy, creating an independent instance. + * + * @param[in] other `FieldPath` to copy from. + */ + FieldPath(const FieldPath& other); + + /** + * @brief Move constructor. + * + * Moving is more efficient than copying for `FieldPath`. After being moved + * from, `FieldPath` is in a valid but unspecified state. + * + * @param[in] other `FieldPath` to move data from. + */ + FieldPath(FieldPath&& other) noexcept; + + ~FieldPath(); + + /** + * @brief Copy assignment operator. + * + * This performs a deep copy, creating an independent instance. + * + * @param[in] other `FieldPath` to copy from. + * + * @return Reference to the destination `FieldPath`. + */ + FieldPath& operator=(const FieldPath& other); + + /** + * @brief Move assignment operator. + * + * Moving is more efficient than copying for `FieldPath`. After being moved + * from, `FieldPath` is in a valid but unspecified state. + * + * @param[in] other `FieldPath` to move data from. + * + * @return Reference to the destination `FieldPath`. + */ + FieldPath& operator=(FieldPath&& other) noexcept; + + /** + * A special sentinel FieldPath to refer to the ID of a document. It can be + * used in queries to sort or filter by the document ID. + */ + static FieldPath DocumentId(); + + /** + * @brief Returns true if this `FieldPath` is valid, false if it is not valid. + * An invalid `FieldPath` could be the result of: + * - Creating a `FieldPath` using the default constructor. + * - Moving from the `FieldPath`. + * + * @return true if this `FieldPath` is valid, false if this `FieldPath` is + * invalid. + */ + bool is_valid() const { return internal_ != nullptr; } + + /** + * Returns a string representation of this `FieldPath` for + * logging/debugging purposes. + * + * @note the exact string representation is unspecified and subject to + * change; don't rely on the format of the string. + */ + std::string ToString() const; + + /** + * Outputs the string representation of this `FieldPath` to the given + * stream. + * + * @see `ToString()` for comments on the representation format. + */ + friend std::ostream& operator<<(std::ostream& out, const FieldPath& path); + + private: + // The type of the internal object that implements the public interface. +#if !defined(SWIG) +#if !defined(__ANDROID__) + using FieldPathInternal = ::firebase::firestore::model::FieldPath; +#else + using FieldPathInternal = ::firebase::firestore::FieldPathPortable; +#endif // !defined(__ANDROID__) +#endif // !defined(SWIG) + + friend bool operator==(const FieldPath& lhs, const FieldPath& rhs); + friend bool operator!=(const FieldPath& lhs, const FieldPath& rhs); + friend struct std::hash; + + friend class DocumentSnapshot; // For access to `FromDotSeparatedString` + friend class Query; + friend class QueryInternal; + friend class SetOptions; // For access to `FromDotSeparatedString` + friend class FieldPathConverter; + friend struct ConverterImpl; + + explicit FieldPath(FieldPathInternal* internal); + + static FieldPathInternal* InternalFromSegments( + std::vector field_names); + + static FieldPath FromDotSeparatedString(const std::string& path); + + FieldPathInternal* internal_ = nullptr; +}; + +} // namespace firestore +} // namespace firebase + +#if !defined(SWIG) +namespace std { +/** + * A convenient specialization of std::hash for FieldPath. + */ +template <> +struct hash { + /** + * Calculates the hash of the argument. + * + * Note: specialization of `std::hash` is provided for convenience only. The + * implementation is subject to change. + */ + size_t operator()(const firebase::firestore::FieldPath& field_path) const; +}; +} // namespace std +#endif // !defined(SWIG) + +#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_FIELD_PATH_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/field_value.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/field_value.h new file mode 100644 index 000000000000..e66814104ed7 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/field_value.h @@ -0,0 +1,436 @@ +/* + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_FIELD_VALUE_H_ +#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_FIELD_VALUE_H_ + +#include +#include +#include +#include +#include + +#include "firebase/firestore/map_field_value.h" +#include "firebase/internal/type_traits.h" + +namespace firebase { + +class Timestamp; + +namespace firestore { + +class DocumentReference; +class FieldValueInternal; +class GeoPoint; + +/** + * @brief A field value represents variant datatypes as stored by Firestore. + * + * FieldValue can be used when reading a particular field with + * DocumentSnapshot::Get() or fields with DocumentSnapshot::GetData(). When + * writing document fields with DocumentReference::Set() or + * DocumentReference::Update(), it can also represent sentinel values in + * addition to real data values. + * + * For a non-sentinel instance, you can check whether it is of a particular type + * with is_foo() and get the value with foo_value(), where foo can be one of + * null, boolean, integer, double, timestamp, string, blob, reference, + * geo_point, array or map. If the instance is not of type foo, the call to + * foo_value() will fail (and cause a crash). + */ +class FieldValue final { + // Helper aliases for `Increment` member functions. + // Qualifying `is_integer` is to prevent ambiguity with the + // `FieldValue::is_integer` member function. + // Note: normally, `enable_if::type` would be included in the alias, but such + // a declaration breaks SWIG (presumably, SWIG cannot handle `typename` within + // an alias template). + template + using EnableIfIntegral = enable_if<::firebase::is_integer::value, int>; + template + using EnableIfFloatingPoint = enable_if::value, int>; + + public: + /** + * The enumeration of all valid runtime types of FieldValue. + */ + enum class Type { + kNull, + kBoolean, + kInteger, + kDouble, + kTimestamp, + kString, + kBlob, + kReference, + kGeoPoint, + kArray, + kMap, + // Below are sentinel types. Sentinel types can be passed to Firestore + // methods as arguments, but are never returned from Firestore. + kDelete, + kServerTimestamp, + kArrayUnion, + kArrayRemove, + kIncrementInteger, + kIncrementDouble, + }; + + /** + * @brief Creates an invalid FieldValue that has to be reassigned before it + * can be used. + * + * Calling any member function on an invalid FieldValue will be a no-op. If + * the function returns a value, it will return a zero, empty, or invalid + * value, depending on the type of the value. + */ + FieldValue(); + + /** + * @brief Copy constructor. + * + * `FieldValue` is immutable and can be efficiently copied (no deep copy is + * performed). + * + * @param[in] other `FieldValue` to copy from. + */ + FieldValue(const FieldValue& other); + + /** + * @brief Move constructor. + * + * Moving is more efficient than copying for a `FieldValue`. After being moved + * from, a `FieldValue` is equivalent to its default-constructed state. + * + * @param[in] other `FieldValue` to move data from. + */ + FieldValue(FieldValue&& other) noexcept; + + ~FieldValue(); + + /** + * @brief Copy assignment operator. + * + * `FieldValue` is immutable and can be efficiently copied (no deep copy is + * performed). + * + * @param[in] other `FieldValue` to copy from. + * + * @return Reference to the destination `FieldValue`. + */ + FieldValue& operator=(const FieldValue& other); + + /** + * @brief Move assignment operator. + * + * Moving is more efficient than copying for a `FieldValue`. After being moved + * from, a `FieldValue` is equivalent to its default-constructed state. + * + * @param[in] other `FieldValue` to move data from. + * + * @return Reference to the destination `FieldValue`. + */ + FieldValue& operator=(FieldValue&& other) noexcept; + + /** + * @brief Constructs a FieldValue containing the given boolean value. + */ + static FieldValue Boolean(bool value); + + /** + * @brief Constructs a FieldValue containing the given 64-bit integer value. + */ + static FieldValue Integer(int64_t value); + + /** + * @brief Constructs a FieldValue containing the given double-precision + * floating point value. + */ + static FieldValue Double(double value); + + /** + * @brief Constructs a FieldValue containing the given Timestamp value. + */ + static FieldValue Timestamp(Timestamp value); + + /** + * @brief Constructs a FieldValue containing the given std::string value. + */ + static FieldValue String(std::string value); + + /** + * @brief Constructs a FieldValue containing the given blob value of given + * size. `value` is copied into the returned FieldValue. + */ + static FieldValue Blob(const uint8_t* value, size_t size); + + /** + * @brief Constructs a FieldValue containing the given reference value. + */ + static FieldValue Reference(DocumentReference value); + + /** + * @brief Constructs a FieldValue containing the given GeoPoint value. + */ + static FieldValue GeoPoint(GeoPoint value); + + /** + * @brief Constructs a FieldValue containing the given FieldValue vector + * value. + */ + static FieldValue Array(std::vector value); + + /** + * @brief Constructs a FieldValue containing the given FieldValue map value. + */ + static FieldValue Map(MapFieldValue value); + + /** @brief Gets the current type contained in this FieldValue. */ + Type type() const; + + /** @brief Gets whether this FieldValue is currently null. */ + bool is_null() const { return type() == Type::kNull; } + + /** @brief Gets whether this FieldValue contains a boolean value. */ + bool is_boolean() const { return type() == Type::kBoolean; } + + /** @brief Gets whether this FieldValue contains an integer value. */ + bool is_integer() const { return type() == Type::kInteger; } + + /** @brief Gets whether this FieldValue contains a double value. */ + bool is_double() const { return type() == Type::kDouble; } + + /** @brief Gets whether this FieldValue contains a timestamp. */ + bool is_timestamp() const { return type() == Type::kTimestamp; } + + /** @brief Gets whether this FieldValue contains a string. */ + bool is_string() const { return type() == Type::kString; } + + /** @brief Gets whether this FieldValue contains a blob. */ + bool is_blob() const { return type() == Type::kBlob; } + + /** + * @brief Gets whether this FieldValue contains a reference to a document in + * the same Firestore. + */ + bool is_reference() const { return type() == Type::kReference; } + + /** @brief Gets whether this FieldValue contains a GeoPoint. */ + bool is_geo_point() const { return type() == Type::kGeoPoint; } + + /** @brief Gets whether this FieldValue contains an array of FieldValues. */ + bool is_array() const { return type() == Type::kArray; } + + /** @brief Gets whether this FieldValue contains a map of std::string to + * FieldValue. */ + bool is_map() const { return type() == Type::kMap; } + + /** @brief Gets the boolean value contained in this FieldValue. */ + bool boolean_value() const; + + /** @brief Gets the integer value contained in this FieldValue. */ + int64_t integer_value() const; + + /** @brief Gets the double value contained in this FieldValue. */ + double double_value() const; + + /** @brief Gets the timestamp value contained in this FieldValue. */ + class Timestamp timestamp_value() const; + + /** @brief Gets the string value contained in this FieldValue. */ + std::string string_value() const; + + /** @brief Gets the blob value contained in this FieldValue. */ + const uint8_t* blob_value() const; + + /** @brief Gets the blob size contained in this FieldValue. */ + size_t blob_size() const; + + /** @brief Gets the DocumentReference contained in this FieldValue. */ + DocumentReference reference_value() const; + + /** @brief Gets the GeoPoint value contained in this FieldValue. */ + class GeoPoint geo_point_value() const; + + /** @brief Gets the vector of FieldValues contained in this FieldValue. */ + std::vector array_value() const; + + /** + * @brief Gets the map of string to FieldValue contained in this FieldValue. + */ + MapFieldValue map_value() const; + + /** + * @brief Returns `true` if this `FieldValue` is valid, `false` if it is not + * valid. An invalid `FieldValue` could be the result of: + * - Creating a `FieldValue` using the default constructor. + * - Moving from the `FieldValue`. + * - Calling `DocumentSnapshot::Get(field)` for a field that does not exist + * in the document. + * + * @return `true` if this `FieldValue` is valid, `false` if this `FieldValue` + * is invalid. + */ + bool is_valid() const { return internal_ != nullptr; } + + /** @brief Constructs a null. */ + static FieldValue Null(); + + /** + * @brief Returns a sentinel for use with Update() to mark a field for + * deletion. + */ + static FieldValue Delete(); + + /** + * Returns a sentinel that can be used with Set() or Update() to include + * a server-generated timestamp in the written data. + */ + static FieldValue ServerTimestamp(); + + /** + * Returns a special value that can be used with Set() or Update() that tells + * the server to union the given elements with any array value that already + * exists on the server. Each specified element that doesn't already exist in + * the array will be added to the end. If the field being modified is not + * already an array, it will be overwritten with an array containing exactly + * the specified elements. + * + * @param elements The elements to union into the array. + * @return The FieldValue sentinel for use in a call to Set() or Update(). + */ + static FieldValue ArrayUnion(std::vector elements); + + /** + * Returns a special value that can be used with Set() or Update() that tells + * the server to remove the given elements from any array value that already + * exists on the server. All instances of each element specified will be + * removed from the array. If the field being modified is not already an + * array, it will be overwritten with an empty array. + * + * @param elements The elements to remove from the array. + * @return The FieldValue sentinel for use in a call to Set() or Update(). + */ + static FieldValue ArrayRemove(std::vector elements); + + /** + * Returns a special value that can be used with `Set()` or `Update()` that + * tells the server to increment the field's current value by the given + * integer value. + * + * If the current field value is an integer, possible integer overflows are + * resolved to `LONG_MAX` or `LONG_MIN`. If the current field value is a + * double, both values will be interpreted as doubles and the arithmetic will + * follow IEEE 754 semantics. + * + * If field is not an integer or a double, or if the field does not yet exist, + * the transformation will set the field to the given value. + * + * @param by_value The integer value to increment by. Should be an integer + * type not larger than `int64_t`. + * @return The FieldValue sentinel for use in a call to `Set()` or `Update().` + */ + template ::type = 0> + static FieldValue Increment(T by_value) { + // Note: Doxygen will run into trouble if this function's definition is + // moved outside the class body. + static_assert( + (std::numeric_limits::max)() <= + (std::numeric_limits::max)(), + "The integer type you provided is larger than can fit in an int64_t. " + "If you are sure the value will not be truncated, please explicitly " + "cast to int64_t before passing it to FieldValue::Increment()."); + return IntegerIncrement(static_cast(by_value)); + } + + /** + * Returns a special value that can be used with `Set()` or `Update()` that + * tells the server to increment the field's current value by the given + * floating point value. + * + * If the current field value is an integer, possible integer overflows are + * resolved to `LONG_MAX` or `LONG_MIN`. If the current field value is a + * double, both values will be interpreted as doubles and the arithmetic will + * follow IEEE 754 semantics. + * + * If field is not an integer or a double, or if the field does not yet exist, + * the transformation will set the field to the given value. + * + * @param by_value The double value to increment by. Should be a floating + * point type no larger than `double`. + * @return The FieldValue sentinel for use in a call to `Set()` or `Update().` + */ + template ::type = 0> + static FieldValue Increment(T by_value) { + // Note: Doxygen will run into trouble if this function's definition is + // moved outside the class body. + static_assert( + (std::numeric_limits::max)() <= (std::numeric_limits::max)(), + "The floating point type you provided is larger than can fit in a " + "double. If you are sure the value will not be truncated, please " + "explicitly cast to double before passing it to " + "FieldValue::Increment()."); + return DoubleIncrement(static_cast(by_value)); + } + + /** + * Returns a string representation of this `FieldValue` for logging/debugging + * purposes. + * + * @note the exact string representation is unspecified and subject to + * change; don't rely on the format of the string. + */ + std::string ToString() const; + + /** + * Outputs the string representation of this `FieldValue` to the given stream. + * + * @see `ToString()` for comments on the representation format. + */ + friend std::ostream& operator<<(std::ostream& out, const FieldValue& value); + + private: + friend class DocumentReferenceInternal; + friend class DocumentSnapshotInternal; + friend class FieldValueInternal; + friend class FirestoreInternal; + friend class QueryInternal; + friend class TransactionInternal; + friend class Wrapper; + friend class WriteBatchInternal; + friend struct ConverterImpl; + friend bool operator==(const FieldValue& lhs, const FieldValue& rhs); + + explicit FieldValue(FieldValueInternal* internal); + + static FieldValue IntegerIncrement(int64_t by_value); + static FieldValue DoubleIncrement(double by_value); + + FieldValueInternal* internal_ = nullptr; +}; + +/** Checks `lhs` and `rhs` for equality. */ +bool operator==(const FieldValue& lhs, const FieldValue& rhs); + +/** Checks `lhs` and `rhs` for inequality. */ +inline bool operator!=(const FieldValue& lhs, const FieldValue& rhs) { + return !(lhs == rhs); +} + +} // namespace firestore +} // namespace firebase + +#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_FIELD_VALUE_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/firestore_errors.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/firestore_errors.h new file mode 100644 index 000000000000..6af214a08df1 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/firestore_errors.h @@ -0,0 +1,116 @@ +/* + * Copyright 2018 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIRESTORE_CORE_INCLUDE_FIREBASE_FIRESTORE_FIRESTORE_ERRORS_H_ +#define FIRESTORE_CORE_INCLUDE_FIREBASE_FIRESTORE_FIRESTORE_ERRORS_H_ + +namespace firebase { +namespace firestore { + +/** + * Error codes used by Cloud Firestore. + * + * The codes are in sync across Firestore SDKs on various platforms. + */ +enum Error { + /** The operation completed successfully. */ + // Note: NSError objects will never have a code with this value. + kErrorOk = 0, + + kErrorNone = 0, + + /** The operation was cancelled (typically by the caller). */ + kErrorCancelled = 1, + + /** Unknown error or an error from a different error domain. */ + kErrorUnknown = 2, + + /** + * Client specified an invalid argument. Note that this differs from + * FailedPrecondition. InvalidArgument indicates arguments that are + * problematic regardless of the state of the system (e.g., an invalid field + * name). + */ + kErrorInvalidArgument = 3, + + /** + * Deadline expired before operation could complete. For operations that + * change the state of the system, this error may be returned even if the + * operation has completed successfully. For example, a successful response + * from a server could have been delayed long enough for the deadline to + * expire. + */ + kErrorDeadlineExceeded = 4, + + /** Some requested document was not found. */ + kErrorNotFound = 5, + + /** Some document that we attempted to create already exists. */ + kErrorAlreadyExists = 6, + + /** The caller does not have permission to execute the specified operation. */ + kErrorPermissionDenied = 7, + + /** + * Some resource has been exhausted, perhaps a per-user quota, or perhaps the + * entire file system is out of space. + */ + kErrorResourceExhausted = 8, + + /** + * Operation was rejected because the system is not in a state required for + * the operation's execution. + */ + kErrorFailedPrecondition = 9, + + /** + * The operation was aborted, typically due to a concurrency issue like + * transaction aborts, etc. + */ + kErrorAborted = 10, + + /** Operation was attempted past the valid range. */ + kErrorOutOfRange = 11, + + /** Operation is not implemented or not supported/enabled. */ + kErrorUnimplemented = 12, + + /** + * Internal errors. Means some invariants expected by underlying system has + * been broken. If you see one of these errors, something is very broken. + */ + kErrorInternal = 13, + + /** + * The service is currently unavailable. This is a most likely a transient + * condition and may be corrected by retrying with a backoff. + */ + kErrorUnavailable = 14, + + /** Unrecoverable data loss or corruption. */ + kErrorDataLoss = 15, + + /** + * The request does not have valid authentication credentials for the + * operation. + */ + kErrorUnauthenticated = 16 +}; + +} // namespace firestore +} // namespace firebase + +#endif // FIRESTORE_CORE_INCLUDE_FIREBASE_FIRESTORE_FIRESTORE_ERRORS_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/firestore_version.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/firestore_version.h new file mode 100644 index 000000000000..627ead9e3ae7 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/firestore_version.h @@ -0,0 +1,29 @@ +/* + * Copyright 2018 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIRESTORE_CORE_INCLUDE_FIREBASE_FIRESTORE_FIRESTORE_VERSION_H_ +#define FIRESTORE_CORE_INCLUDE_FIREBASE_FIRESTORE_FIRESTORE_VERSION_H_ + +namespace firebase { +namespace firestore { + +/** Version string for the Firebase Firestore SDK. */ +extern const char* const kFirestoreVersionString; + +} // namespace firestore +} // namespace firebase + +#endif // FIRESTORE_CORE_INCLUDE_FIREBASE_FIRESTORE_FIRESTORE_VERSION_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/geo_point.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/geo_point.h new file mode 100644 index 000000000000..ac56e74a4515 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/geo_point.h @@ -0,0 +1,120 @@ +/* + * Copyright 2018 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIRESTORE_CORE_INCLUDE_FIREBASE_FIRESTORE_GEO_POINT_H_ +#define FIRESTORE_CORE_INCLUDE_FIREBASE_FIRESTORE_GEO_POINT_H_ + +#include +#include + +namespace firebase { +namespace firestore { + +/** + * An immutable object representing a geographical point in Firestore. The point + * is represented as a latitude/longitude pair. + * + * Latitude values are in the range of [-90, 90]. + * Longitude values are in the range of [-180, 180]. + */ +class GeoPoint { + public: + /** Creates a `GeoPoint` with both latitude and longitude set to 0. */ + GeoPoint() = default; + + /** + * Creates a `GeoPoint` from the provided latitude and longitude values. + * + * @param latitude The latitude as number of degrees between -90 and 90. + * @param longitude The longitude as number of degrees between -180 and 180. + */ + GeoPoint(double latitude, double longitude); + + /** Copy constructor, `GeoPoint` is trivially copyable. */ + GeoPoint(const GeoPoint& other) = default; + + /** Move constructor, equivalent to copying. */ + GeoPoint(GeoPoint&& other) = default; + + /** Copy assignment operator, `GeoPoint` is trivially copyable. */ + GeoPoint& operator=(const GeoPoint& other) = default; + + /** Move assignment operator, equivalent to copying. */ + GeoPoint& operator=(GeoPoint&& other) = default; + + /** Returns the latitude value of this `GeoPoint`. */ + double latitude() const { + return latitude_; + } + + /** Returns the latitude value of this `GeoPoint`. */ + double longitude() const { + return longitude_; + } + + /** + * Returns a string representation of this `GeoPoint` for logging/debugging + * purposes. + * + * @note: the exact string representation is unspecified and subject to + * change; don't rely on the format of the string. + */ + std::string ToString() const; + + /** + * Outputs the string representation of this `GeoPoint` to the given stream. + * + * @see `ToString()` for comments on the representation format. + */ + friend std::ostream& operator<<(std::ostream& out, const GeoPoint& geo_point); + + private: + double latitude_ = 0.0; + double longitude_ = 0.0; +}; + +/** Checks whether `lhs` and `rhs` are in ascending order. */ +bool operator<(const GeoPoint& lhs, const GeoPoint& rhs); + +/** Checks whether `lhs` and `rhs` are in descending order. */ +inline bool operator>(const GeoPoint& lhs, const GeoPoint& rhs) { + return rhs < lhs; +} + +/** Checks whether `lhs` and `rhs` are in non-ascending order. */ +inline bool operator>=(const GeoPoint& lhs, const GeoPoint& rhs) { + return !(lhs < rhs); +} + +/** Checks whether `lhs` and `rhs` are in non-descending order. */ +inline bool operator<=(const GeoPoint& lhs, const GeoPoint& rhs) { + return !(lhs > rhs); +} + +/** Checks `lhs` and `rhs` for inequality. */ +inline bool operator!=(const GeoPoint& lhs, const GeoPoint& rhs) { + return lhs < rhs || lhs > rhs; +} + +/** Checks `lhs` and `rhs` for equality. */ +inline bool operator==(const GeoPoint& lhs, const GeoPoint& rhs) { + return !(lhs != rhs); +} + +} // namespace firestore +} // namespace firebase + +#endif // FIRESTORE_CORE_INCLUDE_FIREBASE_FIRESTORE_GEO_POINT_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/listener_registration.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/listener_registration.h new file mode 100644 index 000000000000..20487943347f --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/listener_registration.h @@ -0,0 +1,130 @@ +/* + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_LISTENER_REGISTRATION_H_ +#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_LISTENER_REGISTRATION_H_ + +namespace firebase { +namespace firestore { + +class FirestoreInternal; +class ListenerRegistrationInternal; + +/** Represents a listener that can be removed by calling Remove(). */ +class ListenerRegistration { + public: + /** + * @brief Creates an invalid ListenerRegistration that has to be reassigned + * before it can be used. + * + * Calling Remove() on an invalid ListenerRegistration is a no-op. + */ + ListenerRegistration(); + + /** + * @brief Copy constructor. + * + * `ListenerRegistration` can be efficiently copied because it simply refers + * to the same underlying listener. If there is more than one copy of + * a `ListenerRegistration`, after calling `Remove` on one of them, the + * listener is removed, and calling `Remove` on any other copies will be + * a no-op. + * + * @param[in] other `ListenerRegistration` to copy from. + */ + ListenerRegistration(const ListenerRegistration& other); + + /** + * @brief Move constructor. + * + * Moving is more efficient than copying for a `ListenerRegistration`. After + * being moved from, a `ListenerRegistration` is equivalent to its + * default-constructed state. + * + * @param[in] other `ListenerRegistration` to move data from. + */ + ListenerRegistration(ListenerRegistration&& other); + + virtual ~ListenerRegistration(); + + /** + * @brief Copy assignment operator. + * + * `ListenerRegistration` can be efficiently copied because it simply refers + * to the same underlying listener. If there is more than one copy of + * a `ListenerRegistration`, after calling `Remove` on one of them, the + * listener is removed, and calling `Remove` on any other copies will be + * a no-op. + * + * @param[in] other `ListenerRegistration` to copy from. + * + * @return Reference to the destination `ListenerRegistration`. + */ + ListenerRegistration& operator=(const ListenerRegistration& other); + + /** + * @brief Move assignment operator. + * + * Moving is more efficient than copying for a `ListenerRegistration`. After + * being moved from, a `ListenerRegistration` is equivalent to its + * default-constructed state. + * + * @param[in] other `ListenerRegistration` to move data from. + * + * @return Reference to the destination `ListenerRegistration`. + */ + ListenerRegistration& operator=(ListenerRegistration&& other); + + /** + * Removes the listener being tracked by this ListenerRegistration. After the + * initial call, subsequent calls have no effect. + */ + virtual void Remove(); + + /** + * @brief Returns true if this `ListenerRegistration` is valid, false if it is + * not valid. An invalid `ListenerRegistration` could be the result of: + * - Creating a `ListenerRegistration` using the default constructor. + * - Moving from the `ListenerRegistration`. + * - Deleting your Firestore instance, which will invalidate all the + * `ListenerRegistration` instances associated with it. + * + * @return true if this `ListenerRegistration` is valid, false if this + * `ListenerRegistration` is invalid. + */ + bool is_valid() const { return internal_ != nullptr; } + + private: + friend class DocumentReferenceInternal; + friend class FirestoreInternal; + friend class ListenerRegistrationInternal; + friend class QueryInternal; + friend struct ConverterImpl; + template + friend struct CleanupFn; + + explicit ListenerRegistration(ListenerRegistrationInternal* internal); + + void Cleanup(); + + FirestoreInternal* firestore_ = nullptr; + mutable ListenerRegistrationInternal* internal_ = nullptr; +}; + +} // namespace firestore +} // namespace firebase + +#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_LISTENER_REGISTRATION_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/load_bundle_task_progress.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/load_bundle_task_progress.h new file mode 100644 index 000000000000..be9b235f1205 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/load_bundle_task_progress.h @@ -0,0 +1,101 @@ +/* + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_LOAD_BUNDLE_TASK_PROGRESS_H_ +#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_LOAD_BUNDLE_TASK_PROGRESS_H_ + +#include + +namespace firebase { +namespace firestore { + +class LoadBundleTaskProgressInternal; + +/** Represents a progress update or the final state from loading bundles. */ +class LoadBundleTaskProgress { + public: + /** + * Represents the state of bundle loading tasks. + * + * Both `kSuccess` and `kError` are final states: the task will abort + * or complete and there will be no more updates after they are reported. + */ + enum class State { kError, kInProgress, kSuccess }; + + LoadBundleTaskProgress() = default; + /** Construct a LoadBundleTaskProgress with specific state. **/ + LoadBundleTaskProgress(int32_t documents_loaded, + int32_t total_documents, + int64_t bytes_loaded, + int64_t total_bytes, + State state); + + /** Returns how many documents have been loaded. */ + int32_t documents_loaded() const { return documents_loaded_; } + + /** + * Returns the total number of documents in the bundle. Returns 0 if the + * bundle failed to parse. + */ + int32_t total_documents() const { return total_documents_; } + + /** Returns how many bytes have been loaded. */ + int64_t bytes_loaded() const { return bytes_loaded_; } + + /** + * Returns the total number of bytes in the bundle. Returns 0 if the bundle + * failed to parse. + */ + int64_t total_bytes() const { return total_bytes_; } + + /** Returns the current state of the loading progress. */ + State state() const { return state_; } + + private: + friend class EventListenerInternal; + friend class LoadBundleTaskProgressInternal; + friend struct ConverterImpl; + +#if defined(__ANDROID__) + explicit LoadBundleTaskProgress(LoadBundleTaskProgressInternal* internal); +#endif // defined(__ANDROID__) + + int32_t documents_loaded_ = 0; + int32_t total_documents_ = 0; + int64_t bytes_loaded_ = 0; + int64_t total_bytes_ = 0; + State state_ = State::kInProgress; +}; + +/** LoadBundleTaskProgress == comparison operator. **/ +inline bool operator==(const LoadBundleTaskProgress& lhs, + const LoadBundleTaskProgress& rhs) { + return lhs.state() == rhs.state() && + lhs.bytes_loaded() == rhs.bytes_loaded() && + lhs.documents_loaded() == rhs.documents_loaded() && + lhs.total_bytes() == rhs.total_bytes() && + lhs.total_documents() == rhs.total_documents(); +} + +/** LoadBundleTaskProgress != comparison operator. **/ +inline bool operator!=(const LoadBundleTaskProgress& lhs, + const LoadBundleTaskProgress& rhs) { + return !(lhs == rhs); +} + +} // namespace firestore +} // namespace firebase + +#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_LOAD_BUNDLE_TASK_PROGRESS_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/map_field_value.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/map_field_value.h new file mode 100644 index 000000000000..8c67c05a1088 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/map_field_value.h @@ -0,0 +1,37 @@ +/* + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_MAP_FIELD_VALUE_H_ +#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_MAP_FIELD_VALUE_H_ + +#include +#include + +namespace firebase { +namespace firestore { + +class FieldPath; +class FieldValue; + +/** @brief A map of `FieldValue`s indexed by stringified field paths. */ +using MapFieldValue = std::unordered_map; +/** @brief A map of `FieldValue`s indexed by field paths. */ +using MapFieldPathValue = std::unordered_map; + +} // namespace firestore +} // namespace firebase + +#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_MAP_FIELD_VALUE_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/metadata_changes.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/metadata_changes.h new file mode 100644 index 000000000000..13f9abe48427 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/metadata_changes.h @@ -0,0 +1,41 @@ +/* + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_METADATA_CHANGES_H_ +#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_METADATA_CHANGES_H_ + +namespace firebase { +namespace firestore { + +/** + * Indicates whether metadata-only changes (that is, + * DocumentSnapshot::metadata() or QuerySnapshot::metadata() changed) should + * trigger snapshot events. + */ +enum class MetadataChanges { + /** Snapshot events will not be triggered by metadata-only changes. */ + kExclude, + + /** + * Snapshot events will be triggered by any changes, including metadata-only + * changes. + */ + kInclude, +}; + +} // namespace firestore +} // namespace firebase +#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_METADATA_CHANGES_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/query.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/query.h new file mode 100644 index 000000000000..d2e73400cee6 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/query.h @@ -0,0 +1,683 @@ +/* + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_QUERY_H_ +#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_QUERY_H_ + +#include +#include +#include +#include +#include + +#include "firebase/internal/common.h" + +#include "firebase/firestore/firestore_errors.h" +#include "firebase/firestore/metadata_changes.h" +#include "firebase/firestore/source.h" + +namespace firebase { +/// @cond FIREBASE_APP_INTERNAL +template +class Future; +/// @endcond + +namespace firestore { + +class DocumentSnapshot; +template +class EventListener; +class FieldPath; +class FieldValue; +class ListenerRegistration; +class Firestore; +class QueryInternal; +class QuerySnapshot; + +/** + * @brief A Query which you can read or listen to. + * + * You can also construct refined Query objects by adding filters and ordering. + * + * You cannot construct a valid Query directly; use CollectionReference + * methods that return a Query instead. + * + * @note Firestore classes are not meant to be subclassed except for use in test + * mocks. Subclassing is not supported in production code and new SDK releases + * may break code that does so. + */ +class Query { + public: + /** + * An enum for the direction of a sort. + */ + enum class Direction { + kAscending, + kDescending, + }; + + /** + * @brief Creates an invalid Query that has to be reassigned before it can be + * used. + * + * Calling any member function on an invalid Query will be a no-op. If the + * function returns a value, it will return a zero, empty, or invalid value, + * depending on the type of the value. + */ + Query(); + + /** + * @brief Copy constructor. + * + * `Query` is immutable and can be efficiently copied (no deep copy is + * performed). + * + * @param[in] other `Query` to copy from. + */ + Query(const Query& other); + + /** + * @brief Move constructor. + * + * Moving is more efficient than copying for a `Query`. After being moved + * from, a `Query` is equivalent to its default-constructed state. + * + * @param[in] other `Query` to move data from. + */ + Query(Query&& other); + + virtual ~Query(); + + /** + * @brief Copy assignment operator. + * + * `Query` is immutable and can be efficiently copied (no deep copy is + * performed). + * + * @param[in] other `Query` to copy from. + * + * @return Reference to the destination `Query`. + */ + Query& operator=(const Query& other); + + /** + * @brief Move assignment operator. + * + * Moving is more efficient than copying for a `Query`. After being moved + * from, a `Query` is equivalent to its default-constructed state. + * + * @param[in] other `Query` to move data from. + * + * @return Reference to the destination `Query`. + */ + Query& operator=(Query&& other); + + /** + * @brief Returns the Firestore instance associated with this query. + * + * The pointer will remain valid indefinitely. + * + * @return Firebase Firestore instance that this Query refers to. + */ + virtual const Firestore* firestore() const; + + /** + * @brief Returns the Firestore instance associated with this query. + * + * The pointer will remain valid indefinitely. + * + * @return Firebase Firestore instance that this Query refers to. + */ + virtual Firestore* firestore(); + + /** + * @brief Creates and returns a new Query with the additional filter that + * documents must contain the specified field and the value should be equal to + * the specified value. + * + * @param[in] field The name of the field to compare. + * @param[in] value The value for comparison. + * + * @return The created Query. + */ + virtual Query WhereEqualTo(const std::string& field, + const FieldValue& value) const; + + /** + * @brief Creates and returns a new Query with the additional filter that + * documents must contain the specified field and the value should be equal to + * the specified value. + * + * @param[in] field The path of the field to compare. + * @param[in] value The value for comparison. + * + * @return The created Query. + */ + virtual Query WhereEqualTo(const FieldPath& field, + const FieldValue& value) const; + + /** + * @brief Creates and returns a new Query with the additional filter that + * documents must contain the specified field and the value does not equal the + * specified value. + * + * A Query can have only one `WhereNotEqualTo()` filter, and it cannot be + * combined with `WhereNotIn()`. + * + * @param[in] field The name of the field to compare. + * @param[in] value The value for comparison. + * + * @return The created Query. + */ + virtual Query WhereNotEqualTo(const std::string& field, + const FieldValue& value) const; + + /** + * @brief Creates and returns a new Query with the additional filter that + * documents must contain the specified field and the value does not equal the + * specified value. + * + * A Query can have only one `WhereNotEqualTo()` filter, and it cannot be + * combined with `WhereNotIn()`. + * + * @param[in] field The path of the field to compare. + * @param[in] value The value for comparison. + * + * @return The created Query. + */ + virtual Query WhereNotEqualTo(const FieldPath& field, + const FieldValue& value) const; + + /** + * @brief Creates and returns a new Query with the additional filter that + * documents must contain the specified field and the value should be less + * than the specified value. + * + * @param[in] field The name of the field to compare. + * @param[in] value The value for comparison. + * + * @return The created Query. + */ + virtual Query WhereLessThan(const std::string& field, + const FieldValue& value) const; + + /** + * @brief Creates and returns a new Query with the additional filter that + * documents must contain the specified field and the value should be less + * than the specified value. + * + * @param[in] field The path of the field to compare. + * @param[in] value The value for comparison. + * + * @return The created Query. + */ + virtual Query WhereLessThan(const FieldPath& field, + const FieldValue& value) const; + + /** + * @brief Creates and returns a new Query with the additional filter that + * documents must contain the specified field and the value should be less + * than or equal to the specified value. + * + * @param[in] field The name of the field to compare. + * @param[in] value The value for comparison. + * + * @return The created Query. + */ + virtual Query WhereLessThanOrEqualTo(const std::string& field, + const FieldValue& value) const; + + /** + * @brief Creates and returns a new Query with the additional filter that + * documents must contain the specified field and the value should be less + * than or equal to the specified value. + * + * @param[in] field The path of the field to compare. + * @param[in] value The value for comparison. + * + * @return The created Query. + */ + virtual Query WhereLessThanOrEqualTo(const FieldPath& field, + const FieldValue& value) const; + + /** + * @brief Creates and returns a new Query with the additional filter that + * documents must contain the specified field and the value should be greater + * than the specified value. + * + * @param[in] field The name of the field to compare. + * @param[in] value The value for comparison. + * + * @return The created Query. + */ + virtual Query WhereGreaterThan(const std::string& field, + const FieldValue& value) const; + + /** + * @brief Creates and returns a new Query with the additional filter that + * documents must contain the specified field and the value should be greater + * than the specified value. + * + * @param[in] field The path of the field to compare. + * @param[in] value The value for comparison. + * + * @return The created Query. + */ + virtual Query WhereGreaterThan(const FieldPath& field, + const FieldValue& value) const; + + /** + * @brief Creates and returns a new Query with the additional filter that + * documents must contain the specified field and the value should be greater + * than or equal to the specified value. + * + * @param[in] field The name of the field to compare. + * @param[in] value The value for comparison. + * + * @return The created Query. + */ + virtual Query WhereGreaterThanOrEqualTo(const std::string& field, + const FieldValue& value) const; + + /** + * @brief Creates and returns a new Query with the additional filter that + * documents must contain the specified field and the value should be greater + * than or equal to the specified value. + * + * @param[in] field The path of the field to compare. + * @param[in] value The value for comparison. + * + * @return The created Query. + */ + virtual Query WhereGreaterThanOrEqualTo(const FieldPath& field, + const FieldValue& value) const; + + /** + * @brief Creates and returns a new Query with the additional filter that + * documents must contain the specified field, the value must be an array, and + * that the array must contain the provided value. + * + * A Query can have only one `WhereArrayContains()` filter and it cannot be + * combined with `WhereArrayContainsAny()` or `WhereIn()`. + * + * @param[in] field The name of the field containing an array to search. + * @param[in] value The value that must be contained in the array. + * + * @return The created Query. + */ + virtual Query WhereArrayContains(const std::string& field, + const FieldValue& value) const; + + /** + * @brief Creates and returns a new Query with the additional filter that + * documents must contain the specified field, the value must be an array, and + * that the array must contain the provided value. + * + * A Query can have only one `WhereArrayContains()` filter and it cannot be + * combined with `WhereArrayContainsAny()` or `WhereIn()`. + * + * @param[in] field The path of the field containing an array to search. + * @param[in] value The value that must be contained in the array. + * + * @return The created Query. + */ + virtual Query WhereArrayContains(const FieldPath& field, + const FieldValue& value) const; + + /** + * @brief Creates and returns a new Query with the additional filter that + * documents must contain the specified field, the value must be an array, and + * that the array must contain at least one value from the provided list. + * + * A Query can have only one `WhereArrayContainsAny()` filter and it cannot be + * combined with `WhereArrayContains()` or `WhereIn()`. + * + * @param[in] field The name of the field containing an array to search. + * @param[in] values The list that contains the values to match. + * + * @return The created Query. + */ + virtual Query WhereArrayContainsAny( + const std::string& field, const std::vector& values) const; + + /** + * @brief Creates and returns a new Query with the additional filter that + * documents must contain the specified field, the value must be an array, and + * that the array must contain at least one value from the provided list. + * + * A Query can have only one `WhereArrayContainsAny()` filter and it cannot be + * combined with` WhereArrayContains()` or `WhereIn()`. + * + * @param[in] field The path of the field containing an array to search. + * @param[in] values The list that contains the values to match. + * + * @return The created Query. + */ + virtual Query WhereArrayContainsAny( + const FieldPath& field, const std::vector& values) const; + + /** + * @brief Creates and returns a new Query with the additional filter that + * documents must contain the specified field and the value must equal one of + * the values from the provided list. + * + * A Query can have only one `WhereIn()` filter and it cannot be + * combined with `WhereArrayContainsAny()`. + * + * @param[in] field The name of the field containing an array to search. + * @param[in] values The list that contains the values to match. + * + * @return The created Query. + */ + virtual Query WhereIn(const std::string& field, + const std::vector& values) const; + + /** + * @brief Creates and returns a new Query with the additional filter that + * documents must contain the specified field and the value must equal one of + * the values from the provided list. + * + * A Query can have only one `WhereIn()` filter and it cannot be + * combined with `WhereArrayContainsAny()`. + * + * @param[in] field The path of the field containing an array to search. + * @param[in] values The list that contains the values to match. + * + * @return The created Query. + */ + virtual Query WhereIn(const FieldPath& field, + const std::vector& values) const; + + /** + * @brief Creates and returns a new Query with the additional filter that + * documents must contain the specified field and the value must not equal any + * of the values from the provided list. + * + * One special case is that `WhereNotIn` cannot match `FieldValue::Null()` + * values. To query for documents where a field exists and is + * `FieldValue::Null()`, use `WhereNotEqualTo`, which can handle this special + * case. + * + * A `Query` can have only one `WhereNotIn()` filter, and it cannot be + * combined with `WhereArrayContains()`, `WhereArrayContainsAny()`, + * `WhereIn()`, or `WhereNotEqualTo()`. + * + * @param[in] field The name of the field containing an array to search. + * @param[in] values The list that contains the values to match. + * + * @return The created Query. + */ + virtual Query WhereNotIn(const std::string& field, + const std::vector& values) const; + + /** + * @brief Creates and returns a new Query with the additional filter that + * documents must contain the specified field and the value must not equal any + * of the values from the provided list. + * + * One special case is that `WhereNotIn` cannot match `FieldValue::Null()` + * values. To query for documents where a field exists and is + * `FieldValue::Null()`, use `WhereNotEqualTo`, which can handle this special + * case. + * + * A `Query` can have only one `WhereNotIn()` filter, and it cannot be + * combined with `WhereArrayContains()`, `WhereArrayContainsAny()`, + * `WhereIn()`, or `WhereNotEqualTo()`. + * + * @param[in] field The path of the field containing an array to search. + * @param[in] values The list that contains the values to match. + * + * @return The created Query. + */ + virtual Query WhereNotIn(const FieldPath& field, + const std::vector& values) const; + + /** + * @brief Creates and returns a new Query that's additionally sorted by the + * specified field. + * + * @param[in] field The field to sort by. + * @param[in] direction The direction to sort (optional). If not specified, + * order will be ascending. + * + * @return The created Query. + */ + virtual Query OrderBy(const std::string& field, + Direction direction = Direction::kAscending) const; + + /** + * @brief Creates and returns a new Query that's additionally sorted by the + * specified field. + * + * @param[in] field The field to sort by. + * @param[in] direction The direction to sort (optional). If not specified, + * order will be ascending. + * + * @return The created Query. + */ + virtual Query OrderBy(const FieldPath& field, + Direction direction = Direction::kAscending) const; + + /** + * @brief Creates and returns a new Query that only returns the first matching + * documents up to the specified number. + * + * @param[in] limit A non-negative integer to specify the maximum number of + * items to return. + * + * @return The created Query. + */ + virtual Query Limit(int32_t limit) const; + + /** + * @brief Creates and returns a new Query that only returns the last matching + * documents up to the specified number. + * + * @param[in] limit A non-negative integer to specify the maximum number of + * items to return. + * + * @return The created Query. + */ + virtual Query LimitToLast(int32_t limit) const; + + /** + * @brief Creates and returns a new Query that starts at the provided document + * (inclusive). The starting position is relative to the order of the query. + * The document must contain all of the fields provided in the order by of + * this query. + * + * @param[in] snapshot The snapshot of the document to start at. + * + * @return The created Query. + */ + virtual Query StartAt(const DocumentSnapshot& snapshot) const; + + /** + * @brief Creates and returns a new Query that starts at the provided fields + * relative to the order of the query. The order of the field values must + * match the order of the order by clauses of the query. + * + * @param[in] values The field values to start this query at, in order of the + * query's order by. + * + * @return The created Query. + */ + virtual Query StartAt(const std::vector& values) const; + + /** + * @brief Creates and returns a new Query that starts after the provided + * document (inclusive). The starting position is relative to the order of the + * query. The document must contain all of the fields provided in the order by + * of this query. + * + * @param[in] snapshot The snapshot of the document to start after. + * + * @return The created Query. + */ + virtual Query StartAfter(const DocumentSnapshot& snapshot) const; + + /** + * @brief Creates and returns a new Query that starts after the provided + * fields relative to the order of the query. The order of the field values + * must match the order of the order by clauses of the query. + * + * @param[in] values The field values to start this query after, in order of + * the query's order by. + * + * @return The created Query. + */ + virtual Query StartAfter(const std::vector& values) const; + + /** + * @brief Creates and returns a new Query that ends before the provided + * document (inclusive). The end position is relative to the order of the + * query. The document must contain all of the fields provided in the order by + * of this query. + * + * @param[in] snapshot The snapshot of the document to end before. + * + * @return The created Query. + */ + virtual Query EndBefore(const DocumentSnapshot& snapshot) const; + + /** + * @brief Creates and returns a new Query that ends before the provided fields + * relative to the order of the query. The order of the field values must + * match the order of the order by clauses of the query. + * + * @param[in] values The field values to end this query before, in order of + * the query's order by. + * + * @return The created Query. + */ + virtual Query EndBefore(const std::vector& values) const; + + /** + * @brief Creates and returns a new Query that ends at the provided document + * (inclusive). The end position is relative to the order of the query. The + * document must contain all of the fields provided in the order by of this + * query. + * + * @param[in] snapshot The snapshot of the document to end at. + * + * @return The created Query. + */ + virtual Query EndAt(const DocumentSnapshot& snapshot) const; + + /** + * @brief Creates and returns a new Query that ends at the provided fields + * relative to the order of the query. The order of the field values must + * match the order of the order by clauses of the query. + * + * @param[in] values The field values to end this query at, in order of the + * query's order by. + * + * @return The created Query. + */ + virtual Query EndAt(const std::vector& values) const; + + /** + * @brief Executes the query and returns the results as a QuerySnapshot. + * + * By default, Get() attempts to provide up-to-date data when possible by + * waiting for data from the server, but it may return cached data or fail if + * you are offline and the server cannot be reached. This behavior can be + * altered via the Source parameter. + * + * @param[in] source A value to configure the get behavior (optional). + * + * @return A Future that will be resolved with the results of the Query. + */ + virtual Future Get(Source source = Source::kDefault) const; + + /** + * @brief Starts listening to the QuerySnapshot events referenced by this + * query. + * + * @param[in] callback The std::function to call. When this function is + * called, snapshot value is valid if and only if error is Error::kErrorOk. + * The std::string is an error message; the value may be empty if an error + * message is not available. + * + * @return A registration object that can be used to remove the listener. + */ + virtual ListenerRegistration AddSnapshotListener( + std::function + callback); + + /** + * @brief Starts listening to the QuerySnapshot events referenced by this + * query. + * + * @param[in] metadata_changes Indicates whether metadata-only changes (that + * is, only DocumentSnapshot::metadata() changed) should trigger snapshot + * events. + * @param[in] callback The std::function to call. When this function is + * called, snapshot value is valid if and only if error is Error::kErrorOk. + * The std::string is an error message; the value may be empty if an error + * message is not available. + * + * @return A registration object that can be used to remove the listener. + */ + virtual ListenerRegistration AddSnapshotListener( + MetadataChanges metadata_changes, + std::function + callback); + + /** + * @brief Returns true if this `Query` is valid, false if it is not valid. An + * invalid `Query` could be the result of: + * - Creating a `Query` using the default constructor. + * - Moving from the `Query`. + * - Deleting your Firestore instance, which will invalidate all the `Query` + * instances associated with it. + * + * @return true if this `Query` is valid, false if this `Query` is invalid. + */ + bool is_valid() const { return internal_ != nullptr; } + + private: + size_t Hash() const; + + friend bool operator==(const Query& lhs, const Query& rhs); + friend size_t QueryHash(const Query& query); + + friend class FirestoreInternal; + friend class QueryInternal; + friend class QuerySnapshotInternal; + friend struct ConverterImpl; + template + friend struct CleanupFn; + // For access to the constructor and to `internal_`. + friend class CollectionReference; + + explicit Query(QueryInternal* internal); + + mutable QueryInternal* internal_ = nullptr; +}; + +/** Checks `lhs` and `rhs` for equality. */ +bool operator==(const Query& lhs, const Query& rhs); + +/** Checks `lhs` and `rhs` for inequality. */ +inline bool operator!=(const Query& lhs, const Query& rhs) { + return !(lhs == rhs); +} + +} // namespace firestore +} // namespace firebase + +#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_QUERY_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/query_snapshot.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/query_snapshot.h new file mode 100644 index 000000000000..2dcf7aaf5239 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/query_snapshot.h @@ -0,0 +1,194 @@ +/* + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_QUERY_SNAPSHOT_H_ +#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_QUERY_SNAPSHOT_H_ + +#include +#include + +#include "firebase/firestore/metadata_changes.h" +#include "firebase/firestore/snapshot_metadata.h" + +namespace firebase { +namespace firestore { + +class DocumentChange; +class DocumentSnapshot; +class Query; +class QuerySnapshotInternal; + +/** + * @brief A QuerySnapshot contains zero or more DocumentSnapshot objects. + * + * QuerySnapshot can be iterated using a range-based for loop, and its size can + * be inspected with empty() and size(). + * + * @note Firestore classes are not meant to be subclassed except for use in test + * mocks. Subclassing is not supported in production code and new SDK releases + * may break code that does so. + */ +class QuerySnapshot { + public: + /** + * @brief Creates an invalid QuerySnapshot that has to be reassigned before it + * can be used. + * + * Calling any member function on an invalid QuerySnapshot will be a no-op. If + * the function returns a value, it will return a zero, empty, or invalid + * value, depending on the type of the value. + */ + QuerySnapshot(); + + /** + * @brief Copy constructor. + * + * `QuerySnapshot` is immutable and can be efficiently copied (no deep copy is + * performed). + * + * @param[in] other `QuerySnapshot` to copy from. + */ + QuerySnapshot(const QuerySnapshot& other); + + /** + * @brief Move constructor. + * + * Moving is more efficient than copying for a `QuerySnapshot`. After being + * moved from, a `QuerySnapshot` is equivalent to its default-constructed + * state. + * + * @param[in] other `QuerySnapshot` to move data from. + */ + QuerySnapshot(QuerySnapshot&& other); + + virtual ~QuerySnapshot(); + + /** + * @brief Copy assignment operator. + * + * `QuerySnapshot` is immutable and can be efficiently copied (no deep copy is + * performed). + * + * @param[in] other `QuerySnapshot` to copy from. + * + * @return Reference to the destination `QuerySnapshot`. + */ + QuerySnapshot& operator=(const QuerySnapshot& other); + + /** + * @brief Move assignment operator. + * + * Moving is more efficient than copying for a `QuerySnapshot`. After being + * moved from, a `QuerySnapshot` is equivalent to its default-constructed + * state. + * + * @param[in] other `QuerySnapshot` to move data from. + * + * @return Reference to the destination `QuerySnapshot`. + */ + QuerySnapshot& operator=(QuerySnapshot&& other); + + /** + * @brief The query from which you got this QuerySnapshot. + */ + virtual Query query() const; + + /** + * @brief Metadata about this snapshot, concerning its source and if it has + * local modifications. + * + * @return The metadata for this document snapshot. + */ + virtual SnapshotMetadata metadata() const; + + /** + * @brief The list of documents that changed since the last snapshot. + * + * If it's the first snapshot, all documents will be in the list as added + * changes. Documents with changes only to their metadata will not be + * included. + * + * @param[in] metadata_changes Indicates whether metadata-only changes (that + * is, only QuerySnapshot::metadata() changed) should be included. + * + * @return The list of document changes since the last snapshot. + */ + virtual std::vector DocumentChanges( + MetadataChanges metadata_changes = MetadataChanges::kExclude) const; + + /** + * @brief The list of documents in this QuerySnapshot in order of the query. + * + * @return The list of documents. + */ + virtual std::vector documents() const; + + /** + * @brief Checks the emptiness of the QuerySnapshot. + * + * @return True if there are no documents in the QuerySnapshot. + */ + bool empty() const { return size() == 0; } + + /** + * @brief Checks the size of the QuerySnapshot. + * + * @return The number of documents in the QuerySnapshot. + */ + virtual std::size_t size() const; + + /** + * @brief Returns true if this `QuerySnapshot` is valid, false if it is not + * valid. An invalid `QuerySnapshot` could be the result of: + * - Creating a `QuerySnapshot` using the default constructor. + * - Moving from the `QuerySnapshot`. + * - Deleting your Firestore instance, which will invalidate all the + * `QuerySnapshot` instances associated with it. + * + * @return true if this `QuerySnapshot` is valid, false if this + * `QuerySnapshot` is invalid. + */ + bool is_valid() const { return internal_ != nullptr; } + + private: + std::size_t Hash() const; + + friend bool operator==(const QuerySnapshot& lhs, const QuerySnapshot& rhs); + friend std::size_t QuerySnapshotHash(const QuerySnapshot& snapshot); + + friend class EventListenerInternal; + friend class FirestoreInternal; + friend struct ConverterImpl; + template + friend struct CleanupFn; + + explicit QuerySnapshot(QuerySnapshotInternal* internal); + + mutable QuerySnapshotInternal* internal_ = nullptr; +}; + +/** Checks `lhs` and `rhs` for equality. */ +bool operator==(const QuerySnapshot& lhs, const QuerySnapshot& rhs); + +/** Checks `lhs` and `rhs` for inequality. */ +inline bool operator!=(const QuerySnapshot& lhs, const QuerySnapshot& rhs) { + return !(lhs == rhs); +} + +} // namespace firestore +} // namespace firebase + +#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_QUERY_SNAPSHOT_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/set_options.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/set_options.h new file mode 100644 index 000000000000..bf21b07a0c45 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/set_options.h @@ -0,0 +1,161 @@ +/* + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_SET_OPTIONS_H_ +#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_SET_OPTIONS_H_ + +#include +#include +#include + +#include "firebase/firestore/field_path.h" + +namespace firebase { +namespace firestore { + +/** + * @brief An options object that configures the behavior of Set() calls. + * + * By providing the SetOptions objects returned by Merge(), the Set() methods in + * DocumentReference, WriteBatch and Transaction can be configured to perform + * granular merges instead of overwriting the target documents in their + * entirety. + */ +class SetOptions final { + public: + /** The enumeration of all types of SetOptions. */ + enum class Type { + /** Overwrites the whole document. */ + kOverwrite, + + /** + * Replaces the values specified in the call parameter while leaves omitted + * fields untouched. + */ + kMergeAll, + + /** + * Replaces the values of the fields explicitly specified in the call + * parameter. + */ + kMergeSpecific, + }; + + /** + * Creates SetOptions with overwrite semantics. + */ + SetOptions() = default; + + /** + * @brief Copy constructor. + * + * This performs a deep copy, creating an independent instance. + * + * @param[in] other `SetOptions` to copy from. + */ + SetOptions(const SetOptions& other) = default; + + /** + * @brief Move constructor. + * + * Moving is more efficient than copying for `SetOptions`. After being moved + * from, `SetOptions` is in a valid but unspecified state. + * + * @param[in] other `SetOptions` to move data from. + */ + SetOptions(SetOptions&& other) = default; + + ~SetOptions(); + + /** + * @brief Copy assignment operator. + * + * This performs a deep copy, creating an independent instance. + * + * @param[in] other `SetOptions` to copy from. + * + * @return Reference to the destination `SetOptions`. + */ + SetOptions& operator=(const SetOptions& other) = default; + + /** + * @brief Move assignment operator. + * + * Moving is more efficient than copying for `SetOptions`. After being moved + * from, `SetOptions` is in a valid but unspecified state. + * + * @param[in] other `SetOptions` to move data from. + * + * @return Reference to the destination `SetOptions`. + */ + SetOptions& operator=(SetOptions&& other) = default; + + /** + * Returns an instance that can be used to change the behavior of Set() calls + * to only replace the values specified in its data argument. Fields omitted + * from the Set() call will remain untouched. + */ + static SetOptions Merge(); + + /** + * Returns an instance that can be used to change the behavior of Set() calls + * to only replace the given fields. Any field that is not specified in + * `fields` is ignored and remains untouched. + * + * It is an error to pass a SetOptions object to a Set() call that is missing + * a value for any of the fields specified here. + * + * @param fields The list of fields to merge. Fields can contain dots to + * reference nested fields within the document. + */ + static SetOptions MergeFields(const std::vector& fields); + + /** + * Returns an instance that can be used to change the behavior of Set() calls + * to only replace the given fields. Any field that is not specified in + * `fields` is ignored and remains untouched. + * + * It is an error to pass a SetOptions object to a Set() call that is missing + * a value for any of the fields specified here in its to data argument. + * + * @param fields The list of fields to merge. + */ + static SetOptions MergeFieldPaths(const std::vector& fields); + + private: + friend bool operator==(const SetOptions& lhs, const SetOptions& rhs); + friend class SetOptionsInternal; + + SetOptions(Type type, std::unordered_set fields); + + Type type_ = Type::kOverwrite; + std::unordered_set fields_; +}; + +/** Checks `lhs` and `rhs` for equality. */ +inline bool operator==(const SetOptions& lhs, const SetOptions& rhs) { + return lhs.type_ == rhs.type_ && lhs.fields_ == rhs.fields_; +} + +/** Checks `lhs` and `rhs` for inequality. */ +inline bool operator!=(const SetOptions& lhs, const SetOptions& rhs) { + return !(lhs == rhs); +} + +} // namespace firestore +} // namespace firebase + +#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_SET_OPTIONS_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/settings.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/settings.h new file mode 100644 index 000000000000..8169d9f594e8 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/settings.h @@ -0,0 +1,247 @@ +/* + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_SETTINGS_H_ +#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_SETTINGS_H_ + +#if defined(__OBJC__) +#include +#endif + +#include +#include +#include +#include + +namespace firebase { +namespace firestore { + +#if !defined(__ANDROID__) +// +// This declaration is guarded by a preprocessor macro because it causes +// problems with name lookup on Android. Android implementation of the public +// API extensively uses function calls of the form `util::Foo` which are +// expected to resolve to `::firebase::util::Foo`. As soon as namespace +// `::firebase::firestore::util` becomes visible, it shadows `::firebase::util` +// (within `::firebase::firestore`), so now all those calls fail to compile +// because they are interpreted as referring to +// `::firebase::firestore::util::Foo`, which doesn't exist. Changing existing +// code is impractical because such usages are numerous. +// +namespace util { +class Executor; +} +#endif + +class FirestoreInternal; + +/** Settings used to configure a Firestore instance. */ +class Settings final { + public: + /** + * Constant to use with `set_cache_size_bytes` to disable garbage collection. + */ + static constexpr int64_t kCacheSizeUnlimited = -1; + + /** + * @brief Creates the default settings. + */ + Settings(); + + /** + * @brief Copy constructor. + * + * This performs a deep copy, creating an independent instance. + * + * @param[in] other `Settings` to copy from. + */ + Settings(const Settings& other) = default; + + /** + * @brief Move constructor. + * + * Moving is more efficient than copying for `Settings`. After being moved + * from, `Settings` is in a valid but unspecified state. + * + * @param[in] other `Settings` to move data from. + */ + Settings(Settings&& other) = default; + + /** + * @brief Copy assignment operator. + * + * This performs a deep copy, creating an independent instance. + * + * @param[in] other `Settings` to copy from. + * + * @return Reference to the destination `Settings`. + */ + Settings& operator=(const Settings& other) = default; + + /** + * @brief Move assignment operator. + * + * Moving is more efficient than copying for `Settings`. After being moved + * from, `Settings` is in a valid but unspecified state. + * + * @param[in] other `Settings` to move data from. + * + * @return Reference to the destination `Settings`. + */ + Settings& operator=(Settings&& other) = default; + + /** + * Gets the host of the Firestore backend to connect to. + */ + const std::string& host() const { return host_; } + + /** + * Returns whether to use SSL when communicating. + */ + bool is_ssl_enabled() const { return ssl_enabled_; } + + /** + * Returns whether to enable local persistent storage. + */ + bool is_persistence_enabled() const { return persistence_enabled_; } + + /** Returns cache size for on-disk data. */ + int64_t cache_size_bytes() const { return cache_size_bytes_; } + + /** + * Sets the host of the Firestore backend. The default is + * "firestore.googleapis.com". + * + * @param host The host string. + */ + void set_host(std::string host); + + /** + * Enables or disables SSL for communication. + * + * @param enabled Set true to enable SSL for communication. + */ + void set_ssl_enabled(bool enabled); + + /** + * Enables or disables local persistent storage. + * + * @param enabled Set true to enable local persistent storage. + */ + void set_persistence_enabled(bool enabled); + + /** + * Sets an approximate cache size threshold for the on-disk data. If the cache + * grows beyond this size, Cloud Firestore will start removing data that + * hasn't been recently used. The size is not a guarantee that the cache will + * stay below that size, only that if the cache exceeds the given size, + * cleanup will be attempted. + * + * By default, collection is enabled with a cache size of 100 MB. The minimum + * value is 1 MB. + */ + void set_cache_size_bytes(int64_t value); + +#if defined(__OBJC__) || defined(DOXYGEN) + /** + * Returns a dispatch queue that Firestore will use to execute callbacks. + * + * The returned dispatch queue is used for all completion handlers and event + * handlers. + * + * If no dispatch queue is explictly set by calling `set_dispatch_queue()` + * then a dedicated "callback queue" will be used; namely, the main thread + * will not be used for callbacks unless expliclty set to do so by a call to + * `set_dispatch_queue()`. + * + * @note This method is only available when `__OBJC__` is defined, such as + * when compiling for iOS or tvOS. + * + * @see `set_dispatch_queue(dispatch_queue_t)` for information on how to + * explicitly set the dispatch queue to use. + */ + dispatch_queue_t dispatch_queue() const; + + /** + * Sets the dispatch queue that Firestore will use to execute callbacks. + * + * The specified dispatch queue will be used for all completion handlers and + * event handlers. + * + * @param queue The dispatch queue to use. + * + * @note This method is only available when `__OBJC__` is defined, such as + * when compiling for iOS or tvOS. + * + * @see `dispatch_queue()` for the "get" counterpart to this method. + */ + void set_dispatch_queue(dispatch_queue_t queue); +#endif // defined(__OBJC__) || defined(DOXYGEN) + + /** + * Returns a string representation of these `Settings` for + * logging/debugging purposes. + * + * @note the exact string representation is unspecified and subject to + * change; don't rely on the format of the string. + */ + std::string ToString() const; + + /** + * Outputs the string representation of these `Settings` to the given + * stream. + * + * @see `ToString()` for comments on the representation format. + */ + friend std::ostream& operator<<(std::ostream& out, const Settings& settings); + + private: + static constexpr int64_t kDefaultCacheSizeBytes = 100 * 1024 * 1024; + + std::string host_; + bool ssl_enabled_ = true; + bool persistence_enabled_ = true; + int64_t cache_size_bytes_ = kDefaultCacheSizeBytes; + + // + // TODO(varconst): fix Android problems and make these declarations + // unconditional. + // +#if !defined(__ANDROID__) + friend class FirestoreInternal; + std::unique_ptr CreateExecutor() const; + + std::shared_ptr executor_; +#endif +}; + +/** Checks `lhs` and `rhs` for equality. */ +inline bool operator==(const Settings& lhs, const Settings& rhs) { + return lhs.host() == rhs.host() && + lhs.is_ssl_enabled() == rhs.is_ssl_enabled() && + lhs.is_persistence_enabled() == rhs.is_persistence_enabled() && + lhs.cache_size_bytes() == rhs.cache_size_bytes(); +} + +/** Checks `lhs` and `rhs` for inequality. */ +inline bool operator!=(const Settings& lhs, const Settings& rhs) { + return !(lhs == rhs); +} + +} // namespace firestore +} // namespace firebase + +#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_SETTINGS_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/snapshot_metadata.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/snapshot_metadata.h new file mode 100644 index 000000000000..ce7f3f2b8607 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/snapshot_metadata.h @@ -0,0 +1,159 @@ +/* + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_SNAPSHOT_METADATA_H_ +#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_SNAPSHOT_METADATA_H_ + +#include +#include + +namespace firebase { +namespace firestore { + +/** Metadata about a snapshot, describing the state of the snapshot. */ +class SnapshotMetadata final { + public: + /** + * Constructs a SnapshotMetadata that has all of its boolean members set to + * false. + */ + SnapshotMetadata() = default; + + /** + * Constructs a SnapshotMetadata by providing boolean parameters that describe + * the state of the snapshot. + * + * @param has_pending_writes Whether there is any pending write on the + * snapshot. + * @param is_from_cache Whether the snapshot is from cache instead of backend. + */ + SnapshotMetadata(bool has_pending_writes, bool is_from_cache) + : has_pending_writes_(has_pending_writes), + is_from_cache_(is_from_cache) {} + + /** + * @brief Copy constructor. + * + * This performs a deep copy, creating an independent instance. + * + * @note This class is currently trivially copyable, but it is not guaranteed + * to stay that way, and code relying on this might be broken by a future + * release. + * + * @param[in] other `SnapshotMetadata` to copy from. + */ + SnapshotMetadata(const SnapshotMetadata& other) = default; + + /** + * @brief Move constructor, equivalent to copying. + * + * After being moved from, `SnapshotMetadata` is in a valid but unspecified + * state. + * + * @param[in] other `SnapshotMetadata` to move data from. + */ + SnapshotMetadata(SnapshotMetadata&& other) = default; + + /** + * @brief Copy assignment operator. + * + * This performs a deep copy, creating an independent instance. + * + * @note This class is currently trivially copyable, but it is not guaranteed + * to stay that way, and code relying on this might be broken by a future + * release. + * + * @param[in] other `SnapshotMetadata` to copy from. + * + * @return Reference to the destination `SnapshotMetadata`. + */ + SnapshotMetadata& operator=(const SnapshotMetadata& other) = default; + + /** + * @brief Move assignment operator, equivalent to copying. + * + * After being moved from, `SnapshotMetadata` is in a valid but unspecified + * state. + * + * @param[in] other `SnapshotMetadata` to move data from. + * + * @return Reference to the destination `SnapshotMetadata`. + */ + SnapshotMetadata& operator=(SnapshotMetadata&& other) = default; + + /** + * Returns whether the snapshot contains the result of local writes. + * + * @return true if the snapshot contains the result of local writes (for + * example, Set() or Update() calls) that have not yet been committed to the + * backend. If your listener has opted into metadata updates (via + * MetadataChanges::kInclude) you will receive another snapshot with + * has_pending_writes() equal to false once the writes have been committed to + * the backend. + */ + bool has_pending_writes() const { return has_pending_writes_; } + + /** + * Returns whether the snapshot was created from cached data. + * + * @return true if the snapshot was created from cached data rather than + * guaranteed up-to-date server data. If your listener has opted into metadata + * updates (via MetadataChanges::kInclude) you will receive another snapshot + * with is_from_cache() equal to false once the client has received up-to-date + * data from the backend. + */ + bool is_from_cache() const { return is_from_cache_; } + + /** + * Returns a string representation of this `SnapshotMetadata` for + * logging/debugging purposes. + * + * @note the exact string representation is unspecified and subject to + * change; don't rely on the format of the string. + */ + std::string ToString() const; + + /** + * Outputs the string representation of this `SnapshotMetadata` to the given + * stream. + * + * @see `ToString()` for comments on the representation format. + */ + friend std::ostream& operator<<(std::ostream& out, + const SnapshotMetadata& metadata); + + private: + bool has_pending_writes_ = false; + bool is_from_cache_ = false; +}; + +/** Checks `lhs` and `rhs` for equality. */ +inline bool operator==(const SnapshotMetadata& lhs, + const SnapshotMetadata& rhs) { + return lhs.has_pending_writes() == rhs.has_pending_writes() && + lhs.is_from_cache() == rhs.is_from_cache(); +} + +/** Checks `lhs` and `rhs` for inequality. */ +inline bool operator!=(const SnapshotMetadata& lhs, + const SnapshotMetadata& rhs) { + return !(lhs == rhs); +} + +} // namespace firestore +} // namespace firebase + +#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_SNAPSHOT_METADATA_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/source.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/source.h new file mode 100644 index 000000000000..743106d9e578 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/source.h @@ -0,0 +1,59 @@ +/* + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_SOURCE_H_ +#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_SOURCE_H_ + +namespace firebase { +namespace firestore { + +/** + * @brief Configures the behavior of DocumentReference::Get() and Query::Get(). + * + * By providing a Source value, these methods can be configured to fetch results + * only from the server, only from the local cache, or attempt to fetch results + * from the server and fall back to the cache (which is the default). + */ +enum class Source { + /** + * Causes Firestore to try to retrieve an up-to-date (server-retrieved) + * snapshot, but fall back to returning cached data if the server can't be + * reached. + */ + kDefault, + + /** + * Causes Firestore to avoid the cache, generating an error if the server + * cannot be reached. Note that the cache will still be updated if the server + * request succeeds. Also note that latency-compensation still takes effect, + * so any pending write operations will be visible in the returned data + * (merged into the server-provided data). + */ + kServer, + + /** + * Causes Firestore to immediately return a value from the cache, ignoring the + * server completely (implying that the returned value may be stale with + * respect to the value on the server). If there is no data in the cache to + * satisfy the DocumentReference::Get() call will return an error and + * Query::Get() will return an empty QuerySnapshot with no documents. + */ + kCache, +}; + +} // namespace firestore +} // namespace firebase +#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_SOURCE_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/timestamp.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/timestamp.h new file mode 100644 index 000000000000..e806bb87c136 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/timestamp.h @@ -0,0 +1,252 @@ +/* + * Copyright 2018 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIRESTORE_CORE_INCLUDE_FIREBASE_FIRESTORE_TIMESTAMP_H_ +#define FIRESTORE_CORE_INCLUDE_FIREBASE_FIRESTORE_TIMESTAMP_H_ + +#include +#include +#include +#include + +#if !defined(_STLPORT_VERSION) +#include // NOLINT(build/c++11) +#endif // !defined(_STLPORT_VERSION) + +namespace firebase { + +/** + * A Timestamp represents a point in time independent of any time zone or + * calendar, represented as seconds and fractions of seconds at nanosecond + * resolution in UTC Epoch time. It is encoded using the Proleptic Gregorian + * Calendar which extends the Gregorian calendar backwards to year one. It is + * encoded assuming all minutes are 60 seconds long, i.e. leap seconds are + * "smeared" so that no leap second table is needed for interpretation. Range is + * from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.999999999Z. + * + * @see + * https://github.com/google/protobuf/blob/master/src/google/protobuf/timestamp.proto + */ +class Timestamp { + public: + /** + * Creates a new timestamp representing the epoch (with seconds and + * nanoseconds set to 0). + */ + Timestamp() = default; + + /** + * Creates a new timestamp. + * + * @param seconds The number of seconds of UTC time since Unix epoch + * 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to + * 9999-12-31T23:59:59Z inclusive; otherwise, assertion failure will be + * triggered. + * @param nanoseconds The non-negative fractions of a second at nanosecond + * resolution. Negative second values with fractions must still have + * non-negative nanoseconds values that count forward in time. Must be + * from 0 to 999,999,999 inclusive; otherwise, assertion failure will be + * triggered. + */ + Timestamp(int64_t seconds, int32_t nanoseconds); + + /** Copy constructor, `Timestamp` is trivially copyable. */ + Timestamp(const Timestamp& other) = default; + + /** Move constructor, equivalent to copying. */ + Timestamp(Timestamp&& other) = default; + + /** Copy assignment operator, `Timestamp` is trivially copyable. */ + Timestamp& operator=(const Timestamp& other) = default; + + /** Move assignment operator, equivalent to copying. */ + Timestamp& operator=(Timestamp&& other) = default; + + /** + * Creates a new timestamp with the current date. + * + * The precision is up to nanoseconds, depending on the system clock. + * + * @return a new timestamp representing the current date. + */ + static Timestamp Now(); + + /** + * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z. + */ + int64_t seconds() const { + return seconds_; + } + + /** + * The non-negative fractions of a second at nanosecond resolution. Negative + * second values with fractions still have non-negative nanoseconds values + * that count forward in time. + */ + int32_t nanoseconds() const { + return nanoseconds_; + } + + /** + * Converts `time_t` to a `Timestamp`. + * + * @param seconds_since_unix_epoch + * @parblock + * The number of seconds of UTC time since Unix epoch + * 1970-01-01T00:00:00Z. Can be negative to represent dates before the + * epoch. Must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z + * inclusive; otherwise, assertion failure will be triggered. + * + * Note that while the epoch of `time_t` is unspecified, it's usually Unix + * epoch. If this assumption is broken, this function will produce + * incorrect results. + * @endparblock + * + * @return a new timestamp with the given number of seconds and zero + * nanoseconds. + */ + static Timestamp FromTimeT(time_t seconds_since_unix_epoch); + +#if !defined(_STLPORT_VERSION) + /** + * Converts `std::chrono::time_point` to a `Timestamp`. + * + * @param time_point + * @parblock + * The time point with system clock's epoch, which is + * presumed to be Unix epoch 1970-01-01T00:00:00Z. Can be negative to + * represent dates before the epoch. Must be from 0001-01-01T00:00:00Z to + * 9999-12-31T23:59:59Z inclusive; otherwise, assertion failure will be + * triggered. + * + * Note that while the epoch of `std::chrono::system_clock` is + * unspecified, it's usually Unix epoch. If this assumption is broken, + * this constructor will produce incorrect results. + * @endparblock + */ + static Timestamp FromTimePoint( + std::chrono::time_point time_point); + + /** + * Converts this `Timestamp` to a `time_point`. + * + * Important: if overflow would occur, the returned value will be the maximum + * or minimum value that `Duration` can hold. Note in particular that `long + * long` is insufficient to hold the full range of `Timestamp` values with + * nanosecond precision (which is why `Duration` defaults to `microseconds`). + */ + template + std::chrono::time_point ToTimePoint() const; +#endif // !defined(_STLPORT_VERSION) + + /** + * Returns a string representation of this `Timestamp` for logging/debugging + * purposes. + * + * @note: the exact string representation is unspecified and subject to + * change; don't rely on the format of the string. + */ + std::string ToString() const; + + /** + * Outputs the string representation of this `Timestamp` to the given stream. + * + * @see `ToString()` for comments on the representation format. + */ + friend std::ostream& operator<<(std::ostream& out, + const Timestamp& timestamp); + + private: + // Checks that the number of seconds is within the supported date range, and + // that nanoseconds satisfy 0 <= ns <= 1second. + void ValidateBounds() const; + + int64_t seconds_ = 0; + int32_t nanoseconds_ = 0; +}; + +/** Checks whether `lhs` and `rhs` are in ascending order. */ +inline bool operator<(const Timestamp& lhs, const Timestamp& rhs) { + return lhs.seconds() < rhs.seconds() || + (lhs.seconds() == rhs.seconds() && + lhs.nanoseconds() < rhs.nanoseconds()); +} + +/** Checks whether `lhs` and `rhs` are in descending order. */ +inline bool operator>(const Timestamp& lhs, const Timestamp& rhs) { + return rhs < lhs; +} + +/** Checks whether `lhs` and `rhs` are in non-ascending order. */ +inline bool operator>=(const Timestamp& lhs, const Timestamp& rhs) { + return !(lhs < rhs); +} + +/** Checks whether `lhs` and `rhs` are in non-descending order. */ +inline bool operator<=(const Timestamp& lhs, const Timestamp& rhs) { + return !(lhs > rhs); +} + +/** Checks `lhs` and `rhs` for inequality. */ +inline bool operator!=(const Timestamp& lhs, const Timestamp& rhs) { + return lhs < rhs || lhs > rhs; +} + +/** Checks `lhs` and `rhs` for equality. */ +inline bool operator==(const Timestamp& lhs, const Timestamp& rhs) { + return !(lhs != rhs); +} + +#if !defined(_STLPORT_VERSION) + +// Make sure the header compiles even when included after `` without +// `NOMINMAX` defined. `push/pop_macro` pragmas are supported by Visual Studio +// as well as Clang and GCC. +#pragma push_macro("min") +#pragma push_macro("max") +#undef min +#undef max + +template +std::chrono::time_point Timestamp::ToTimePoint() const { + namespace chr = std::chrono; + using TimePoint = chr::time_point; + + // Saturate on overflow + const auto max_seconds = chr::duration_cast(Duration::max()); + if (seconds_ > 0 && max_seconds.count() <= seconds_) { + return TimePoint{Duration::max()}; + } + const auto min_seconds = chr::duration_cast(Duration::min()); + if (seconds_ < 0 && min_seconds.count() >= seconds_) { + return TimePoint{Duration::min()}; + } + + const auto seconds = chr::duration_cast(chr::seconds(seconds_)); + const auto nanoseconds = + chr::duration_cast(chr::nanoseconds(nanoseconds_)); + return TimePoint{seconds + nanoseconds}; +} + +#pragma pop_macro("max") +#pragma pop_macro("min") + +#endif // !defined(_STLPORT_VERSION) + +} // namespace firebase + +#endif // FIRESTORE_CORE_INCLUDE_FIREBASE_FIRESTORE_TIMESTAMP_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/transaction.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/transaction.h new file mode 100644 index 000000000000..af78e0a2fb70 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/transaction.h @@ -0,0 +1,143 @@ +/* + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_TRANSACTION_H_ +#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_TRANSACTION_H_ + +#include + +#include "firebase/firestore/firestore_errors.h" +#include "firebase/firestore/map_field_value.h" +#include "firebase/firestore/set_options.h" + +namespace firebase { +namespace firestore { + +class DocumentReference; +class DocumentSnapshot; +class TransactionInternal; + +/** + * @brief Transaction provides methods to read and write data within + * a transaction. + * + * You cannot create a `Transaction` directly; use `Firestore::RunTransaction()` + * function instead. + * + * @note Firestore classes are not meant to be subclassed except for use in test + * mocks. Subclassing is not supported in production code and new SDK releases + * may break code that does so. + */ +class Transaction { + public: + /** Destructor. */ + virtual ~Transaction(); + + /** + * @brief Deleted copy constructor. + * + * A `Transaction` object is only valid for the duration of the callback you + * pass to `Firestore::RunTransaction()` and cannot be copied. + */ + Transaction(const Transaction& other) = delete; + + /** + * @brief Deleted copy assignment operator. + * + * A `Transaction` object is only valid for the duration of the callback you + * pass to `Firestore::RunTransaction()` and cannot be copied. + */ + Transaction& operator=(const Transaction& other) = delete; + + /** + * @brief Writes to the document referred to by the provided reference. + * + * If the document does not yet exist, it will be created. If you pass + * SetOptions, the provided data can be merged into an existing document. + * + * @param[in] document The DocumentReference to overwrite. + * @param[in] data A map of the fields and values to write to the document. + * @param[in] options An object to configure the Set() behavior (optional). + */ + virtual void Set(const DocumentReference& document, + const MapFieldValue& data, + const SetOptions& options = SetOptions()); + + /** + * Updates fields in the document referred to by the provided reference. If no + * document exists yet, the update will fail. + * + * @param[in] document The DocumentReference to update. + * @param[in] data A map of field / value pairs to update. Fields can contain + * dots to reference nested fields within the document. + */ + virtual void Update(const DocumentReference& document, + const MapFieldValue& data); + + /** + * Updates fields in the document referred to by the provided reference. If no + * document exists yet, the update will fail. + * + * @param[in] document The DocumentReference to update. + * @param[in] data A map from FieldPath to FieldValue to update. + */ + virtual void Update(const DocumentReference& document, + const MapFieldPathValue& data); + + /** + * Deletes the document referred to by the provided reference. + * + * @param[in] document The DocumentReference to delete. + */ + virtual void Delete(const DocumentReference& document); + + /** + * Reads the document referred by the provided reference. + * + * @param[in] document The DocumentReference to read. + * @param[out] error_code An out parameter to capture an error, if one + * occurred. + * @param[out] error_message An out parameter to capture error message, if + * any. + * @return The contents of the document at this DocumentReference or invalid + * DocumentSnapshot if there is any error. + */ + virtual DocumentSnapshot Get(const DocumentReference& document, + Error* error_code, + std::string* error_message); + + protected: + /** + * Default constructor, to be used only for mocking a `Transaction`. + */ + Transaction() = default; + + private: + friend class FirestoreInternal; + friend class TransactionInternal; + friend struct ConverterImpl; + template + friend struct CleanupFn; + + explicit Transaction(TransactionInternal* internal); + + mutable TransactionInternal* internal_ = nullptr; +}; + +} // namespace firestore +} // namespace firebase + +#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_TRANSACTION_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/transaction_options.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/transaction_options.h new file mode 100644 index 000000000000..9433578879b3 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/transaction_options.h @@ -0,0 +1,137 @@ +/* + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_TRANSACTION_OPTIONS_H_ +#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_TRANSACTION_OPTIONS_H_ + +#include +#include +#include + +namespace firebase { +namespace firestore { + +/** + * Options to customize transaction behavior for `Firestore.runTransaction()`. + */ +class TransactionOptions final { + public: + /** + * @brief Creates the default `TransactionOptions`. + */ + TransactionOptions() = default; + + /** + * @brief Copy constructor. + * + * This performs a deep copy, creating an independent instance. + * + * @param[in] other `TransactionOptions` to copy from. + */ + TransactionOptions(const TransactionOptions& other) = default; + + /** + * @brief Move constructor. + * + * Moving is not any more efficient than copying for `TransactionOptions` + * because this class is trivially copyable; however, future additions to this + * class may make it not trivially copyable, at which point moving would be + * more efficient than copying. After being moved from, `TransactionOptions` + * is in a valid but unspecified state. + * + * @param[in] other `TransactionOptions` to move data from. + */ + TransactionOptions(TransactionOptions&& other) = default; + + /** + * @brief Copy assignment operator. + * + * This performs a deep copy, creating an independent instance. + * + * @param[in] other `TransactionOptions` to copy from. + * + * @return Reference to the destination `TransactionOptions`. + */ + TransactionOptions& operator=(const TransactionOptions& other) = default; + + /** + * @brief Move assignment operator. + * + * Moving is not any more efficient than copying for `TransactionOptions` + * because this class is trivially copyable; however, future additions to this + * class may make it not trivially copyable, at which point moving would be + * more efficient than copying. After being moved from, `TransactionOptions` + * is in a valid but unspecified state. + * + * @param[in] other `TransactionOptions` to move data from. + * + * @return Reference to the destination `TransactionOptions`. + */ + TransactionOptions& operator=(TransactionOptions&& other) = default; + + /** + * @brief Gets the maximum number of attempts to commit, after which the + * transaction fails. + * + * The default value is 5. + */ + int32_t max_attempts() const { return max_attempts_; } + + /** + * @brief Sets the maximum number of attempts to commit, after which the + * transaction fails. + * + * The default value is 5. + * + * @param[in] max_attempts The maximum number of attempts; must be greater + * than zero. + */ + void set_max_attempts(int32_t max_attempts); + + /** + * Returns a string representation of this `TransactionOptions` object for + * logging/debugging purposes. + * + * @note the exact string representation is unspecified and subject to + * change; don't rely on the format of the string. + */ + std::string ToString() const; + + /** + * Outputs the string representation of this `TransactionOptions` object to + * the given stream. + * + * @see `ToString()` for comments on the representation format. + */ + friend std::ostream& operator<<(std::ostream&, const TransactionOptions&); + + private: + int32_t max_attempts_ = 5; +}; + +/** Compares two `TransactionOptions` objects for equality. */ +bool operator==(const TransactionOptions&, const TransactionOptions&); + +/** Compares two `TransactionOptions` objects for inequality. */ +inline bool operator!=(const TransactionOptions& lhs, + const TransactionOptions& rhs) { + return !(lhs == rhs); +} + +} // namespace firestore +} // namespace firebase + +#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_TRANSACTION_OPTIONS_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/write_batch.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/write_batch.h new file mode 100644 index 000000000000..1e92cd693516 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/write_batch.h @@ -0,0 +1,188 @@ +/* + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_WRITE_BATCH_H_ +#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_WRITE_BATCH_H_ + +#include "firebase/firestore/map_field_value.h" +#include "firebase/firestore/set_options.h" + +namespace firebase { + +/// @cond FIREBASE_APP_INTERNAL +template +class Future; +/// @endcond + +namespace firestore { + +class DocumentReference; +class WriteBatchInternal; + +/** + * @brief A write batch is used to perform multiple writes as a single atomic + * unit. + * + * A WriteBatch object provides methods for adding writes to the write batch. + * None of the writes will be committed (or visible locally) until Commit() is + * called. + * + * Unlike transactions, write batches are persisted offline and therefore are + * preferable when you don't need to condition your writes on read data. + * + * @note Firestore classes are not meant to be subclassed except for use in test + * mocks. Subclassing is not supported in production code and new SDK releases + * may break code that does so. + */ +class WriteBatch { + public: + /** + * @brief Creates an invalid WriteBatch that has to be reassigned before it + * can be used. + * + * Calling any member function on an invalid WriteBatch will be a no-op. If + * the function returns a value, it will return a zero, empty, or invalid + * value, depending on the type of the value. + */ + WriteBatch(); + + /** + * @brief Copy constructor. + * + * This performs a deep copy, creating an independent instance. + * + * @param[in] other `WriteBatch` to copy from. + */ + WriteBatch(const WriteBatch& other); + + /** + * @brief Move constructor. + * + * Moving is more efficient than copying for a `WriteBatch`. After being moved + * from, a `WriteBatch` is equivalent to its default-constructed state. + * + * @param[in] other `WriteBatch` to move data from. + */ + WriteBatch(WriteBatch&& other); + + virtual ~WriteBatch(); + + /** + * @brief Copy assignment operator. + * + * This performs a deep copy, creating an independent instance. + * + * @param[in] other `WriteBatch` to copy from. + * + * @return Reference to the destination `WriteBatch`. + */ + WriteBatch& operator=(const WriteBatch& other); + + /** + * @brief Move assignment operator. + * + * Moving is more efficient than copying for a `WriteBatch`. After being moved + * from, a `WriteBatch` is equivalent to its default-constructed state. + * + * @param[in] other `WriteBatch` to move data from. + * + * @return Reference to the destination `WriteBatch`. + */ + WriteBatch& operator=(WriteBatch&& other); + + /** + * @brief Writes to the document referred to by the provided reference. + * + * If the document does not yet exist, it will be created. If you pass + * SetOptions, the provided data can be merged into an existing document. + * + * @param document The DocumentReference to write to. + * @param data A map of the fields and values to write to the document. + * @param[in] options An object to configure the Set() behavior (optional). + * + * @return This WriteBatch instance. Used for chaining method calls. + */ + virtual WriteBatch& Set(const DocumentReference& document, + const MapFieldValue& data, + const SetOptions& options = SetOptions()); + + /** + * Updates fields in the document referred to by the provided reference. If no + * document exists yet, the update will fail. + * + * @param document The DocumentReference to update. + * @param data A map of field / value pairs to update. Fields can contain dots + * to reference nested fields within the document. + * @return This WriteBatch instance. Used for chaining method calls. + */ + virtual WriteBatch& Update(const DocumentReference& document, + const MapFieldValue& data); + + /** + * Updates fields in the document referred to by the provided reference. If no + * document exists yet, the update will fail. + * + * @param document The DocumentReference to update. + * @param data A map from FieldPath to FieldValue to update. + * @return This WriteBatch instance. Used for chaining method calls. + */ + virtual WriteBatch& Update(const DocumentReference& document, + const MapFieldPathValue& data); + + /** + * Deletes the document referred to by the provided reference. + * + * @param document The DocumentReference to delete. + * @return This WriteBatch instance. Used for chaining method calls. + */ + virtual WriteBatch& Delete(const DocumentReference& document); + + /** + * Commits all of the writes in this write batch as a single atomic unit. + * + * @return A Future that will be resolved when the write finishes. + */ + virtual Future Commit(); + + /** + * @brief Returns true if this `WriteBatch` is valid, false if it is not + * valid. An invalid `WriteBatch` could be the result of: + * - Creating a `WriteBatch` using the default constructor. + * - Moving from the `WriteBatch`. + * - Deleting your Firestore instance, which will invalidate all the + * `WriteBatch` instances associated with it. + * + * @return true if this `WriteBatch` is valid, false if this `WriteBatch` is + * invalid. + */ + bool is_valid() const { return internal_ != nullptr; } + + private: + friend class FirestoreInternal; + friend class WriteBatchInternal; + friend struct ConverterImpl; + template + friend struct CleanupFn; + + explicit WriteBatch(WriteBatchInternal* internal); + + mutable WriteBatchInternal* internal_ = nullptr; +}; + +} // namespace firestore +} // namespace firebase + +#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_WRITE_BATCH_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/functions.h b/packages/firebase_core/firebase_core/firebase_core/firebase/functions.h new file mode 100644 index 000000000000..500a05cc7ae9 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/functions.h @@ -0,0 +1,115 @@ +// Copyright 2017 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef FIREBASE_FUNCTIONS_SRC_INCLUDE_FIREBASE_FUNCTIONS_H_ +#define FIREBASE_FUNCTIONS_SRC_INCLUDE_FIREBASE_FUNCTIONS_H_ + +#include + +#include "firebase/app.h" +#include "firebase/functions/callable_reference.h" +#include "firebase/functions/callable_result.h" +#include "firebase/functions/common.h" + +namespace firebase { + +/// Namespace for the Firebase C++ SDK for Cloud Functions. +namespace functions { + +/// @cond FIREBASE_APP_INTERNAL +namespace internal { +class FunctionsInternal; +} // namespace internal +/// @endcond + +class FunctionsReference; + +#ifndef SWIG +/// @brief Entry point for the Firebase C++ SDK for Cloud Functions. +/// +/// To use the SDK, call firebase::functions::Functions::GetInstance() to +/// obtain an instance of Functions, then use GetHttpsCallable() to obtain +/// references to callable functions. From there you can call them with +/// CallableReference::Call(). +#endif // SWIG +class Functions { + public: + /// @brief Destructor. You may delete an instance of Functions when + /// you are finished using it, to shut down the Functions library. + ~Functions(); + + /// @brief Get an instance of Functions corresponding to the given App. + /// + /// Cloud Functions uses firebase::App to communicate with Firebase + /// Authentication to authenticate users to the server backend. + /// + /// @param[in] app An instance of firebase::App. Cloud Functions will use + /// this to communicate with Firebase Authentication. + /// @param[out] init_result_out Optional: If provided, write the init result + /// here. Will be set to kInitResultSuccess if initialization succeeded, or + /// kInitResultFailedMissingDependency on Android if Google Play services is + /// not available on the current device. + /// + /// @returns An instance of Functions corresponding to the given App. + static Functions* GetInstance(::firebase::App* app, + InitResult* init_result_out = nullptr); + + /// @brief Get an instance of Functions corresponding to the given App. + /// + /// Cloud Functions uses firebase::App to communicate with Firebase + /// Authentication to authenticate users to the server backend. + /// + /// @param[in] app An instance of firebase::App. Cloud Functions will use + /// this to communicate with Firebase Authentication. + /// @param[in] region The region to call functions in. + /// @param[out] init_result_out Optional: If provided, write the init result + /// here. Will be set to kInitResultSuccess if initialization succeeded, or + /// kInitResultFailedMissingDependency on Android if Google Play services is + /// not available on the current device. + /// + /// @returns An instance of Functions corresponding to the given App. + static Functions* GetInstance(::firebase::App* app, const char* region, + InitResult* init_result_out = nullptr); + + /// @brief Get the firebase::App that this Functions was created with. + /// + /// @returns The firebase::App this Functions was created with. + ::firebase::App* app(); + + /// @brief Get a FunctionsReference for the specified path. + HttpsCallableReference GetHttpsCallable(const char* name) const; + + /// @brief Get a FunctionsReference for the specified URL. + HttpsCallableReference GetHttpsCallableFromURL(const char* url) const; + + /// @brief Sets an origin for a Cloud Functions emulator to use. + void UseFunctionsEmulator(const char* origin); + + private: + /// @cond FIREBASE_APP_INTERNAL + Functions(::firebase::App* app, const char* region); + Functions(const Functions& src); + Functions& operator=(const Functions& src); + + // Delete the internal_ data. + void DeleteInternal(); + + internal::FunctionsInternal* internal_; + /// @endcond +}; + +} // namespace functions +} // namespace firebase + +#endif // FIREBASE_FUNCTIONS_SRC_INCLUDE_FIREBASE_FUNCTIONS_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/functions/callable_reference.h b/packages/firebase_core/firebase_core/firebase_core/firebase/functions/callable_reference.h new file mode 100644 index 000000000000..9641c23564df --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/functions/callable_reference.h @@ -0,0 +1,124 @@ +// Copyright 2017 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef FIREBASE_FUNCTIONS_SRC_INCLUDE_FIREBASE_FUNCTIONS_CALLABLE_REFERENCE_H_ +#define FIREBASE_FUNCTIONS_SRC_INCLUDE_FIREBASE_FUNCTIONS_CALLABLE_REFERENCE_H_ + +#include +#include + +#include "firebase/future.h" +#include "firebase/internal/common.h" + +namespace firebase { +class Variant; + +namespace functions { +class Functions; +class HttpsCallableResult; + +/// @cond FIREBASE_APP_INTERNAL +namespace internal { +class HttpsCallableReferenceInternal; +} // namespace internal +/// @endcond + +#ifndef SWIG +/// Represents a reference to a Cloud Functions object. +/// Developers can call HTTPS Callable Functions. +#endif // SWIG +class HttpsCallableReference { + public: + /// @brief Default constructor. This creates an invalid + /// HttpsCallableReference. Attempting to perform any operations on this + /// reference will fail unless a valid HttpsCallableReference has been + /// assigned to it. + HttpsCallableReference() : internal_(nullptr) {} + + ~HttpsCallableReference(); + + /// @brief Copy constructor. It's totally okay (and efficient) to copy + /// HttpsCallableReference instances, as they simply point to the same + /// location. + /// + /// @param[in] reference HttpsCallableReference to copy from. + HttpsCallableReference(const HttpsCallableReference& reference); + + /// @brief Copy assignment operator. It's totally okay (and efficient) to copy + /// HttpsCallableReference instances, as they simply point to the same + /// location. + /// + /// @param[in] reference HttpsCallableReference to copy from. + /// + /// @returns Reference to the destination HttpsCallableReference. + HttpsCallableReference& operator=(const HttpsCallableReference& reference); + +#if defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) + /// @brief Move constructor. Moving is an efficient operation for + /// HttpsCallableReference instances. + /// + /// @param[in] other HttpsCallableReference to move data from. + HttpsCallableReference(HttpsCallableReference&& other); + + /// @brief Move assignment operator. Moving is an efficient operation for + /// HttpsCallableReference instances. + /// + /// @param[in] other HttpsCallableReference to move data from. + /// + /// @returns Reference to the destination HttpsCallableReference. + HttpsCallableReference& operator=(HttpsCallableReference&& other); +#endif // defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) + + /// @brief Gets the firebase::functions::Functions instance to which we refer. + /// + /// The pointer will remain valid indefinitely. + /// + /// @returns The firebase::functions::Functions instance that this + /// HttpsCallableReference refers to. + Functions* functions(); + + /// @brief Calls the function. + /// + /// @returns The result of the call; + Future Call(); + + /// @brief Calls the function. + /// + /// @param[in] data The params to pass to the function. + /// @returns The result of the call; + Future Call(const Variant& data); + + /// @brief Returns true if this HttpsCallableReference is valid, false if it + /// is not valid. An invalid HttpsCallableReference indicates that the + /// reference is uninitialized (created with the default constructor) or that + /// there was an error retrieving the reference. + /// + /// @returns true if this HttpsCallableReference is valid, false if this + /// HttpsCallableReference is invalid. + bool is_valid() const; + + private: + /// @cond FIREBASE_APP_INTERNAL + friend class Functions; + + HttpsCallableReference(internal::HttpsCallableReferenceInternal* internal); + + internal::HttpsCallableReferenceInternal* internal_; + /// @endcond +}; + +} // namespace functions +} // namespace firebase + +#endif // FIREBASE_FUNCTIONS_SRC_INCLUDE_FIREBASE_FUNCTIONS_CALLABLE_REFERENCE_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/functions/callable_result.h b/packages/firebase_core/firebase_core/firebase_core/firebase/functions/callable_result.h new file mode 100644 index 000000000000..5186377ae828 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/functions/callable_result.h @@ -0,0 +1,96 @@ +// Copyright 2018 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef FIREBASE_FUNCTIONS_SRC_INCLUDE_FIREBASE_FUNCTIONS_CALLABLE_RESULT_H_ +#define FIREBASE_FUNCTIONS_SRC_INCLUDE_FIREBASE_FUNCTIONS_CALLABLE_RESULT_H_ + +#include "firebase/functions/common.h" +#include "firebase/variant.h" + +namespace firebase { +namespace functions { + +/// @cond FIREBASE_APP_INTERNAL +namespace internal { +class HttpsCallableReferenceInternal; +} +/// @endcond + +/// An HttpsCallableResult contains the result of calling an HttpsCallable. +class HttpsCallableResult { + public: + /// @brief Creates an HttpsCallableResult with null data. + HttpsCallableResult() {} + + ~HttpsCallableResult() {} + + /// @brief Copy constructor. Copying is as efficient as copying a Variant. + /// + /// @param[in] other HttpsCallableResult to copy data from. + HttpsCallableResult(const HttpsCallableResult& other) : data_(other.data_) {} + + /// @brief Assignment operator. Copying is as efficient as copying a Variant. + /// + /// @param[in] other HttpsCallableResult to copy data from. + /// + /// @returns Reference to the destination HttpsCallableResult. + HttpsCallableResult& operator=(const HttpsCallableResult& other) { + data_ = other.data_; + return *this; + } + +#if defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) + /// @brief Move constructor. Moving is an efficient operation for + /// HttpsCallableResult instances. + /// + /// @param[in] other HttpsCallableResult to move data from. + HttpsCallableResult(HttpsCallableResult&& other) { + data_ = std::move(other.data_); + } + + /// @brief Move assignment operator. Moving is an efficient operation for + /// HttpsCallableResult instances. + /// + /// @param[in] other HttpsCallableResult to move data from. + /// + /// @returns Reference to the destination HttpsCallableResult. + HttpsCallableResult& operator=(HttpsCallableResult&& other) { + data_ = std::move(other.data_); + return *this; + } + +#endif // defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) + + /// @brief Returns the data that is the result of a Call. + /// + /// @returns The variant containing the data. + const Variant& data() const { return data_; } + + private: + /// @cond FIREBASE_APP_INTERNAL + // Only functions are allowed to construct results. + friend class ::firebase::functions::internal::HttpsCallableReferenceInternal; + HttpsCallableResult(const Variant& data) : data_(data) {} +#if defined(FIREBASE_USE_MOVE_OPERATORS) + HttpsCallableResult(Variant&& data) : data_(std::move(data)) {} +#endif // defined(FIREBASE_USE_MOVE_OPERATORS) + + Variant data_; + /// @endcond +}; + +} // namespace functions +} // namespace firebase + +#endif // FIREBASE_FUNCTIONS_SRC_INCLUDE_FIREBASE_FUNCTIONS_CALLABLE_RESULT_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/functions/common.h b/packages/firebase_core/firebase_core/firebase_core/firebase/functions/common.h new file mode 100644 index 000000000000..143dc8257618 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/functions/common.h @@ -0,0 +1,202 @@ +// Copyright 2017 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef FIREBASE_FUNCTIONS_SRC_INCLUDE_FIREBASE_FUNCTIONS_COMMON_H_ +#define FIREBASE_FUNCTIONS_SRC_INCLUDE_FIREBASE_FUNCTIONS_COMMON_H_ + +#include "firebase/variant.h" + +namespace firebase { +namespace functions { + +/// Error code returned by Cloud Functions C++ functions. +/// Standard gRPC error codes, as defined in: +/// https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto +enum Error { +#ifdef INTERNAL_EXPERIMENTAL +// LINT.IfChange +#endif // INTERNAL_EXPERIMENTAL + + // Not an error; returned on success + // + // HTTP Mapping: 200 OK + kErrorNone = 0, + + // The operation was cancelled, typically by the caller. + // + // HTTP Mapping: 499 Client Closed Request + kErrorCancelled = 1, + + // Unknown error. For example, this error may be returned when + // a `Status` value received from another address space belongs to + // an error space that is not known in this address space. Also + // errors raised by APIs that do not return enough error information + // may be converted to this error. + // + // HTTP Mapping: 500 Internal Server Error + kErrorUnknown = 2, + + // The client specified an invalid argument. Note that this differs + // from `FAILED_PRECONDITION`. `INVALID_ARGUMENT` indicates arguments + // that are problematic regardless of the state of the system + // (e.g., a malformed file name). + // + // HTTP Mapping: 400 Bad Request + kErrorInvalidArgument = 3, + + // The deadline expired before the operation could complete. For operations + // that change the state of the system, this error may be returned + // even if the operation has completed successfully. For example, a + // successful response from a server could have been delayed long + // enough for the deadline to expire. + // + // HTTP Mapping: 504 Gateway Timeout + kErrorDeadlineExceeded = 4, + + // Some requested entity (e.g., file or directory) was not found. + // + // Note to server developers: if a request is denied for an entire class + // of users, such as gradual feature rollout or undocumented whitelist, + // `NOT_FOUND` may be used. If a request is denied for some users within + // a class of users, such as user-based access control, `PERMISSION_DENIED` + // must be used. + // + // HTTP Mapping: 404 Not Found + kErrorNotFound = 5, + + // The entity that a client attempted to create (e.g., file or directory) + // already exists. + // + // HTTP Mapping: 409 Conflict + kErrorAlreadyExists = 6, + + // The caller does not have permission to execute the specified + // operation. `PERMISSION_DENIED` must not be used for rejections + // caused by exhausting some resource (use `RESOURCE_EXHAUSTED` + // instead for those errors). `PERMISSION_DENIED` must not be + // used if the caller can not be identified (use `UNAUTHENTICATED` + // instead for those errors). This error code does not imply the + // request is valid or the requested entity exists or satisfies + // other pre-conditions. + // + // HTTP Mapping: 403 Forbidden + kErrorPermissionDenied = 7, + + // The request does not have valid authentication credentials for the + // operation. + // + // HTTP Mapping: 401 Unauthorized + kErrorUnauthenticated = 16, + + // Some resource has been exhausted, perhaps a per-user quota, or + // perhaps the entire file system is out of space. + // + // HTTP Mapping: 429 Too Many Requests + kErrorResourceExhausted = 8, + + // The operation was rejected because the system is not in a state + // required for the operation's execution. For example, the directory + // to be deleted is non-empty, an rmdir operation is applied to + // a non-directory, etc. + // + // Service implementors can use the following guidelines to decide + // between `FAILED_PRECONDITION`, `ABORTED`, and `UNAVAILABLE`: + // (a) Use `UNAVAILABLE` if the client can retry just the failing call. + // (b) Use `ABORTED` if the client should retry at a higher level + // (e.g., when a client-specified test-and-set fails, indicating the + // client should restart a read-modify-write sequence). + // (c) Use `FAILED_PRECONDITION` if the client should not retry until + // the system state has been explicitly fixed. E.g., if an "rmdir" + // fails because the directory is non-empty, `FAILED_PRECONDITION` + // should be returned since the client should not retry unless + // the files are deleted from the directory. + // + // HTTP Mapping: 400 Bad Request + kErrorFailedPrecondition = 9, + + // The operation was aborted, typically due to a concurrency issue such as + // a sequencer check failure or transaction abort. + // + // See the guidelines above for deciding between `FAILED_PRECONDITION`, + // `ABORTED`, and `UNAVAILABLE`. + // + // HTTP Mapping: 409 Conflict + kErrorAborted = 10, + + // The operation was attempted past the valid range. E.g., seeking or + // reading past end-of-file. + // + // Unlike `INVALID_ARGUMENT`, this error indicates a problem that may + // be fixed if the system state changes. For example, a 32-bit file + // system will generate `INVALID_ARGUMENT` if asked to read at an + // offset that is not in the range [0,2^32-1], but it will generate + // `OUT_OF_RANGE` if asked to read from an offset past the current + // file size. + // + // There is a fair bit of overlap between `FAILED_PRECONDITION` and + // `OUT_OF_RANGE`. We recommend using `OUT_OF_RANGE` (the more specific + // error) when it applies so that callers who are iterating through + // a space can easily look for an `OUT_OF_RANGE` error to detect when + // they are done. + // + // HTTP Mapping: 400 Bad Request + kErrorOutOfRange = 11, + + // The operation is not implemented or is not supported/enabled in this + // service. + // + // HTTP Mapping: 501 Not Implemented + kErrorUnimplemented = 12, + + // Internal errors. This means that some invariants expected by the + // underlying system have been broken. This error code is reserved + // for serious errors. + // + // HTTP Mapping: 500 Internal Server Error + kErrorInternal = 13, + + // The service is currently unavailable. This is most likely a + // transient condition, which can be corrected by retrying with + // a backoff. + // + // See the guidelines above for deciding between `FAILED_PRECONDITION`, + // `ABORTED`, and `UNAVAILABLE`. + // + // HTTP Mapping: 503 Service Unavailable + kErrorUnavailable = 14, + + // Unrecoverable data loss or corruption. + // + // HTTP Mapping: 500 Internal Server Error + kErrorDataLoss = 15, + +}; + +#ifdef INTERNAL_EXPERIMENTAL +/// @cond FIREBASE_APP_INTERNAL +namespace internal { + +// Get the human-readable error message corresponding to an error code. +// +// Returns a statically-allocated string describing the error code you pass in. +const char* GetErrorMessage(Error error); + +} // namespace internal +/// @endcond +#endif // INTERNAL_EXPERIMENTAL + +} // namespace functions +} // namespace firebase + +#endif // FIREBASE_FUNCTIONS_SRC_INCLUDE_FIREBASE_FUNCTIONS_COMMON_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/future.h b/packages/firebase_core/firebase_core/firebase_core/firebase/future.h new file mode 100644 index 000000000000..0d09fc079a32 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/future.h @@ -0,0 +1,533 @@ +/* + * Copyright 2016 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_APP_SRC_INCLUDE_FIREBASE_FUTURE_H_ +#define FIREBASE_APP_SRC_INCLUDE_FIREBASE_FUTURE_H_ + +#include +#include + +#include + +#include "firebase/internal/common.h" +#include "firebase/internal/mutex.h" + +#ifdef FIREBASE_USE_STD_FUNCTION +#include +#endif + +namespace firebase { + +// Predeclarations. +/// @cond FIREBASE_APP_INTERNAL +namespace detail { +class FutureApiInterface; +class CompletionCallbackHandle; +} // namespace detail +/// @endcond + +/// Asynchronous call status. +enum FutureStatus { + /// Results are ready. + kFutureStatusComplete, + + /// Result is still being processed. + kFutureStatusPending, + + /// No result is pending. + /// FutureBase::Release() or move operator was called. + kFutureStatusInvalid +}; + +/// Handle that the API uses to identify an asynchronous call. +/// The exact interpretation of the handle is up to the API. +typedef uintptr_t FutureHandleId; + +/// Class that provides more context to FutureHandleId, which allows the +/// underlying API to track handles, perform reference counting, etc. +class FutureHandle { + public: + /// @cond FIREBASE_APP_INTERNAL + FutureHandle(); + explicit FutureHandle(FutureHandleId id) : FutureHandle(id, nullptr) {} + FutureHandle(FutureHandleId id, detail::FutureApiInterface* api); + ~FutureHandle(); + + // Copy constructor and assignment operator. + FutureHandle(const FutureHandle& rhs); + FutureHandle& operator=(const FutureHandle& rhs); + +#if defined(FIREBASE_USE_MOVE_OPERATORS) + // Move constructor and assignment operator. + FutureHandle(FutureHandle&& rhs) noexcept; + FutureHandle& operator=(FutureHandle&& rhs) noexcept; +#endif // defined(FIREBASE_USE_MOVE_OPERATORS) + + // Comparison operators. + bool operator!=(const FutureHandle& rhs) const { return !(*this == rhs); } + bool operator==(const FutureHandle& rhs) const { + // Only compare IDs, since the API is irrelevant (comparison will only occur + // within the context of a single API anyway). + return id() == rhs.id(); + } + + FutureHandleId id() const { return id_; } + detail::FutureApiInterface* api() const { return api_; } + + // Detach from the FutureApi. This handle will no longer increment the + // Future's reference count. This is mainly used for testing, so that you can + // still look up the Future based on its handle's ID without affecting the + // reference count yourself. + void Detach(); + + // Called by CleanupNotifier when the API is being deleted. At this point we + // can ignore all of the reference counts since all Future data is about to be + // deleted anyway. + void Cleanup() { api_ = nullptr; } + + private: + FutureHandleId id_; + detail::FutureApiInterface* api_; + /// @endcond +}; + +/// @brief Type-independent return type of asynchronous calls. +/// +/// @see Future for code samples. +/// +/// @cond FIREBASE_APP_INTERNAL +/// Notes: +/// - Futures have pointers back to the API, but the API does not maintain +/// pointers to its Futures. Therefore, all Futures must be destroyed +/// *before* the API is destroyed. +/// - Futures can be moved or copied. Call results are reference counted, +/// and are destroyed when they are no longer referenced by any Futures. +/// - The actual `Status`, `Error`, and `Result` values are kept inside the +/// API. This makes synchronization and data management easier. +/// +/// WARNING: This class should remain POD (plain old data). It should not have +/// virtual methods. Nor should the derived Future class add any +/// data. Internally, we static_cast FutureBase to Future, +/// so the underlying data should remain the same. +/// @endcond +class FutureBase { + public: + /// Function pointer for a completion callback. When we call this, we will + /// send the completed future, along with the user data that you specified + /// when you set up the callback. + typedef void (*CompletionCallback)(const FutureBase& result_data, + void* user_data); + +#if defined(INTERNAL_EXPERIMENTAL) + /// Handle, representing a completion callback, that can be passed to + /// RemoveOnCompletion. + using CompletionCallbackHandle = detail::CompletionCallbackHandle; +#endif + + /// Construct an untyped future. + FutureBase(); + + /// @cond FIREBASE_APP_INTERNAL + + /// Construct an untyped future using the specified API and handle. + /// + /// @param api API class used to provide the future implementation. + /// @param handle Handle to the future. + FutureBase(detail::FutureApiInterface* api, const FutureHandle& handle); + + /// @endcond + + ~FutureBase(); + + /// Copy constructor and operator. + /// Increment the reference count when creating a copy of the future. + FutureBase(const FutureBase& rhs); + + /// Copy an untyped future. + FutureBase& operator=(const FutureBase& rhs); + +#if defined(FIREBASE_USE_MOVE_OPERATORS) + /// Move constructor and operator. + /// Move is more efficient than copy and delete because we don't touch the + /// reference counting in the API. + FutureBase(FutureBase&& rhs) noexcept; + + /// Copy an untyped future. + FutureBase& operator=(FutureBase&& rhs) noexcept; +#endif // defined(FIREBASE_USE_MOVE_OPERATORS) + + /// Explicitly release the internal resources for a future. + /// Future will become invalid. + void Release(); + + /// Completion status of the asynchronous call. + FutureStatus status() const; + + /// When status() is firebase::kFutureStatusComplete, returns the API-defined + /// error code. Otherwise, return value is undefined. + int error() const; + + /// When status() is firebase::kFutureStatusComplete, returns the API-defined + /// error message, as human-readable text, or an empty string if the API does + /// not provide a human readable description of the error. + /// + /// @note The returned pointer is only valid for the lifetime of the Future + /// or its copies. + const char* error_message() const; + + /// Result of the asynchronous call, or nullptr if the result is still + /// pending. Cast is required since GetFutureResult() returns void*. + const void* result_void() const; + +#if defined(INTERNAL_EXPERIMENTAL) + /// Special timeout value indicating an infinite timeout. + /// + /// Passing this value to FutureBase::Wait() or Future::Await() will cause + /// those methods to wait until the future is complete. + /// + /// @Warning It is inadvisable to use this from code that could be called + /// from an event loop. + static const int kWaitTimeoutInfinite; + + /// Block (i.e. suspend the current thread) until either the future is + /// completed or the specified timeout period (in milliseconds) has elapsed. + /// If `timeout_milliseconds` is `kWaitTimeoutInfinite`, then the timeout + /// period is treated as being infinite, i.e. this will block until the + /// future is completed. + /// + /// @return True if the future completed, or + /// false if the timeout period elapsed before the future completed. + bool Wait(int timeout_milliseconds) const; +#endif // defined(INTERNAL_EXPERIMENTAL) + + /// Register a single callback that will be called at most once, when the + /// future is completed. + /// + /// If you call any OnCompletion() method more than once on the same future, + /// only the most recent callback you registered with OnCompletion() will be + /// called. +#if defined(INTERNAL_EXPERIMENTAL) + /// However completions registered with AddCompletion() will still be + /// called even if there is a subsequent call to OnCompletion(). + /// + /// When the future completes, first the most recent callback registered with + /// OnCompletion(), if any, will be called; then all callbacks registered with + /// AddCompletion() will be called, in the order that they were registered. +#endif + /// + /// When your callback is called, the user_data that you supplied here will be + /// passed back as the second parameter. + /// + /// @param[in] callback Function pointer to your callback. + /// @param[in] user_data Optional user data. We will pass this back to your + /// callback. + void OnCompletion(CompletionCallback callback, void* user_data) const; + +#if defined(FIREBASE_USE_STD_FUNCTION) || defined(DOXYGEN) + /// Register a single callback that will be called at most once, when the + /// future is completed. + /// + /// If you call any OnCompletion() method more than once on the same future, + /// only the most recent callback you registered with OnCompletion() will be + /// called. +#if defined(INTERNAL_EXPERIMENTAL) + /// However completions registered with AddCompletion() will still be + /// called even if there is a subsequent call to OnCompletion(). + /// + /// When the future completes, first the most recent callback registered with + /// OnCompletion(), if any, will be called; then all callbacks registered with + /// AddCompletion() will be called, in the order that they were registered. +#endif + /// + /// @param[in] callback Function or lambda to call. + /// + /// @note This method is not available when using STLPort on Android, as + /// `std::function` is not supported on STLPort. + void OnCompletion(std::function callback) const; +#endif // defined(FIREBASE_USE_STD_FUNCTION) || defined(DOXYGEN) + +#if defined(INTERNAL_EXPERIMENTAL) + /// Like OnCompletion, but allows adding multiple callbacks. + /// + /// If you call AddCompletion() more than once, all of the completions that + /// you register will be called, when the future is completed. However, any + /// callbacks which were subsequently removed by calling RemoveOnCompletion + /// will not be called. + /// + /// When the future completes, first the most recent callback registered with + /// OnCompletion(), if any, will be called; then all callbacks registered with + /// AddCompletion() will be called, in the order that they were registered. + /// + /// @param[in] callback Function pointer to your callback. + /// @param[in] user_data Optional user data. We will pass this back to your + /// callback. + /// @return A handle that can be passed to RemoveOnCompletion. + CompletionCallbackHandle AddOnCompletion(CompletionCallback callback, + void* user_data) const; + +#if defined(FIREBASE_USE_STD_FUNCTION) || defined(DOXYGEN) + /// Like OnCompletion, but allows adding multiple callbacks. + /// + /// If you call AddCompletion() more than once, all of the completions that + /// you register will be called, when the future is completed. However, any + /// callbacks which were subsequently removed by calling RemoveOnCompletion + /// will not be called. + /// + /// When the future completes, first the most recent callback registered with + /// OnCompletion(), if any, will be called; then all callbacks registered with + /// AddCompletion() will be called, in the order that they were registered. + /// + /// @param[in] callback Function or lambda to call. + /// @return A handle that can be passed to RemoveOnCompletion. + /// + /// @note This method is not available when using STLPort on Android, as + /// `std::function` is not supported on STLPort. + CompletionCallbackHandle AddOnCompletion( + std::function callback) const; + +#endif // defined(FIREBASE_USE_STD_FUNCTION) || defined(DOXYGEN) + + /// Unregisters a callback that was previously registered with + /// AddOnCompletion. + /// + /// @param[in] completion_handle The return value of a previous call to + /// AddOnCompletion. + void RemoveOnCompletion(CompletionCallbackHandle completion_handle) const; +#endif // defined(INTERNAL_EXPERIMENTAL) + + /// Returns true if the two Futures reference the same result. + bool operator==(const FutureBase& rhs) const { + MutexLock lock(mutex_); + return api_ == rhs.api_ && handle_ == rhs.handle_; + } + + /// Returns true if the two Futures reference different results. + bool operator!=(const FutureBase& rhs) const { return !operator==(rhs); } + +#if defined(INTERNAL_EXPERIMENTAL) + /// Returns the API-specific handle. Should only be called by the API. + FutureHandle GetHandle() const { + MutexLock lock(mutex_); + return handle_; + } +#endif // defined(INTERNAL_EXPERIMENTAL) + + protected: + /// @cond FIREBASE_APP_INTERNAL + + mutable Mutex mutex_; + + /// Backpointer to the issuing API class. + /// Set to nullptr when Future is invalidated. + detail::FutureApiInterface* api_; + + /// API-specified handle type. + FutureHandle handle_; + + /// @endcond +}; + +/// @brief Type-specific version of FutureBase. +/// +/// The Firebase C++ SDK uses this class to return results from asynchronous +/// operations. All Firebase C++ functions and method calls that operate +/// asynchronously return a Future, and provide a "LastResult" function to +/// retrieve the most recent Future result. +/// +/// @code +/// // You can retrieve the Future from the function call directly, like this: +/// Future< SampleResultType > future = firebase::SampleAsyncOperation(); +/// +/// // Or you can retrieve it later, like this: +/// firebase::SampleAsyncOperation(); +/// // [...] +/// Future< SampleResultType > future = +/// firebase::SampleAsyncOperationLastResult(); +/// @endcode +/// +/// When you have a Future from an asynchronous operation, it will eventually +/// complete. Once it is complete, you can check for errors (a nonzero error() +/// means an error occurred) and get the result data if no error occurred by +/// calling result(). +/// +/// There are two ways to find out that a Future has completed. You can poll +/// its status(), or set an OnCompletion() callback: +/// +/// @code +/// // Check whether the status is kFutureStatusComplete. +/// if (future.status() == firebase::kFutureStatusComplete) { +/// if (future.error() == 0) { +/// DoSomethingWithResultData(future.result()); +/// } +/// else { +/// LogMessage("Error %d: %s", future.error(), future.error_message()); +/// } +/// } +/// +/// // Or, set an OnCompletion callback, which accepts a C++11 lambda or +/// // function pointer. You can pass your own user data to the callback. In +/// // most cases, the callback will be running in a different thread, so take +/// // care to make sure your code is thread-safe. +/// future.OnCompletion([](const Future< SampleResultType >& completed_future, +/// void* user_data) { +/// // We are probably in a different thread right now. +/// if (completed_future.error() == 0) { +/// DoSomethingWithResultData(completed_future.result()); +/// } +/// else { +/// LogMessage("Error %d: %s", +/// completed_future.error(), +/// completed_future.error_message()); +/// } +/// }, user_data); +/// @endcode +/// +/// @tparam ResultType The type of this Future's result. +// +// WARNING: This class should not have virtual methods or data members. +// See the warning in FutureBase for further details. +template +class Future : public FutureBase { + public: + /// Function pointer for a completion callback. When we call this, we will + /// send the completed future, along with the user data that you specified + /// when you set up the callback. + typedef void (*TypedCompletionCallback)(const Future& result_data, + void* user_data); + + /// Construct a future. + Future() {} + + /// @cond FIREBASE_APP_INTERNAL + + /// Construct a future using the specified API and handle. + /// + /// @param api API class used to provide the future implementation. + /// @param handle Handle to the future. + Future(detail::FutureApiInterface* api, const FutureHandle& handle) + : FutureBase(api, handle) {} + + /// @endcond + + /// Result of the asynchronous call, or nullptr if the result is still + /// pending. Allows the API to provide a type-specific interface. + /// + const ResultType* result() const { + return static_cast(result_void()); + } + +#if defined(INTERNAL_EXPERIMENTAL) + /// Waits (blocks) until either the future is completed, or the specified + /// timeout period (in milliseconds) has elapsed, then returns the result of + /// the asynchronous call. + /// + /// This is a convenience method that calls Wait() and then returns result(). + /// + /// If `timeout_milliseconds` is `kWaitTimeoutInfinite`, then the timeout + /// period is treated as being infinite, i.e. this will block until the + /// future is completed. + const ResultType* Await(int timeout_milliseconds) const { + Wait(timeout_milliseconds); + return result(); + } +#endif // defined(INTERNAL_EXPERIMENTAL) + + /// Register a single callback that will be called at most once, when the + /// future is completed. + /// + /// If you call any OnCompletion() method more than once on the same future, + /// only the most recent callback you registered will be called. + /// + /// When your callback is called, the user_data that you supplied here will be + /// passed back as the second parameter. + /// + /// @param[in] callback Function pointer to your callback. + /// @param[in] user_data Optional user data. We will pass this back to your + /// callback. + /// + /// @note This is the same callback as FutureBase::OnCompletion(), so you + /// can't expect to set both and have both run; again, only the most recently + /// registered one will run. + inline void OnCompletion(TypedCompletionCallback callback, + void* user_data) const; + +#if defined(FIREBASE_USE_STD_FUNCTION) || defined(DOXYGEN) + /// Register a single callback that will be called at most once, when the + /// future is completed. + /// + /// If you call any OnCompletion() method more than once on the same future, + /// only the most recent callback you registered will be called. + /// + /// @param[in] callback Function or lambda to call. + /// + /// @note This method is not available when using STLPort on Android, as + /// `std::function` is not supported on STLPort. + /// + /// @note This is the same callback as FutureBase::OnCompletion(), so you + /// can't expect to set both and have both run; again, only the most recently + /// registered one will run. + inline void OnCompletion( + std::function&)> callback) const; +#endif // defined(FIREBASE_USE_STD_FUNCTION) || defined(DOXYGEN) + +#if defined(INTERNAL_EXPERIMENTAL) + /// Like OnCompletion, but allows adding multiple callbacks. + /// + /// If you call AddCompletion() more than once, all of the completions that + /// you register will be called, when the future is completed. However, any + /// callbacks which were subsequently removed by calling RemoveOnCompletion + /// will not be called. + /// + /// When the future completes, first the most recent callback registered with + /// OnCompletion(), if any, will be called; then all callbacks registered with + /// AddCompletion() will be called, in the order that they were registered. + /// + /// @param[in] callback Function pointer to your callback. + /// @param[in] user_data Optional user data. We will pass this back to your + /// callback. + /// @return A handle that can be passed to RemoveOnCompletion. + inline CompletionCallbackHandle AddOnCompletion( + TypedCompletionCallback callback, void* user_data) const; + +#if defined(FIREBASE_USE_STD_FUNCTION) || defined(DOXYGEN) + /// Like OnCompletion, but allows adding multiple callbacks. + /// + /// If you call AddCompletion() more than once, all of the completions that + /// you register will be called, when the future is completed. However, any + /// callbacks which were subsequently removed by calling RemoveOnCompletion + /// will not be called. + /// + /// When the future completes, first the most recent callback registered with + /// OnCompletion(), if any, will be called; then all callbacks registered with + /// AddCompletion() will be called, in the order that they were registered. + /// + /// @param[in] callback Function or lambda to call. + /// @return A handle that can be passed to RemoveOnCompletion. + /// + /// @note This method is not available when using STLPort on Android, as + /// `std::function` is not supported on STLPort. + inline CompletionCallbackHandle AddOnCompletion( + std::function&)> callback) const; +#endif // defined(FIREBASE_USE_STD_FUNCTION) || defined(DOXYGEN) +#endif // defined(INTERNAL_EXPERIMENTAL) +}; + +} // namespace firebase + +// Include the inline implementation. +#include "firebase/internal/future_impl.h" + +#endif // FIREBASE_APP_SRC_INCLUDE_FIREBASE_FUTURE_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/gma.h b/packages/firebase_core/firebase_core/firebase_core/firebase/gma.h new file mode 100644 index 000000000000..b7da2cf569b9 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/gma.h @@ -0,0 +1,207 @@ +/* + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_GMA_SRC_INCLUDE_FIREBASE_GMA_H_ +#define FIREBASE_GMA_SRC_INCLUDE_FIREBASE_GMA_H_ + +#include "firebase/internal/platform.h" + +#if FIREBASE_PLATFORM_ANDROID +#include +#endif // FIREBASE_PLATFORM_ANDROID + +#include + +#include "firebase/app.h" +#include "firebase/gma/ad_view.h" +#include "firebase/gma/interstitial_ad.h" +#include "firebase/gma/rewarded_ad.h" +#include "firebase/gma/types.h" +#include "firebase/internal/common.h" + +#if !defined(DOXYGEN) && !defined(SWIG) +FIREBASE_APP_REGISTER_CALLBACKS_REFERENCE(gma) +#endif // !defined(DOXYGEN) && !defined(SWIG) + +namespace firebase { +// In the GMA docs, link to firebase::Future in the Firebase C++ docs. +#if defined(DOXYGEN_ADMOB) +/// @brief The Google Mobile Ads C++ SDK uses this class to return results from +/// asynchronous operations. All C++ functions and method calls that operate +/// asynchronously return a %Future, and provide a "LastResult" +/// function to retrieve the most recent %Future result. +/// +/// The Google Mobile Ads C++ SDK uses this class from the Firebase C++ SDK to +/// return results from asynchronous operations. For more information, see the +/// Firebase +/// C++ SDK documentation. +template +class Future { + // Empty class (used for documentation only). +}; +#endif // defined(DOXYGEN_ADMOB) + +/// @brief API for Google Mobile Ads with Firebase. +/// +/// The GMA API allows you to load and display mobile ads using the Google +/// Mobile Ads SDK. Each ad format has its own header file. +namespace gma { + +/// Initializes Google Mobile Ads (GMA) via Firebase. +/// +/// @param[in] app The Firebase app for which to initialize mobile ads. +/// +/// @param[out] init_result_out Optional: If provided, write the basic init +/// result here. kInitResultSuccess if initialization succeeded, or +/// kInitResultFailedMissingDependency on Android if Google Play services is not +/// available on the current device and the Google Mobile Ads SDK requires +/// Google Play services (for example, when using 'play-services-ads-lite'). +/// Note that this does not include the adapter initialization status, which is +/// returned in the Future. +/// +/// @return If init_result_out is kInitResultSuccess, this Future will contain +/// the initialization status of each adapter once initialization is complete. +/// Otherwise, the returned Future will have kFutureStatusInvalid. +Future Initialize( + const ::firebase::App& app, InitResult* init_result_out = nullptr); + +#if FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) +/// Initializes Google Mobile Ads (GMA) without Firebase for Android. +/// +/// The arguments to @ref Initialize are platform-specific so the caller must do +/// something like this: +/// @code +/// #if defined(__ANDROID__) +/// firebase::gma::Initialize(jni_env, activity); +/// #else +/// firebase::gma::Initialize(); +/// #endif +/// @endcode +/// +/// @param[in] jni_env JNIEnv pointer. +/// @param[in] activity Activity used to start the application. +/// @param[out] init_result_out Optional: If provided, write the basic init +/// result here. kInitResultSuccess if initialization succeeded, or +/// kInitResultFailedMissingDependency on Android if Google Play services is not +/// available on the current device and the Google Mobile Ads SDK requires +/// Google Play services (for example, when using 'play-services-ads-lite'). +/// Note that this does not include the adapter initialization status, which is +/// returned in the Future. +/// +/// @return If init_result_out is kInitResultSuccess, this Future will contain +/// the initialization status of each adapter once initialization is complete. +/// Otherwise, the returned Future will have kFutureStatusInvalid. +Future Initialize( + JNIEnv* jni_env, jobject activity, InitResult* init_result_out = nullptr); + +#endif // defined(__ANDROID__) || defined(DOXYGEN) +#if !FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) +/// Initializes Google Mobile Ads (GMA) without Firebase for iOS. +/// +/// @param[out] init_result_out Optional: If provided, write the basic init +/// result here. kInitResultSuccess if initialization succeeded, or +/// kInitResultFailedMissingDependency on Android if Google Play services is not +/// available on the current device and the Google Mobile Ads SDK requires +/// Google Play services (for example, when using 'play-services-ads-lite'). +/// Note that this does not include the adapter initialization status, which is +/// returned in the Future. +/// +/// @return If init_result_out is kInitResultSuccess, this Future +/// will contain the initialization status of each adapter once initialization +/// is complete. Otherwise, the returned Future will have +/// kFutureStatusInvalid. +Future Initialize( + InitResult* init_result_out = nullptr); +#endif // !defined(__ANDROID__) || defined(DOXYGEN) + +/// Get the Future returned by a previous call to +/// @ref firebase::gma::Initialize(). +Future InitializeLastResult(); + +/// Get the current adapter initialization status. You can poll this method to +/// check which adapters have been initialized. +AdapterInitializationStatus GetInitializationStatus(); + +/// Disables automated SDK crash reporting on iOS. If not called, the SDK +/// records the original exception handler if available and registers a new +/// exception handler. The new exception handler only reports SDK related +/// exceptions and calls the recorded original exception handler. +/// +/// This method has no effect on Android. +void DisableSDKCrashReporting(); + +/// Disables mediation adapter initialization on iOS during initialization of +/// the GMA SDK. Calling this method may negatively impact your ad +/// performance and should only be called if you will not use GMA SDK +/// controlled mediation during this app session. This method must be called +/// before initializing the GMA SDK or loading ads and has no effect once the +/// SDK has been initialized. +/// +/// This method has no effect on Android. +void DisableMediationInitialization(); + +/// Sets the global @ref RequestConfiguration that will be used for +/// every @ref AdRequest during the app's session. +/// +/// @param[in] request_configuration The request configuration that should be +/// applied to all ad requests. +void SetRequestConfiguration(const RequestConfiguration& request_configuration); + +/// Gets the global RequestConfiguration. +/// +/// @return the currently active @ref RequestConfiguration that's being +/// used for every ad request. +/// @note: on iOS, the +/// @ref RequestConfiguration::tag_for_child_directed_treatment and +/// @ref RequestConfiguration::tag_for_under_age_of_consent fields will be set +/// to RequestConfiguration.kChildDirectedTreatmentUnspecified, and +/// RequestConfiguration.kUnderAgeOfConsentUnspecified, respectfully. +RequestConfiguration GetRequestConfiguration(); + +/// Opens the ad inspector UI. +/// +/// @param[in] parent The platform-specific UI element that will host the +/// ad inspector. For iOS this should be the window's +/// UIViewController. For Android this is the +/// Activity Context which the GMA SDK is running in. +/// @param[in] listener The listener will be invoked when the user closes +/// the ad inspector UI. @ref firebase::gma::Initialize(). must be called +/// prior to this function. +void OpenAdInspector(AdParent parent, AdInspectorClosedListener* listener); + +/// Controls whether the Google Mobile Ads SDK Same App Key is enabled. +/// +/// This function must be invoked after GMA has been initialized. The value set +/// persists across app sessions. The key is enabled by default. +/// +/// This operation is supported on iOS only. This is a no-op on Android +/// systems. +/// +/// @param[in] is_enabled whether the Google Mobile Ads SDK Same App Key is +/// enabled. +void SetIsSameAppKeyEnabled(bool is_enabled); + +/// @brief Terminate GMA. +/// +/// Frees resources associated with GMA that were allocated during +/// @ref firebase::gma::Initialize(). +void Terminate(); + +} // namespace gma +} // namespace firebase + +#endif // FIREBASE_GMA_SRC_INCLUDE_FIREBASE_GMA_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/gma/ad_view.h b/packages/firebase_core/firebase_core/firebase_core/firebase/gma/ad_view.h new file mode 100644 index 000000000000..16916a21665f --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/gma/ad_view.h @@ -0,0 +1,267 @@ +/* + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_GMA_SRC_INCLUDE_FIREBASE_GMA_AD_VIEW_H_ +#define FIREBASE_GMA_SRC_INCLUDE_FIREBASE_GMA_AD_VIEW_H_ + +#include "firebase/future.h" +#include "firebase/gma/types.h" +#include "firebase/internal/common.h" + +namespace firebase { +namespace gma { + +namespace internal { +// Forward declaration for platform-specific data, implemented in each library. +class AdViewInternal; +} // namespace internal + +class AdViewBoundingBoxListener; +struct BoundingBox; + +/// @brief Loads and displays Google Mobile Ads AdView ads. +/// +/// Each AdView object corresponds to a single GMA ad placement of a specified +/// size. There are methods to load an ad, move it, show it and hide it, and +/// retrieve the bounds of the ad onscreen. +/// +/// AdView objects provide information about their current state through +/// Futures. Methods like @ref Initialize, @ref LoadAd, and @ref Hide each have +/// a corresponding @ref Future from which the result of the last call can be +/// determined. The two variants of @ref SetPosition share a single result +/// @ref Future, since they're essentially the same action. +/// +/// For example, you could initialize, load, and show an AdView while +/// checking the result of the previous action at each step as follows: +/// +/// @code +/// namespace gma = ::firebase::gma; +/// gma::AdView* ad_view = new gma::AdView(); +/// ad_view->Initialize(ad_parent, "YOUR_AD_UNIT_ID", desired_ad_size) +/// @endcode +/// +/// Then, later: +/// +/// @code +/// if (ad_view->InitializeLastResult().status() == +/// ::firebase::kFutureStatusComplete && +/// ad_view->InitializeLastResult().error() == +/// firebase::gma::kAdErrorCodeNone) { +/// ad_view->LoadAd(your_ad_request); +/// } +/// @endcode +class AdView { + public: + /// The possible screen positions for a @ref AdView, configured via + /// @ref SetPosition. + enum Position { + /// The position isn't one of the predefined screen locations. + kPositionUndefined = -1, + /// Top of the screen, horizontally centered. + kPositionTop = 0, + /// Bottom of the screen, horizontally centered. + kPositionBottom, + /// Top-left corner of the screen. + kPositionTopLeft, + /// Top-right corner of the screen. + kPositionTopRight, + /// Bottom-left corner of the screen. + kPositionBottomLeft, + /// Bottom-right corner of the screen. + kPositionBottomRight, + }; + + /// Creates an uninitialized @ref AdView object. + /// @ref Initialize must be called before the object is used. + AdView(); + + ~AdView(); + + /// Initializes the @ref AdView object. + /// @param[in] parent The platform-specific UI element that will host the ad. + /// @param[in] ad_unit_id The ad unit ID to use when requesting ads. + /// @param[in] size The desired ad size for the ad. + Future Initialize(AdParent parent, const char* ad_unit_id, + const AdSize& size); + + /// Returns a @ref Future that has the status of the last call to + /// @ref Initialize. + Future InitializeLastResult() const; + + /// Begins an asynchronous request for an ad. If successful, the ad will + /// automatically be displayed in the AdView. + /// @param[in] request An AdRequest struct with information about the request + /// to be made (such as targeting info). + Future LoadAd(const AdRequest& request); + + /// Returns a @ref Future containing the status of the last call to + /// @ref LoadAd. + Future LoadAdLastResult() const; + + /// Retrieves the @ref AdView's current onscreen size and location. + /// + /// @return The current size and location. Values are in pixels, and location + /// coordinates originate from the top-left corner of the screen. + BoundingBox bounding_box() const; + + /// Sets an AdListener for this ad view. + /// + /// @param[in] listener An AdListener object which will be invoked + /// when lifecycle events occur on this AdView. + void SetAdListener(AdListener* listener); + + /// Sets a listener to be invoked when the Ad's bounding box + /// changes size or location. + /// + /// @param[in] listener A AdViewBoundingBoxListener object which will be + /// invoked when the ad changes size, shape, or position. + void SetBoundingBoxListener(AdViewBoundingBoxListener* listener); + + /// Sets a listener to be invoked when this ad is estimated to have earned + /// money. + /// + /// @param[in] listener A PaidEventListener object to be invoked when a + /// paid event occurs on the ad. + void SetPaidEventListener(PaidEventListener* listener); + + /// Moves the @ref AdView so that its top-left corner is located at + /// (x, y). Coordinates are in pixels from the top-left corner of the screen. + /// + /// When built for Android, the library will not display an ad on top of or + /// beneath an Activity's status bar. If a call to SetPostion + /// would result in an overlap, the @ref AdView is placed just below the + /// status bar, so no overlap occurs. + /// @param[in] x The desired horizontal coordinate. + /// @param[in] y The desired vertical coordinate. + /// + /// @return a @ref Future which will be completed when this move operation + /// completes. + Future SetPosition(int x, int y); + + /// Moves the @ref AdView so that it's located at the given predefined + /// position. + /// + /// @param[in] position The predefined position to which to move the + /// @ref AdView. + /// + /// @return a @ref Future which will be completed when this move operation + /// completes. + Future SetPosition(Position position); + + /// Returns a @ref Future containing the status of the last call to either + /// version of @ref SetPosition. + Future SetPositionLastResult() const; + + /// Hides the AdView. + Future Hide(); + + /// Returns a @ref Future containing the status of the last call to + /// @ref Hide. + Future HideLastResult() const; + + /// Shows the @ref AdView. + Future Show(); + + /// Returns a @ref Future containing the status of the last call to + /// @ref Show. + Future ShowLastResult() const; + + /// Pauses the @ref AdView. Should be called whenever the C++ engine + /// pauses or the application loses focus. + Future Pause(); + + /// Returns a @ref Future containing the status of the last call to + /// @ref Pause. + Future PauseLastResult() const; + + /// Resumes the @ref AdView after pausing. + Future Resume(); + + /// Returns a @ref Future containing the status of the last call to + /// @ref Resume. + Future ResumeLastResult() const; + + /// Cleans up and deallocates any resources used by the @ref AdView. + /// You must call this asynchronous operation before this object's destructor + /// is invoked or risk leaking device resources. + Future Destroy(); + + /// Returns a @ref Future containing the status of the last call to + /// @ref Destroy. + Future DestroyLastResult() const; + + /// Returns the AdSize of the AdView. + /// + /// @return An @ref AdSize object representing the size of the ad. If this + /// view has not been initialized then the AdSize will be 0,0. + AdSize ad_size() const; + + protected: + /// Pointer to a listener for AdListener events. + AdListener* ad_listener_; + + /// Pointer to a listener for BoundingBox events. + AdViewBoundingBoxListener* ad_view_bounding_box_listener_; + + /// Pointer to a listener for paid events. + PaidEventListener* paid_event_listener_; + + private: + // An internal, platform-specific implementation object that this class uses + // to interact with the Google Mobile Ads SDKs for iOS and Android. + internal::AdViewInternal* internal_; +}; + +/// A listener class that developers can extend and pass to an @ref AdView +/// object's @ref AdView::SetBoundingBoxListener method to be notified of +/// changes to the size of the Ad's bounding box. +class AdViewBoundingBoxListener { + public: + virtual ~AdViewBoundingBoxListener(); + + /// This method is called when the @ref AdView object's bounding box + /// changes. + /// + /// @param[in] ad_view The view whose bounding box changed. + /// @param[in] box The new bounding box. + virtual void OnBoundingBoxChanged(AdView* ad_view, BoundingBox box) = 0; +}; + +/// @brief The screen location and dimensions of an AdView once it has been +/// initialized. +struct BoundingBox { + /// Default constructor which initializes all member variables to 0. + BoundingBox() + : height(0), width(0), x(0), y(0), position(AdView::kPositionUndefined) {} + + /// Height of the ad in pixels. + int height; + /// Width of the ad in pixels. + int width; + /// Horizontal position of the ad in pixels from the left. + int x; + /// Vertical position of the ad in pixels from the top. + int y; + + /// The position of the AdView if one has been set as the target position, or + /// kPositionUndefined otherwise. + AdView::Position position; +}; + +} // namespace gma +} // namespace firebase + +#endif // FIREBASE_GMA_SRC_INCLUDE_FIREBASE_GMA_AD_VIEW_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/gma/interstitial_ad.h b/packages/firebase_core/firebase_core/firebase_core/firebase/gma/interstitial_ad.h new file mode 100644 index 000000000000..4680537178c8 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/gma/interstitial_ad.h @@ -0,0 +1,128 @@ +/* + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_GMA_SRC_INCLUDE_FIREBASE_GMA_INTERSTITIAL_AD_H_ +#define FIREBASE_GMA_SRC_INCLUDE_FIREBASE_GMA_INTERSTITIAL_AD_H_ + +#include "firebase/future.h" +#include "firebase/gma/types.h" +#include "firebase/internal/common.h" + +namespace firebase { +namespace gma { + +namespace internal { +// Forward declaration for platform-specific data, implemented in each library. +class InterstitialAdInternal; +} // namespace internal + +/// @brief Loads and displays Google Mobile Ads interstitial ads. +/// +/// @ref InterstitialAd is a single-use object that can load and show a +/// single GMA interstitial ad. +/// +/// InterstitialAd objects provide information about their current state +/// through Futures. @ref Initialize, @ref LoadAd, and @ref Show each have a +/// corresponding @ref Future from which you can determine result of the +/// previous call. +/// +/// Here's how one might initialize, load, and show an interstitial ad while +/// checking against the result of the previous action at each step: +/// +/// @code +/// namespace gma = ::firebase::gma; +/// gma::InterstitialAd* interstitial = new gma::InterstitialAd(); +/// interstitial->Initialize(ad_parent); +/// @endcode +/// +/// Then, later: +/// +/// @code +/// if (interstitial->InitializeLastResult().status() == +/// ::firebase::kFutureStatusComplete && +/// interstitial->InitializeLastResult().error() == +/// firebase::gma::kAdErrorCodeNone) { +/// interstitial->LoadAd( "YOUR_AD_UNIT_ID", my_ad_request); +/// } +/// @endcode +/// +/// And after that: +/// +/// @code +/// if (interstitial->LoadAdLastResult().status() == +/// ::firebase::kFutureStatusComplete && +/// interstitial->LoadAdLastResult().error() == +/// firebase::gma::kAdErrorCodeNone)) { +/// interstitial->Show(); +/// } +/// @endcode +class InterstitialAd { + public: + /// Creates an uninitialized @ref InterstitialAd object. + /// @ref Initialize must be called before the object is used. + InterstitialAd(); + + ~InterstitialAd(); + + /// Initialize the @ref InterstitialAd object. + /// @param[in] parent The platform-specific UI element that will host the ad. + Future Initialize(AdParent parent); + + /// Returns a @ref Future containing the status of the last call to + /// @ref Initialize. + Future InitializeLastResult() const; + + /// Begins an asynchronous request for an ad. + /// + /// @param[in] ad_unit_id The ad unit ID to use in loading the ad. + /// @param[in] request An AdRequest struct with information about the request + /// to be made (such as targeting info). + Future LoadAd(const char* ad_unit_id, const AdRequest& request); + + /// Returns a @ref Future containing the status of the last call to + /// @ref LoadAd. + Future LoadAdLastResult() const; + + /// Shows the @ref InterstitialAd. This should not be called unless an ad has + /// already been loaded. + Future Show(); + + /// Returns a @ref Future containing the status of the last call to + /// @ref Show. + Future ShowLastResult() const; + + /// Sets the @ref FullScreenContentListener for this @ref InterstitialAd. + /// + /// @param[in] listener A valid @ref FullScreenContentListener to receive + /// callbacks. + void SetFullScreenContentListener(FullScreenContentListener* listener); + + /// Registers a callback to be invoked when this ad is estimated to have + /// earned money + /// + /// @param[in] listener A valid @ref PaidEventListener to receive callbacks. + void SetPaidEventListener(PaidEventListener* listener); + + private: + // An internal, platform-specific implementation object that this class uses + // to interact with the Google Mobile Ads SDKs for iOS and Android. + internal::InterstitialAdInternal* internal_; +}; + +} // namespace gma +} // namespace firebase + +#endif // FIREBASE_GMA_SRC_INCLUDE_FIREBASE_GMA_INTERSTITIAL_AD_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/gma/rewarded_ad.h b/packages/firebase_core/firebase_core/firebase_core/firebase/gma/rewarded_ad.h new file mode 100644 index 000000000000..a3c5431486d4 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/gma/rewarded_ad.h @@ -0,0 +1,152 @@ +/* + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_GMA_SRC_INCLUDE_FIREBASE_GMA_REWARDED_AD_H_ +#define FIREBASE_GMA_SRC_INCLUDE_FIREBASE_GMA_REWARDED_AD_H_ + +#include + +#include "firebase/future.h" +#include "firebase/gma/types.h" +#include "firebase/internal/common.h" + +namespace firebase { +namespace gma { + +namespace internal { +// Forward declaration for platform-specific data, implemented in each library. +class RewardedAdInternal; +} // namespace internal + +/// @brief Loads and displays Google Mobile Ads rewarded ads. +/// +/// @ref RewardedAd is a single-use object that can load and show a +/// single GMA rewarded ad. +/// +/// RewardedAd objects provide information about their current state +/// through Futures. @ref Initialize, @ref LoadAd, and @ref Show each have a +/// corresponding @ref Future from which you can determine result of the +/// previous call. +/// +/// Here's how one might initialize, load, and show an rewarded ad while +/// checking against the result of the previous action at each step: +/// +/// @code +/// namespace gma = ::firebase::gma; +/// gma::RewardedAd* rewarded = new gma::RewardedAd(); +/// rewarded->Initialize(ad_parent); +/// @endcode +/// +/// Then, later: +/// +/// @code +/// if (rewarded->InitializeLastResult().status() == +/// ::firebase::kFutureStatusComplete && +/// rewarded->InitializeLastResult().error() == +/// firebase::gma::kAdErrorCodeNone) { +/// rewarded->LoadAd( "YOUR_AD_UNIT_ID", my_ad_request); +/// } +/// @endcode +/// +/// And after that: +/// +/// @code +/// if (rewarded->LoadAdLastResult().status() == +/// ::firebase::kFutureStatusComplete && +/// rewarded->LoadAdLastResult().error() == +/// firebase::gma::kAdErrorCodeNone)) { +/// rewarded->Show(&my_user_earned_reward_listener); +/// } +/// @endcode +class RewardedAd { + public: + /// Options for RewardedAd server-side verification callbacks. Set options on + /// a RewardedAd object using the @ref SetServerSideVerificationOptions + /// method. + struct ServerSideVerificationOptions { + /// Custom data to be included in server-side verification callbacks. + std::string custom_data; + + /// User id to be used in server-to-server reward callbacks. + std::string user_id; + }; + + /// Creates an uninitialized @ref RewardedAd object. + /// @ref Initialize must be called before the object is used. + RewardedAd(); + + ~RewardedAd(); + + /// Initialize the @ref RewardedAd object. + /// @param[in] parent The platform-specific UI element that will host the ad. + Future Initialize(AdParent parent); + + /// Returns a @ref Future containing the status of the last call to + /// @ref Initialize. + Future InitializeLastResult() const; + + /// Begins an asynchronous request for an ad. + /// + /// @param[in] ad_unit_id The ad unit ID to use in loading the ad. + /// @param[in] request An AdRequest struct with information about the request + /// to be made (such as targeting info). + Future LoadAd(const char* ad_unit_id, const AdRequest& request); + + /// Returns a @ref Future containing the status of the last call to + /// @ref LoadAd. + Future LoadAdLastResult() const; + + /// Shows the @ref RewardedAd. This should not be called unless an ad has + /// already been loaded. + /// + /// @param[in] listener The @ref UserEarnedRewardListener to be notified when + /// user earns a reward. + Future Show(UserEarnedRewardListener* listener); + + /// Returns a @ref Future containing the status of the last call to + /// @ref Show. + Future ShowLastResult() const; + + /// Sets the @ref FullScreenContentListener for this @ref RewardedAd. + /// + /// @param[in] listener A valid @ref FullScreenContentListener to receive + /// callbacks. + void SetFullScreenContentListener(FullScreenContentListener* listener); + + /// Registers a callback to be invoked when this ad is estimated to have + /// earned money + /// + /// @param[in] listener A valid @ref PaidEventListener to receive callbacks. + void SetPaidEventListener(PaidEventListener* listener); + + /// Sets the server side verification options. + /// + /// @param[in] serverSideVerificationOptions A @ref + /// ServerSideVerificationOptions object containing custom data and a user + /// Id. + void SetServerSideVerificationOptions( + const ServerSideVerificationOptions& serverSideVerificationOptions); + + private: + // An internal, platform-specific implementation object that this class uses + // to interact with the Google Mobile Ads SDKs for iOS and Android. + internal::RewardedAdInternal* internal_; +}; + +} // namespace gma +} // namespace firebase + +#endif // FIREBASE_GMA_SRC_INCLUDE_FIREBASE_GMA_REWARDED_AD_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/gma/types.h b/packages/firebase_core/firebase_core/firebase_core/firebase/gma/types.h new file mode 100644 index 000000000000..292ee4138a68 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/gma/types.h @@ -0,0 +1,939 @@ +/* + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_GMA_SRC_INCLUDE_FIREBASE_GMA_TYPES_H_ +#define FIREBASE_GMA_SRC_INCLUDE_FIREBASE_GMA_TYPES_H_ + +#include +#include +#include +#include +#include + +#include "firebase/future.h" +#include "firebase/internal/platform.h" + +#if FIREBASE_PLATFORM_ANDROID +#include +#elif FIREBASE_PLATFORM_IOS || FIREBASE_PLATFORM_TVOS +extern "C" { +#include +} // extern "C" +#endif // FIREBASE_PLATFORM_ANDROID, FIREBASE_PLATFORM_IOS, + // FIREBASE_PLATFORM_TVOS + +namespace firebase { +namespace gma { + +struct AdErrorInternal; +struct AdapterResponseInfoInternal; +struct BoundingBox; +struct ResponseInfoInternal; + +class AdapterResponseInfo; +class AdViewBoundingBoxListener; +class GmaInternal; +class AdView; +class InterstitialAd; +class PaidEventListener; +class ResponseInfo; + +namespace internal { +class AdViewInternal; +} + +/// This is a platform specific datatype that is required to create +/// a Google Mobile Ads ad. +/// +/// The following defines the datatype on each platform: +///
    +///
  • Android: A `jobject` which references an Android Activity.
  • +///
  • iOS: An `id` which references an iOS UIView.
  • +///
+#if FIREBASE_PLATFORM_ANDROID +/// An Android Activity from Java. +typedef jobject AdParent; +#elif FIREBASE_PLATFORM_IOS || FIREBASE_PLATFORM_TVOS +/// A pointer to an iOS UIView. +typedef id AdParent; +#else +/// A void pointer for stub classes. +typedef void* AdParent; +#endif // FIREBASE_PLATFORM_ANDROID, FIREBASE_PLATFORM_IOS, + // FIREBASE_PLATFORM_TVOS + +/// Error codes returned by Future::error(). +enum AdErrorCode { + /// Call completed successfully. + kAdErrorCodeNone, + /// The ad has not been fully initialized. + kAdErrorCodeUninitialized, + /// The ad is already initialized (repeat call). + kAdErrorCodeAlreadyInitialized, + /// A call has failed because an ad is currently loading. + kAdErrorCodeLoadInProgress, + /// A call to load an ad has failed due to an internal SDK error. + kAdErrorCodeInternalError, + /// A call to load an ad has failed due to an invalid request. + kAdErrorCodeInvalidRequest, + /// A call to load an ad has failed due to a network error. + kAdErrorCodeNetworkError, + /// A call to load an ad has failed because no ad was available to serve. + kAdErrorCodeNoFill, + /// An attempt has been made to show an ad on an Android Activity that has + /// no window token (such as one that's not done initializing). + kAdErrorCodeNoWindowToken, + /// An attempt to load an Ad Network extras class for an ad request has + /// failed. + kAdErrorCodeAdNetworkClassLoadError, + /// The ad server experienced a failure processing the request. + kAdErrorCodeServerError, + /// The current device’s OS is below the minimum required version. + kAdErrorCodeOSVersionTooLow, + /// The request was unable to be loaded before being timed out. + kAdErrorCodeTimeout, + /// Will not send request because the interstitial object has already been + /// used. + kAdErrorCodeInterstitialAlreadyUsed, + /// The mediation response was invalid. + kAdErrorCodeMediationDataError, + /// Error finding or creating a mediation ad network adapter. + kAdErrorCodeMediationAdapterError, + /// Attempting to pass an invalid ad size to an adapter. + kAdErrorCodeMediationInvalidAdSize, + /// Invalid argument error. + kAdErrorCodeInvalidArgument, + /// Received invalid response. + kAdErrorCodeReceivedInvalidResponse, + /// Will not send a request because the rewarded ad object has already been + /// used. + kAdErrorCodeRewardedAdAlreadyUsed, + /// A mediation ad network adapter received an ad request, but did not fill. + /// The adapter’s error is included as an underlyingError. + kAdErrorCodeMediationNoFill, + /// Will not send request because the ad object has already been used. + kAdErrorCodeAdAlreadyUsed, + /// Will not send request because the application identifier is missing. + kAdErrorCodeApplicationIdentifierMissing, + /// Android Ad String is invalid. + kAdErrorCodeInvalidAdString, + /// The ad can not be shown when app is not in the foreground. + kAdErrorCodeAppNotInForeground, + /// A mediation adapter failed to show the ad. + kAdErrorCodeMediationShowError, + /// The ad is not ready to be shown. + kAdErrorCodeAdNotReady, + /// Ad is too large for the scene. + kAdErrorCodeAdTooLarge, + /// Attempted to present ad from a non-main thread. This is an internal + /// error which should be reported to support if encountered. + kAdErrorCodeNotMainThread, + /// A debug operation failed because the device is not in test mode. + kAdErrorCodeNotInTestMode, + /// An attempt to load the Ad Inspector failed. + kAdErrorCodeInspectorFailedToLoad, + /// The request to show the Ad Inspector failed because it's already open. + kAdErrorCodeInsepctorAlreadyOpen, + /// Fallback error for any unidentified cases. + kAdErrorCodeUnknown, +}; + +/// A listener for receiving notifications during the lifecycle of a BannerAd. +class AdListener { + public: + virtual ~AdListener(); + + /// Called when a click is recorded for an ad. + virtual void OnAdClicked() {} + + /// Called when the user is about to return to the application after clicking + /// on an ad. + virtual void OnAdClosed() {} + + /// Called when an impression is recorded for an ad. + virtual void OnAdImpression() {} + + /// Called when an ad opens an overlay that covers the screen. + virtual void OnAdOpened() {} +}; + +/// Information about why an ad operation failed. +class AdError { + public: + /// Default Constructor. + AdError(); + + /// Copy Constructor. + AdError(const AdError& ad_error); + + /// Destructor. + virtual ~AdError(); + + /// Assignment operator. + AdError& operator=(const AdError& obj); + + /// Retrieves an AdError which represents the cause of this error. + /// + /// @return a pointer to an adError which represents the cause of this + /// AdError. If there was no cause then nullptr is returned. + std::unique_ptr GetCause() const; + + /// Gets the error's code. + AdErrorCode code() const; + + /// Gets the domain of the error. + const std::string& domain() const; + + /// Gets the message describing the error. + const std::string& message() const; + + /// Gets the ResponseInfo if an error occurred during a loadAd operation. + /// The ResponseInfo will have empty fields if this AdError does not + /// represent an error stemming from a load ad operation. + const ResponseInfo& response_info() const; + + /// Returns a log friendly string version of this object. + virtual const std::string& ToString() const; + + /// A domain string which represents an undefined error domain. + /// + /// The GMA SDK returns this domain for domain() method invocations when + /// converting error information from legacy mediation adapter callbacks. + static const char* const kUndefinedDomain; + + private: + friend class AdapterResponseInfo; + friend class GmaInternal; + friend class AdView; + friend class InterstitialAd; + + /// Constructor used when building results in Ad event callbacks. + explicit AdError(const AdErrorInternal& ad_error_internal); + + // Collection of response from adapters if this Result is due to a loadAd + // operation. + ResponseInfo* response_info_; + + // An internal, platform-specific implementation object that this class uses + // to interact with the Google Mobile Ads SDKs for iOS and Android. + AdErrorInternal* internal_; +}; + +/// Information about an ad response. +class ResponseInfo { + public: + /// Constructor creates an uninitialized ResponseInfo. + ResponseInfo(); + + /// Gets the AdapterResponseInfo objects for the ad response. + /// + /// @return a vector of AdapterResponseInfo objects containing metadata for + /// each adapter included in the ad response. + const std::vector& adapter_responses() const { + return adapter_responses_; + } + + /// A class name that identifies the ad network that returned the ad. + /// Returns an empty string if the ad failed to load. + const std::string& mediation_adapter_class_name() const { + return mediation_adapter_class_name_; + } + + /// Gets the response ID string for the loaded ad. Returns an empty + /// string if the ad fails to load. + const std::string& response_id() const { return response_id_; } + + /// Gets a log friendly string version of this object. + const std::string& ToString() const { return to_string_; } + + private: + friend class AdError; + friend class GmaInternal; + + explicit ResponseInfo(const ResponseInfoInternal& internal); + + std::vector adapter_responses_; + std::string mediation_adapter_class_name_; + std::string response_id_; + std::string to_string_; +}; + +/// Information about the result of an ad operation. +class AdResult { + public: + /// Default Constructor. + AdResult(); + + /// Constructor. + explicit AdResult(const AdError& ad_error); + + /// Destructor. + virtual ~AdResult(); + + /// Returns true if the operation was successful. + bool is_successful() const; + + /// An object representing an error which occurred during an ad operation. + /// If the @ref AdResult::is_successful() returned true, then the + /// @ref AdError object returned via this method will contain no contextual + /// information. + const AdError& ad_error() const; + + /// For debugging and logging purposes, successfully loaded ads provide a + /// ResponseInfo object which contains information about the adapter which + /// loaded the ad. If the ad failed to load then the object returned from + /// this method will have default values. Information about the error + /// should be retrieved via @ref AdResult::ad_error() instead. + const ResponseInfo& response_info() const; + + private: + friend class GmaInternal; + + /// Constructor invoked upon successful ad load. This contains response + /// information from the adapter which loaded the ad. + explicit AdResult(const ResponseInfo& response_info); + + /// Denotes if the @ref AdResult represents a success or an error. + bool is_successful_; + + /// Information about the error. Will be a default-constructed @ref AdError + /// if this result represents a success. + AdError ad_error_; + + /// Information from the adapter which loaded the ad. + ResponseInfo response_info_; +}; + +/// A snapshot of a mediation adapter's initialization status. +class AdapterStatus { + public: + AdapterStatus() : is_initialized_(false), latency_(0) {} + + /// Detailed description of the status. + /// + /// This method should only be used for informational purposes, such as + /// logging. Use @ref is_initialized to make logical decisions regarding an + /// adapter's status. + const std::string& description() const { return description_; } + + /// Returns the adapter's initialization state. + bool is_initialized() const { return is_initialized_; } + + /// The adapter's initialization latency in milliseconds. + /// 0 if initialization has not yet ended. + int latency() const { return latency_; } + +#if !defined(DOXYGEN) + // Equality operator for testing. + bool operator==(const AdapterStatus& rhs) const { + return (description() == rhs.description() && + is_initialized() == rhs.is_initialized() && + latency() == rhs.latency()); + } +#endif // !defined(DOXYGEN) + + private: + friend class GmaInternal; + std::string description_; + bool is_initialized_; + int latency_; +}; + +/// An immutable snapshot of the GMA SDK’s initialization status, categorized +/// by mediation adapter. +class AdapterInitializationStatus { + public: + /// Initialization status of each known ad network, keyed by its adapter's + /// class name. + std::map GetAdapterStatusMap() const { + return adapter_status_map_; + } +#if !defined(DOXYGEN) + // Equality operator for testing. + bool operator==(const AdapterInitializationStatus& rhs) const { + return (GetAdapterStatusMap() == rhs.GetAdapterStatusMap()); + } +#endif // !defined(DOXYGEN) + + private: + friend class GmaInternal; + std::map adapter_status_map_; +}; + +/// Listener to be invoked when the Ad Inspector has been closed. +class AdInspectorClosedListener { + public: + virtual ~AdInspectorClosedListener(); + + /// Called when the user clicked the ad. The AdResult contains the status of + /// the operation, including details of the error if one occurred. + virtual void OnAdInspectorClosed(const AdResult& ad_result) = 0; +}; + +/// @brief Response information for an individual ad network contained within +/// a @ref ResponseInfo object. +class AdapterResponseInfo { + public: + /// Destructor + ~AdapterResponseInfo(); + + /// @brief Information about the result including whether an error + /// occurred, and any contextual information about that error. + /// + /// @return the error that occurred while rendering the ad. If no error + /// occurred then the AdResult's successful method will return true. + AdResult ad_result() const { return ad_result_; } + + /// Returns a string representation of a class name that identifies the ad + /// network adapter. + const std::string& adapter_class_name() const { return adapter_class_name_; } + + /// Amount of time the ad network spent loading an ad. + /// + /// @return number of milliseconds the network spent loading an ad. This value + /// is 0 if the network did not make a load attempt. + int64_t latency_in_millis() const { return latency_; } + + /// A log friendly string version of this object. + const std::string& ToString() const { return to_string_; } + + private: + friend class ResponseInfo; + + /// Constructs an Adapter Response Info Object. + explicit AdapterResponseInfo(const AdapterResponseInfoInternal& internal); + + AdResult ad_result_; + std::string adapter_class_name_; + int64_t latency_; + std::string to_string_; +}; + +/// The size of a banner ad. +class AdSize { + public: + /// Denotes the orientation of the AdSize. + enum Orientation { + /// AdSize should reflect the current orientation of the device. + kOrientationCurrent = 0, + + /// AdSize will be adaptively formatted in Landscape mode. + kOrientationLandscape, + + /// AdSize will be adaptively formatted in Portrait mode. + kOrientationPortrait + }; + + /// Denotes the type size object that the @ref AdSize represents. + enum Type { + /// The standard AdSize type of a set height and width. + kTypeStandard = 0, + + /// An adaptive size anchored to a portion of the screen. + kTypeAnchoredAdaptive, + + /// An adaptive size intended to be embedded in scrollable content. + kTypeInlineAdaptive, + }; + + /// Mobile Marketing Association (MMA) banner ad size (320x50 + /// density-independent pixels). + static const AdSize kBanner; + + /// Interactive Advertising Bureau (IAB) full banner ad size + /// (468x60 density-independent pixels). + static const AdSize kFullBanner; + + /// Taller version of kBanner. Typically 320x100. + static const AdSize kLargeBanner; + + /// Interactive Advertising Bureau (IAB) leaderboard ad size + /// (728x90 density-independent pixels). + static const AdSize kLeaderboard; + + /// Interactive Advertising Bureau (IAB) medium rectangle ad size + /// (300x250 density-independent pixels). + static const AdSize kMediumRectangle; + + /// Creates a new AdSize. + /// + /// @param[in] width The width of the ad in density-independent pixels. + /// @param[in] height The height of the ad in density-independent pixels. + AdSize(uint32_t width, uint32_t height); + + /// @brief Creates an AdSize with the given width and a Google-optimized + /// height to create a banner ad in landscape mode. + /// + /// @param[in] width The width of the ad in density-independent pixels. + /// + /// @return an AdSize with the given width and a Google-optimized height + /// to create a banner ad. The size returned will have an aspect ratio + /// similar to BANNER, suitable for anchoring near the top or bottom of + /// your app. The exact size of the ad returned can be retrieved by calling + /// @ref AdView::ad_size once the ad has been loaded. + static AdSize GetLandscapeAnchoredAdaptiveBannerAdSize(uint32_t width); + + /// @brief Creates an AdSize with the given width and a Google-optimized + /// height to create a banner ad in portrait mode. + /// + /// @param[in] width The width of the ad in density-independent pixels. + /// + /// @return an AdSize with the given width and a Google-optimized height + /// to create a banner ad. The size returned will have an aspect ratio + /// similar to BANNER, suitable for anchoring near the top or bottom + /// of your app. The exact size of the ad returned can be retrieved by + /// calling @ref AdView::ad_size once the ad has been loaded. + static AdSize GetPortraitAnchoredAdaptiveBannerAdSize(uint32_t width); + + /// @brief Creates an AdSize with the given width and a Google-optimized + /// height to create a banner ad given the current orientation. + /// + /// @param[in] width The width of the ad in density-independent pixels. + /// + /// @return an AdSize with the given width and a Google-optimized height + /// to create a banner ad. The size returned will have an aspect ratio + /// similar to AdSize, suitable for anchoring near the top or bottom of + /// your app. The exact size of the ad returned can be retrieved by calling + /// @ref AdView::ad_size once the ad has been loaded. + static AdSize GetCurrentOrientationAnchoredAdaptiveBannerAdSize( + uint32_t width); + + /// @brief This ad size is most suitable for banner ads given a maximum + /// height. + /// + /// This AdSize allows Google servers to choose an optimal ad size with + /// a height less than or equal to the max height given in + /// + /// @param[in] width The width of the ad in density-independent pixels. + /// @param[in] max_height The maximum height that a loaded ad will have. Must + /// be + /// at least 32 dp, but a maxHeight of 50 dp or higher is recommended. + /// + /// @return an AdSize with the given width and a height that is always 0. + /// The exact size of the ad returned can be retrieved by calling + /// @ref AdView::ad_size once the ad has been loaded. + static AdSize GetInlineAdaptiveBannerAdSize(int width, int max_height); + + /// @brief Creates an AdSize with the given width and the device’s + /// landscape height. + /// + /// This ad size allows Google servers to choose an optimal ad size with + /// a height less than or equal to the height of the screen in landscape + /// orientation. + /// + /// @param[in] width The width of the ad in density-independent pixels. + /// + /// @return an AdSize with the given width and a height that is always 0. + /// The exact size of the ad returned can be retrieved by calling + /// @ref AdView::ad_size once the ad has been loaded. + static AdSize GetLandscapeInlineAdaptiveBannerAdSize(int width); + + /// @brief Creates an AdSize with the given width and the device’s + /// portrait height. + /// + /// This ad size allows Google servers to choose an optimal ad size with + /// a height less than or equal to the height of the screen in portrait + /// orientation. + /// + /// @param[in] width The width of the ad in density-independent pixels. + /// + /// @return an AdSize with the given width and a height that is always 0. + /// The exact size of the ad returned can be retrieved by calling + /// @ref AdView::ad_size once the ad has been loaded. + static AdSize GetPortraitInlineAdaptiveBannerAdSize(int width); + + /// @brief A convenience method to return an inline adaptive banner ad size + /// given the current interface orientation. + /// + /// This AdSize allows Google servers to choose an optimal ad size with a + /// height less than or equal to the height of the screen in the requested + /// orientation. + /// + /// @param[in] width The width of the ad in density-independent pixels. + /// + /// @return an AdSize with the given width and a height that is always 0. + /// The exact size of the ad returned can be retrieved by calling + /// @ref AdView::ad_size once the ad has been loaded. + static AdSize GetCurrentOrientationInlineAdaptiveBannerAdSize(int width); + + /// Comparison operator. + /// + /// @return true if `rhs` refers to the same AdSize as `this`. + bool operator==(const AdSize& rhs) const; + + /// Comparison operator. + /// + /// @returns true if `rhs` refers to a different AdSize as `this`. + bool operator!=(const AdSize& rhs) const; + + /// The width of the region represented by this AdSize. Value is in + /// density-independent pixels. + uint32_t width() const { return width_; } + + /// The height of the region represented by this AdSize. Value is in + /// density-independent pixels. + uint32_t height() const { return height_; } + + /// The AdSize orientation. + Orientation orientation() const { return orientation_; } + + /// The AdSize type, either standard size or adaptive. + Type type() const { return type_; } + + private: + friend class firebase::gma::internal::AdViewInternal; + + /// Returns an Anchor Adpative AdSize Object given a width and orientation. + static AdSize GetAnchoredAdaptiveBannerAdSize(uint32_t width, + Orientation orientation); + + /// Returns true if the AdSize parameter is equivalient to this AdSize object. + bool is_equal(const AdSize& ad_size) const; + + /// Denotes the orientation for anchored adaptive AdSize objects. + Orientation orientation_; + + /// Advertisement width in platform-indepenent pixels. + uint32_t width_; + + /// Advertisement width in platform-indepenent pixels. + uint32_t height_; + + /// The type of AdSize (standard or adaptive) + Type type_; +}; + +/// Contains targeting information used to fetch an ad. +class AdRequest { + public: + /// Creates an @ref AdRequest with no custom configuration. + AdRequest(); + + /// Creates an @ref AdRequest with the optional content URL. + /// + /// When requesting an ad, apps may pass the URL of the content they are + /// serving. This enables keyword targeting to match the ad with the content. + /// + /// The URL is ignored if null or the number of characters exceeds 512. + /// + /// @param[in] content_url the url of the content being viewed. + explicit AdRequest(const char* content_url); + + ~AdRequest(); + + /// The content URL targeting information. + /// + /// @return the content URL for the @ref AdRequest. The string will be empty + /// if no content URL has been configured. + const std::string& content_url() const { return content_url_; } + + /// A Map of adapter class names to their collection of extra parameters, as + /// configured via @ref add_extra. + const std::map >& extras() + const { + return extras_; + } + + /// Keywords which will help GMA to provide targeted ads, as added by + /// @ref add_keyword. + const std::unordered_set& keywords() const { return keywords_; } + + /// Returns the set of neighboring content URLs or an empty set if no URLs + /// were set via @ref add_neighboring_content_urls(). + const std::unordered_set& neighboring_content_urls() const { + return neighboring_content_urls_; + } + + /// Add a network extra for the associated ad mediation adapter. + /// + /// Appends an extra to the corresponding list of extras for the ad mediation + /// adapter. Each ad mediation adapter can have multiple extra strings. + /// + /// @param[in] adapter_class_name the class name of the ad mediation adapter + /// for which to add the extra. + /// @param[in] extra_key a key which will be passed to the corresponding ad + /// mediation adapter. + /// @param[in] extra_value the value associated with extra_key. + void add_extra(const char* adapter_class_name, const char* extra_key, + const char* extra_value); + + /// Adds a keyword for targeting purposes. + /// + /// Multiple keywords may be added via repeated invocations of this method. + /// + /// @param[in] keyword a string that GMA will use to aid in targeting ads. + void add_keyword(const char* keyword); + + /// When requesting an ad, apps may pass the URL of the content they are + /// serving. This enables keyword targeting to match the ad with the content. + /// + /// The URL is ignored if null or the number of characters exceeds 512. + /// + /// @param[in] content_url the url of the content being viewed. + void set_content_url(const char* content_url); + + /// Adds to the list of URLs which represent web content near an ad. + /// + /// Promotes brand safety and allows displayed ads to have an app level + /// rating (MA, T, PG, etc) that is more appropriate to neighboring content. + /// + /// Subsequent invocations append to the existing list. + /// + /// @param[in] neighboring_content_urls neighboring content URLs to be + /// attached to the existing neighboring content URLs. + void add_neighboring_content_urls( + const std::vector& neighboring_content_urls); + + private: + std::string content_url_; + std::map > extras_; + std::unordered_set keywords_; + std::unordered_set neighboring_content_urls_; +}; + +/// Describes a reward credited to a user for interacting with a RewardedAd. +class AdReward { + public: + /// Creates an @ref AdReward. + AdReward(const std::string& type, int64_t amount) + : type_(type), amount_(amount) {} + + /// Returns the reward amount. + int64_t amount() const { return amount_; } + + /// Returns the type of the reward. + const std::string& type() const { return type_; } + + private: + const int64_t amount_; + const std::string type_; +}; + +/// The monetary value earned from an ad. +class AdValue { + public: + /// Allowed constants for @ref precision_type(). + enum PrecisionType { + /// An ad value with unknown precision. + kdValuePrecisionUnknown = 0, + /// An ad value estimated from aggregated data. + kAdValuePrecisionEstimated, + /// A publisher-provided ad value, such as manual CPMs in a mediation group. + kAdValuePrecisionPublisherProvided = 2, + /// The precise value paid for this ad. + kAdValuePrecisionPrecise = 3 + }; + + /// Constructor + AdValue(const char* currency_code, PrecisionType precision_type, + int64_t value_micros) + : currency_code_(currency_code), + precision_type_(precision_type), + value_micros_(value_micros) {} + + /// The value's ISO 4217 currency code. + const std::string& currency_code() const { return currency_code_; } + + /// The precision of the reported ad value. + PrecisionType precision_type() const { return precision_type_; } + + /// The ad's value in micro-units, where 1,000,000 micro-units equal one + /// unit of the currency. + int64_t value_micros() const { return value_micros_; } + + private: + const std::string currency_code_; + const PrecisionType precision_type_; + const int64_t value_micros_; +}; + +/// @brief Listener to be invoked when ads show and dismiss full screen content, +/// such as a fullscreen ad experience or an in-app browser. +class FullScreenContentListener { + public: + virtual ~FullScreenContentListener(); + + /// Called when the user clicked the ad. + virtual void OnAdClicked() {} + + /// Called when the ad dismissed full screen content. + virtual void OnAdDismissedFullScreenContent() {} + + /// Called when the ad failed to show full screen content. + /// + /// @param[in] ad_error An object containing detailed information + /// about the error. + virtual void OnAdFailedToShowFullScreenContent(const AdError& ad_error) {} + + /// Called when an impression is recorded for an ad. + virtual void OnAdImpression() {} + + /// Called when the ad showed the full screen content. + virtual void OnAdShowedFullScreenContent() {} +}; + +/// Listener to be invoked when ads have been estimated to earn money. +class PaidEventListener { + public: + virtual ~PaidEventListener(); + + /// Called when an ad is estimated to have earned money. + virtual void OnPaidEvent(const AdValue& value) {} +}; + +/// @brief Global configuration that will be used for every @ref AdRequest. +/// Set the configuration via @ref SetRequestConfiguration. +struct RequestConfiguration { + /// A maximum ad content rating, which may be configured via + /// @ref max_ad_content_rating. + enum MaxAdContentRating { + /// No content rating has been specified. + kMaxAdContentRatingUnspecified = -1, + + /// Content suitable for general audiences, including families. + kMaxAdContentRatingG, + + /// Content suitable only for mature audiences. + kMaxAdContentRatingMA, + + /// Content suitable for most audiences with parental guidance. + kMaxAdContentRatingPG, + + /// Content suitable for teen and older audiences. + kMaxAdContentRatingT + }; + + /// Specify whether you would like your app to be treated as child-directed + /// for purposes of the Children’s Online Privacy Protection Act (COPPA). + /// Values defined here may be configured via + /// @ref tag_for_child_directed_treatment. + enum TagForChildDirectedTreatment { + /// Indicates that ad requests will include no indication of how you would + /// like your app treated with respect to COPPA. + kChildDirectedTreatmentUnspecified = -1, + + /// Indicates that your app should not be treated as child-directed for + /// purposes of the Children’s Online Privacy Protection Act (COPPA). + kChildDirectedTreatmentFalse, + + /// Indicates that your app should be treated as child-directed for purposes + /// of the Children’s Online Privacy Protection Act (COPPA). + kChildDirectedTreatmentTrue + }; + + /// Configuration values to mark your app to receive treatment for users in + /// the European Economic Area (EEA) under the age of consent. Values defined + /// here should be configured via @ref tag_for_under_age_of_consent. + enum TagForUnderAgeOfConsent { + /// Indicates that the publisher has not specified whether the ad request + /// should receive treatment for users in the European Economic Area (EEA) + /// under the age of consent. + kUnderAgeOfConsentUnspecified = -1, + + /// Indicates the publisher specified that the ad request should not receive + /// treatment for users in the European Economic Area (EEA) under the age of + /// consent. + kUnderAgeOfConsentFalse, + + /// Indicates the publisher specified that the ad request should receive + /// treatment for users in the European Economic Area (EEA) under the age of + /// consent. + kUnderAgeOfConsentTrue + }; + + /// Sets a maximum ad content rating. GMA ads returned for your app will + /// have a content rating at or below that level. + MaxAdContentRating max_ad_content_rating; + + /// @brief Allows you to specify whether you would like your app + /// to be treated as child-directed for purposes of the Children’s Online + /// Privacy Protection Act (COPPA) - + /// http://business.ftc.gov/privacy-and-security/childrens-privacy. + /// + /// If you set this value to + /// RequestConfiguration.kChildDirectedTreatmentTrue, you will indicate + /// that your app should be treated as child-directed for purposes of the + /// Children’s Online Privacy Protection Act (COPPA). + /// + /// If you set this value to + /// RequestConfiguration.kChildDirectedTreatmentFalse, you will indicate + /// that your app should not be treated as child-directed for purposes of the + /// Children’s Online Privacy Protection Act (COPPA). + /// + /// If you do not set this value, or set this value to + /// RequestConfiguration.kChildDirectedTreatmentUnspecified, ad requests will + /// include no indication of how you would like your app treated with respect + /// to COPPA. + /// + /// By setting this value, you certify that this notification is accurate and + /// you are authorized to act on behalf of the owner of the app. You + /// understand that abuse of this setting may result in termination of your + /// Google account. + /// + /// @note: it may take some time for this designation to be fully implemented + /// in applicable Google services. + /// + TagForChildDirectedTreatment tag_for_child_directed_treatment; + + /// This value allows you to mark your app to receive treatment for users in + /// the European Economic Area (EEA) under the age of consent. This feature is + /// designed to help facilitate compliance with the General Data Protection + /// Regulation (GDPR). Note that you may have other legal obligations under + /// GDPR. Please review the European Union's guidance and consult with your + /// own legal counsel. Please remember that Google's tools are designed to + /// facilitate compliance and do not relieve any particular publisher of its + /// obligations under the law. + /// + /// When using this feature, a Tag For Users under the Age of Consent in + /// Europe (TFUA) parameter will be included in all ad requests. This + /// parameter disables personalized advertising, including remarketing, for + /// that specific ad request. It also disables requests to third-party ad + /// vendors, such as ad measurement pixels and third-party ad servers. + /// + /// If you set this value to RequestConfiguration.kUnderAgeOfConsentTrue, you + /// will indicate that you want your app to be handled in a manner suitable + /// for users under the age of consent. + /// + /// If you set this value to RequestConfiguration.kUnderAgeOfConsentFalse, + /// you will indicate that you don't want your app to be handled in a manner + /// suitable for users under the age of consent. + /// + /// If you do not set this value, or set this value to + /// kUnderAgeOfConsentUnspecified, your app will include no indication of how + /// you would like your app to be handled in a manner suitable for users under + /// the age of consent. + TagForUnderAgeOfConsent tag_for_under_age_of_consent; + + /// Sets a list of test device IDs corresponding to test devices which will + /// always request test ads. + std::vector test_device_ids; +}; + +/// Listener to be invoked when the user earned a reward. +class UserEarnedRewardListener { + public: + virtual ~UserEarnedRewardListener(); + /// Called when the user earned a reward. The app is responsible for + /// crediting the user with the reward. + /// + /// @param[in] reward the @ref AdReward that should be granted to the user. + virtual void OnUserEarnedReward(const AdReward& reward) {} +}; + +} // namespace gma +} // namespace firebase + +#endif // FIREBASE_GMA_SRC_INCLUDE_FIREBASE_GMA_TYPES_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/installations.h b/packages/firebase_core/firebase_core/firebase_core/firebase/installations.h new file mode 100644 index 000000000000..c9774bc37e73 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/installations.h @@ -0,0 +1,123 @@ +// Copyright 2020 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef FIREBASE_INSTALLATIONS_SRC_INCLUDE_FIREBASE_INSTALLATIONS_H_ +#define FIREBASE_INSTALLATIONS_SRC_INCLUDE_FIREBASE_INSTALLATIONS_H_ + +#include +#include + +#include "firebase/app.h" +#include "firebase/future.h" +#include "firebase/internal/common.h" + +/// @brief Namespace that encompasses all Firebase APIs. +namespace firebase { + +namespace installations { + +/// Installations error codes. +enum Error { + kErrorNone = 0, + /// An unknown error occurred. + kErrorUnknown, + /// Installations service cannot be accessed. + kErrorNoAccess, + /// Some of the parameters of the request were invalid. + kErrorInvalidConfiguration, +}; + +namespace internal { +// Implementation specific data for an Installation. +class InstallationsInternal; +} // namespace internal + +/// @brief Installations provides a unique identifier for each app instance and +/// a mechanism to authenticate and authorize actions (for example, sending an +/// FCM message). +/// +/// Provides a unique identifier for a Firebase installation. +/// Provides an auth token for a Firebase installation. +/// Provides a API to perform data deletion for a Firebase +/// installation. +class Installations { + public: + ~Installations(); + + /// @brief Get the App this object is connected to. + /// + /// @return App this object is connected to. + App* app() const { return app_; } + + /// @brief Returns the Installations object for an App creating the + /// Installations if required. + /// + /// @param[in] app The App to create an Installations object from. + /// + /// @return Installations object if successful, nullptr otherwise. + static Installations* GetInstance(App* app); + + /// @brief Returns a stable identifier that uniquely identifies the app + /// installation. + /// + /// @return Unique identifier for the app installation. + Future GetId(); + + /// @brief Get the results of the most recent call to @ref GetId. + Future GetIdLastResult(); + + /// @brief Call to delete this Firebase app installation from the Firebase + /// backend. + Future Delete(); + + /// @brief Get the results of the most recent call to @ref Delete. + Future DeleteLastResult(); + + /// @brief Returns a token that authorizes an Entity to perform an action on + /// behalf of the application identified by installations. + /// + /// This is similar to an OAuth2 token except it applies to the + /// application instance instead of a user. + /// + /// For example, to get a token that can be used to send messages to an + /// application via Firebase Cloud Messaging, set entity to the + /// sender ID, and set scope to "FCM". + /// + /// @param forceRefresh If set true, will always return a new token. + /// + /// @return Returns a valid authentication token for the Firebase + /// installation. + Future GetToken(bool forceRefresh); + + /// @brief Get the results of the most recent call to @ref GetToken. + Future GetTokenLastResult(); + + private: + explicit Installations(App* app); + + static Installations* FindInstallations(App* app); + // Installations internal initialize. + bool InitInternal(); + // Clean up Installations instance. + void DeleteInternal(); + + App* app_; + internal::InstallationsInternal* installations_internal_; +}; + +} // namespace installations + +} // namespace firebase + +#endif // FIREBASE_INSTALLATIONS_SRC_INCLUDE_FIREBASE_INSTALLATIONS_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/internal/common.h b/packages/firebase_core/firebase_core/firebase_core/firebase/internal/common.h new file mode 100644 index 000000000000..2e2878a0bd97 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/internal/common.h @@ -0,0 +1,128 @@ +/* + * Copyright 2016 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_APP_SRC_INCLUDE_FIREBASE_INTERNAL_COMMON_H_ +#define FIREBASE_APP_SRC_INCLUDE_FIREBASE_INTERNAL_COMMON_H_ + +// This file contains definitions that configure the SDK. + +// Include a STL header file, othewise _STLPORT_VERSION won't be set. +#include + +// Move operators use rvalue references, which are a C++11 extension. +// Also, Visual Studio 2010 and later actually support move operators despite +// reporting __cplusplus to be 199711L, so explicitly check for that. +// Also, stlport doesn't implement std::move(). +#if (__cplusplus >= 201103L || _MSC_VER >= 1600) && !defined(_STLPORT_VERSION) +#define FIREBASE_USE_MOVE_OPERATORS +#endif + +// stlport doesn't implement std::function. +#if !defined(_STLPORT_VERSION) +#define FIREBASE_USE_STD_FUNCTION +#endif // !defined(_STLPORT_VERSION) + +// stlport doesn't implement std::aligned_storage. +#if defined(_STLPORT_VERSION) +#include + +namespace firebase { +template +struct AlignedStorage { + struct type { + alignas(Alignment) unsigned char data[Length]; + }; +}; +} // namespace firebase +#define FIREBASE_ALIGNED_STORAGE ::firebase::AlignedStorage +#else +#include +#define FIREBASE_ALIGNED_STORAGE std::aligned_storage +#endif // defined(_STLPORT_VERSION) + +// Visual Studio 2013 does not support snprintf, so use streams instead. +#if !(defined(_MSC_VER) && _MSC_VER <= 1800) +#define FIREBASE_USE_SNPRINTF +#endif // !(defined(_MSC_VER) && _MSC_VER <= 1800) + +#if !(defined(_MSC_VER) && _MSC_VER <= 1800) +#define FIREBASE_USE_EXPLICIT_DEFAULT_METHODS +#endif // !(defined(_MSC_VER) && _MSC_VER <= 1800) + +#if !defined(DOXYGEN) && !defined(SWIG) +#if !defined(_WIN32) && !defined(__CYGWIN__) +// Prevent GCC & Clang from stripping a symbol. +#define FIREBASE_APP_KEEP_SYMBOL __attribute__((used)) +#else +// MSVC needs to reference a symbol directly in the application for it to be +// kept in the final executable. In this case, the end user's application +// must include the appropriate Firebase header (e.g firebase/analytics.h) to +// initialize the module. +#define FIREBASE_APP_KEEP_SYMBOL +#endif // !defined(_WIN32) && !defined(__CYGWIN__) + +// Module initializer's name. +// +// This can be used to explicitly include a module initializer in an application +// to prevent the object from being stripped by the linker. The symbol is +// located in the "firebase" namespace so can be referenced using: +// +// ::firebase::FIREBASE_APP_REGISTER_CALLBACKS_REFERENCE_NAME(name) +// +// Where "name" is the module name, for example "analytics". +#define FIREBASE_APP_REGISTER_CALLBACKS_INITIALIZER_NAME(module_name) \ + g_##module_name##_initializer + +// Declare a module initializer variable as a global. +#define FIREBASE_APP_REGISTER_CALLBACKS_INITIALIZER_VARIABLE(module_name) \ + namespace firebase { \ + extern void* FIREBASE_APP_REGISTER_CALLBACKS_INITIALIZER_NAME(module_name); \ + } /* namespace firebase */ + +// Generates code which references a module initializer. +// For example, FIREBASE_APP_REGISTER_REFERENCE(analytics) will register the +// module initializer for the analytics module. +#define FIREBASE_APP_REGISTER_CALLBACKS_REFERENCE(module_name) \ + FIREBASE_APP_REGISTER_CALLBACKS_INITIALIZER_VARIABLE(module_name) \ + namespace firebase { \ + static void* module_name##_ref FIREBASE_APP_KEEP_SYMBOL = \ + &FIREBASE_APP_REGISTER_CALLBACKS_INITIALIZER_NAME(module_name); \ + } /* namespace firebase */ +#endif // !defined(DOXYGEN) && !defined(SWIG) + +#if defined(SWIG) || defined(DOXYGEN) +// SWIG needs to ignore the FIREBASE_DEPRECATED tag. +#define FIREBASE_DEPRECATED +#endif // defined(SWIG) || defined(DOXYGEN) + +#ifndef FIREBASE_DEPRECATED +#ifdef __GNUC__ +#define FIREBASE_DEPRECATED __attribute__((deprecated)) +#elif defined(_MSC_VER) +#define FIREBASE_DEPRECATED __declspec(deprecated) +#else +// We don't know how to mark functions as "deprecated" with this compiler. +#define FIREBASE_DEPRECATED +#endif +#endif // FIREBASE_DEPRECATED + +// Calculates the number of elements in an array. +#define FIREBASE_ARRAYSIZE(x) (sizeof(x) / sizeof((x)[0])) + +// Guaranteed compile time strlen. +#define FIREBASE_STRLEN(s) (FIREBASE_ARRAYSIZE(s) - sizeof((s)[0])) + +#endif // FIREBASE_APP_SRC_INCLUDE_FIREBASE_INTERNAL_COMMON_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/internal/future_impl.h b/packages/firebase_core/firebase_core/firebase_core/firebase/internal/future_impl.h new file mode 100644 index 000000000000..59e7771d010b --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/internal/future_impl.h @@ -0,0 +1,359 @@ +/* + * Copyright 2016 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_APP_SRC_INCLUDE_FIREBASE_INTERNAL_FUTURE_IMPL_H_ +#define FIREBASE_APP_SRC_INCLUDE_FIREBASE_INTERNAL_FUTURE_IMPL_H_ + +/// @cond FIREBASE_APP_INTERNAL + +// You shouldn't include future_impl.h directly, since its just the inline +// implementation of the functions in future.h. Include future.h instead. +#include "firebase/future.h" + +#if defined(FIREBASE_USE_MOVE_OPERATORS) +#include +#endif // defined(FIREBASE_USE_MOVE_OPERATORS) + +namespace firebase { + +class ReferenceCountedFutureImpl; + +namespace detail { + +class CompletionCallbackHandle; + +/// Pure-virtual interface that APIs must implement to use Futures. +class FutureApiInterface { + public: + // typedef void FutureCallbackFn(const FutureBase* future); + virtual ~FutureApiInterface(); + + /// Increment the reference count on handle's asynchronous call. + /// Called when the Future is copied. + virtual void ReferenceFuture(const FutureHandle& handle) = 0; + + /// Decrement the reference count on handle's asynchronous call. + /// Called when the Future is destroyed or moved. + /// If the reference count drops to zero, the asynchronous call can be + /// forgotten. + virtual void ReleaseFuture(const FutureHandle& handle) = 0; + + /// Return the status of the asynchronous call. + virtual FutureStatus GetFutureStatus(const FutureHandle& handle) const = 0; + + /// Return the API-specific error. + /// Valid when GetFutureStatus() is kFutureStatusComplete, and undefined + /// otherwise. + virtual int GetFutureError(const FutureHandle& handle) const = 0; + + /// Return the API-specific error, in human-readable form, or "" if no message + /// has been provided. + /// Valid when GetFutureStatus() is kFutureStatusComplete, and undefined + /// otherwise. + virtual const char* GetFutureErrorMessage( + const FutureHandle& handle) const = 0; + + /// Return a pointer to the completed asynchronous result, or NULL if + /// result is still pending. + /// After an asynchronous call is marked complete, the API should not + /// modify the result (especially on a callback thread), since the threads + /// owning the Future can reference the result memory via this function. + virtual const void* GetFutureResult(const FutureHandle& handle) const = 0; + + /// Register a callback that will be called when this future's status is set + /// to Complete. If clear_existing_callbacks is true, then the new callback + /// will replace any existing callbacks, otherwise it will be added to the + /// list of callbacks. + /// + /// The future's result data will be passed back when the callback is + /// called, along with the user_data supplied here. + /// + /// After the callback has been called, if `user_data_delete_fn_ptr` is + /// non-null, then `(*user_data_delete_fn_ptr)(user_data)` will be called. + virtual CompletionCallbackHandle AddCompletionCallback( + const FutureHandle& handle, FutureBase::CompletionCallback callback, + void* user_data, void (*user_data_delete_fn)(void*), + bool clear_existing_callbacks) = 0; + + /// Unregister a callback that was previously registered with + /// `AddCompletionCallback`. + virtual void RemoveCompletionCallback( + const FutureHandle& handle, CompletionCallbackHandle callback_handle) = 0; + +#if defined(FIREBASE_USE_STD_FUNCTION) + /// Register a callback that will be called when this future's status is set + /// to Complete. + /// + /// If `clear_existing_callbacks` is true, then the new callback + /// will replace any existing callbacks, otherwise it will be added to the + /// list of callbacks. + /// + /// The future's result data will be passed back when the callback is + /// called. + /// + /// @return A handle that can be passed to `FutureBase::RemoveCompletion`. + virtual CompletionCallbackHandle AddCompletionCallbackLambda( + const FutureHandle& handle, + std::function callback, + bool clear_existing_callbacks) = 0; +#endif // defined(FIREBASE_USE_STD_FUNCTION) + + /// Register this Future instance to be cleaned up. + virtual void RegisterFutureForCleanup(FutureBase* future) = 0; + + /// Unregister this Future instance from the cleanup list. + virtual void UnregisterFutureForCleanup(FutureBase* future) = 0; +}; + +inline void RegisterForCleanup(FutureApiInterface* api, FutureBase* future) { + if (api != NULL) { // NOLINT + api->RegisterFutureForCleanup(future); + } +} + +inline void UnregisterForCleanup(FutureApiInterface* api, FutureBase* future) { + if (api != NULL) { // NOLINT + api->UnregisterFutureForCleanup(future); + } +} + +class CompletionCallbackHandle { + public: + // Construct a null CompletionCallbackHandle. + CompletionCallbackHandle() + : callback_(nullptr), + user_data_(nullptr), + user_data_delete_fn_(nullptr) {} + + private: + friend class ::firebase::FutureBase; + friend class ::firebase::ReferenceCountedFutureImpl; + CompletionCallbackHandle(FutureBase::CompletionCallback callback, + void* user_data, void (*user_data_delete_fn)(void*)) + : callback_(callback), + user_data_(user_data), + user_data_delete_fn_(user_data_delete_fn) {} + + FutureBase::CompletionCallback callback_; + void* user_data_; + void (*user_data_delete_fn_)(void*); +}; + +} // namespace detail + +template +void Future::OnCompletion(TypedCompletionCallback callback, + void* user_data) const { + FutureBase::OnCompletion(reinterpret_cast(callback), + user_data); +} + +#if defined(FIREBASE_USE_STD_FUNCTION) +template +inline void Future::OnCompletion( + std::function&)> callback) const { + FutureBase::OnCompletion( + *reinterpret_cast*>(&callback)); +} +#endif // defined(FIREBASE_USE_STD_FUNCTION) + +#if defined(INTERNAL_EXPERIMENTAL) +template +FutureBase::CompletionCallbackHandle Future::AddOnCompletion( + TypedCompletionCallback callback, void* user_data) const { + return FutureBase::AddOnCompletion( + reinterpret_cast(callback), user_data); +} + +#if defined(FIREBASE_USE_STD_FUNCTION) +template +inline FutureBase::CompletionCallbackHandle Future::AddOnCompletion( + std::function&)> callback) const { + return FutureBase::AddOnCompletion( + *reinterpret_cast*>(&callback)); +} +#endif // defined(FIREBASE_USE_STD_FUNCTION) + +#endif // defined(INTERNAL_EXPERIMENTAL) + +inline FutureBase::FutureBase() + : mutex_(Mutex::Mode::kModeNonRecursive), + api_(NULL), + handle_(0) {} // NOLINT + +inline FutureBase::FutureBase(detail::FutureApiInterface* api, + const FutureHandle& handle) + : mutex_(Mutex::Mode::kModeNonRecursive), api_(api), handle_(handle) { + api_->ReferenceFuture(handle_); + // Once the FutureBase has reference, we don't need extra handle reference. + handle_.Detach(); + detail::RegisterForCleanup(api_, this); +} + +inline FutureBase::~FutureBase() { Release(); } + +inline FutureBase::FutureBase(const FutureBase& rhs) + : mutex_(Mutex::Mode::kModeNonRecursive), + api_(NULL) // NOLINT +{ // NOLINT + *this = rhs; +} + +inline FutureBase& FutureBase::operator=(const FutureBase& rhs) { + Release(); + + detail::FutureApiInterface* new_api; + FutureHandle new_handle; + { + MutexLock lock(rhs.mutex_); + new_api = rhs.api_; + new_handle = rhs.handle_; + } + + { + MutexLock lock(mutex_); + api_ = new_api; + handle_ = new_handle; + + if (api_ != NULL) { // NOLINT + api_->ReferenceFuture(handle_); + } + detail::RegisterForCleanup(api_, this); + } + + return *this; +} + +#if defined(FIREBASE_USE_MOVE_OPERATORS) +inline FutureBase::FutureBase(FutureBase&& rhs) noexcept + : mutex_(Mutex::Mode::kModeNonRecursive), + api_(NULL) // NOLINT +{ + *this = std::move(rhs); +} + +inline FutureBase& FutureBase::operator=(FutureBase&& rhs) noexcept { + Release(); + + detail::FutureApiInterface* new_api; + FutureHandle new_handle; + { + MutexLock lock(rhs.mutex_); + detail::UnregisterForCleanup(rhs.api_, &rhs); + new_api = rhs.api_; + new_handle = rhs.handle_; + rhs.api_ = NULL; // NOLINT + } + + MutexLock lock(mutex_); + api_ = new_api; + handle_ = new_handle; + detail::RegisterForCleanup(api_, this); + return *this; +} +#endif // defined(FIREBASE_USE_MOVE_OPERATORS) + +inline void FutureBase::Release() { + MutexLock lock(mutex_); + if (api_ != NULL) { // NOLINT + detail::UnregisterForCleanup(api_, this); + api_->ReleaseFuture(handle_); + api_ = NULL; // NOLINT + } +} + +inline FutureStatus FutureBase::status() const { + MutexLock lock(mutex_); + return api_ == NULL ? // NOLINT + kFutureStatusInvalid + : api_->GetFutureStatus(handle_); +} + +inline int FutureBase::error() const { + MutexLock lock(mutex_); + return api_ == NULL ? -1 : api_->GetFutureError(handle_); // NOLINT +} + +inline const char* FutureBase::error_message() const { + MutexLock lock(mutex_); + return api_ == NULL ? NULL : api_->GetFutureErrorMessage(handle_); // NOLINT +} + +inline const void* FutureBase::result_void() const { + MutexLock lock(mutex_); + return api_ == NULL ? NULL : api_->GetFutureResult(handle_); // NOLINT +} + +inline void FutureBase::OnCompletion(CompletionCallback callback, + void* user_data) const { + MutexLock lock(mutex_); + if (api_ != NULL) { // NOLINT + api_->AddCompletionCallback(handle_, callback, user_data, nullptr, + /*clear_existing_callbacks=*/true); + } +} + +#if defined(INTERNAL_EXPERIMENTAL) +inline FutureBase::CompletionCallbackHandle FutureBase::AddOnCompletion( + CompletionCallback callback, void* user_data) const { + MutexLock lock(mutex_); + if (api_ != NULL) { // NOLINT + return api_->AddCompletionCallback(handle_, callback, user_data, nullptr, + /*clear_existing_callbacks=*/false); + } + return CompletionCallbackHandle(); +} + +inline void FutureBase::RemoveOnCompletion( + CompletionCallbackHandle completion_handle) const { + MutexLock lock(mutex_); + if (api_ != NULL) { // NOLINT + api_->RemoveCompletionCallback(handle_, completion_handle); + } +} +#endif // defined(INTERNAL_EXPERIMENTAL) + +#if defined(FIREBASE_USE_STD_FUNCTION) +inline void FutureBase::OnCompletion( + std::function callback) const { + MutexLock lock(mutex_); + if (api_ != NULL) { // NOLINT + api_->AddCompletionCallbackLambda(handle_, callback, + /*clear_existing_callbacks=*/true); + } +} + +#if defined(INTERNAL_EXPERIMENTAL) +inline FutureBase::CompletionCallbackHandle FutureBase::AddOnCompletion( + std::function callback) const { + MutexLock lock(mutex_); + if (api_ != NULL) { // NOLINT + return api_->AddCompletionCallbackLambda( + handle_, callback, + /*clear_existing_callbacks=*/false); + } + return CompletionCallbackHandle(); +} +#endif // defined(INTERNAL__EXPERIMENTAL) + +#endif // defined(FIREBASE_USE_STD_FUNCTION) + +// NOLINTNEXTLINE - allow namespace overridden +} // namespace firebase + +/// @endcond + +#endif // FIREBASE_APP_SRC_INCLUDE_FIREBASE_INTERNAL_FUTURE_IMPL_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/internal/mutex.h b/packages/firebase_core/firebase_core/firebase_core/firebase/internal/mutex.h new file mode 100644 index 000000000000..86f6a45d1b38 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/internal/mutex.h @@ -0,0 +1,100 @@ +/* + * Copyright 2016 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_APP_SRC_INCLUDE_FIREBASE_INTERNAL_MUTEX_H_ +#define FIREBASE_APP_SRC_INCLUDE_FIREBASE_INTERNAL_MUTEX_H_ + +#include "firebase/internal/platform.h" + +#if FIREBASE_PLATFORM_WINDOWS +#include +#else +#include +#endif // FIREBASE_PLATFORM_WINDOWS + +namespace firebase { + +#if !defined(DOXYGEN) + +/// @brief A simple synchronization lock. Only one thread at a time can Acquire. +class Mutex { + public: + // Bitfield that describes the mutex configuration. + enum Mode { + kModeNonRecursive = (0 << 0), + kModeRecursive = (1 << 0), + }; + + Mutex() : Mutex(kModeRecursive) {} + + explicit Mutex(Mode mode); + + ~Mutex(); + + // Acquires the lock for this mutex, blocking until it is available. + void Acquire(); + + // Releases the lock for this mutex acquired by a previous `Acquire()` call. + void Release(); + +// Returns the implementation-defined native mutex handle. +// Used by firebase::Thread implementation. +#if FIREBASE_PLATFORM_WINDOWS + HANDLE* native_handle() { return &synchronization_object_; } +#else + pthread_mutex_t* native_handle() { return &mutex_; } +#endif // FIREBASE_PLATFORM_WINDOWS + + private: + Mutex(const Mutex&) = delete; + Mutex& operator=(const Mutex&) = delete; + +#if FIREBASE_PLATFORM_WINDOWS + HANDLE synchronization_object_; + Mode mode_; +#else + pthread_mutex_t mutex_; +#endif // FIREBASE_PLATFORM_WINDOWS +}; + +/// @brief Acquire and hold a /ref Mutex, while in scope. +/// +/// Example usage: +/// \code{.cpp} +/// Mutex syncronization_mutex; +/// void MyFunctionThatRequiresSynchronization() { +/// MutexLock lock(syncronization_mutex); +/// // ... logic ... +/// } +/// \endcode +class MutexLock { + public: + explicit MutexLock(Mutex& mutex) : mutex_(&mutex) { mutex_->Acquire(); } + ~MutexLock() { mutex_->Release(); } + + private: + // Copy is disallowed. + MutexLock(const MutexLock& rhs); // NOLINT + MutexLock& operator=(const MutexLock& rhs); + + Mutex* mutex_; +}; + +#endif // !defined(DOXYGEN) + +} // namespace firebase + +#endif // FIREBASE_APP_SRC_INCLUDE_FIREBASE_INTERNAL_MUTEX_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/internal/platform.h b/packages/firebase_core/firebase_core/firebase_core/firebase/internal/platform.h new file mode 100644 index 000000000000..17d64e32d022 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/internal/platform.h @@ -0,0 +1,110 @@ +/* + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_APP_SRC_INCLUDE_FIREBASE_INTERNAL_PLATFORM_H_ +#define FIREBASE_APP_SRC_INCLUDE_FIREBASE_INTERNAL_PLATFORM_H_ + +// This header serts exactly one of these FIREBASE_PLATFORM macros to 1, and the +// rest to 0: +// +// FIREBASE_PLATFORM_ANDROID +// FIREBASE_PLATFORM_IOS +// FIREBASE_PLATFORM_TVOS +// FIREBASE_PLATFORM_OSX +// FIREBASE_PLATFORM_WINDOWS +// FIREBASE_PLATFORM_LINUX +// FIREBASE_PLATFORM_UNKNOWN +// +// You can use e.g. #if FIREBASE_PLATFORM_OSX to conditionally compile code +// after including this header. +// +// It also defines some convenience macros: +// FIREBASE_PLATFORM_DESKTOP (1 on OSX, WINDOWS, and LINUX, 0 otherwise) +// FIREBASE_PLATFORM_MOBILE (1 on IOS and ANDROID, 0 otherwise) + +#define FIREBASE_PLATFORM_ANDROID 0 +#define FIREBASE_PLATFORM_IOS 0 +#define FIREBASE_PLATFORM_TVOS 0 +#define FIREBASE_PLATFORM_OSX 0 +#define FIREBASE_PLATFORM_WINDOWS 0 +#define FIREBASE_PLATFORM_LINUX 0 +#define FIREBASE_PLATFORM_UNKNOWN 0 + +#ifdef __APPLE__ +#include "TargetConditionals.h" +#endif // __APPLE__ + +#if defined(__ANDROID__) +#undef FIREBASE_PLATFORM_ANDROID +#define FIREBASE_PLATFORM_ANDROID 1 +#elif defined(TARGET_OS_IOS) && TARGET_OS_IOS +#undef FIREBASE_PLATFORM_IOS +#define FIREBASE_PLATFORM_IOS 1 +#elif defined(TARGET_OS_TV) && TARGET_OS_TV +#undef FIREBASE_PLATFORM_TVOS +#define FIREBASE_PLATFORM_TVOS 1 +#elif defined(TARGET_OS_OSX) && TARGET_OS_OSX +#undef FIREBASE_PLATFORM_OSX +#define FIREBASE_PLATFORM_OSX 1 +#elif defined(_WIN32) +#undef FIREBASE_PLATFORM_WINDOWS +#define FIREBASE_PLATFORM_WINDOWS 1 +#elif defined(__linux__) +#undef FIREBASE_PLATFORM_LINUX +#define FIREBASE_PLATFORM_LINUX 1 +#else +#undef FIREBASE_PLATFORM_UNKNOWN +#define FIREBASE_PLATFORM_UNKNOWN 1 +#endif + +#if FIREBASE_PLATFORM_LINUX + +// Include std library header to get version defines +#include + +#if defined(__clang__) +#define FIREBASE_COMPILER_CLANG 1 +#elif defined(__GNUC__) +#define FIREBASE_COMPILER_GCC 1 +#endif + +#if defined(_LIBCPP_VERSION) +#define FIREBASE_STANDARD_LIBCPP 1 +#elif defined(__GLIBCXX__) +#define FIREBASE_STANDARD_LIBSTDCPP 1 +#endif + +#if (FIREBASE_COMPILER_CLANG && FIREBASE_STANDARD_LIBCPP) +#define FIREBASE_LINUX_BUILD_CONFIG_STRING "clang_libstdcpp" +#elif (FIREBASE_COMPILER_CLANG && FIREBASE_STANDARD_LIBSTDCPP) +#define FIREBASE_LINUX_BUILD_CONFIG_STRING "clang_libcpp" +#elif (FIREBASE_COMPILER_GCC && FIREBASE_STANDARD_LIBCPP) +#define FIREBASE_LINUX_BUILD_CONFIG_STRING "gcc_libstdcpp" +#elif (FIREBASE_COMPILER_GCC && FIREBASE_STANDARD_LIBSTDCPP) +#define FIREBASE_LINUX_BUILD_CONFIG_STRING "gcc_libcpp" +#else +#error "Unsupported compiler or standard library" +#endif + +#endif // FIREBASE_PLATFORM_LINUX + +#define FIREBASE_PLATFORM_MOBILE \ + (FIREBASE_PLATFORM_IOS || FIREBASE_PLATFORM_ANDROID) +#define FIREBASE_PLATFORM_DESKTOP \ + (FIREBASE_PLATFORM_LINUX || FIREBASE_PLATFORM_WINDOWS || \ + FIREBASE_PLATFORM_OSX) + +#endif // FIREBASE_APP_SRC_INCLUDE_FIREBASE_INTERNAL_PLATFORM_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/internal/type_traits.h b/packages/firebase_core/firebase_core/firebase_core/firebase/internal/type_traits.h new file mode 100644 index 000000000000..7c465ea27c1e --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/internal/type_traits.h @@ -0,0 +1,134 @@ +/* + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_APP_SRC_INCLUDE_FIREBASE_INTERNAL_TYPE_TRAITS_H_ +#define FIREBASE_APP_SRC_INCLUDE_FIREBASE_INTERNAL_TYPE_TRAITS_H_ + +#include +#include + +// Doxygen breaks trying to parse this file, and since it is internal logic, +// it doesn't need to be included in the generated documentation. +#ifndef DOXYGEN + +namespace firebase { + +template +struct remove_reference { + typedef T type; +}; + +template +struct remove_reference { + typedef T type; +}; + +template +struct remove_reference { + typedef T type; +}; + +template +struct is_array { + static constexpr bool value = false; +}; + +template +struct is_array { + static constexpr bool value = true; +}; + +template +struct is_array { + static constexpr bool value = true; +}; + +template +struct is_lvalue_reference { + static constexpr bool value = false; +}; + +template +struct is_lvalue_reference { + static constexpr bool value = true; +}; + +// STLPort does include header, but its contents are in `std::tr1` +// namespace. To work around this, use aliases. +// TODO(varconst): all of the reimplementations of traits above can be replaced +// with appropriate aliases. +// TODO(varconst): the traits in this file would be more conformant if they +// inherited from `std::integral_constant`. +#ifdef STLPORT +#define FIREBASE_TYPE_TRAITS_NS std::tr1 +#else +#define FIREBASE_TYPE_TRAITS_NS std +#endif + +template +using decay = FIREBASE_TYPE_TRAITS_NS::decay; + +template +using decay_t = typename decay::type; + +template +using enable_if = FIREBASE_TYPE_TRAITS_NS::enable_if; + +template +using is_floating_point = FIREBASE_TYPE_TRAITS_NS::is_floating_point; + +template +using is_integral = FIREBASE_TYPE_TRAITS_NS::is_integral; + +template +using is_same = FIREBASE_TYPE_TRAITS_NS::is_same; + +template +using integral_constant = FIREBASE_TYPE_TRAITS_NS::integral_constant; + +using true_type = FIREBASE_TYPE_TRAITS_NS::true_type; +using false_type = FIREBASE_TYPE_TRAITS_NS::false_type; + +#undef FIREBASE_TYPE_TRAITS_NS + +// `is_char::value` is true iff `T` is a character type (including `wchar_t` +// and C++11 fixed-width character types). +template +struct is_char { + static constexpr bool value = +#if __cplusplus >= 202002L + is_same::value || +#endif +#if __cplusplus >= 201103L + is_same::value || is_same::value || +#endif + is_same::value || is_same::value || + is_same::value || is_same::value; +}; + +// A subset of `std::is_integral`: excludes `bool` and character types. +template +struct is_integer { + static constexpr bool value = + is_integral::value && !is_same::value && !is_char::value; +}; + +// NOLINTNEXTLINE - allow namespace overridden +} // namespace firebase + +#endif // DOXYGEN + +#endif // FIREBASE_APP_SRC_INCLUDE_FIREBASE_INTERNAL_TYPE_TRAITS_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/log.h b/packages/firebase_core/firebase_core/firebase_core/firebase/log.h new file mode 100644 index 000000000000..3d36ce37dcb3 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/log.h @@ -0,0 +1,54 @@ +/* + * Copyright 2016 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_APP_SRC_INCLUDE_FIREBASE_LOG_H_ +#define FIREBASE_APP_SRC_INCLUDE_FIREBASE_LOG_H_ + +/// @brief Namespace that encompasses all Firebase APIs. +namespace firebase { + +/// @brief Levels used when logging messages. +enum LogLevel { + /// Verbose Log Level + kLogLevelVerbose = 0, + /// Debug Log Level + kLogLevelDebug, + /// Info Log Level + kLogLevelInfo, + /// Warning Log Level + kLogLevelWarning, + /// Error Log Level + kLogLevelError, + /// Assert Log Level + kLogLevelAssert, +}; + +/// @brief Sets the logging verbosity. +/// All log messages at or above the specific log level. +/// +/// @param[in] level Log level to display, by default this is set to +/// kLogLevelInfo. +void SetLogLevel(LogLevel level); + +/// @brief Gets the logging verbosity. +/// +/// @return Get the currently configured logging verbosity. +LogLevel GetLogLevel(); + +// NOLINTNEXTLINE - allow namespace overridden +} // namespace firebase + +#endif // FIREBASE_APP_SRC_INCLUDE_FIREBASE_LOG_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/messaging.h b/packages/firebase_core/firebase_core/firebase_core/firebase/messaging.h new file mode 100644 index 000000000000..e7c7f5776868 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/messaging.h @@ -0,0 +1,728 @@ +// Copyright 2016 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef FIREBASE_MESSAGING_SRC_INCLUDE_FIREBASE_MESSAGING_H_ +#define FIREBASE_MESSAGING_SRC_INCLUDE_FIREBASE_MESSAGING_H_ + +#include + +#include +#include +#include + +#include "firebase/app.h" +#include "firebase/future.h" +#include "firebase/internal/common.h" + +#if !defined(DOXYGEN) && !defined(SWIG) +FIREBASE_APP_REGISTER_CALLBACKS_REFERENCE(messaging) +#endif // !defined(DOXYGEN) && !defined(SWIG) + +namespace firebase { + +/// @brief Firebase Cloud Messaging API. +/// +/// Firebase Cloud Messaging allows you to send data from your server to your +/// users' devices, and receive messages from devices on the same connection +/// if you're using a XMPP server. +/// +/// The FCM service handles all aspects of queueing of messages and delivery +/// to client applications running on target devices. +namespace messaging { + +/// @brief A class to configure the behavior of Firebase Cloud Messaging. +/// +/// This class contains various configuration options that control some of +/// Firebase Cloud Messaging's behavior. +struct MessagingOptions { + /// Default constructor. + MessagingOptions() : suppress_notification_permission_prompt(false) {} + + /// If true, do not display the prompt to the user requesting permission to + /// allow notifications to this app. If the prompt is suppressed in this way, + /// the developer must manually prompt the user for permission at some point + /// in the future using `RequestPermission()`. + /// + /// If this prompt has already been accepted once in the past the prompt will + /// not be displayed again. + /// + /// This option currently only applies to iOS and tvOS. + bool suppress_notification_permission_prompt; +}; + +/// @brief Data structure for parameters that are unique to the Android +/// implementation. +struct AndroidNotificationParams { + /// The channel id that was provided when the message was sent. + std::string channel_id; +}; + +/// Used for messages that display a notification. +/// +/// On android, this requires that the app is using the Play Services client +/// library. +struct Notification { + Notification() : android(nullptr) {} + +#ifndef SWIG + /// Copy constructor. Makes a deep copy of this Message. + Notification(const Notification& other) : android(nullptr) { *this = other; } +#endif // !SWIG + +#ifndef SWIG + /// Copy assignment operator. Makes a deep copy of this Message. + Notification& operator=(const Notification& other) { + this->title = other.title; + this->body = other.body; + this->icon = other.icon; + this->sound = other.sound; + this->tag = other.tag; + this->color = other.color; + this->click_action = other.click_action; + this->body_loc_key = other.body_loc_key; + this->body_loc_args = other.body_loc_args; + this->title_loc_key = other.title_loc_key; + this->title_loc_args = other.title_loc_args; + delete this->android; + if (other.android) { + this->android = new AndroidNotificationParams(*other.android); + } else { + this->android = nullptr; + } + return *this; + } +#endif // !SWIG + + /// Destructor. + ~Notification() { delete android; } + + /// Indicates notification title. This field is not visible on tvOS, iOS + /// phones and tablets. + std::string title; + + /// Indicates notification body text. + std::string body; + + /// Indicates notification icon. Sets value to myicon for drawable resource + /// myicon. + std::string icon; + + /// Indicates a sound to play when the device receives the notification. + /// Supports default, or the filename of a sound resource bundled in the + /// app. + /// + /// Android sound files must reside in /res/raw/, while iOS and tvOS sound + /// files can be in the main bundle of the client app or in the + /// Library/Sounds folder of the app’s data container. + std::string sound; + + /// Indicates the badge on the client app home icon. iOS and tvOS only. + std::string badge; + + /// Indicates whether each notification results in a new entry in the + /// notification drawer on Android. If not set, each request creates a new + /// notification. If set, and a notification with the same tag is already + /// being shown, the new notification replaces the existing one in the + /// notification drawer. + std::string tag; + + /// Indicates color of the icon, expressed in \#rrggbb format. Android only. + std::string color; + + /// The action associated with a user click on the notification. + /// + /// On Android, if this is set, an activity with a matching intent filter is + /// launched when user clicks the notification. + /// + /// If set on iOS or tvOS, corresponds to category in APNS payload. + std::string click_action; + + /// Indicates the key to the body string for localization. + /// + /// On iOS and tvOS, this corresponds to "loc-key" in APNS payload. + /// + /// On Android, use the key in the app's string resources when populating this + /// value. + std::string body_loc_key; + + /// Indicates the string value to replace format specifiers in body string + /// for localization. + /// + /// On iOS and tvOS, this corresponds to "loc-args" in APNS payload. + /// + /// On Android, these are the format arguments for the string resource. For + /// more information, see [Formatting strings][1]. + /// + /// [1]: + /// https://developer.android.com/guide/topics/resources/string-resource.html#FormattingAndStyling + std::vector body_loc_args; + + /// Indicates the key to the title string for localization. + /// + /// On iOS and tvOS, this corresponds to "title-loc-key" in APNS payload. + /// + /// On Android, use the key in the app's string resources when populating this + /// value. + std::string title_loc_key; + + /// Indicates the string value to replace format specifiers in title string + /// for localization. + /// + /// On iOS and tvOS, this corresponds to "title-loc-args" in APNS payload. + /// + /// On Android, these are the format arguments for the string resource. For + /// more information, see [Formatting strings][1]. + /// + /// [1]: + /// https://developer.android.com/guide/topics/resources/string-resource.html#FormattingAndStyling + std::vector title_loc_args; + + /// Parameters that are unique to the Android implementation. + AndroidNotificationParams* android; +}; + +/// @brief Data structure used to send messages to, and receive messages from, +/// cloud messaging. +struct Message { + /// Initialize the message. + Message() + : time_to_live(0), + notification(nullptr), + notification_opened(false), + sent_time(0) {} + + /// Destructor. + ~Message() { delete notification; } + +#ifndef SWIG + /// Copy constructor. Makes a deep copy of this Message. + Message(const Message& other) : notification(nullptr) { *this = other; } +#endif // !SWIG + +#ifndef SWIG + /// Copy assignment operator. Makes a deep copy of this Message. + Message& operator=(const Message& other) { + this->from = other.from; + this->to = other.to; + this->collapse_key = other.collapse_key; + this->data = other.data; + this->raw_data = other.raw_data; + this->message_id = other.message_id; + this->message_type = other.message_type; + this->priority = other.priority; + this->original_priority = other.original_priority; + this->sent_time = other.sent_time; + this->time_to_live = other.time_to_live; + this->error = other.error; + this->error_description = other.error_description; + delete this->notification; + if (other.notification) { + this->notification = new Notification(*other.notification); + } else { + this->notification = nullptr; + } + this->notification_opened = other.notification_opened; + this->link = other.link; + return *this; + } +#endif // !SWIG + + /// Authenticated ID of the sender. This is a project number in most cases. + /// + /// Any value starting with google.com, goog. or gcm. are reserved. + /// + /// This field is only used for downstream messages received through + /// Listener::OnMessage(). + std::string from; + + /// This parameter specifies the recipient of a message. + /// + /// For example it can be a registration token, a topic name, an Instance ID + /// or project ID. + /// + /// PROJECT_ID@gcm.googleapis.com or Instance ID are accepted. + std::string to; + + /// This parameter identifies a group of messages (e.g., with collapse_key: + /// "Updates Available") that can be collapsed, so that only the last message + /// gets sent when delivery can be resumed. This is intended to avoid sending + /// too many of the same messages when the device comes back online or becomes + /// active. + /// + /// Note that there is no guarantee of the order in which messages get sent. + /// + /// Note: A maximum of 4 different collapse keys is allowed at any given time. + /// This means a FCM connection server can simultaneously store 4 different + /// send-to-sync messages per client app. If you exceed this number, there is + /// no guarantee which 4 collapse keys the FCM connection server will keep. + /// + /// This field is only used for downstream messages received through + /// Listener::OnMessage(). + std::string collapse_key; + + /// The metadata, including all original key/value pairs. Includes some of the + /// HTTP headers used when sending the message. `gcm`, `google` and `goog` + /// prefixes are reserved for internal use. + std::map data; + + /// Binary payload. + std::vector raw_data; + + /// Message ID. This can be specified by sender. Internally a hash of the + /// message ID and other elements will be used for storage. The ID must be + /// unique for each topic subscription - using the same ID may result in + /// overriding the original message or duplicate delivery. + std::string message_id; + + /// Equivalent with a content-type. + /// + /// Defined values: + /// - "deleted_messages" - indicates the server had too many messages and + /// dropped some, and the client should sync with his own server. + /// Current limit is 100 messages stored. + /// - "send_event" - indicates an upstream message has been pushed to the + /// FCM server. It does not guarantee the upstream destination received + /// it. + /// Parameters: "message_id" + /// - "send_error" - indicates an upstream message expired, without being + /// sent to the FCM server. + /// Parameters: "message_id" and "error" + /// + /// If this field is missing, the message is a regular message. + /// + /// This field is only used for downstream messages received through + /// Listener::OnMessage(). + std::string message_type; + + /// Sets the priority of the message. Valid values are "normal" and "high." On + /// iOS and tvOS, these correspond to APNs priority 5 and 10. + /// + /// By default, messages are sent with normal priority. Normal priority + /// optimizes the client app's battery consumption, and should be used unless + /// immediate delivery is required. For messages with normal priority, the app + /// may receive the message with unspecified delay. + /// + /// When a message is sent with high priority, it is sent immediately, and the + /// app can wake a sleeping device and open a network connection to your + /// server. + /// + /// For more information, see [Setting the priority of a message][1]. + /// + /// This field is only used for downstream messages received through + /// Listener::OnMessage(). + /// + /// [1]: + /// https://firebase.google.com/docs/cloud-messaging/concept-options#setting-the-priority-of-a-message + std::string priority; + + /// This parameter specifies 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. For more + /// information, see [Setting the lifespan of a message][1]. + /// + /// This field is only used for downstream messages received through + /// Listener::OnMessage(). + /// + /// [1]: https://firebase.google.com/docs/cloud-messaging/concept-options#ttl + int32_t time_to_live; + + /// Error code. Used in "nack" messages for CCS, and in responses from the + /// server. + /// See the CCS specification for the externally-supported list. + /// + /// This field is only used for downstream messages received through + /// Listener::OnMessage(). + std::string error; + + /// Human readable details about the error. + /// + /// This field is only used for downstream messages received through + /// Listener::OnMessage(). + std::string error_description; + + /// Optional notification to show. This only set if a notification was + /// received with this message, otherwise it is null. + /// + /// The notification is only guaranteed to be valid during the call to + /// Listener::OnMessage(). If you need to keep it around longer you will need + /// to make a copy of either the Message or Notification. Copying the Message + /// object implicitly makes a deep copy of the notification (allocated with + /// new) which is owned by the Message. + /// + /// This field is only used for downstream messages received through + /// Listener::OnMessage(). + Notification* notification; + + /// A flag indicating whether this message was opened by tapping a + /// notification in the OS system tray. If the message was received this way + /// this flag is set to true. + bool notification_opened; + + /// The link into the app from the message. + /// + /// This field is only used for downstream messages received through + /// Listener::OnMessage(). + std::string link; + + /// @cond FIREBASE_APP_INTERNAL + /// Original priority of the message. + std::string original_priority; + + /// UTC timestamp in milliseconds when the message was sent. + /// See https://en.wikipedia.org/wiki/Unix_time for details of UTC. + int64_t sent_time; + /// @endcond +}; + +/// @brief Base class used to receive messages from Firebase Cloud Messaging. +/// +/// You need to override base class methods to handle any events required by the +/// application. Methods are invoked asynchronously and may be invoked on other +/// threads. +class Listener { + public: + virtual ~Listener(); + + /// Called on the client when a message arrives. + /// + /// @param[in] message The data describing this message. + virtual void OnMessage(const Message& message) = 0; + + /// Called on the client when a registration token arrives. This function + /// will eventually be called in response to a call to + /// firebase::messaging::Initialize(...). + /// + /// @param[in] token The registration token. + virtual void OnTokenReceived(const char* token) = 0; +}; + +/// @brief Initialize Firebase Cloud Messaging. +/// +/// After Initialize is called, the implementation may call functions on the +/// Listener provided at any time. +/// +/// @param[in] app The Firebase App object for this application. +/// @param[in] listener A Listener object that listens for events from the +/// Firebase Cloud Messaging servers. +/// +/// @return kInitResultSuccess if initialization succeeded, or +/// kInitResultFailedMissingDependency on Android if Google Play services is +/// not available on the current device. +InitResult Initialize(const App& app, Listener* listener); + +/// @brief Initialize Firebase Cloud Messaging. +/// +/// After Initialize is called, the implementation may call functions on the +/// Listener provided at any time. +/// +/// @param[in] app The Firebase App object for this application. +/// @param[in] listener A Listener object that listens for events from the +/// Firebase Cloud Messaging servers. +/// @param[in] options A set of options that configure the +/// initialzation behavior of Firebase Cloud Messaging. +/// +/// @return kInitResultSuccess if initialization succeeded, or +/// kInitResultFailedMissingDependency on Android if Google Play services is +/// not available on the current device. +InitResult Initialize(const App& app, Listener* listener, + const MessagingOptions& options); + +/// @brief Terminate Firebase Cloud Messaging. +/// +/// Frees resources associated with Firebase Cloud Messaging. +/// +/// @note On Android, the services will not be shut down by this method. +void Terminate(); + +/// Determines if automatic token registration during initalization is enabled. +/// +/// @return true if auto token registration is enabled and false if disabled. +bool IsTokenRegistrationOnInitEnabled(); + +/// Enable or disable token registration during initialization of Firebase Cloud +/// Messaging. +/// +/// This token is what identifies the user to Firebase, so disabling this avoids +/// creating any new identity and automatically sending it to Firebase, unless +/// consent has been granted. +/// +/// If this setting is enabled, it triggers the token registration refresh +/// immediately. This setting is persisted across app restarts and overrides the +/// setting "firebase_messaging_auto_init_enabled" specified in your Android +/// manifest (on Android) or Info.plist (on iOS and tvOS). +/// +///

By default, token registration during initialization is enabled. +/// +/// The registration happens before you can programmatically disable it, so +/// if you need to change the default, (for example, because you want to prompt +/// the user before FCM generates/refreshes a registration token on app +/// startup), add to your application’s manifest: +/// +/// +/// @if NOT_DOXYGEN +/// +/// @else +/// @code +/// <meta-data android:name="firebase_messaging_auto_init_enabled" +/// android:value="false" /> +/// @endcode +/// @endif +/// +/// or on iOS or tvOS to your Info.plist: +/// +/// @if NOT_DOXYGEN +/// FirebaseMessagingAutoInitEnabled +/// +/// @else +/// @code +/// <key>FirebaseMessagingAutoInitEnabled</key> +/// <false/> +/// @endcode +/// @endif +/// +/// @param enable sets if a registration token should be requested on +/// initialization. +void SetTokenRegistrationOnInitEnabled(bool enable); + +#ifndef SWIG +/// @brief Set the listener for events from the Firebase Cloud Messaging +/// servers. +/// +/// A listener must be set for the application to receive messages from +/// the Firebase Cloud Messaging servers. The implementation may call functions +/// on the Listener provided at any time. +/// +/// @param[in] listener A Listener object that listens for events from the +/// Firebase Cloud Messaging servers. +/// +/// @return Pointer to the previously set listener. +Listener* SetListener(Listener* listener); +#endif // !SWIG + +/// Error code returned by Firebase Cloud Messaging C++ functions. +enum Error { + /// The operation was a success, no error occurred. + kErrorNone = 0, + /// Permission to receive notifications was not granted. + kErrorFailedToRegisterForRemoteNotifications, + /// Topic name is invalid for subscription/unsubscription. + kErrorInvalidTopicName, + /// Could not subscribe/unsubscribe because there is no registration token. + kErrorNoRegistrationToken, + /// Unknown error. + kErrorUnknown, +}; + +/// @brief Displays a prompt to the user requesting permission to display +/// notifications. +/// +/// The permission prompt only appears on iOS and tvOS. If the user has +/// already agreed to allow notifications, no prompt is displayed and the +/// returned future is completed immediately. +/// +/// @return A future that completes when the notification prompt has been +/// dismissed. +Future RequestPermission(); + +/// @brief Gets the result of the most recent call to RequestPermission(); +/// +/// @return Result of the most recent call to RequestPermission(). +Future RequestPermissionLastResult(); + +/// @brief Subscribe to receive all messages to the specified topic. +/// +/// Subscribes an app instance to a topic, enabling it to receive messages +/// sent to that topic. +/// +/// Call this function from the main thread. FCM is not thread safe. +/// +/// @param[in] topic The name of the topic to subscribe. Must match the +/// following regular expression: `[a-zA-Z0-9-_.~%]{1,900}`. +Future Subscribe(const char* topic); + +/// @brief Gets the result of the most recent call to Unsubscribe(); +/// +/// @return Result of the most recent call to Unsubscribe(). +Future SubscribeLastResult(); + +/// @brief Unsubscribe from a topic. +/// +/// Unsubscribes an app instance from a topic, stopping it from receiving +/// any further messages sent to that topic. +/// +/// Call this function from the main thread. FCM is not thread safe. +/// +/// @param[in] topic The name of the topic to unsubscribe from. Must match the +/// following regular expression: `[a-zA-Z0-9-_.~%]{1,900}`. +Future Unsubscribe(const char* topic); + +/// @brief Gets the result of the most recent call to Unsubscribe(); +/// +/// @return Result of the most recent call to Unsubscribe(). +Future UnsubscribeLastResult(); + +/// Determines whether Firebase Cloud Messaging exports message delivery metrics +/// to BigQuery. +/// +/// This function is currently only implemented on Android, and returns false +/// with no other behavior on other platforms. +/// +/// @return true if Firebase Cloud Messaging exports message delivery metrics to +/// BigQuery. +bool DeliveryMetricsExportToBigQueryEnabled(); + +/// Enables or disables Firebase Cloud Messaging message delivery metrics export +/// to BigQuery. +/// +/// By default, message delivery metrics are not exported to BigQuery. Use this +/// method to enable or disable the export at runtime. In addition, you can +/// enable the export by adding to your manifest. Note that the run-time method +/// call will override the manifest value. +/// +/// +/// +/// This function is currently only implemented on Android, and has no behavior +/// on other platforms. +/// +/// @param[in] enable Whether Firebase Cloud Messaging should export message +/// delivery metrics to BigQuery. +void SetDeliveryMetricsExportToBigQuery(bool enable); + +/// @brief This creates a Firebase Installations ID, if one does not exist, and +/// sends information about the application and the device where it's running to +/// the Firebase backend. +/// +/// @return A future with the token. +Future GetToken(); + +/// @brief Gets the result of the most recent call to GetToken(); +/// +/// @return Result of the most recent call to GetToken(). +Future GetTokenLastResult(); + +/// @brief Deletes the default token for this Firebase project. +/// +/// Note that this does not delete the Firebase Installations ID that may have +/// been created when generating the token. See Installations.Delete() for +/// deleting that. +/// +/// @return A future that completes when the token is deleted. +Future DeleteToken(); + +/// @brief Gets the result of the most recent call to DeleteToken(); +/// +/// @return Result of the most recent call to DeleteToken(). +Future DeleteTokenLastResult(); + +class PollableListenerImpl; + +/// @brief A listener that can be polled to consume pending `Message`s. +/// +/// This class is intended to be used with applications that have a main loop +/// that frequently updates, such as in the case of a game that has a main +/// loop that updates 30 to 60 times a second. Rather than respond to incoming +/// messages and tokens via the `OnMessage` virtual function, this class will +/// queue up the message internally in a thread-safe manner so that it can be +/// consumed with `PollMessage`. For example: +/// +/// ::firebase::messaging::PollableListener listener; +/// ::firebase::messaging::Initialize(app, &listener); +/// +/// while (true) { +/// std::string token; +/// if (listener.PollRegistrationToken(&token)) { +/// LogMessage("Received a registration token"); +/// } +/// +/// ::firebase::messaging::Message message; +/// while (listener.PollMessage(&message)) { +/// LogMessage("Received a new message"); +/// } +/// +/// // Remainder of application logic... +/// } +class PollableListener : public Listener { + public: + /// @brief The default constructor. + PollableListener(); + + /// @brief The required virtual destructor. + virtual ~PollableListener(); + + /// @brief An implementation of `OnMessage` which adds the incoming messages + /// to a queue, which can be consumed by calling `PollMessage`. + virtual void OnMessage(const Message& message); + + /// @brief An implementation of `OnTokenReceived` which stores the incoming + /// token so that it can be consumed by calling `PollRegistrationToken`. + virtual void OnTokenReceived(const char* token); + + /// @brief Returns the first message queued up, if any. + /// + /// If one or more messages has been received, the first message in the + /// queue will be popped and used to populate the `message` argument and the + /// function will return `true`. If there are no pending messages, `false` is + /// returned. This function should be called in a loop until all messages have + /// been consumed, like so: + /// + /// ::firebase::messaging::Message message; + /// while (listener.PollMessage(&message)) { + /// LogMessage("Received a new message"); + /// } + /// + /// @param[out] message The `Message` struct to be populated. If there were no + /// pending messages, `message` is not modified. + /// + /// @return Returns `true` if there was a pending message, `false` otherwise. + bool PollMessage(Message* message); + + /// @brief Returns the registration key, if a new one has been received. + /// + /// When a new registration token is received, it is cached internally and can + /// be retrieved by calling `PollRegistrationToken`. The cached registration + /// token will be used to populate the `token` argument, then the cache will + /// be cleared and the function will return `true`. If there is no cached + /// registration token this function retuns `false`. + /// + /// std::string token; + /// if (listener.PollRegistrationToken(&token)) { + /// LogMessage("Received a registration token"); + /// } + /// + /// @param[out] token A string to be populated with the new token if one has + /// been received. If there were no new token, the string is left unmodified. + /// + /// @return Returns `true` if there was a new token, `false` otherwise. + bool PollRegistrationToken(std::string* token) { + bool got_token; + std::string token_received = PollRegistrationToken(&got_token); + if (got_token) { + *token = token_received; + } + return got_token; + } + + private: + std::string PollRegistrationToken(bool* got_token); + + // The implementation of the `PollableListener`. + PollableListenerImpl* impl_; +}; + +} // namespace messaging +} // namespace firebase + +#endif // FIREBASE_MESSAGING_SRC_INCLUDE_FIREBASE_MESSAGING_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/remote_config.h b/packages/firebase_core/firebase_core/firebase_core/firebase/remote_config.h new file mode 100644 index 000000000000..a2bd41775775 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/remote_config.h @@ -0,0 +1,526 @@ +// Copyright 2016 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef FIREBASE_REMOTE_CONFIG_SRC_INCLUDE_FIREBASE_REMOTE_CONFIG_H_ +#define FIREBASE_REMOTE_CONFIG_SRC_INCLUDE_FIREBASE_REMOTE_CONFIG_H_ + +#include +#include +#include + +#include "firebase/app.h" +#include "firebase/future.h" +#include "firebase/internal/common.h" +#include "firebase/internal/platform.h" +#ifndef SWIG +#include "firebase/variant.h" +#endif // SWIG + +#if !defined(DOXYGEN) && !defined(SWIG) +FIREBASE_APP_REGISTER_CALLBACKS_REFERENCE(remote_config) +#endif // !defined(DOXYGEN) && !defined(SWIG) + +/// @brief Namespace that encompasses all Firebase APIs. +namespace firebase { + +#ifndef SWIG +/// @brief Firebase Remote Config API. +/// +/// Firebase Remote Config is a cloud service that lets you change the +/// appearance and behavior of your app without requiring users to download an +/// app update. +#endif // SWIG +namespace remote_config { + +/// @brief Describes the most recent fetch request status. +enum LastFetchStatus { + /// The most recent fetch was a success, and its data is ready to be + /// applied, if you have not already done so. + kLastFetchStatusSuccess, + /// The most recent fetch request failed. + kLastFetchStatusFailure, + /// The most recent fetch is still in progress. + kLastFetchStatusPending, +}; + +/// @brief Describes the most recent fetch failure. +enum FetchFailureReason { + /// The fetch has not yet failed. + kFetchFailureReasonInvalid, + /// The most recent fetch failed because it was throttled by the server. + /// (You are sending too many fetch requests in too short a time.) + kFetchFailureReasonThrottled, + /// The most recent fetch failed for an unknown reason. + kFetchFailureReasonError, +}; + +/// @brief Describes the state of the most recent Fetch() call. +/// Normally returned as a result of the GetInfo() function. +struct ConfigInfo { + /// @brief The time (in milliseconds since the epoch) that the last fetch + /// operation completed. + uint64_t fetch_time; + + /// @brief The status of the last fetch request. + LastFetchStatus last_fetch_status; + + /// @brief The reason the most recent fetch failed. + FetchFailureReason last_fetch_failure_reason; + + /// @brief The time (in milliseconds since the epoch) when the refreshing of + /// Remote Config data is throttled. + uint64_t throttled_end_time; +}; + +/// @brief Describes the source a config value was retrieved from. +enum ValueSource { + /// The value was not specified and no default was specified, so a static + /// value (0 for numeric values, an empty string for strings) was returned. + kValueSourceStaticValue, + /// The value was found in the remote data store, and returned. + kValueSourceRemoteValue, + /// The value was not specified, so the specified default value was + /// returned instead. + kValueSourceDefaultValue, +}; + +/// @brief Describes a retrieved value. +struct ValueInfo { + /// Where the config value was retrieved from (Default Config or Active + /// Config). + ValueSource source; + /// If true this indicates conversion to the requested type + /// succeeded, otherwise conversion failed so the static value for the + /// requested type was retrieved instead. + bool conversion_successful; +}; + +/// @brief Keys of API settings. +/// +/// @see SetConfigSetting +/// @see GetConfigSetting +enum ConfigSetting { + /// Set the value associated with this key to "1" to enable developer mode + /// (i.e disable throttling) and "0" to disable. + kConfigSettingDeveloperMode, +}; + +/// @brief The default cache expiration used by Fetch(), equal to 12 hours, +/// in milliseconds. +static const uint64_t kDefaultCacheExpiration = 60 * 60 * 12 * 1000; + +/// @brief The default timeout used by Fetch(), equal to 30 seconds, +/// in milliseconds. +static const uint64_t kDefaultTimeoutInMilliseconds = 30 * 1000; + +/// @brief Describes a mapping of a key to a string value. Used to set default +/// values. +struct ConfigKeyValue { + /// The lookup key string. +#ifndef SWIG + /// + /// @note Ensure this string stays valid for the duration of the + /// call to SetDefaults. +#endif // SWIG + const char* key; + /// The value string to be stored. +#ifndef SWIG + /// + /// @note Ensure this string stays valid for the duration of the + /// call to SetDefaults. +#endif // SWIG + const char* value; +}; + +#ifndef SWIG +/// @brief Describes a mapping of a key to a value of any type. Used to set +/// default values. +struct ConfigKeyValueVariant { + /// The lookup key string. + /// + /// @note Ensure this string stays valid for the duration of the + /// call to SetDefaults. + const char* key; + /// The value to be stored. The type of the Variant determines the type of + /// default data for the given key. + /// + /// @note If you use a Variant of type StaticString, ensure it stays + /// valid for the duration of the call to SetDefaults. + Variant value; +}; +#endif // SWIG + +/// @brief Configurations for Remote Config behavior. +struct ConfigSettings { + /// The timeout specifies how long the client should wait for a connection to + /// the Firebase Remote Config servers. + /// + /// @note A fetch call will fail if it takes longer than the specified timeout + /// to connect to the Remote Config servers. Default is 60 seconds. + uint64_t fetch_timeout_in_milliseconds = kDefaultTimeoutInMilliseconds; + + /// The minimum interval between successive fetch calls. + /// + /// @note Fetches less than duration seconds after the last fetch from the + /// Firebase Remote Config server would use values returned during the last + /// fetch. Default is 12 hours. + uint64_t minimum_fetch_interval_in_milliseconds = kDefaultCacheExpiration; +}; + +namespace internal { +class RemoteConfigInternal; +} // namespace internal + +#ifndef SWIG +/// @brief Entry point for the Firebase C++ SDK for Remote Config. +/// +/// To use the SDK, call firebase::remote_config::RemoteConfig::GetInstance() to +/// obtain an instance of RemoteConfig, then call operations on that instance. +/// The instance contains the complete set of FRC parameter values available to +/// your app. The instance also stores values fetched from the FRC Server until +/// they are made available for use with a call to @ref Activate(). +#endif // SWIG +class RemoteConfig { + public: + ~RemoteConfig(); + + /// @brief Returns a Future that contains ConfigInfo representing the + /// initialization status of this Firebase Remote Config instance. + /// Use this method to ensure Set/Get call not being blocked. + Future EnsureInitialized(); + + /// @brief Get the (possibly still pending) results of the most recent + /// EnsureInitialized() call. + /// + /// @return The future result from the last call to EnsureInitialized(). + Future EnsureInitializedLastResult(); + + /// Asynchronously activates the most recently fetched configs, so that the + /// fetched key value pairs take effect. + /// + /// @return A Future that contains true if fetched configs were + /// activated. The future will contain false if the configs were already + /// activated. + Future Activate(); + + /// @brief Get the (possibly still pending) results of the most recent + /// Activate() call. + /// + /// @return The future result from the last call to Activate(). + Future ActivateLastResult(); + + /// Asynchronously fetches and then activates the fetched configs. + /// + /// If the time elapsed since the last fetch from the Firebase Remote Config + /// backend is more than the default minimum fetch interval, configs are + /// fetched from the backend. + /// + /// After the fetch is complete, the configs are activated so that the fetched + /// key value pairs take effect. + /// + /// @return A Future that contains true if the current call + /// activated the fetched configs; if no configs were fetched from the backend + /// and the local fetched configs have already been activated, the future will + /// contain false. + Future FetchAndActivate(); + + /// @brief Get the (possibly still pending) results of the most recent + /// FetchAndActivate() call. + /// + /// @return The future result from the last call to FetchAndActivate(). + Future FetchAndActivateLastResult(); + + /// @brief Fetches config data from the server. + /// + /// @note This does not actually apply the data or make it accessible, + /// it merely retrieves it and caches it. To accept and access the newly + /// retrieved values, you must call @ref Activate(). + /// + /// Note that this function is asynchronous, and will normally take an + /// unspecified amount of time before completion. + /// + /// @return A Future which can be used to determine when the fetch is + /// complete. + Future Fetch(); + + /// @brief Fetches config data from the server. + /// + /// @note This does not actually apply the data or make it accessible, + /// it merely retrieves it and caches it. To accept and access the newly + /// retrieved values, you must call @ref Activate(). + /// Note that this function is asynchronous, and will normally take an + /// unspecified amount of time before completion. + /// + /// @param[in] cache_expiration_in_seconds The number of seconds to keep + /// previously fetch data available. If cached data is available that is + /// newer than cache_expiration_in_seconds, then the function returns + /// immediately and does not fetch any data. A cache_expiration_in_seconds of + /// zero will always cause a fetch. + /// + /// @return A Future which can be used to determine when the fetch is + /// complete. + Future Fetch(uint64_t cache_expiration_in_seconds); + + /// @brief Get the (possibly still pending) results of the most recent Fetch() + /// call. + /// + /// @return The future result from the last call to Fetch(). + Future FetchLastResult(); + +#if defined(__ANDROID__) + /// @brief Sets the default values, using an XML resource. + /// + /// @note This method is specific to the Android implementation. + /// + /// This completely overwrites all previous default values. + /// + /// @param[in] defaults_resource_id Id for the XML resource, which should be + /// in your applications res/xml folder. + /// + /// @return a Future which can be used to determine when the operation is + /// complete. + Future SetDefaults(int defaults_resource_id); +#endif // __ANDROID__ + +#ifndef SWIG + /// @brief Sets the default values based on a mapping of string to Variant. + /// This allows you to specify defaults of type other than string. + /// + /// The type of each Variant in the map determines the type of data for which + /// you are providing a default. For example, boolean values can be retrieved + /// with GetBool(), integer values can be retrieved with GetLong(), double + /// values can be retrieved with GetDouble(), string values can be retrieved + /// with GetString(), and binary data can be retrieved with GetData(). + /// Aggregate Variant types are not allowed. + /// + /// @see firebase::Variant for more information on how to create a Variant of + /// each type. + /// + /// @note This completely overrides all previous values. + /// + /// @param defaults Array of ConfigKeyValueVariant, representing the new set + /// of defaults to apply. If the same key is specified multiple times, the + /// value associated with the last duplicate key is applied. + /// @param number_of_defaults Number of elements in the defaults array. + /// + /// @return a Future which can be used to determine when the operation is + /// complete. + Future SetDefaults(const ConfigKeyValueVariant* defaults, + size_t number_of_defaults); +#endif // SWIG + + /// @brief Sets the default values based on a string map. + /// + /// @note This completely overrides all previous values. + /// + /// @param defaults Array of ConfigKeyValue, representing the new set of + /// defaults to apply. If the same key is specified multiple times, the + /// value associated with the last duplicate key is applied. + /// @param number_of_defaults Number of elements in the defaults array. + /// + /// @return a Future which can be used to determine when the operation is + /// complete. + Future SetDefaults(const ConfigKeyValue* defaults, + size_t number_of_defaults); + + /// @brief Get the (possibly still pending) results of the most recent + /// SetDefaults() call. + /// + /// @return The future result from the last call to SetDefaults(). + Future SetDefaultsLastResult(); + + /// @brief Asynchronously changes the settings for this Remote Config + /// instance. + /// + /// @param settings The new settings to be applied. + /// + /// @return a Future which can be used to determine when the operation is + /// complete. + Future SetConfigSettings(ConfigSettings settings); + + /// @brief Gets the current settings of the RemoteConfig object. + /// + /// @return A ConfigSettings struct. + ConfigSettings GetConfigSettings(); + + /// @brief Get the (possibly still pending) results of the most recent + /// SetConfigSettings() call. + /// + /// @return The future result from the last call to SetConfigSettings(). + Future SetConfigSettingsLastResult(); + + /// @brief Returns the value associated with a key, converted to a bool. + /// + /// Values of "1", "true", "t", "yes", "y" and "on" are interpreted (case + /// insensitive) as true and "0", "false", "f", "no", "n", "off", + /// and empty strings are interpreted (case insensitive) as + /// false. + /// + /// @param[in] key Key of the value to be retrieved. + /// + /// @return Value associated with the specified key converted to a boolean + /// value. + bool GetBoolean(const char* key); + + /// @brief Returns the value associated with a key, converted to a bool. + /// + /// Values of "1", "true", "t", "yes", "y" and "on" are interpreted (case + /// insensitive) as true and "0", "false", "f", "no", "n", "off", + /// and empty strings are interpreted (case insensitive) as + /// false. + /// + /// @param[in] key Key of the value to be retrieved. + /// @param[out] info A return value, specifying the source of the returned + /// value. + /// + /// @return Value associated with the specified key converted to a boolean + /// value. + bool GetBoolean(const char* key, ValueInfo* info); + + /// @brief Returns the value associated with a key, converted to a 64-bit + /// integer. + /// + /// @param[in] key Key of the value to be retrieved. + /// + /// @return Value associated with the specified key converted to a 64-bit + /// integer. + int64_t GetLong(const char* key); + + /// @brief Returns the value associated with a key, converted to a 64-bit + /// integer. + /// + /// @param[in] key Key of the value to be retrieved. + /// @param[out] info A return value, specifying the source of the returned + /// value. + /// + /// @return Value associated with the specified key converted to a 64-bit + /// integer. + int64_t GetLong(const char* key, ValueInfo* info); + + /// @brief Returns the value associated with a key, converted to a double. + /// + /// @param[in] key Key of the value to be retrieved. + /// + /// @return Value associated with the specified key converted to a double. + double GetDouble(const char* key); + + /// @brief Returns the value associated with a key, converted to a double. + /// + /// @param[in] key Key of the value to be retrieved. + /// @param[out] info A return value, specifying the source of the returned + /// value. + /// + /// @return Value associated with the specified key converted to a double. + double GetDouble(const char* key, ValueInfo* info); + + /// @brief Returns the value associated with a key, converted to a string. + /// + /// @param[in] key Key of the value to be retrieved. + /// + /// @return Value as a string associated with the specified key. + std::string GetString(const char* key); + + /// @brief Returns the value associated with a key, converted to a string. + /// + /// @param[in] key Key of the value to be retrieved. + /// @param[out] info A return value, specifying the source of the returned + /// value. + /// + /// @return Value as a string associated with the specified key. + std::string GetString(const char* key, ValueInfo* info); + + /// @brief Returns the value associated with a key, as a vector of raw + /// byte-data. + /// + /// @param[in] key Key of the value to be retrieved. + /// + /// @return Vector of bytes. + std::vector GetData(const char* key); + + /// @brief Returns the value associated with a key, as a vector of raw + /// byte-data. + /// + /// @param[in] key Key of the value to be retrieved. + /// @param[out] info A return value, specifying the source of the returned + /// value. + /// + /// @return Vector of bytes. + std::vector GetData(const char* key, ValueInfo* info); + + /// @brief Gets the set of keys that start with the given prefix. + /// + /// @param[in] prefix The key prefix to look for. If empty or null, this + /// method will return all keys. + /// + /// @return Set of Remote Config parameter keys that start with the specified + /// prefix. Will return an empty set if there are no keys with the given + /// prefix. + std::vector GetKeysByPrefix(const char* prefix); + + /// @brief Gets the set of all keys. + /// + /// @return Set of all Remote Config parameter keys. + std::vector GetKeys(); + + /// @brief Returns a Map of Firebase Remote Config key value pairs. + /// + /// Evaluates the values of the parameters in the following order: + /// The activated value, if the last successful @ref Activate() contained the + /// key. The default value, if the key was set with @ref SetDefaults(). + std::map GetAll(); + + /// @brief Returns information about the last fetch request, in the form + /// of a ConfigInfo struct. + /// + /// @return A ConfigInfo struct, containing fields reflecting the state + /// of the most recent fetch request. + const ConfigInfo GetInfo(); + + /// Gets the App this remote config object is connected to. + App* app() { return app_; } + + /// Returns the RemoteConfig object for an App. Creates the RemoteConfig if + /// required. + /// + /// To get the RemoteConfig object for the default app, use, + /// GetInstance(GetDefaultFirebaseApp()); + /// + /// If the library RemoteConfig fails to initialize, init_result_out will be + /// written with the result status (if a pointer is given). + /// + /// @param[in] app The App to use for the RemoteConfig object. + static RemoteConfig* GetInstance(App* app); + + private: + explicit RemoteConfig(App* app); + + // Find RemoteConfig instance using App. Return null if the instance does not + // exist. + static RemoteConfig* FindRemoteConfig(App* app); + + // Clean up RemoteConfig instance. + void DeleteInternal(); + + /// The Firebase App this remote config is connected to. + App* app_; + + bool InitInternal(); + + internal::RemoteConfigInternal* internal_; +}; + +} // namespace remote_config +} // namespace firebase + +#endif // FIREBASE_REMOTE_CONFIG_SRC_INCLUDE_FIREBASE_REMOTE_CONFIG_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/storage.h b/packages/firebase_core/firebase_core/firebase_core/firebase/storage.h new file mode 100644 index 000000000000..8d081e4c0ead --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/storage.h @@ -0,0 +1,161 @@ +// Copyright 2016 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_H_ +#define FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_H_ + +#include + +#include "firebase/app.h" +#include "firebase/internal/common.h" +#include "firebase/storage/common.h" +#include "firebase/storage/controller.h" +#include "firebase/storage/listener.h" +#include "firebase/storage/metadata.h" +#include "firebase/storage/storage_reference.h" + +#if !defined(DOXYGEN) +#ifndef SWIG +FIREBASE_APP_REGISTER_CALLBACKS_REFERENCE(storage) +#endif // SWIG +#endif // !defined(DOXYGEN) + +namespace firebase { + +/// Namespace for the Firebase C++ SDK for Cloud Storage. +namespace storage { + +namespace internal { +class StorageInternal; +class MetadataInternal; +} // namespace internal + +class StorageReference; + +#ifndef SWIG +/// @brief Entry point for the Firebase C++ SDK for Cloud Storage. +/// +/// To use the SDK, call firebase::storage::Storage::GetInstance() to +/// obtain an instance of Storage, then use GetReference() to obtain references +/// to child blobs. From there you can upload data with +/// StorageReference::PutStream(), get data via StorageReference::GetStream(). +#endif // SWIG +class Storage { + public: + /// @brief Destructor. You may delete an instance of Storage when + /// you are finished using it, to shut down the Storage library. + ~Storage(); + + /// @brief Get an instance of Storage corresponding to the given App. + /// + /// Cloud Storage uses firebase::App to communicate with Firebase + /// Authentication to authenticate users to the server backend. + /// + /// @param[in] app An instance of firebase::App. Cloud Storage will use + /// this to communicate with Firebase Authentication. + /// @param[out] init_result_out Optional: If provided, write the init result + /// here. Will be set to kInitResultSuccess if initialization succeeded, or + /// kInitResultFailedMissingDependency on Android if Google Play services is + /// not available on the current device. + /// + /// @returns An instance of Storage corresponding to the given App. + static Storage* GetInstance(::firebase::App* app, + InitResult* init_result_out = nullptr); + + /// @brief Get an instance of Storage corresponding to the given App, + /// with the given Cloud Storage URL. + /// + /// Cloud Storage uses firebase::App to communicate with Firebase + /// Authentication to authenticate users to the server backend. + /// + /// @param[in] app An instance of firebase::App. Cloud Storage will use + /// this to communicate with Firebase Authentication. + /// @param[in] url Cloud Storage URL. + /// @param[out] init_result_out Optional: If provided, write the init result + /// here. Will be set to kInitResultSuccess if initialization succeeded, or + /// kInitResultFailedMissingDependency on Android if Google Play services is + /// not available on the current device. + /// + /// @returns An instance of Storage corresponding to the given App. + static Storage* GetInstance(::firebase::App* app, const char* url, + InitResult* init_result_out = nullptr); + + /// @brief Get the firease::App that this Storage was created with. + /// + /// @returns The firebase::App this Storage was created with. + ::firebase::App* app(); + + /// @brief Get the URL that this Storage was created with. + /// + /// @returns The URL this Storage was created with, or an empty + /// string if this Storage was created with default parameters. + std::string url(); + + /// @brief Get a StorageReference to the root of the database. + StorageReference GetReference() const; + + /// @brief Get a StorageReference for the specified path. + StorageReference GetReference(const char* path) const; + /// @brief Get a StorageReference for the specified path. + StorageReference GetReference(const std::string& path) const { + return GetReference(path.c_str()); + } + + /// @brief Get a StorageReference for the provided URL. + StorageReference GetReferenceFromUrl(const char* url) const; + /// @brief Get a StorageReference for the provided URL. + StorageReference GetReferenceFromUrl(const std::string& url) const { + return GetReferenceFromUrl(url.c_str()); + } + + /// @brief Returns the maximum time in seconds to retry a download if a + /// failure occurs. + double max_download_retry_time(); + /// @brief Sets the maximum time to retry a download if a failure occurs. + /// Defaults to 600 seconds (10 minutes). + void set_max_download_retry_time(double max_transfer_retry_seconds); + + /// @brief Returns the maximum time to retry an upload if a failure occurs. + double max_upload_retry_time(); + /// @brief Sets the maximum time to retry an upload if a failure occurs. + /// Defaults to 600 seconds (10 minutes). + void set_max_upload_retry_time(double max_transfer_retry_seconds); + + /// @brief Returns the maximum time to retry operations other than upload + /// and download if a failure occurs. + double max_operation_retry_time(); + /// @brief Sets the maximum time to retry operations other than upload and + /// download if a failure occurs. Defaults to 120 seconds (2 minutes). + void set_max_operation_retry_time(double max_transfer_retry_seconds); + + private: + /// @cond FIREBASE_APP_INTERNAL + friend class Metadata; + friend class internal::MetadataInternal; + + Storage(::firebase::App* app, const char* url); + Storage(const Storage& src); + Storage& operator=(const Storage& src); + + // Destroy the internal_ object. + void DeleteInternal(); + + internal::StorageInternal* internal_; + /// @endcond +}; + +} // namespace storage +} // namespace firebase + +#endif // FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/storage/common.h b/packages/firebase_core/firebase_core/firebase_core/firebase/storage/common.h new file mode 100644 index 000000000000..567ed714920c --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/storage/common.h @@ -0,0 +1,62 @@ +// Copyright 2016 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_COMMON_H_ +#define FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_COMMON_H_ + +namespace firebase { +namespace storage { + +/// Error code returned by Cloud Storage C++ functions. +enum Error { + /// The operation was a success, no error occurred. + kErrorNone = 0, + /// An unknown error occurred. + kErrorUnknown, + /// No object exists at the desired reference. + kErrorObjectNotFound, + /// No bucket is configured for Cloud Storage. + kErrorBucketNotFound, + /// No project is configured for Cloud Storage. + kErrorProjectNotFound, + /// Quota on your Cloud Storage bucket has been exceeded. + kErrorQuotaExceeded, + /// User is unauthenticated. + kErrorUnauthenticated, + /// User is not authorized to perform the desired action. + kErrorUnauthorized, + /// The maximum time limit on an operation (upload, download, delete, etc.) + /// has been exceeded. + kErrorRetryLimitExceeded, + /// File on the client does not match the checksum of the file received by the + /// server. + kErrorNonMatchingChecksum, + /// Size of the downloaded file exceeds the amount of memory allocated for the + /// download. + kErrorDownloadSizeExceeded, + /// User cancelled the operation. + kErrorCancelled, +}; + +/// @brief Get the human-readable error message corresponding to an error code. +/// +/// @param[in] error Error code to get the error message for. +/// +/// @returns Statically-allocated string describing the error. +const char* GetErrorMessage(Error error); + +} // namespace storage +} // namespace firebase + +#endif // FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_COMMON_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/storage/controller.h b/packages/firebase_core/firebase_core/firebase_core/firebase/storage/controller.h new file mode 100644 index 000000000000..42f29aa0c73b --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/storage/controller.h @@ -0,0 +1,146 @@ +// Copyright 2016 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_CONTROLLER_H_ +#define FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_CONTROLLER_H_ + +#include "firebase/storage/storage_reference.h" + +namespace firebase { +namespace storage { + +/// @cond FIREBASE_APP_INTERNAL +namespace internal { +class ControllerInternal; +class ListenerInternal; +class RestOperation; +} // namespace internal +/// @endcond + +/// @brief Controls an ongoing operation, allowing the caller to Pause, Resume +/// or Cancel an ongoing download or upload. +/// +/// An instance of Controller can be constructed and passed to +/// StorageReference::GetBytes(), StorageReference::GetFile(), +/// StorageReference::PutBytes(), or StorageReference::PutFile() to become +/// associated with it. Each Controller can only be associated with one +/// operation at a time. +/// +/// A Controller is also passed as an argument to Listener's callbacks. The +/// Controller passed to a StorageReference operation is not the same object +/// passed to Listener callbacks (though it refers to the same operation), so +/// there are no restrictions on the lifetime of the Controller the user creates +/// (but the Controller passed into a Listener callbacks should only be used +/// from within that callback). +/// +/// This class is currently not thread safe and can only be called on the main +/// thread. +class Controller { + public: + /// @brief Default constructor. + /// + /// You may construct your own Controller to pass into various + /// StorageReference operations. + Controller(); + + /// @brief Destructor. + ~Controller(); + + /// @brief Copy constructor. + /// + /// @param[in] other Controller to copy from. + Controller(const Controller& other); + + /// @brief Copy assignment operator. + /// + /// @param[in] other Controller to copy from. + /// + /// @returns Reference to the destination Controller. + Controller& operator=(const Controller& other); + +#if defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) + /// @brief Move constructor. Moving is an efficient operation for + /// Controller instances. + /// + /// @param[in] other Controller to move from. + Controller(Controller&& other); + + /// @brief Move assignment operator. Moving is an efficient operation for + /// Controller instances. + /// + /// @param[in] other Controller to move from. + /// + /// @returns Reference to the destination Controller. + Controller& operator=(Controller&& other); +#endif // defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) + + /// @brief Pauses the operation currently in progress. + /// + /// @returns True if the operation was successfully paused, false otherwise. + bool Pause(); + + /// @brief Resumes the operation that is paused. + /// + /// @returns True if the operation was successfully resumed, false otherwise. + bool Resume(); + + /// @brief Cancels the operation currently in progress. + /// + /// @returns True if the operation was successfully canceled, false otherwise. + bool Cancel(); + + /// @brief Returns true if the operation is paused. + bool is_paused() const; + + /// @brief Returns the number of bytes transferred so far. + /// + /// @returns The number of bytes transferred so far. + int64_t bytes_transferred() const; + + /// @brief Returns the total bytes to be transferred. + /// + /// @returns The total bytes to be transferred. This will return -1 if + /// the size of the transfer is unknown. + int64_t total_byte_count() const; + + /// @brief Returns the StorageReference associated with this Controller. + /// + /// @returns The StorageReference associated with this Controller. + StorageReference GetReference() const; + + /// @brief Returns true if this Controller is valid, false if it is not + /// valid. An invalid Controller is one that is not associated with an + /// operation. + /// + /// @returns true if this Controller is valid, false if this Controller is + /// invalid. + bool is_valid() const; + + private: + /// @cond FIREBASE_APP_INTERNAL + friend class internal::StorageReferenceInternal; + friend class internal::ControllerInternal; + friend class internal::ListenerInternal; + friend class internal::RestOperation; + + Controller(internal::ControllerInternal* internal); + + internal::ControllerInternal* internal_; + /// @endcond +}; + +} // namespace storage +} // namespace firebase + +#endif // FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_CONTROLLER_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/storage/listener.h b/packages/firebase_core/firebase_core/firebase_core/firebase/storage/listener.h new file mode 100644 index 000000000000..8bd624f61537 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/storage/listener.h @@ -0,0 +1,74 @@ +// Copyright 2016 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_LISTENER_H_ +#define FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_LISTENER_H_ + +#include "firebase/storage/controller.h" + +namespace firebase { +namespace storage { + +/// @cond FIREBASE_APP_INTERNAL +namespace internal { +class ListenerInternal; +class StorageInternal; +class StorageReferenceInternal; +class RestOperation; +} // namespace internal +/// @endcond + +/// @brief Base class used to receive pause and progress events on a running +/// read or write operation. +/// +/// Subclasses of this listener class can be used to receive events about data +/// transfer progress a location. Attach the listener to a location using +/// StorageReference::GetBytes(), StorageReference::GetFile(), +/// StorageReference::PutBytes(), and StorageReference::PutFile(); then +/// OnPaused() will be called whenever the Read or Write operation is paused, +/// and OnProgress() will be called periodically as the transfer makes progress. +class Listener { + public: + /// @brief Constructor. + Listener(); + + /// @brief Virtual destructor. + virtual ~Listener(); + + /// @brief The operation was paused. + /// + /// @param[in] controller A controller that can be used to check the status + /// and make changes to the ongoing operation. + virtual void OnPaused(Controller* controller) = 0; + + /// @brief There has been progress event. + /// + /// @param[in] controller A controller that can be used to check the status + /// and make changes to the ongoing operation. + virtual void OnProgress(Controller* controller) = 0; + + private: + /// @cond FIREBASE_APP_INTERNAL + friend class internal::StorageReferenceInternal; + friend class internal::RestOperation; + + // Platform specific data. + internal::ListenerInternal* impl_; + /// @endcond +}; + +} // namespace storage +} // namespace firebase + +#endif // FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_LISTENER_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/storage/metadata.h b/packages/firebase_core/firebase_core/firebase_core/firebase/storage/metadata.h new file mode 100644 index 000000000000..8d697c1072e7 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/storage/metadata.h @@ -0,0 +1,276 @@ +// Copyright 2016 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_METADATA_H_ +#define FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_METADATA_H_ + +#include +#include +#include +#include + +#include "firebase/internal/common.h" + +namespace firebase { +namespace storage { + +namespace internal { +class MetadataInternal; +class MetadataInternalCommon; +class StorageInternal; +class StorageReferenceInternal; +} // namespace internal + +class Storage; +class StorageReference; + +/// @brief Metadata stores default attributes such as size and content type. +/// +/// Metadata for a StorageReference. You may also store custom metadata key +/// value pairs. Metadata values may be used to authorize operations using +/// declarative validation rules. +class Metadata { + public: + /// @brief Create a default Metadata that you can modify and use. + Metadata(); + +#ifdef INTERNAL_EXPERIMENTAL + Metadata(internal::MetadataInternal* internal); +#endif + + /// @brief Copy constructor. + /// + /// @param[in] other Metadata to copy from. + Metadata(const Metadata& other); + + /// @brief Copy assignment operator. + /// + /// @param[in] other Metadata to copy from. + /// + /// @returns Reference to the destination Metadata. + Metadata& operator=(const Metadata& other); + +#if defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) + /// @brief Move constructor. Moving is an efficient operation for Metadata. + /// + /// @param[in] other Metadata to move from. + Metadata(Metadata&& other); + + /// @brief Move assignment operator. Moving is an efficient operation for + /// Metadata. + /// + /// @param[in] other Metadata to move from. + /// + /// @returns Reference to the destination Metadata. + Metadata& operator=(Metadata&& other); +#endif // defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) + + ~Metadata(); + + /// @brief Return the owning Google Cloud Storage bucket for the + /// StorageReference. + /// + /// @returns The owning Google Cloud Storage bucket for the StorageReference. + const char* bucket() const; + + /// @brief Set the Cache Control setting of the StorageReference. + /// + /// @see https://tools.ietf.org/html/rfc7234#section-5.2 + void set_cache_control(const char* cache_control); + + /// @brief Set the Cache Control setting of the StorageReference. + /// + /// @see https://tools.ietf.org/html/rfc7234#section-5.2 + void set_cache_control(const std::string& cache_control) { + set_cache_control(cache_control.c_str()); + } + + /// @brief Return the Cache Control setting of the StorageReference. + /// + /// @returns The Cache Control setting of the StorageReference. + /// + /// @see https://tools.ietf.org/html/rfc7234#section-5.2 + const char* cache_control() const; + + /// @brief Set the content disposition of the StorageReference. + /// + /// @see https://tools.ietf.org/html/rfc6266 + void set_content_disposition(const char* disposition); + + /// @brief Set the content disposition of the StorageReference. + /// + /// @see https://tools.ietf.org/html/rfc6266 + void set_content_disposition(const std::string& disposition) { + set_content_disposition(disposition.c_str()); + } + + /// @brief Return the content disposition of the StorageReference. + /// + /// @returns The content disposition of the StorageReference. + /// + /// @see https://tools.ietf.org/html/rfc6266 + const char* content_disposition() const; + + /// @brief Set the content encoding for the StorageReference. + /// + /// @see https://tools.ietf.org/html/rfc2616#section-14.11 + void set_content_encoding(const char* encoding); + + /// @brief Set the content encoding for the StorageReference. + /// + /// @see https://tools.ietf.org/html/rfc2616#section-14.11 + void set_content_encoding(const std::string& encoding) { + set_content_encoding(encoding.c_str()); + } + + /// @brief Return the content encoding for the StorageReference. + /// + /// @returns The content encoding for the StorageReference. + /// + /// @see https://tools.ietf.org/html/rfc2616#section-14.11 + const char* content_encoding() const; + + /// @brief Set the content language for the StorageReference. + /// + /// @see https://tools.ietf.org/html/rfc2616#section-14.12 + void set_content_language(const char* language); + + /// @brief Set the content language for the StorageReference. + /// + /// This must be an ISO 639-1 two-letter language code. + /// E.g. "zh", "es", "en". + /// + /// @see https://www.loc.gov/standards/iso639-2/php/code_list.php + void set_content_language(const std::string& language) { + set_content_language(language.c_str()); + } + + /// @brief Return the content language for the StorageReference. + /// + /// @returns The content language for the StorageReference. + /// + /// @see https://tools.ietf.org/html/rfc2616#section-14.12 + const char* content_language() const; + + /// @brief Set the content type of the StorageReference. + /// + /// @see https://tools.ietf.org/html/rfc2616#section-14.17 + void set_content_type(const char* type); + + /// @brief Set the content type of the StorageReference. + /// + /// @see https://tools.ietf.org/html/rfc2616#section-14.17 + void set_content_type(const std::string& type) { + set_content_type(type.c_str()); + } + + /// @brief Return the content type of the StorageReference. + /// + /// @returns The content type of the StorageReference. + /// + /// @see https://tools.ietf.org/html/rfc2616#section-14.17 + const char* content_type() const; + + /// @brief Return the time the StorageReference was created in milliseconds + /// since the epoch. + /// + /// @returns The time the StorageReference was created in milliseconds since + /// the epoch. + int64_t creation_time() const; + + /// @brief Return a map of custom metadata key value pairs. + /// + /// The pointer returned is only valid during the lifetime of the Metadata + /// object that owns it. + /// + /// @returns The keys for custom metadata. + std::map* custom_metadata() const; + + // download_url() and download_urls() are deprecated and removed. + // Please use StorageReference::GetDownloadUrl() instead. + + /// @brief Return a version String indicating what version of the + /// StorageReference. + /// + /// @returns A value indicating the version of the StorageReference. + int64_t generation() const; + + /// @brief Return a version String indicating the version of this + /// StorageMetadata. + /// + /// @returns A value indicating the version of this StorageMetadata. + int64_t metadata_generation() const; + + /// @brief Return a simple name of the StorageReference object. + /// + /// @returns A simple name of the StorageReference object. + const char* name() const; + + /// @brief Return the path of the StorageReference object. + /// + /// @returns The path of the StorageReference object. + const char* path() const; + + /// @brief Return the associated StorageReference to which this Metadata + /// belongs. + /// + /// @returns The associated StorageReference to which this Metadata belongs. + /// If this Metadata is invalid or is not associated with any file, an invalid + /// StorageReference is returned. + StorageReference GetReference() const; + + /// @brief Return the stored Size in bytes of the StorageReference object. + /// + /// @returns The stored Size in bytes of the StorageReference object. + int64_t size_bytes() const; + + /// @brief Return the time the StorageReference was last updated in + /// milliseconds since the epoch. + /// + /// @return The time the StorageReference was last updated in milliseconds + /// since the epoch. + int64_t updated_time() const; + + /// @brief Returns true if this Metadata is valid, false if it is not + /// valid. An invalid Metadata is returned when a method such as + /// StorageReference::GetMetadata() completes with an error. + /// + /// @returns true if this Metadata is valid, false if this Metadata is + /// invalid. + bool is_valid() const; + + /// @brief MD5 hash of the data; encoded using base64. + /// + /// @returns MD5 hash of the data; encoded using base64. + const char* md5_hash() const; + + private: + /// @cond FIREBASE_APP_INTERNAL + friend class StorageReference; + friend class internal::MetadataInternal; + friend class internal::MetadataInternalCommon; + friend class internal::StorageReferenceInternal; + +#ifndef INTERNAL_EXPERIMENTAL + Metadata(internal::MetadataInternal* internal); +#endif + + internal::MetadataInternal* internal_; + /// @endcond +}; + +} // namespace storage +} // namespace firebase + +#endif // FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_METADATA_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/storage/storage_reference.h b/packages/firebase_core/firebase_core/firebase_core/firebase/storage/storage_reference.h new file mode 100644 index 000000000000..e5c7c2f85ae6 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/storage/storage_reference.h @@ -0,0 +1,361 @@ +// Copyright 2016 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_STORAGE_REFERENCE_H_ +#define FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_STORAGE_REFERENCE_H_ + +#include +#include + +#include "firebase/future.h" +#include "firebase/internal/common.h" +#include "firebase/storage/metadata.h" + +namespace firebase { +namespace storage { + +class Controller; +class Listener; +class Storage; + +/// @cond FIREBASE_APP_INTERNAL +namespace internal { +class ControllerInternal; +class MetadataInternal; +class StorageInternal; +class StorageReferenceInternalCommon; +class StorageReferenceInternal; +} // namespace internal +/// @endcond FIREBASE_APP_INTERNAL + +#ifndef SWIG +/// Represents a reference to a Cloud Storage object. +/// Developers can upload and download objects, get/set object metadata, and +/// delete an object at a specified path. +#endif // SWIG +class StorageReference { + public: + /// @brief Default constructor. This creates an invalid StorageReference. + /// Attempting to perform any operations on this reference will fail unless a + /// valid StorageReference has been assigned to it. + StorageReference() : internal_(nullptr) {} + + ~StorageReference(); + + /// @brief Copy constructor. It's totally okay (and efficient) to copy + /// StorageReference instances, as they simply point to the same location. + /// + /// @param[in] reference StorageReference to copy from. + StorageReference(const StorageReference& reference); + + /// @brief Copy assignment operator. It's totally okay (and efficient) to copy + /// StorageReference instances, as they simply point to the same location. + /// + /// @param[in] reference StorageReference to copy from. + /// + /// @returns Reference to the destination StorageReference. + StorageReference& operator=(const StorageReference& reference); + +#if defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) + /// @brief Move constructor. Moving is an efficient operation for + /// StorageReference instances. + /// + /// @param[in] other StorageReference to move data from. + StorageReference(StorageReference&& other); + + /// @brief Move assignment operator. Moving is an efficient operation for + /// StorageReference instances. + /// + /// @param[in] other StorageReference to move data from. + /// + /// @returns Reference to the destination StorageReference. + StorageReference& operator=(StorageReference&& other); +#endif // defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) + + /// @brief Gets the firebase::storage::Storage instance to which we refer. + /// + /// The pointer will remain valid indefinitely. + /// + /// @returns The firebase::storage::Storage instance that this + /// StorageReference refers to. + Storage* storage(); + + /// @brief Gets a reference to a location relative to this one. + /// + /// @param[in] path Path relative to this reference's location. + /// The pointer only needs to be valid during this call. + /// + /// @returns Child relative to this location. + StorageReference Child(const char* path) const; + + /// @brief Gets a reference to a location relative to this one. + /// + /// @param[in] path Path relative to this reference's location. + /// + /// @returns Child relative to this location. + StorageReference Child(const std::string& path) const { + return Child(path.c_str()); + } + + /// @brief Deletes the object at the current path. + /// + /// @returns A Future result, which will complete when the operation either + /// succeeds or fails. When the Future is completed, if its Error is + /// kErrorNone, the operation succeeded. + Future Delete(); + + /// @brief Returns the result of the most recent call to RemoveValue(); + /// + /// @returns The result of the most recent call to RemoveValue(); + Future DeleteLastResult(); + + /// @brief Return the Google Cloud Storage bucket that holds this object. + /// + /// @returns The bucket. + std::string bucket(); + + /// @brief Return the full path of the storage reference, not including + /// the Google Cloud Storage bucket. + /// + /// @returns Full path to the storage reference, not including GCS bucket. + /// For example, for the reference "gs://bucket/path/to/object.txt", the full + /// path would be "path/to/object.txt". + std::string full_path(); + + /// @brief Asynchronously downloads the object from this StorageReference. + /// + /// A byte array will be allocated large enough to hold the entire file in + /// memory. Therefore, using this method will impact memory usage of your + /// process. + /// + /// @param[in] path Path to local file on device to download into. + /// @param[in] listener A listener that will respond to events on this read + /// operation. If not nullptr, a listener that will respond to events on this + /// read operation. The caller is responsible for allocating and deallocating + /// the listener. The same listener can be used for multiple operations. + /// @param[out] controller_out Controls the write operation, providing the + /// ability to pause, resume or cancel an ongoing write operation. If not + /// nullptr, this method will output a Controller here that you can use to + /// control the write operation. + /// + /// @returns A future that returns the number of bytes read. + Future GetFile(const char* path, Listener* listener = nullptr, + Controller* controller_out = nullptr); + + /// @brief Returns the result of the most recent call to GetFile(); + /// + /// @returns The result of the most recent call to GetFile(); + Future GetFileLastResult(); + + /// @brief Asynchronously downloads the object from this StorageReference. + /// + /// A byte array will be allocated large enough to hold the entire file in + /// memory. Therefore, using this method will impact memory usage of your + /// process. + /// + /// @param[in] buffer A byte buffer to read the data into. This buffer must + /// be valid for the duration of the transfer. + /// @param[in] buffer_size The size of the byte buffer. + /// @param[in] listener A listener that will respond to events on this read + /// operation. If not nullptr, a listener that will respond to events on this + /// read operation. The caller is responsible for allocating and deallocating + /// the listener. The same listener can be used for multiple operations. + /// @param[out] controller_out Controls the write operation, providing the + /// ability to pause, resume or cancel an ongoing write operation. If not + /// nullptr, this method will output a Controller here that you can use to + /// control the write operation. + /// + /// @returns A future that returns the number of bytes read. + Future GetBytes(void* buffer, size_t buffer_size, + Listener* listener = nullptr, + Controller* controller_out = nullptr); + + /// @brief Returns the result of the most recent call to GetBytes(); + /// + /// @returns The result of the most recent call to GetBytes(); + Future GetBytesLastResult(); + + /// @brief Asynchronously retrieves a long lived download URL with a revokable + /// token. + /// + /// This can be used to share the file with others, but can be revoked by a + /// developer in the Firebase Console if desired. + /// + /// @returns A Future result, which will complete when the operation either + /// succeeds or fails. When the Future is completed, if its Error is + /// kErrorNone, the operation succeeded and the URL is returned. + Future GetDownloadUrl(); + + /// @brief Returns the result of the most recent call to GetDownloadUrl(); + /// + /// @returns The result of the most recent call to GetDownloadUrl(); + Future GetDownloadUrlLastResult(); + + /// @brief Retrieves metadata associated with an object at this + /// StorageReference. + /// + /// @returns A Future result, which will complete when the operation either + /// succeeds or fails. When the Future is completed, if its Error is + /// kErrorNone, the operation succeeded and the Metadata is returned. + Future GetMetadata(); + + /// @brief Returns the result of the most recent call to GetMetadata(); + /// + /// @returns The result of the most recent call to GetMetadata(); + Future GetMetadataLastResult(); + + /// @brief Updates the metadata associated with this StorageReference. + /// + /// @returns A Future result, which will complete when the operation either + /// succeeds or fails. When the Future is completed, if its Error is + /// kErrorNone, the operation succeeded and the Metadata is returned. + Future UpdateMetadata(const Metadata& metadata); + + /// @brief Returns the result of the most recent call to UpdateMetadata(); + /// + /// @returns The result of the most recent call to UpdateMetadata(); + Future UpdateMetadataLastResult(); + + /// @brief Returns the short name of this object. + /// + /// @returns the short name of this object. + std::string name(); + + /// @brief Returns a new instance of StorageReference pointing to the parent + /// location or null if this instance references the root location. + /// + /// @returns The parent StorageReference. + StorageReference GetParent(); + + /// @brief Asynchronously uploads data to the currently specified + /// StorageReference, without additional metadata. + /// + /// @param[in] buffer A byte buffer to write data from. This buffer must be + /// valid for the duration of the transfer. + /// @param[in] buffer_size The size of the byte buffer. + /// @param[in] listener A listener that will respond to events on this read + /// operation. If not nullptr, a listener that will respond to events on this + /// write operation. The caller is responsible for allocating and deallocating + /// the listener. The same listener can be used for multiple operations. + /// @param[out] controller_out Controls the write operation, providing the + /// ability to pause, resume or cancel an ongoing write operation. If not + /// nullptr, this method will output a Controller here that you can use to + /// control the write operation. + /// + /// @returns A future that returns the Metadata. + Future PutBytes(const void* buffer, size_t buffer_size, + Listener* listener = nullptr, + Controller* controller_out = nullptr); + + /// @brief Asynchronously uploads data to the currently specified + /// StorageReference, without additional metadata. + /// + /// @param[in] buffer A byte buffer to write data from. This buffer must be + /// valid for the duration of the transfer. + /// @param[in] buffer_size The number of bytes to write. + /// @param[in] metadata Metadata containing additional information (MIME type, + /// etc.) about the object being uploaded. + /// @param[in] listener A listener that will respond to events on this read + /// operation. If not nullptr, a listener that will respond to events on this + /// write operation. The caller is responsible for allocating and deallocating + /// the listener. The same listener can be used for multiple operations. + /// @param[out] controller_out Controls the write operation, providing the + /// ability to pause, resume or cancel an ongoing write operation. If not + /// nullptr, this method will output a Controller here that you can use to + /// control the write operation. + /// + /// @returns A future that returns the Metadata. + Future PutBytes(const void* buffer, size_t buffer_size, + const Metadata& metadata, + Listener* listener = nullptr, + Controller* controller_out = nullptr); + + /// @brief Returns the result of the most recent call to PutBytes(); + /// + /// @returns The result of the most recent call to PutBytes(); + Future PutBytesLastResult(); + + /// @brief Asynchronously uploads data to the currently specified + /// StorageReference, without additional metadata. + /// + /// @param[in] path Path to local file on device to upload to Firebase + /// Storage. + /// @param[in] listener A listener that will respond to events on this read + /// operation. If not nullptr, a listener that will respond to events on this + /// write operation. The caller is responsible for allocating and deallocating + /// the listener. The same listener can be used for multiple operations. + /// @param[out] controller_out Controls the write operation, providing the + /// ability to pause, resume or cancel an ongoing write operation. If not + /// nullptr, this method will output a Controller here that you can use to + /// control the write operation. + /// + /// @returns A future that returns the Metadata. + Future PutFile(const char* path, Listener* listener = nullptr, + Controller* controller_out = nullptr); + + /// @brief Asynchronously uploads data to the currently specified + /// StorageReference, without additional metadata. + /// + /// @param[in] path Path to local file on device to upload to Firebase + /// Storage. + /// @param[in] metadata Metadata containing additional information (MIME type, + /// etc.) about the object being uploaded. + /// @param[in] listener A listener that will respond to events on this read + /// operation. If not nullptr, a listener that will respond to events on this + /// write operation. The caller is responsible for allocating and deallocating + /// the listener. The same listener can be used for multiple operations. + /// @param[out] controller_out Controls the write operation, providing the + /// ability to pause, resume or cancel an ongoing write operation. If not + /// nullptr, this method will output a Controller here that you can use to + /// control the write operation. + /// + /// @returns A future that returns the Metadata. + Future PutFile(const char* path, const Metadata& metadata, + Listener* listener = nullptr, + Controller* controller_out = nullptr); + + /// @brief Returns the result of the most recent call to PutFile(); + /// + /// @returns The result of the most recent call to PutFile(); + Future PutFileLastResult(); + + /// @brief Returns true if this StorageReference is valid, false if it is not + /// valid. An invalid StorageReference indicates that the reference is + /// uninitialized (created with the default constructor) or that there was an + /// error retrieving the reference. + /// + /// @returns true if this StorageReference is valid, false if this + /// StorageReference is invalid. + bool is_valid() const; + + private: + /// @cond FIREBASE_APP_INTERNAL + friend class Controller; + friend class internal::ControllerInternal; + friend class Metadata; + friend class internal::MetadataInternal; + friend class Storage; + friend class internal::StorageReferenceInternal; + friend class internal::StorageReferenceInternalCommon; + + StorageReference(internal::StorageReferenceInternal* internal); + + internal::StorageReferenceInternal* internal_; + /// @endcond +}; + +} // namespace storage +} // namespace firebase + +#endif // FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_STORAGE_REFERENCE_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/util.h b/packages/firebase_core/firebase_core/firebase_core/firebase/util.h new file mode 100644 index 000000000000..4c78d45f3ac8 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/util.h @@ -0,0 +1,101 @@ +/* + * Copyright 2016 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_APP_SRC_INCLUDE_FIREBASE_UTIL_H_ +#define FIREBASE_APP_SRC_INCLUDE_FIREBASE_UTIL_H_ + +#include "firebase/app.h" +#include "firebase/future.h" + +namespace firebase { + +struct ModuleInitializerData; + +/// @brief Utility class to help with initializing Firebase modules. +/// +/// This optional class handles a basic Firebase C++ SDK code pattern: attempt +/// to initialize a Firebase module, and if the initialization fails on Android +/// due to Google Play services being unavailable, prompt the user to +/// update/enable Google Play services on their device. +/// +/// If the developer wants more advanced behavior (for example, wait to prompt +/// the user to update or enable Google Play services until later, or opt not to +/// use Firebase modules), they can still initialize each Firebase module +/// individually, and use google_play_services::MakeAvailable() directly if any +/// initializations fail. +class ModuleInitializer { + public: + /// @brief Initialization function, which should initialize a single Firebase + /// module and return the InitResult. + typedef InitResult (*InitializerFn)(App* app, void* context); + + ModuleInitializer(); + virtual ~ModuleInitializer(); + + /// @brief Initialize Firebase modules by calling one or more user-supplied + /// functions, each of which must initialize at most one library, and should + /// return the InitResult of the initialization. + /// + /// This function will run the initializers in order, checking the return + /// value of each. On Android, if the InitResult returned is + /// kInitResultFailedMissingDependency, this indicates that Google Play + /// services is not available and a Firebase module requires it. This function + /// will attempt to fix Google Play services, and will retry initializations + /// where it left off, beginning with the one that failed. + /// + /// @returns A future result. When all of the initializers are completed, the + /// Future will be completed with Error() = 0. If an initializer fails and the + /// situation cannot be fixed, the Future will be completed with Error() equal + /// to the number of initializers that did not succeed (since they are run in + /// order, this tells you which ones failed). + /// + /// @param[in] app The firebase::App that will be passed to the initializers, + /// as well as used to fix Google Play services on Android if needed. + /// + /// @param[in] context User-defined context, which will be passed to the + /// initializer functions. If you don't need this, you can use nullptr. + /// + /// @param[in] init_fns Your initialization functions to call, in an array. At + /// their simplest, these will each simply call a single Firebase module's + /// Initialize(app) and return the result, but you can perform more complex + /// logic if you prefer. + /// + /// @param[in] init_fns_count Number of initialization functions in the + /// supplied array. + /// + /// @note If a pending Initialize() is already running, this function will + /// return the existing Future rather than adding any new functions to the + /// initializer list. + Future Initialize(App* app, void* context, + const InitializerFn* init_fns, size_t init_fns_count); + + /// @brief Initialize one Firebase module by calling a single user-supplied + /// function that should initialize a Firebase module and return the + /// InitResult. @see Initialize(::firebase::App*, void*, const InitializerFn*) + /// for more information. + Future Initialize(App* app, void* context, InitializerFn init_fn); + + /// @brief Get the result of the most recent call to @see Initialize(). + Future InitializeLastResult(); + + private: + ModuleInitializerData* data_; +}; + +// NOLINTNEXTLINE - allow namespace overridden +} // namespace firebase + +#endif // FIREBASE_APP_SRC_INCLUDE_FIREBASE_UTIL_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/variant.h b/packages/firebase_core/firebase_core/firebase_core/firebase/variant.h new file mode 100644 index 000000000000..ef1d552dffa4 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/variant.h @@ -0,0 +1,1197 @@ +/* + * Copyright 2016 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_APP_SRC_INCLUDE_FIREBASE_VARIANT_H_ +#define FIREBASE_APP_SRC_INCLUDE_FIREBASE_VARIANT_H_ + +#include + +#include +#include +#include +#include +#include + +#include "firebase/internal/common.h" + +/// @brief Namespace that encompasses all Firebase APIs. + +namespace firebase { +namespace internal { +class VariantInternal; +} +} // namespace firebase + +namespace firebase { + +// +// SWIG uses the Variant class as a readonly object, and so ignores most of the +// functions. In order to keep things clean, functions that should be exposed +// are explicitly listed in app.SWIG, and everything else is ignored. +// + +/// Variant data type used by Firebase libraries. +class Variant { + public: + /// Type of data that this variant object contains. + enum Type { + /// Null, or no data. + kTypeNull, + /// A 64-bit integer. + kTypeInt64, + /// A double-precision floating point number. + kTypeDouble, + /// A boolean value. + kTypeBool, + /// A statically-allocated string we point to. + kTypeStaticString, + /// A std::string. + kTypeMutableString, + /// A std::vector of Variant. + kTypeVector, + /// A std::map, mapping Variant to Variant. + kTypeMap, + /// An statically-allocated blob of data that we point to. Never constructed + /// by default. Use Variant::FromStaticBlob() to create a Variant of this + /// type. + kTypeStaticBlob, + /// A blob of data that the Variant holds. Never constructed by default. Use + /// Variant::FromMutableBlob() to create a Variant of this type, and copy + /// binary data from an existing source. + kTypeMutableBlob, + + // Note: If you add new types update enum InternalType; + }; + +// +// Because of the VariantVariantMap C# class, we need to hide the constructors +// explicitly, as the SWIG ignore does not seem to work with that macro. +// +#ifndef SWIG + /// @brief Construct a null Variant. + /// + /// The Variant constructed will be of type Null. + Variant() : type_(kInternalTypeNull), value_({}) {} + + /// @brief Construct a Variant with the given templated type. + /// + /// @param[in] value The value to construct the variant. + /// + /// Valid types for this constructor are `int`, `int64_t`, `float`, `double`, + /// `bool`, `const char*`, and `char*` (but see below for additional Variant + /// types). + /// + /// + /// Type `int` or `int64_t`: + /// * The Variant constructed will be of type Int64. + /// + /// Type `double` or `float`: + /// * The Variant constructed will be of type Double. + /// + /// Type `bool`: + /// * The Variant constructed will be of type Bool. + /// + /// Type `const char*`: + /// * The Variant constructed will be of type StaticString, and is_string() + /// will return true. **Note:** If you use this constructor, you must + /// ensure that the memory pointed to stays valid for the life of the + /// Variant, otherwise call mutable_string() or set_mutable_string(), + /// which will copy the string to an internal buffer. + /// + /// Type `char*`: + /// * The Variant constructed will be of type MutableString, and is_string() + /// will return true. + /// + /// Other types will result in compiler error unless using the following + /// constructor overloads: + /// * `std::string` + /// * `std::vector` + /// * `std::vector` where T is convertible to variant type + /// * `T*`, `size_t` where T is convertible to variant type + /// * `std::map` + /// * `std::map` where K and V is convertible to variant type + template + Variant(T value) // NOLINT + : type_(kInternalTypeNull) { + set_value_t(value); + } + + /// @brief Construct a Variant containing the given string value (makes a + /// copy). + /// + /// The Variant constructed will be of type MutableString, and is_string() + /// will return true. + /// + /// @param[in] value The string to use for the Variant. + Variant(const std::string& value) // NOLINT + : type_(kInternalTypeNull) { + set_mutable_string(value); + } + + /// @brief Construct a Variant containing the given std::vector of Variant. + /// + /// The Variant constructed will be of type Vector. + /// + /// @param[in] value The STL vector to copy into the Variant. + Variant(const std::vector& value) // NOLINT + : type_(kInternalTypeNull) { + set_vector(value); + } + + /// @brief Construct a Variant containing the given std::vector of something + /// that can be constructed into a Variant. + /// + /// The Variant constructed will be of type Vector. + /// + /// @param[in] value An STL vector containing elements that can be converted + /// to Variant (such as ints, strings, vectors). A Variant will be created for + /// each element, and copied into the Vector Variant constructed here. + template + Variant(const std::vector& value) // NOLINT + : type_(kInternalTypeNull) { + Clear(kTypeVector); + vector().reserve(value.size()); + for (size_t i = 0; i < value.size(); i++) { + vector().push_back(Variant(static_cast(value[i]))); + } + } + + /// @brief Construct a Variant from an array of supported types into a Vector. + /// + /// The Variant constructed will be of type Vector. + /// + /// @param[in] array_of_values A C array containing elements that can be + /// converted to Variant (such as ints, strings, vectors). A Variant will be + /// created for each element, and copied into the Vector Variant constructed + /// here. + /// @param[in] array_size Number of elements of the array. + template + Variant(const T array_of_values[], size_t array_size) + : type_(kInternalTypeNull) { + Clear(kTypeVector); + vector().reserve(array_size); + for (size_t i = 0; i < array_size; i++) { + vector()[i] = Variant(array_of_values[i]); + } + } + + /// @brief Construct a Variatn containing the given std::map of Variant to + /// Variant. + /// + /// The Variant constructed will be of type Map. + /// + /// @param[in] value The STL map to copy into the Variant. + Variant(const std::map& value) // NOLINT + : type_(kInternalTypeNull) { + set_map(value); + } + + /// @brief Construct a Variant containing the given std::map of something that + /// can be constructed into a Variant, to something that can be constructed + /// into a Variant. + /// + /// The Variant constructed will be of type Map. + /// + /// @param[in] value An STL map containing keys and values that can be + /// converted to Variant (such as ints, strings, vectors). A Variant will be + /// created for each key and for each value, and copied by pairs into the Map + /// Variant constructed here. + template + Variant(const std::map& value) // NOLINT + : type_(kInternalTypeNull) { + Clear(kTypeMap); + for (typename std::map::const_iterator i = value.begin(); + i != value.end(); ++i) { + map().insert(std::make_pair(Variant(i->first), Variant(i->second))); + } + } + + /// @brief Copy constructor. Performs a deep copy. + /// + /// @param[in] other Source Variant to copy from. + Variant(const Variant& other) : type_(kInternalTypeNull) { *this = other; } + + /// @brief Copy assignment operator. Performs a deep copy. + /// + /// @param[in] other Source Variant to copy from. + Variant& operator=(const Variant& other); + +#if defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) + + /// @brief Move constructor. Efficiently moves the more complex data types by + /// simply reassigning pointer ownership. + /// + /// @param[in] other Source Variant to move from. + Variant(Variant&& other) noexcept : type_(kInternalTypeNull) { + *this = std::move(other); + } + + /// @brief Move assignment operator. Efficiently moves the more complex data + /// types by simply reassigning pointer ownership. + /// + /// @param[in] other Source Variant to move from. + Variant& operator=(Variant&& other) noexcept; + +#endif // defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) +#endif // SWIG + + /// Destructor. Frees the memory that this Variant owns. + ~Variant() { Clear(); } + + /// @brief Equality operator. Both the type and the value must be equal + /// (except that static strings CAN be == to mutable strings). For container + /// types, element-by-element comparison is performed. For strings, string + /// comparison is performed. + /// + /// @param[in] other Variant to compare to. + /// + /// @return True if the Variants are of identical types and values, false + /// otherwise. + bool operator==(const Variant& other) const; + + /// @brief Inequality operator, only meant for internal use. + /// + /// Explanation: In order to use Variant as a key for std::map, we must + /// provide a comparison function. This comparison function is ONLY for + /// std::map to be able to use a Variant as a map key. + /// + /// We define v1 < v2 IFF: + /// * If different types, compare type as int: v1.type() < v2.type() + /// (note: this means that Variant(1) < Variant(0.0) - be careful!) + /// * If both are int64: v1.int64_value() < v2.int64_value(); + /// * If both are double: v1.double_value() < v2.double_value() + /// * If both are bool: v1.bool_value() < v2.bool_value(); + /// * If both are either static or mutable strings: strcmp(v1, v2) < 0 + /// * If both are vectors: + /// * If v1[0] < v2[0], that means v1 < v2 == true. Otherwise: + /// * If v1[0] > v2[0], that means v1 < v2 == false. Otherwise: + /// * Continue to the next element of both vectors and compare again. + /// * If you reach the end of one vector first, that vector is considered + /// to be lesser. + /// * If both are maps, iterate similar to vectors (since maps are ordered), + /// but for each element, first compare the key, then the value. + /// * If both are blobs, the smaller-sized blob is considered lesser. If both + /// blobs are the same size, use memcmp to compare the bytes. + /// + /// We have defined this operation such that if !(v1 < v2) && !(v2 < v1), it + /// must follow that v1 == v2. + /// + /// @param[in] other Variant to compare to. + /// + /// @return Results of the comparison, as described in this documentation. + /// + /// @note This will not give you the results you expect if you compare + /// Variants of different types! For example, Variant(0.0) < Variant(1). + bool operator<(const Variant& other) const; + + /// @brief Inequality operator: x != y is evaluated as !(x == y). + /// + /// @param[in] other Variant to compare to. + /// + /// @return Results of the comparison. + bool operator!=(const Variant& other) const { return !(*this == other); } + + /// @brief Inequality operator: x > y is evaluated as y < x + /// + /// @param[in] other Variant to compare to. + /// + /// @return Results of the comparison. + bool operator>(const Variant& other) const { return other < *this; } + + /// @brief Inequality operator: x >= y is evaluated as !(x < y) + /// + /// @param[in] other Variant to compare to. + /// + /// @return Results of the comparison. + bool operator>=(const Variant& other) const { return !(*this < other); } + + /// @brief Inequality operator: x <= y is evaluated as !(x > y) + /// + /// @param[in] other Variant to compare to. + /// + /// @return Results of the comparison. + bool operator<=(const Variant& other) const { return !(*this > other); } + + /// @brief Clear the given Variant data, optionally into a new type. Frees up + /// any memory that might have been allocated. After calling this, you can + /// access the Variant as the new type. + /// + /// @param[in] new_type Optional new type to clear the Variant to. You may + /// immediately begin using the Variant as that new type. + void Clear(Type new_type = kTypeNull); + + // Convenience functions (used similarly to constants). + + /// @brief Get a Variant of type Null. + /// + /// @return A Variant of type Null. + static Variant Null() { return Variant(); } + + /// @brief Get a Variant of integer value 0. + /// + /// @return A Variant of type Int64, with value 0. + static Variant Zero() { return Variant::FromInt64(0L); } + + /// @brief Get a Variant of integer value 1. + /// + /// @return A Variant of type Int64, with value 1. + static Variant One() { return Variant::FromInt64(1L); } + + /// @brief Get a Variant of double value 0.0. + /// + /// @return A Variant of type Double, with value 0.0. + static Variant ZeroPointZero() { return Variant::FromDouble(0.0); } + + /// @brief Get a Variant of double value 1.0. + /// + /// @return A Variant of type Double, with value 1.0. + static Variant OnePointZero() { return Variant::FromDouble(1.0); } + + /// @brief Get a Variant of bool value false. + /// + /// @return A Variant of type Bool, with value false. + static Variant False() { return Variant::FromBool(false); } + + /// @brief Get a Variant of bool value true. + /// + /// @return A Variant of type Bool, with value true. + static Variant True() { return Variant::FromBool(true); } + + /// @brief Get an empty string variant. + /// + /// @return A Variant of type StaticString, referring to an empty string. + static Variant EmptyString() { return Variant::FromStaticString(""); } + + /// @brief Get a Variant containing an empty mutable string. + /// + /// @return A Variant of type MutableString, containing an empty string. + static Variant EmptyMutableString() { + Variant v; + v.Clear(kTypeMutableString); + return v; + } + + /// @brief Get a Variant containing an empty vector. You can immediately call + /// vector() on it to work with the vector it contains. + /// + /// @return A Variant of type Vector, containing no elements. + static Variant EmptyVector() { + Variant v; + v.Clear(kTypeVector); + return v; + } + + /// @brief Get a Variant containing an empty map. You can immediately call + /// map() on + /// it to work with the map it contains. + /// + /// @return A Variant of type Map, containing no elements. + static Variant EmptyMap() { + Variant v; + v.Clear(kTypeMap); + return v; + } + + /// @brief Return a Variant containing an empty mutable blob of the requested + /// size, filled with 0-bytes. + /// + /// @param[in] size_bytes Size of the buffer you want, in bytes. + /// + /// @returns A Variant containing a mutable blob of the requested size, filled + /// with 0-bytes. + static Variant EmptyMutableBlob(size_t size_bytes) { + Variant v; + uint8_t* blank_data = new uint8_t[size_bytes]; + memset(blank_data, 0, size_bytes); + v.Clear(kTypeMutableBlob); + v.set_blob_pointer(blank_data, size_bytes); + return v; + } + + /// @brief Get the current type contained in this Variant. + /// + /// @return The Variant's type. + Type type() const { + // To avoid breaking user code, alias the small string type to mutable + // string. + if (type_ == kInternalTypeSmallString) { + return kTypeMutableString; + } + + return static_cast(type_); + } + + /// @brief Get whether this Variant is currently null. + /// + /// @return True if the Variant is Null, false otherwise. + bool is_null() const { return type() == kTypeNull; } + + /// @brief Get whether this Variant contains an integer. + /// + /// @return True if the Variant's type is Int64, false otherwise. + bool is_int64() const { return type() == kTypeInt64; } + + /// @brief Get whether this Variant contains a double. + /// + /// @return True if the Variant's type is Double, false otherwise. + bool is_double() const { return type() == kTypeDouble; } + + /// @brief Get whether this Variant contains a bool. + /// + /// @return True if the Variant's type is Bool, false otherwise. + bool is_bool() const { return type() == kTypeBool; } + + /// @brief Get whether this Variant contains a vector. + /// + /// @return True if the Variant's type is Vector, false otherwise. + bool is_vector() const { return type() == kTypeVector; } + + /// @brief Get whether this Variant contains a map. + /// + /// @return True if the Variant's type is Map, false otherwise. + bool is_map() const { return type() == kTypeMap; } + + /// @brief Get whether this Variant contains a static string. + /// + /// @return True if the Variant's type is StaticString, false otherwise. + bool is_static_string() const { return type() == kTypeStaticString; } + + /// @brief Get whether this Variant contains a mutable string. + /// + /// @return True if the Variant's type is MutableString, false otherwise. + bool is_mutable_string() const { return type() == kTypeMutableString; } + + /// @brief Get whether this Variant contains a string. + /// + /// @return True if the Variant's type is either StaticString or + /// MutableString or SmallString; false otherwise. + /// + /// @note No matter which type of string the Variant contains, you can read + /// its value via string_value(). + bool is_string() const { + return is_static_string() || is_mutable_string() || is_small_string(); + } + + /// @brief Get whether this Variant contains a static blob. + /// + /// @return True if the Variant's type is StaticBlob, false otherwise. + bool is_static_blob() const { return type() == kTypeStaticBlob; } + + /// @brief Get whether this Variant contains a mutable blob. + /// + /// @return True if the Variant's type is MutableBlob, false otherwise. + bool is_mutable_blob() const { return type() == kTypeMutableBlob; } + + /// @brief Get whether this Variant contains a blob. + /// + /// @return True if the Variant's type is either StaticBlob or + /// MutableBlob; false otherwise. + /// + /// @note No matter which type of blob the Variant contains, you can read + /// its data via blob_data() and get its size via blob_size(). + bool is_blob() const { return is_static_blob() || is_mutable_blob(); } + + /// @brief Get whether this Variant contains a numeric type, Int64 or Double. + /// + /// @return True if the Variant's type is either Int64 or Double; false + /// otherwise. + bool is_numeric() const { return is_int64() || is_double(); } + + /// @brief Get whether this Variant contains a fundamental type: Null, Int64, + /// Double, Bool, or one of the two String types. Essentially + /// !is_containerType(). + /// + /// @return True if the Variant's type is Int64, Double, Bool, or Null; false + /// otherwise. + bool is_fundamental_type() const { + return is_int64() || is_double() || is_string() || is_bool() || is_null(); + } + + /// @brief Get whether this Variant contains a container type: Vector or Map. + /// + /// @return True if the Variant's type is Vector or Map; false otherwise. + bool is_container_type() const { return is_vector() || is_map(); } + + /// @brief Get the current Variant converted into a string. Only valid for + /// fundamental types. + /// + /// Special cases: Booleans will be returned as "true" or "false". Null will + /// be returned as an empty string. The returned string may be either mutable + /// or static, depending on the source type. All other cases will return an + /// empty string. + /// + /// @return A Variant containing a String that represents the value of this + /// original Variant. + Variant AsString() const; + + /// @brief Get the current Variant converted into an integer. Only valid for + /// fundamental types. + /// + /// Special cases: If a String can be parsed as a number + /// via strtol(), it will be. If a Bool is true, this will return 1. All other + /// cases (including non-fundamental types) will return 0. + /// + /// @return A Variant containing an Int64 that represents the value of this + /// original Variant. + Variant AsInt64() const; + + /// @brief Get the current Variant converted into a floating-point + /// number. Only valid for fundamental types. + /// + /// Special cases: If a Bool is true, this will return 1. All other cases will + /// return 0. + /// + /// @return A Variant containing a Double that represents the value of this + /// original Variant. + Variant AsDouble() const; + + /// @brief Get the current Variant converted into a boolean. Null, 0, 0.0, + /// empty strings, empty vectors, empty maps, blobs of size 0, and "false" + /// (case-sensitive) are all considered false. All other values are true. + /// + /// @return A Variant of type Bool containing the original Variant interpreted + /// as a Bool. + Variant AsBool() const; + + /// @brief Mutable accessor for a Variant containing a string. + /// + /// If the Variant contains a static string, it will be converted into a + /// mutable string, which copies the const char*'s data into a std::string. + /// + /// @return Reference to the string contained in this Variant. + /// + /// @note If the Variant is not one of the two String types, this will assert. + std::string& mutable_string() { + if (type_ == kInternalTypeStaticString || + type_ == kInternalTypeSmallString) { + // Automatically promote a static or small string to a mutable string. + set_mutable_string(string_value(), false); + } + assert_is_type(kTypeMutableString); + return *value_.mutable_string_value; + } + + /// @brief Get the size of a blob. This method works with both static + /// and mutable blobs. + /// + /// @return Number of bytes of binary data contained in the blob. + size_t blob_size() const { + assert_is_blob(); + return value_.blob_value.size; + } + + /// @brief Get the pointer to the binary data contained in a blob. + /// This method works with both static and mutable blob. + /// + /// @return Pointer to the binary data. Use blob_size() to get the + /// number of bytes. + const uint8_t* blob_data() const { + assert_is_blob(); + return value_.blob_value.ptr; + } + + /// @brief Get a mutable pointer to the binary data contained in + /// a blob. + /// + /// If the Variant contains a static blob, it will be converted into a mutable + /// blob, which copies the binary data into the Variant's buffer. + /// + /// @returns Pointer to a mutable buffer of binary data. The size of the + /// buffer cannot be changed, but the contents are mutable. + uint8_t* mutable_blob_data() { + if (type_ == kInternalTypeStaticBlob) { + // Automatically promote a static blob to a mutable blob. + set_mutable_blob(blob_data(), blob_size()); + } + assert_is_type(kTypeMutableBlob); + return const_cast(value_.blob_value.ptr); + } + + /// @brief Const accessor for a Variant contianing mutable blob data. + /// + /// @note Unlike the non-const accessor, this accessor cannot "promote" a + /// static blob to mutable, and thus will assert if the Variant you pass in + /// is not of MutableBlob type. + /// + /// @returns Pointer to a mutable buffer of binary data. The size of the + /// buffer cannot be changed, but the contents are mutable. + uint8_t* mutable_blob_data() const { + assert_is_type(kTypeMutableBlob); + return const_cast(value_.blob_value.ptr); + } + + /// @brief Mutable accessor for a Variant containing a vector of Variant + /// data. + /// + /// @return Reference to the vector contained in this Variant. + /// + /// @note If the Variant is not of Vector type, this will assert. + std::vector& vector() { + assert_is_type(kTypeVector); + return *value_.vector_value; + } + /// @brief Mutable accessor for a Variant containing a map of Variant data. + /// + /// @return Reference to the map contained in this Variant. + /// + /// @note If the Variant is not of Map type, this will assert. + std::map& map() { + assert_is_type(kTypeMap); + return *value_.map_value; + } + + /// @brief Const accessor for a Variant containing an integer. + /// + /// @return The integer contained in this Variant. + /// + /// @note If the Variant is not of Int64 type, this will assert. + int64_t int64_value() const { + assert_is_type(kTypeInt64); + return value_.int64_value; + } + + /// @brief Const accessor for a Variant containing a double. + /// + /// @return The double contained in this Variant. + /// + /// @note If the Variant is not of Double type, this will assert. + double double_value() const { + assert_is_type(kTypeDouble); + return value_.double_value; + } + + /// @brief Const accessor for a Variant containing a bool. + /// + /// @return The bool contained in this Variant. + /// + /// @note If the Variant is not of Bool type, this will assert. + const bool& bool_value() const { + assert_is_type(kTypeBool); + return value_.bool_value; + } + + /// @brief Const accessor for a Variant containing a string. + /// + /// This can return both static and mutable strings. The pointer is only + /// guaranteed to persist if this Variant's type is StaticString. + /// + /// @return The string contained in this Variant. + /// + /// @note If the Variant is not of StaticString or MutableString type, this + /// will assert. + const char* string_value() const { + assert_is_string(); + if (type_ == kInternalTypeMutableString) + return value_.mutable_string_value->c_str(); + else if (type_ == kInternalTypeStaticString) + return value_.static_string_value; + else // if (type_ == kInternalTypeSmallString) + return value_.small_string; + } + + /// @brief Const accessor for a Variant containing a string. + /// + /// @note Unlike the non-const accessor, this accessor cannot "promote" a + /// static string to mutable, and thus returns a std::string copy instead of a + /// const reference to a std::string + /// + /// @return std::string with the string contents contained in this Variant. + std::string mutable_string() const { + assert_is_string(); + return string_value(); + } + + /// @brief Const accessor for a Variant containing a vector of Variant data. + /// + /// @return Reference to the vector contained in this Variant. + /// + /// @note If the Variant is not of Vector type, this will assert. + const std::vector& vector() const { + assert_is_type(kTypeVector); + return *value_.vector_value; + } + + /// @brief Const accessor for a Variant containing a map of strings to + /// Variant + /// data. + /// + /// @return Reference to the map contained in this Variant. + /// + /// @note If the Variant is not of Map type, this will assert. + const std::map& map() const { + assert_is_type(kTypeMap); + return *value_.map_value; + } + + /// @brief Sets the Variant value to null. + /// + /// The Variant's type will be Null. + void set_null() { Clear(kTypeNull); } + + /// @brief Sets the Variant to an 64-bit integer value. + /// + /// The Variant's type will be set to Int64. + /// + /// @param[in] value The 64-bit integer value for the Variant. + void set_int64_value(int64_t value) { + Clear(kTypeInt64); + value_.int64_value = value; + } + + /// @brief Sets the Variant to an double-precision floating point value. + /// + /// The Variant's type will be set to Double. + /// + /// @param[in] value The double-precision floating point value for the + /// Variant. + void set_double_value(double value) { + Clear(kTypeDouble); + value_.double_value = value; + } + + /// @brief Sets the Variant to the given boolean value. + /// + /// The Variant's type will be set to Bool. + /// + /// @param[in] value The boolean value for the Variant. + void set_bool_value(bool value) { + Clear(kTypeBool); + value_.bool_value = value; + } + + /// @brief Sets the Variant to point to a static string buffer. + /// + /// The Variant's type will be set to StaticString. + /// + /// @note If you use this method, you must ensure that the memory pointed to + /// stays valid for the life of the Variant, or otherwise call + /// mutable_string() or set_mutable_string(), which will copy the string to an + /// internal buffer. + /// + /// @param[in] value A pointer to the static null-terminated string for the + /// Variant. + void set_string_value(const char* value) { + Clear(kTypeStaticString); + value_.static_string_value = value; + } + + /// @brief Sets the Variant to a mutable string. + /// + /// The Variant's type will be set to MutableString. + /// + /// @param[in] value A pointer to a null-terminated string, which will be + /// copied into to the Variant. + void set_string_value(char* value) { + size_t len = strlen(value); + if (len < kMaxSmallStringSize) { + Clear(static_cast(kInternalTypeSmallString)); + strncpy(value_.small_string, value, len + 1); + } else { + set_mutable_string(std::string(value, len)); + } + } + + /// @brief Sets the Variant to a mutable string. + /// + /// The Variant's type will be set to MutableString. + /// + /// @param[in] value The string to use for the Variant. + void set_string_value(const std::string& value) { set_mutable_string(value); } + + /// @brief Sets the Variant to a copy of the given string. + /// + /// The Variant's type will be set to SmallString if the size of the string is + /// less than kMaxSmallStringSize (8 bytes on x86, 16 bytes on x64) or + /// otherwise set to MutableString. + /// + /// @param[in] value The string to use for the Variant. + /// @param[in] use_small_string Check to see if the input string should be + /// treated as a small string or left as a mutable string + void set_mutable_string(const std::string& value, + bool use_small_string = true) { + if (value.size() < kMaxSmallStringSize && use_small_string) { + Clear(static_cast(kInternalTypeSmallString)); + strncpy(value_.small_string, value.data(), value.size() + 1); + } else { + Clear(kTypeMutableString); + *value_.mutable_string_value = value; + } + } + + /// @brief Sets the Variant to a copy of the given binary data. + /// + /// The Variant's type will be set to MutableBlob. + /// + /// @param[in] src_data The data to use for the Variant. If you + /// pass in nullptr, no data will be copied, but a buffer of the + /// requested size will be allocated. + /// @param[in] size_bytes The size of the data, in bytes. + void set_mutable_blob(const void* src_data, size_t size_bytes) { + uint8_t* dest_data = new uint8_t[size_bytes]; // Will be deleted when + // `this` is deleted. + if (src_data != nullptr) { + memcpy(dest_data, src_data, size_bytes); + } + Clear(kTypeMutableBlob); + set_blob_pointer(dest_data, size_bytes); + } + + /// @brief Sets the Variant to point to static binary data. + /// + /// The Variant's type will be set to kTypeStaticBlob. + /// + /// @param[in] static_data Pointer to statically-allocated binary data. The + /// Variant will point to the data, not copy it. + /// @param[in] size_bytes Size of the data, in bytes. + /// + /// @note If you use this method, you must ensure that the memory pointer to + /// stays valid for the life of the Variant, or otherwise call + /// mutable_blob_data() or set_mutable_blob(), which will copy the data into + /// an internal buffer. + void set_static_blob(const void* static_data, size_t size_bytes) { + Clear(kTypeStaticBlob); + set_blob_pointer(static_data, size_bytes); + } + + /// @brief Sets the Variant to a copy of the given vector. + /// + /// The Variant's type will be set to Vector. + /// + /// @param[in] value The STL vector to copy into the Variant. + + void set_vector(const std::vector& value) { + Clear(kTypeVector); + *value_.vector_value = value; + } + + /// @brief Sets the Variant to a copy of the given map. + /// + /// The Variant's type will be set to Map. + /// + /// @param[in] value The STL map to copy into the Variant. + void set_map(const std::map& value) { + Clear(kTypeMap); + *value_.map_value = value; + } + + /// @brief Assigns an existing string which was allocated on the heap into the + /// Variant without performing a copy. This object will take over ownership of + /// the pointer, and will set the std::string* you pass in to NULL. + /// + /// The Variant's type will be set to MutableString. + /// + /// @param[in, out] str Pointer to a pointer to an STL string. The Variant + /// will take over ownership of the pointer to the string, and set the + /// pointer + /// you passed in to NULL. + void AssignMutableString(std::string** str) { + Clear(kTypeNull); + type_ = kInternalTypeMutableString; + value_.mutable_string_value = *str; + *str = NULL; // NOLINT + } + + /// @brief Assigns an existing vector which was allocated on the heap into the + /// Variant without performing a copy. This object will take over ownership of + /// the pointer, and will set the std::vector* you pass in to NULL. + /// + /// The Variant's type will be set to Vector. + /// + /// @param[in, out] vect Pointer to a pointer to an STL vector. The Variant + /// will take over ownership of the pointer to the vector, and set the + /// pointer + /// you passed in to NULL. + void AssignVector(std::vector** vect) { + Clear(kTypeNull); + type_ = kInternalTypeVector; + value_.vector_value = *vect; + *vect = NULL; // NOLINT + } + + /// @brief Assigns an existing map which was allocated on the heap into the + /// Variant without performing a copy. This object will take over ownership + /// of + /// the map, and will set the std::map** you pass in to NULL. + /// + /// The Variant's type will be set to Map. + /// + /// @param[in, out] map Pointer to a pointer to an STL map. The Variant will + /// take over ownership of the pointer to the map, and set the pointer you + /// passed in to NULL. + void AssignMap(std::map** map) { + Clear(kTypeNull); + type_ = kInternalTypeMap; + value_.map_value = *map; + *map = NULL; // NOLINT + } + + // Convenience methods for the times when constructors are too ambiguious. + + /// @brief Return a Variant from a 64-bit integer. + /// + /// @param[in] value 64-bit integer value to put into the Variant. + /// + /// @returns A Variant containing the 64-bit integer. + static Variant FromInt64(int64_t value) { return Variant(value); } + + /// @brief Return a Variant from a double-precision floating point number. + /// + /// @param[in] value Double-precision floating point value to put into the + /// Variant; + /// + /// @returns A Variant containing the double-precision floating point number. + static Variant FromDouble(double value) { return Variant(value); } + + /// @brief Return a Variant from a boolean. + /// + /// @param[in] value Boolean value to put into the Variant. + /// + /// @returns A Variant containing the Boolean. + static Variant FromBool(bool value) { return Variant(value); } + + /// @brief Return a Variant from a static string. + /// + /// @param[in] value Pointer to statically-allocated null-terminated string. + /// + /// @returns A Variant referring to the string pointer you passed in. + /// + /// @note If you use this function, you must ensure that the memory pointed + /// to stays valid for the life of the Variant, otherwise call + /// mutable_string() or set_mutable_string(), which will copy the string to an + /// internal buffer. + static Variant FromStaticString(const char* value) { return Variant(value); } + + /// @brief Return a Variant from a string. + /// + /// This method makes a copy of the string. + /// + /// @param[in] value String value to copy into the Variant. + /// + /// @returns A Variant containing a copy of the string. + static Variant FromMutableString(const std::string& value) { + return Variant(value); + } + + /// @brief Return a Variant that points to static binary data. + /// + /// @param[in] static_data Pointer to statically-allocated binary data. The + /// Variant will point to the data, not copy it. + /// @param[in] size_bytes Size of the data, in bytes. + /// + /// @returns A Variant pointing to the binary data. + /// + /// @note If you use this function, you must ensure that the memory pointed + /// to stays valid for the life of the Variant, otherwise call + /// mutable_blob() or set_mutable_blob(), which will copy the data to an + /// internal buffer. + static Variant FromStaticBlob(const void* static_data, size_t size_bytes) { + Variant v; + v.set_static_blob(static_data, size_bytes); + return v; + } + + /// @brief Return a Variant containing a copy of binary data. + /// + /// @param[in] src_data Pointer to binary data to be copied into the Variant. + /// @param[in] size_bytes Size of the data, in bytes. + /// + /// @returns A Variant containing a copy of the binary data. + static Variant FromMutableBlob(const void* src_data, size_t size_bytes) { + Variant v; + v.set_mutable_blob(src_data, size_bytes); + return v; + } + + /// @brief Return a Variant from a string, but make it mutable. + /// + /// Only copies the string once, unlike Variant(std::string(value)), which + /// copies the string twice. + /// + /// @param[in] value String value to copy into the Variant and make mutable. + /// + /// @returns A Variant containing a mutable copy of the string. + static Variant MutableStringFromStaticString(const char* value) { + std::string* str = new std::string(value); + Variant v; + v.AssignMutableString(&str); + return v; + } + + /// @brief Get the human-readable type name of a Variant type. + /// + /// @param[in] type Variant type to describe. + /// + /// @returns A string describing the type, suitable for error messages or + /// debugging. For example "Int64" or "MutableString". + static const char* TypeName(Type type); + + private: + // Internal Type of data that this variant object contains to avoid breaking + // API + enum InternalType { + /// Null, or no data. + kInternalTypeNull = kTypeNull, + /// A 64-bit integer. + kInternalTypeInt64 = kTypeInt64, + /// A double-precision floating point number. + kInternalTypeDouble = kTypeDouble, + /// A boolean value. + kInternalTypeBool = kTypeBool, + /// A statically-allocated string we point to. + kInternalTypeStaticString = kTypeStaticString, + /// A std::string. + kInternalTypeMutableString = kTypeMutableString, + /// A std::vector of Variant. + kInternalTypeVector = kTypeVector, + /// A std::map, mapping Variant to Variant. + kInternalTypeMap = kTypeMap, + /// An statically-allocated blob of data that we point to. Never constructed + /// by default. Use Variant::FromStaticBlob() to create a Variant of this + /// type. + kInternalTypeStaticBlob = kTypeStaticBlob, + /// A blob of data that the Variant holds. Never constructed by default. Use + /// Variant::FromMutableBlob() to create a Variant of this type, and copy + /// binary data from an existing source. + kInternalTypeMutableBlob = kTypeMutableBlob, + // A c string stored in the Variant internal data blob as opposed to be + // newed as a std::string. Max size is 16 bytes on x64 and 8 bytes on x86. + kInternalTypeSmallString = kTypeMutableBlob + 1, + // Not a valid type. Used to get the total number of Variant types. + kMaxTypeValue, + }; + + /// Human-readable type names, for error logging. + static const char* const kTypeNames[]; + + /// Assert that this Variant is of the given type, failing if it is not. + void assert_is_type(Type type) const; + + /// Assert that this Variant is NOT of the given type, failing if it is. + void assert_is_not_type(Type type) const; + + /// Assert that this Variant is a static string or mutable string, failing if + /// it is not. + void assert_is_string() const; + + /// Assert that this Variant is a static blob or mutable blob, failing if + /// it is not. + void assert_is_blob() const; + + /// Sets the blob's data pointer, for kTypeStaticBlob and kTypeMutableBlob. + /// Asserts if the Variant isn't a blob. Caller is responsible for managing + /// the pointer's memory and deleting any existing data at the location. + void set_blob_pointer(const void* blob_ptr, size_t size) { + assert_is_blob(); + value_.blob_value.ptr = static_cast(blob_ptr); + value_.blob_value.size = size; + } + + // If you hit a compiler error here it means you are trying to construct a + // variant with unsupported type. Ether cast to correct type or add support + // below. + template + void set_value_t(T value) = delete; + + // Get whether this Variant contains a small string. + bool is_small_string() const { return type_ == kInternalTypeSmallString; } + + // Current type contained in this Variant. + InternalType type_; + + // Older versions of visual studio cant have this inline in the union and do + // sizeof for small string + typedef struct { + const uint8_t* ptr; + size_t size; + } BlobValue; + + // Union of plain old data (scalars or pointers). + union Value { + int64_t int64_value; + double double_value; + bool bool_value; + const char* static_string_value; + std::string* mutable_string_value; + std::vector* vector_value; + std::map* map_value; + BlobValue blob_value; + char small_string[sizeof(BlobValue)]; + } value_; + + static constexpr size_t kMaxSmallStringSize = sizeof(Value::small_string); + + friend class firebase::internal::VariantInternal; +}; + +template <> +inline void Variant::set_value_t(int64_t value) { + set_int64_value(value); +} + +template <> +inline void Variant::set_value_t(int value) { + set_int64_value(static_cast(value)); +} + +template <> +inline void Variant::set_value_t(int16_t value) { + set_int64_value(static_cast(value)); +} + +template <> +inline void Variant::set_value_t(uint8_t value) { + set_int64_value(static_cast(value)); +} + +template <> +inline void Variant::set_value_t(int8_t value) { + set_int64_value(static_cast(value)); +} + +template <> +inline void Variant::set_value_t(char value) { + set_int64_value(static_cast(value)); +} + +template <> +inline void Variant::set_value_t(double value) { + set_double_value(value); +} + +template <> +inline void Variant::set_value_t(float value) { + set_double_value(static_cast(value)); +} + +template <> +inline void Variant::set_value_t(bool value) { + set_bool_value(value); +} + +template <> +inline void Variant::set_value_t(const char* value) { + set_string_value(value); +} + +template <> +inline void Variant::set_value_t(char* value) { + set_mutable_string(value); +} + +// NOLINTNEXTLINE - allow namespace overridden +} // namespace firebase + +#endif // FIREBASE_APP_SRC_INCLUDE_FIREBASE_VARIANT_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/version.h b/packages/firebase_core/firebase_core/firebase_core/firebase/version.h new file mode 100644 index 000000000000..79d77fc8af4a --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/version.h @@ -0,0 +1,68 @@ +// Copyright 2016 Google Inc. All Rights Reserved. + +#ifndef FIREBASE_APP_CLIENT_CPP_SRC_VERSION_H_ +#define FIREBASE_APP_CLIENT_CPP_SRC_VERSION_H_ + +/// @def FIREBASE_VERSION_MAJOR +/// @brief Major version number of the Firebase C++ SDK. +/// @see kFirebaseVersionString +#define FIREBASE_VERSION_MAJOR 10 +/// @def FIREBASE_VERSION_MINOR +/// @brief Minor version number of the Firebase C++ SDK. +/// @see kFirebaseVersionString +#define FIREBASE_VERSION_MINOR 5 +/// @def FIREBASE_VERSION_REVISION +/// @brief Revision number of the Firebase C++ SDK. +/// @see kFirebaseVersionString +#define FIREBASE_VERSION_REVISION 0 + +/// @cond FIREBASE_APP_INTERNAL +#define FIREBASE_STRING_EXPAND(X) #X +#define FIREBASE_STRING(X) FIREBASE_STRING_EXPAND(X) +/// @endcond + +// Version number. +// clang-format off +#define FIREBASE_VERSION_NUMBER_STRING \ + FIREBASE_STRING(FIREBASE_VERSION_MAJOR) "." \ + FIREBASE_STRING(FIREBASE_VERSION_MINOR) "." \ + FIREBASE_STRING(FIREBASE_VERSION_REVISION) +// clang-format on + +// Identifier for version string, e.g. kFirebaseVersionString. +#define FIREBASE_VERSION_IDENTIFIER(library) k##library##VersionString + +// Concatenated version string, e.g. "Firebase C++ x.y.z". +#define FIREBASE_VERSION_STRING(library) \ + #library " C++ " FIREBASE_VERSION_NUMBER_STRING + +#if !defined(DOXYGEN) +#if !defined(_WIN32) && !defined(__CYGWIN__) +#define DEFINE_FIREBASE_VERSION_STRING(library) \ + extern volatile __attribute__((weak)) \ + const char* FIREBASE_VERSION_IDENTIFIER(library); \ + volatile __attribute__((weak)) \ + const char* FIREBASE_VERSION_IDENTIFIER(library) = \ + FIREBASE_VERSION_STRING(library) +#else +#define DEFINE_FIREBASE_VERSION_STRING(library) \ + static const char* FIREBASE_VERSION_IDENTIFIER(library) = \ + FIREBASE_VERSION_STRING(library) +#endif // !defined(_WIN32) && !defined(__CYGWIN__) +#else // if defined(DOXYGEN) + +/// @brief Namespace that encompasses all Firebase APIs. +namespace firebase { + +/// @brief String which identifies the current version of the Firebase C++ +/// SDK. +/// +/// @see FIREBASE_VERSION_MAJOR +/// @see FIREBASE_VERSION_MINOR +/// @see FIREBASE_VERSION_REVISION +static const char* kFirebaseVersionString = FIREBASE_VERSION_STRING; + +} // namespace firebase +#endif // !defined(DOXYGEN) + +#endif // FIREBASE_APP_CLIENT_CPP_SRC_VERSION_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/generate_xml_from_google_services_json.py b/packages/firebase_core/firebase_core/firebase_core/generate_xml_from_google_services_json.py new file mode 100644 index 000000000000..8996cd8490f3 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/generate_xml_from_google_services_json.py @@ -0,0 +1,496 @@ +#!/usr/bin/python + +# Copyright 2016 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Stand-alone implementation of the Gradle Firebase plugin. + +Converts the services json file to xml: +https://googleplex-android.googlesource.com/platform/tools/base/+/studio-master-dev/build-system/google-services/src/main/groovy/com/google/gms/googleservices +""" + +__author__ = 'Wouter van Oortmerssen' + +import argparse +import ctypes +import json +import os +import platform +import sys +from xml.etree import ElementTree + +if platform.system().lower() == 'windows': + import ctypes.wintypes # pylint: disable=g-import-not-at-top + +# Map Python 2's unicode method to encode a string as bytes in python 3. +try: + unicode('') # See whether unicode class is available (Python < 3) +except NameError: + unicode = str # pylint: disable=redefined-builtin,invalid-name + +# Input filename if it isn't set. +DEFAULT_INPUT_FILENAME = 'app/google-services.json' +# Output filename if it isn't set. +DEFAULT_OUTPUT_FILENAME = 'res/values/googleservices.xml' +# Input filename for .plist files, if it isn't set. +DEFAULT_PLIST_INPUT_FILENAME = 'GoogleService-Info.plist' +# Output filename for .json files, if it isn't set. +DEFAULT_JSON_OUTPUT_FILENAME = 'google-services-desktop.json' + +OAUTH_CLIENT_TYPE_ANDROID_APP = 1 +OAUTH_CLIENT_TYPE_WEB = 3 + + +def read_xml_value(xml_node): + """Utility method for reading values from the plist XML. + + Args: + xml_node: An ElementTree node, that contains a value. + + Returns: + The value of the node, or None, if it could not be read. + """ + if xml_node.tag == 'string': + return xml_node.text + elif xml_node.tag == 'integer': + return int(xml_node.text) + elif xml_node.tag == 'real': + return float(xml_node.text) + elif xml_node.tag == 'false': + return 0 + elif xml_node.tag == 'true': + return 1 + else: + # other types of input are ignored. (data, dates, arrays, etc.) + return None + + +def construct_plist_dictionary(xml_root): + """Constructs a dictionary of values based on the contents of a plist file. + + Args: + xml_root: An ElementTree node, that represents the root of the xml file + that is to be parsed. (Which should be a dictionary containing + key-value pairs of the properties that need to be extracted.) + + Returns: + A dictionary, containing key-value pairs for all (supported) entries in the + node. + """ + xml_dict = xml_root.find('dict') + + if xml_dict is None: + return None + + plist_dict = {} + i = 0 + while i < len(xml_dict): + if xml_dict[i].tag == 'key': + key = xml_dict[i].text + i += 1 + if i < len(xml_dict): + value = read_xml_value(xml_dict[i]) + if value is not None: + plist_dict[key] = value + i += 1 + + return plist_dict + + +def update_dict_keys(key_map, input_dict): + """Creates a dict from input_dict with the same values but new keys. + + Two dictionaries are passed to this function: the key_map that represents a + mapping of source keys to destination keys, and the input_dict that is the + dictionary that is to be duplicated, replacing any key that matches a source + key with a destination key. Source keys that are not present in the + input_dict will not have their destination key represented in the result. + + In other words, if key_map is `{'old': 'new', 'foo': 'bar'}`, and input_dict + is `{'old': 10}`, the result will be `{'new': 10}`. + + Args: + key_map (dict): A dictionary of strings to strings that maps source keys to + destination keys. + input_dict (dict): The dictionary of string keys to any value type, which + is to be duplicated, replacing source keys with the corresponding + destination keys from key_map. + + Returns: + dict: A new dictionary with updated keys. + """ + return { + new_key: input_dict[old_key] + for (old_key, new_key) in key_map.items() + if old_key in input_dict + } + + +def construct_google_services_json(xml_dict): + """Constructs a google services json file from a dictionary. + + Args: + xml_dict: A dictionary of all the key/value pairs that are needed for the + output json file. + Returns: + A string representing the output json file. + """ + + try: + json_struct = { + 'project_info': + update_dict_keys( + { + 'GCM_SENDER_ID': 'project_number', + 'DATABASE_URL': 'firebase_url', + 'PROJECT_ID': 'project_id', + 'STORAGE_BUCKET': 'storage_bucket' + }, xml_dict), + 'client': [{ + 'client_info': { + 'mobilesdk_app_id': xml_dict['GOOGLE_APP_ID'], + 'android_client_info': { + 'package_name': xml_dict['BUNDLE_ID'] + } + }, + 'oauth_client': [{ + 'client_id': xml_dict['CLIENT_ID'], + }], + 'api_key': [{ + 'current_key': xml_dict['API_KEY'] + }], + 'services': { + 'analytics_service': { + 'status': xml_dict['IS_ANALYTICS_ENABLED'] + }, + 'appinvite_service': { + 'status': xml_dict['IS_APPINVITE_ENABLED'] + } + } + },], + 'configuration_version': + '1' + } + return json.dumps(json_struct, indent=2) + except KeyError as e: + sys.stderr.write('Could not find key in plist file: [%s]\n' % (e.args[0])) + return None + + +def convert_plist_to_json(plist_string, input_filename): + """Converts an input plist string into a .json file and saves it. + + Args: + plist_string: The contents of the loaded plist file. + + input_filename: The file name that the plist data was read from. + Returns: + the converted string, or None if there were errors. + """ + + try: + root = ElementTree.fromstring(plist_string) + except ElementTree.ParseError: + sys.stderr.write('Error parsing file %s.\n' + 'It does not appear to be valid XML.\n' % (input_filename)) + return None + + plist_dict = construct_plist_dictionary(root) + if plist_dict is None: + sys.stderr.write('In file %s, could not locate a top-level \'dict\' ' + 'element.\n' + 'File format should be plist XML, with a top-level ' + 'dictionary containing project settings as key-value ' + 'pairs.\n' % (input_filename)) + return None + + json_string = construct_google_services_json(plist_dict) + return json_string + + +def gen_string(parent, name, text): + """Generate one element and put into the list of keeps. + + Args: + parent: The object that will hold the string. + name: The name to store the string under. + text: The text of the string. + """ + if text: + prev = parent.get('tools:keep', '') + if prev: + prev += ',' + parent.set('tools:keep', prev + '@string/' + name) + child = ElementTree.SubElement(parent, 'string', { + 'name': name, + 'translatable': 'false' + }) + child.text = text + + +def indent(elem, level=0): + """Recurse through XML tree and add indentation. + + Args: + elem: The element to recurse over + level: The current indentation level. + """ + i = '\n' + level*' ' + if elem is not None: + if not elem.text or not elem.text.strip(): + elem.text = i + ' ' + if not elem.tail or not elem.tail.strip(): + elem.tail = i + for elem in elem: + indent(elem, level+1) + if not elem.tail or not elem.tail.strip(): + elem.tail = i + else: + if level and (not elem.tail or not elem.tail.strip()): + elem.tail = i + + +def argv_as_unicode_win32(): + """Returns unicode command line arguments on windows. + """ + + get_command_line_w = ctypes.cdll.kernel32.GetCommandLineW + get_command_line_w.restype = ctypes.wintypes.LPCWSTR + + # CommandLineToArgvW parses the Unicode command line + command_line_to_argv_w = ctypes.windll.shell32.CommandLineToArgvW + command_line_to_argv_w.argtypes = [ + ctypes.wintypes.LPCWSTR, + ctypes.POINTER(ctypes.c_int) + ] + command_line_to_argv_w.restype = ctypes.POINTER( + ctypes.wintypes.LPWSTR) + + argc = ctypes.c_int(0) + argv = command_line_to_argv_w(get_command_line_w(), argc) + + # Strip the python executable from the arguments if it exists + # (It would be listed as the first argument on the windows command line, but + # not in the arguments to the python script) + sys_argv_len = len(sys.argv) + return [unicode(argv[i]) for i in + range(argc.value - sys_argv_len, argc.value)] + + +def main(): + parser = argparse.ArgumentParser( + description=(( + 'Converts a Firebase %s into %s similar to the Gradle plugin, or ' + 'converts a Firebase %s into a %s suitible for use on desktop apps.' % + (DEFAULT_INPUT_FILENAME, DEFAULT_OUTPUT_FILENAME, + DEFAULT_PLIST_INPUT_FILENAME, DEFAULT_JSON_OUTPUT_FILENAME)))) + parser.add_argument('-i', help='Override input file name', + metavar='FILE', required=False) + parser.add_argument('-o', help='Override destination file name', + metavar='FILE', required=False) + parser.add_argument('-p', help=('Package ID to select within the set of ' + 'packages in the input file. If this is ' + 'not specified, the first package in the ' + 'input file is selected.')) + parser.add_argument('-l', help=('List all package IDs referenced by the ' + 'input file. If this is specified, ' + 'the output file is not created.'), + action='store_true', default=False, required=False) + parser.add_argument('-f', help=('Print project fields from the input file ' + 'in the form \'name=value\\n\' for each ' + 'field. If this is specified, the output ' + 'is not created.'), + action='store_true', default=False, required=False) + parser.add_argument( + '--plist', + help=( + 'Specifies a plist file to convert to a JSON configuration file. ' + 'If this is enabled, the script will expect a .plist file as input, ' + 'which it will convert into %s file. The output file is ' + '*not* suitable for use with Firebase on Android.' % + (DEFAULT_JSON_OUTPUT_FILENAME)), + action='store_true', + default=False, + required=False) + + # python 2 on Windows doesn't handle unicode arguments well, so we need to + # pre-process the command line arguments before trying to parse them. + if platform.system() == 'Windows': + sys.argv = argv_as_unicode_win32() + + args = parser.parse_args() + + if args.plist: + input_filename = DEFAULT_PLIST_INPUT_FILENAME + output_filename = DEFAULT_JSON_OUTPUT_FILENAME + else: + input_filename = DEFAULT_INPUT_FILENAME + output_filename = DEFAULT_OUTPUT_FILENAME + + if args.i: + # Encode the input string (type unicode) as a normal string (type str) + # using the 'utf-8' encoding so that it can be worked with the same as + # input names from other sources (like the defaults). + input_filename_raw = args.i.encode('utf-8') + # Decode the filename to a unicode string using the 'utf-8' encoding to + # properly handle filepaths with unicode characters in them. + input_filename = input_filename_raw.decode('utf-8') + + if args.o: + output_filename = args.o + + with open(input_filename, 'r') as ifile: + file_string = ifile.read() + + json_string = None + if args.plist: + json_string = convert_plist_to_json(file_string, input_filename) + if json_string is None: + return 1 + jsobj = json.loads(json_string) + else: + jsobj = json.loads(file_string) + + root = ElementTree.Element('resources') + root.set('xmlns:tools', 'http://schemas.android.com/tools') + + project_info = jsobj.get('project_info') + if project_info: + gen_string(root, 'firebase_database_url', project_info.get('firebase_url')) + gen_string(root, 'gcm_defaultSenderId', project_info.get('project_number')) + gen_string(root, 'google_storage_bucket', + project_info.get('storage_bucket')) + gen_string(root, 'project_id', project_info.get('project_id')) + + if args.f: + if not project_info: + sys.stderr.write('No project info found in %s.' % input_filename) + return 1 + for field, value in sorted(project_info.items()): + sys.stdout.write('%s=%s\n' % (field, value)) + return 0 + + packages = set() + client_list = jsobj.get('client') + if client_list: + # Search for the user specified package in the file. + selected_package_name = '' + selected_client = client_list[0] + find_package_name = args.p + for client in client_list: + package_name = client.get('client_info', {}).get( + 'android_client_info', {}).get('package_name', '') + if not package_name: + package_name = client.get('oauth_client', {}).get( + 'android_info', {}).get('package_name', '') + if package_name: + if not selected_package_name: + selected_package_name = package_name + selected_client = client + if package_name == find_package_name: + selected_package_name = package_name + selected_client = client + packages.add(package_name) + + if args.p and selected_package_name != find_package_name: + sys.stderr.write('No packages found in %s which match the package ' + 'name %s\n' + '\n' + 'Found the following:\n' + '%s\n' % (input_filename, find_package_name, + '\n'.join(packages))) + return 1 + + client_api_key = selected_client.get('api_key') + if client_api_key: + client_api_key0 = client_api_key[0] + gen_string(root, 'google_api_key', client_api_key0.get('current_key')) + gen_string(root, 'google_crash_reporting_api_key', + client_api_key0.get('current_key')) + + client_info = selected_client.get('client_info') + if client_info: + gen_string(root, 'google_app_id', client_info.get('mobilesdk_app_id')) + + # Only include the first matching OAuth client ID per type. + client_id_web_parsed = False + client_id_android_parsed = False + + oauth_client_list = selected_client.get('oauth_client') + if oauth_client_list: + for oauth_client in oauth_client_list: + client_type = oauth_client.get('client_type') + client_id = oauth_client.get('client_id') + if not (client_type and client_id): continue + if (client_type == OAUTH_CLIENT_TYPE_WEB and + not client_id_web_parsed): + gen_string(root, 'default_web_client_id', client_id) + client_id_web_parsed = True + if (client_type == OAUTH_CLIENT_TYPE_ANDROID_APP and + not client_id_android_parsed): + gen_string(root, 'default_android_client_id', client_id) + client_id_android_parsed = True + + services = selected_client.get('services') + if services: + ads_service = services.get('ads_service') + if ads_service: + gen_string(root, 'test_banner_ad_unit_id', + ads_service.get('test_banner_ad_unit_id')) + gen_string(root, 'test_interstitial_ad_unit_id', + ads_service.get('test_interstitial_ad_unit_id')) + analytics_service = services.get('analytics_service') + if analytics_service: + analytics_property = analytics_service.get('analytics_property') + if analytics_property: + gen_string(root, 'ga_trackingId', + analytics_property.get('tracking_id')) + # enable this once we have an example if this service being present + # in the json data: + maps_service_enabled = False + if maps_service_enabled: + maps_service = services.get('maps_service') + if maps_service: + maps_api_key = maps_service.get('api_key') + if maps_api_key: + for k in range(0, len(maps_api_key)): + # generates potentially multiple of these keys, which is + # the same behavior as the java plugin. + gen_string(root, 'google_maps_key', + maps_api_key[k].get('maps_api_key')) + + tree = ElementTree.ElementTree(root) + + indent(root) + + if args.l: + for package in sorted(packages): + if package: + sys.stdout.write(package + '\n') + else: + path = os.path.dirname(output_filename) + + if path and not os.path.exists(path): + os.makedirs(path) + + if not args.plist: + tree.write(output_filename, 'utf-8', True) + else: + with open(output_filename, 'w') as ofile: + ofile.write(json_string) + + return 0 + +if __name__ == '__main__': + sys.exit(main()) \ No newline at end of file diff --git a/packages/firebase_core/firebase_core/firebase_core/generated_bindings.dart b/packages/firebase_core/firebase_core/firebase_core/generated_bindings.dart new file mode 100644 index 000000000000..f58d1524bee8 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/generated_bindings.dart @@ -0,0 +1,26 @@ +// AUTO GENERATED FILE, DO NOT EDIT. +// +// Generated by `package:ffigen`. +import 'dart:ffi' as ffi; + +class NativeLibrary { + /// Holds the symbol lookup function. + final ffi.Pointer Function(String symbolName) + _lookup; + + /// The symbols are looked up in [dynamicLibrary]. + NativeLibrary(ffi.DynamicLibrary dynamicLibrary) + : _lookup = dynamicLibrary.lookup; + + /// The symbols are looked up with [lookup]. + NativeLibrary.fromLookup( + ffi.Pointer Function(String symbolName) + lookup) + : _lookup = lookup; + + late final ffi.Pointer _firebase = _lookup('firebase'); + + int get firebase => _firebase.value; + + set firebase(int value) => _firebase.value = value; +} diff --git a/packages/firebase_core/firebase_core/firebase_core/google-services-desktop.json b/packages/firebase_core/firebase_core/firebase_core/google-services-desktop.json new file mode 100644 index 000000000000..a3bf216f4de0 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/google-services-desktop.json @@ -0,0 +1,37 @@ +{ + "project_info": { + "project_number": "406099696497", + "firebase_url": "https://flutterfire-e2e-tests-default-rtdb.europe-west1.firebasedatabase.app", + "project_id": "flutterfire-e2e-tests", + "storage_bucket": "flutterfire-e2e-tests.appspot.com" + }, + "client": [ + { + "client_info": { + "mobilesdk_app_id": "1:406099696497:ios:58cbc26aca8e5cf83574d0", + "android_client_info": { + "package_name": "io.flutter.plugins.firebase.auth.example" + } + }, + "oauth_client": [ + { + "client_id": "406099696497-134k3722m01rtrsklhf3b7k8sqa5r7in.apps.googleusercontent.com" + } + ], + "api_key": [ + { + "current_key": "AIzaSyDooSUGSf63Ghq02_iIhtnmwMDs4HlWS6c" + } + ], + "services": { + "analytics_service": { + "status": 0 + }, + "appinvite_service": { + "status": 1 + } + } + } + ], + "configuration_version": "1" +} \ No newline at end of file diff --git a/packages/firebase_core/firebase_core/firebase_core/lib/firebase_core.dart b/packages/firebase_core/firebase_core/firebase_core/lib/firebase_core.dart new file mode 100644 index 000000000000..d1295e26ad15 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/lib/firebase_core.dart @@ -0,0 +1,8 @@ + +import 'firebase_core_platform_interface.dart'; + +class FirebaseCore { + Future getPlatformVersion() { + return FirebaseCorePlatform.instance.getPlatformVersion(); + } +} diff --git a/packages/firebase_core/firebase_core/firebase_core/lib/firebase_core_method_channel.dart b/packages/firebase_core/firebase_core/firebase_core/lib/firebase_core_method_channel.dart new file mode 100644 index 000000000000..5da300fa9013 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/lib/firebase_core_method_channel.dart @@ -0,0 +1,17 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter/services.dart'; + +import 'firebase_core_platform_interface.dart'; + +/// An implementation of [FirebaseCorePlatform] that uses method channels. +class MethodChannelFirebaseCore extends FirebaseCorePlatform { + /// The method channel used to interact with the native platform. + @visibleForTesting + final methodChannel = const MethodChannel('firebase_core'); + + @override + Future getPlatformVersion() async { + final version = await methodChannel.invokeMethod('getPlatformVersion'); + return version; + } +} diff --git a/packages/firebase_core/firebase_core/firebase_core/lib/firebase_core_platform_interface.dart b/packages/firebase_core/firebase_core/firebase_core/lib/firebase_core_platform_interface.dart new file mode 100644 index 000000000000..6f6e165b7957 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/lib/firebase_core_platform_interface.dart @@ -0,0 +1,29 @@ +import 'package:plugin_platform_interface/plugin_platform_interface.dart'; + +import 'firebase_core_method_channel.dart'; + +abstract class FirebaseCorePlatform extends PlatformInterface { + /// Constructs a FirebaseCorePlatform. + FirebaseCorePlatform() : super(token: _token); + + static final Object _token = Object(); + + static FirebaseCorePlatform _instance = MethodChannelFirebaseCore(); + + /// The default instance of [FirebaseCorePlatform] to use. + /// + /// Defaults to [MethodChannelFirebaseCore]. + static FirebaseCorePlatform get instance => _instance; + + /// Platform-specific implementations should set this with their own + /// platform-specific class that extends [FirebaseCorePlatform] when + /// they register themselves. + static set instance(FirebaseCorePlatform instance) { + PlatformInterface.verifyToken(instance, _token); + _instance = instance; + } + + Future getPlatformVersion() { + throw UnimplementedError('platformVersion() has not been implemented.'); + } +} diff --git a/packages/firebase_core/firebase_core/firebase_core/linux/CMakeLists.txt b/packages/firebase_core/firebase_core/firebase_core/linux/CMakeLists.txt new file mode 100644 index 000000000000..5cec31c86b71 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/linux/CMakeLists.txt @@ -0,0 +1,47 @@ +# The Flutter tooling requires that developers have CMake 3.10 or later +# installed. You should not increase this version, as doing so will cause +# the plugin to fail to compile for some customers of the plugin. +cmake_minimum_required(VERSION 3.10) + +# Project-level configuration. +set(PROJECT_NAME "firebase_core") +project(${PROJECT_NAME} LANGUAGES CXX) + +# This value is used when generating builds using this plugin, so it must +# not be changed. +set(PLUGIN_NAME "firebase_core_plugin") + +# Define the plugin library target. Its name must not be changed (see comment +# on PLUGIN_NAME above). +# +# Any new source files that you add to the plugin should be added here. +add_library(${PLUGIN_NAME} SHARED + "firebase_core_plugin.cc" +) + +# Apply a standard set of build settings that are configured in the +# application-level CMakeLists.txt. This can be removed for plugins that want +# full control over build settings. +apply_standard_settings(${PLUGIN_NAME}) + +# Symbols are hidden by default to reduce the chance of accidental conflicts +# between plugins. This should not be removed; any symbols that should be +# exported should be explicitly exported with the FLUTTER_PLUGIN_EXPORT macro. +set_target_properties(${PLUGIN_NAME} PROPERTIES + CXX_VISIBILITY_PRESET hidden) +target_compile_definitions(${PLUGIN_NAME} PRIVATE FLUTTER_PLUGIN_IMPL) + +# Source include directories and library dependencies. Add any plugin-specific +# dependencies here. +target_include_directories(${PLUGIN_NAME} INTERFACE + "${CMAKE_CURRENT_SOURCE_DIR}/include") +target_link_libraries(${PLUGIN_NAME} PRIVATE flutter) +target_link_libraries(${PLUGIN_NAME} PRIVATE PkgConfig::GTK) + +# List of absolute paths to libraries that should be bundled with the plugin. +# This list could contain prebuilt libraries, or libraries created by an +# external build triggered from this build file. +set(firebase_core_bundled_libraries + "" + PARENT_SCOPE +) diff --git a/packages/firebase_core/firebase_core/firebase_core/linux/firebase_core_plugin.cc b/packages/firebase_core/firebase_core/firebase_core/linux/firebase_core_plugin.cc new file mode 100644 index 000000000000..4fd897624ca4 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/linux/firebase_core_plugin.cc @@ -0,0 +1,70 @@ +#include "include/firebase_core/firebase_core_plugin.h" + +#include +#include +#include + +#include + +#define FIREBASE_CORE_PLUGIN(obj) \ + (G_TYPE_CHECK_INSTANCE_CAST((obj), firebase_core_plugin_get_type(), \ + FirebaseCorePlugin)) + +struct _FirebaseCorePlugin { + GObject parent_instance; +}; + +G_DEFINE_TYPE(FirebaseCorePlugin, firebase_core_plugin, g_object_get_type()) + +// Called when a method call is received from Flutter. +static void firebase_core_plugin_handle_method_call( + FirebaseCorePlugin* self, + FlMethodCall* method_call) { + g_autoptr(FlMethodResponse) response = nullptr; + + const gchar* method = fl_method_call_get_name(method_call); + + if (strcmp(method, "getPlatformVersion") == 0) { + struct utsname uname_data = {}; + uname(&uname_data); + g_autofree gchar *version = g_strdup_printf("Linux %s", uname_data.version); + g_autoptr(FlValue) result = fl_value_new_string(version); + response = FL_METHOD_RESPONSE(fl_method_success_response_new(result)); + } else { + response = FL_METHOD_RESPONSE(fl_method_not_implemented_response_new()); + } + + fl_method_call_respond(method_call, response, nullptr); +} + +static void firebase_core_plugin_dispose(GObject* object) { + G_OBJECT_CLASS(firebase_core_plugin_parent_class)->dispose(object); +} + +static void firebase_core_plugin_class_init(FirebaseCorePluginClass* klass) { + G_OBJECT_CLASS(klass)->dispose = firebase_core_plugin_dispose; +} + +static void firebase_core_plugin_init(FirebaseCorePlugin* self) {} + +static void method_call_cb(FlMethodChannel* channel, FlMethodCall* method_call, + gpointer user_data) { + FirebaseCorePlugin* plugin = FIREBASE_CORE_PLUGIN(user_data); + firebase_core_plugin_handle_method_call(plugin, method_call); +} + +void firebase_core_plugin_register_with_registrar(FlPluginRegistrar* registrar) { + FirebaseCorePlugin* plugin = FIREBASE_CORE_PLUGIN( + g_object_new(firebase_core_plugin_get_type(), nullptr)); + + g_autoptr(FlStandardMethodCodec) codec = fl_standard_method_codec_new(); + g_autoptr(FlMethodChannel) channel = + fl_method_channel_new(fl_plugin_registrar_get_messenger(registrar), + "firebase_core", + FL_METHOD_CODEC(codec)); + fl_method_channel_set_method_call_handler(channel, method_call_cb, + g_object_ref(plugin), + g_object_unref); + + g_object_unref(plugin); +} diff --git a/packages/firebase_core/firebase_core/firebase_core/linux/include/firebase_core/firebase_core_plugin.h b/packages/firebase_core/firebase_core/firebase_core/linux/include/firebase_core/firebase_core_plugin.h new file mode 100644 index 000000000000..3f15a61a3e72 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/linux/include/firebase_core/firebase_core_plugin.h @@ -0,0 +1,26 @@ +#ifndef FLUTTER_PLUGIN_FIREBASE_CORE_PLUGIN_H_ +#define FLUTTER_PLUGIN_FIREBASE_CORE_PLUGIN_H_ + +#include + +G_BEGIN_DECLS + +#ifdef FLUTTER_PLUGIN_IMPL +#define FLUTTER_PLUGIN_EXPORT __attribute__((visibility("default"))) +#else +#define FLUTTER_PLUGIN_EXPORT +#endif + +typedef struct _FirebaseCorePlugin FirebaseCorePlugin; +typedef struct { + GObjectClass parent_class; +} FirebaseCorePluginClass; + +FLUTTER_PLUGIN_EXPORT GType firebase_core_plugin_get_type(); + +FLUTTER_PLUGIN_EXPORT void firebase_core_plugin_register_with_registrar( + FlPluginRegistrar* registrar); + +G_END_DECLS + +#endif // FLUTTER_PLUGIN_FIREBASE_CORE_PLUGIN_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/pubspec.yaml b/packages/firebase_core/firebase_core/firebase_core/pubspec.yaml new file mode 100644 index 000000000000..ce38f84906e8 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/pubspec.yaml @@ -0,0 +1,34 @@ +name: firebase_core +description: A new Flutter plugin project. +version: 0.0.1 +homepage: + +environment: + sdk: '>=2.19.2 <3.0.0' + flutter: '>=2.5.0' + +dependencies: + ffi: ^2.0.1 + flutter: + sdk: flutter + plugin_platform_interface: ^2.0.2 + +dev_dependencies: + flutter_test: + sdk: flutter + flutter_lints: ^2.0.0 + ffigen: ^7.2.6 + +flutter: + plugin: + platforms: + linux: + pluginClass: FirebaseCorePlugin + +ffigen: + output: 'generated_bindings.dart' + headers: + entry-points: + - 'firebase/app.h' + include-directives: + - 'firebase/**.h' diff --git a/packages/firebase_core/firebase_core/firebase_core/test/firebase_core_method_channel_test.dart b/packages/firebase_core/firebase_core/firebase_core/test/firebase_core_method_channel_test.dart new file mode 100644 index 000000000000..70c7fc5e7362 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/test/firebase_core_method_channel_test.dart @@ -0,0 +1,24 @@ +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:firebase_core/firebase_core_method_channel.dart'; + +void main() { + MethodChannelFirebaseCore platform = MethodChannelFirebaseCore(); + const MethodChannel channel = MethodChannel('firebase_core'); + + TestWidgetsFlutterBinding.ensureInitialized(); + + setUp(() { + channel.setMockMethodCallHandler((MethodCall methodCall) async { + return '42'; + }); + }); + + tearDown(() { + channel.setMockMethodCallHandler(null); + }); + + test('getPlatformVersion', () async { + expect(await platform.getPlatformVersion(), '42'); + }); +} diff --git a/packages/firebase_core/firebase_core/firebase_core/test/firebase_core_test.dart b/packages/firebase_core/firebase_core/firebase_core/test/firebase_core_test.dart new file mode 100644 index 000000000000..bb8e54416b4e --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/test/firebase_core_test.dart @@ -0,0 +1,29 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:firebase_core/firebase_core.dart'; +import 'package:firebase_core/firebase_core_platform_interface.dart'; +import 'package:firebase_core/firebase_core_method_channel.dart'; +import 'package:plugin_platform_interface/plugin_platform_interface.dart'; + +class MockFirebaseCorePlatform + with MockPlatformInterfaceMixin + implements FirebaseCorePlatform { + + @override + Future getPlatformVersion() => Future.value('42'); +} + +void main() { + final FirebaseCorePlatform initialPlatform = FirebaseCorePlatform.instance; + + test('$MethodChannelFirebaseCore is the default instance', () { + expect(initialPlatform, isInstanceOf()); + }); + + test('getPlatformVersion', () async { + FirebaseCore firebaseCorePlugin = FirebaseCore(); + MockFirebaseCorePlatform fakePlatform = MockFirebaseCorePlatform(); + FirebaseCorePlatform.instance = fakePlatform; + + expect(await firebaseCorePlugin.getPlatformVersion(), '42'); + }); +} From 3ca38483cc0c318017b4cbe9f46cb59a2d400bf1 Mon Sep 17 00:00:00 2001 From: Guillaume Bernos Date: Mon, 6 Mar 2023 14:52:47 +0100 Subject: [PATCH 09/65] add windows --- .../firebase_core/firebase_core/.metadata | 12 +- .../firebase_core/example/windows/.gitignore | 17 ++ .../example/windows/CMakeLists.txt | 101 ++++++ .../example/windows/flutter/CMakeLists.txt | 104 +++++++ .../example/windows/runner/CMakeLists.txt | 40 +++ .../example/windows/runner/Runner.rc | 121 ++++++++ .../example/windows/runner/flutter_window.cpp | 66 ++++ .../example/windows/runner/flutter_window.h | 33 ++ .../example/windows/runner/main.cpp | 43 +++ .../example/windows/runner/resource.h | 16 + .../windows/runner/resources/app_icon.ico | Bin 0 -> 33772 bytes .../windows/runner/runner.exe.manifest | 20 ++ .../example/windows/runner/utils.cpp | 64 ++++ .../example/windows/runner/utils.h | 19 ++ .../example/windows/runner/win32_window.cpp | 288 ++++++++++++++++++ .../example/windows/runner/win32_window.h | 102 +++++++ .../firebase_core/firebase_core/pubspec.yaml | 2 + .../firebase_core/windows/.gitignore | 17 ++ .../firebase_core/windows/CMakeLists.txt | 53 ++++ .../windows/firebase_core_plugin.cpp | 59 ++++ .../windows/firebase_core_plugin.h | 32 ++ .../windows/firebase_core_plugin_c_api.cpp | 12 + .../firebase_core_plugin_c_api.h | 23 ++ 23 files changed, 1238 insertions(+), 6 deletions(-) create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/windows/.gitignore create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/windows/CMakeLists.txt create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/windows/flutter/CMakeLists.txt create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/windows/runner/CMakeLists.txt create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/windows/runner/Runner.rc create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/windows/runner/flutter_window.cpp create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/windows/runner/flutter_window.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/windows/runner/main.cpp create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/windows/runner/resource.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/windows/runner/resources/app_icon.ico create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/windows/runner/runner.exe.manifest create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/windows/runner/utils.cpp create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/windows/runner/utils.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/windows/runner/win32_window.cpp create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/windows/runner/win32_window.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/windows/.gitignore create mode 100644 packages/firebase_core/firebase_core/firebase_core/windows/CMakeLists.txt create mode 100644 packages/firebase_core/firebase_core/firebase_core/windows/firebase_core_plugin.cpp create mode 100644 packages/firebase_core/firebase_core/firebase_core/windows/firebase_core_plugin.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/windows/firebase_core_plugin_c_api.cpp create mode 100644 packages/firebase_core/firebase_core/firebase_core/windows/include/firebase_core/firebase_core_plugin_c_api.h diff --git a/packages/firebase_core/firebase_core/firebase_core/.metadata b/packages/firebase_core/firebase_core/firebase_core/.metadata index 74867a0b132b..97ef0fff36d0 100644 --- a/packages/firebase_core/firebase_core/firebase_core/.metadata +++ b/packages/firebase_core/firebase_core/firebase_core/.metadata @@ -4,7 +4,7 @@ # This file should be version controlled. version: - revision: 9944297138845a94256f1cf37beb88ff9a8e811a + revision: 12cb4eb7a009f52b347b62ade7cb4854b926af72 channel: stable project_type: plugin @@ -13,11 +13,11 @@ project_type: plugin migration: platforms: - platform: root - create_revision: 9944297138845a94256f1cf37beb88ff9a8e811a - base_revision: 9944297138845a94256f1cf37beb88ff9a8e811a - - platform: linux - create_revision: 9944297138845a94256f1cf37beb88ff9a8e811a - base_revision: 9944297138845a94256f1cf37beb88ff9a8e811a + create_revision: 12cb4eb7a009f52b347b62ade7cb4854b926af72 + base_revision: 12cb4eb7a009f52b347b62ade7cb4854b926af72 + - platform: windows + create_revision: 12cb4eb7a009f52b347b62ade7cb4854b926af72 + base_revision: 12cb4eb7a009f52b347b62ade7cb4854b926af72 # User provided section diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/.gitignore b/packages/firebase_core/firebase_core/firebase_core/example/windows/.gitignore new file mode 100644 index 000000000000..d492d0d98c8f --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/windows/.gitignore @@ -0,0 +1,17 @@ +flutter/ephemeral/ + +# Visual Studio user-specific files. +*.suo +*.user +*.userosscache +*.sln.docstates + +# Visual Studio build-related files. +x64/ +x86/ + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!*.[Cc]ache/ diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/CMakeLists.txt b/packages/firebase_core/firebase_core/firebase_core/example/windows/CMakeLists.txt new file mode 100644 index 000000000000..ddf92aa378e1 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/windows/CMakeLists.txt @@ -0,0 +1,101 @@ +# Project-level configuration. +cmake_minimum_required(VERSION 3.14) +project(firebase_core_example LANGUAGES CXX) + +# The name of the executable created for the application. Change this to change +# the on-disk name of your application. +set(BINARY_NAME "firebase_core_example") + +# Explicitly opt in to modern CMake behaviors to avoid warnings with recent +# versions of CMake. +cmake_policy(SET CMP0063 NEW) + +# Define build configuration option. +get_property(IS_MULTICONFIG GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG) +if(IS_MULTICONFIG) + set(CMAKE_CONFIGURATION_TYPES "Debug;Profile;Release" + CACHE STRING "" FORCE) +else() + if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) + set(CMAKE_BUILD_TYPE "Debug" CACHE + STRING "Flutter build mode" FORCE) + set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS + "Debug" "Profile" "Release") + endif() +endif() +# Define settings for the Profile build mode. +set(CMAKE_EXE_LINKER_FLAGS_PROFILE "${CMAKE_EXE_LINKER_FLAGS_RELEASE}") +set(CMAKE_SHARED_LINKER_FLAGS_PROFILE "${CMAKE_SHARED_LINKER_FLAGS_RELEASE}") +set(CMAKE_C_FLAGS_PROFILE "${CMAKE_C_FLAGS_RELEASE}") +set(CMAKE_CXX_FLAGS_PROFILE "${CMAKE_CXX_FLAGS_RELEASE}") + +# Use Unicode for all projects. +add_definitions(-DUNICODE -D_UNICODE) + +# Compilation settings that should be applied to most targets. +# +# Be cautious about adding new options here, as plugins use this function by +# default. In most cases, you should add new options to specific targets instead +# of modifying this function. +function(APPLY_STANDARD_SETTINGS TARGET) + target_compile_features(${TARGET} PUBLIC cxx_std_17) + target_compile_options(${TARGET} PRIVATE /W4 /WX /wd"4100") + target_compile_options(${TARGET} PRIVATE /EHsc) + target_compile_definitions(${TARGET} PRIVATE "_HAS_EXCEPTIONS=0") + target_compile_definitions(${TARGET} PRIVATE "$<$:_DEBUG>") +endfunction() + +# Flutter library and tool build rules. +set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") +add_subdirectory(${FLUTTER_MANAGED_DIR}) + +# Application build; see runner/CMakeLists.txt. +add_subdirectory("runner") + +# Generated plugin build rules, which manage building the plugins and adding +# them to the application. +include(flutter/generated_plugins.cmake) + + +# === Installation === +# Support files are copied into place next to the executable, so that it can +# run in place. This is done instead of making a separate bundle (as on Linux) +# so that building and running from within Visual Studio will work. +set(BUILD_BUNDLE_DIR "$") +# Make the "install" step default, as it's required to run. +set(CMAKE_VS_INCLUDE_INSTALL_TO_DEFAULT_BUILD 1) +if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) + set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) +endif() + +set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") +set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}") + +install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +if(PLUGIN_BUNDLED_LIBRARIES) + install(FILES "${PLUGIN_BUNDLED_LIBRARIES}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endif() + +# Fully re-copy the assets directory on each build to avoid having stale files +# from a previous install. +set(FLUTTER_ASSET_DIR_NAME "flutter_assets") +install(CODE " + file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") + " COMPONENT Runtime) +install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" + DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) + +# Install the AOT library on non-Debug builds only. +install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + CONFIGURATIONS Profile;Release + COMPONENT Runtime) diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/flutter/CMakeLists.txt b/packages/firebase_core/firebase_core/firebase_core/example/windows/flutter/CMakeLists.txt new file mode 100644 index 000000000000..930d2071a324 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/windows/flutter/CMakeLists.txt @@ -0,0 +1,104 @@ +# This file controls Flutter-level build steps. It should not be edited. +cmake_minimum_required(VERSION 3.14) + +set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") + +# Configuration provided via flutter tool. +include(${EPHEMERAL_DIR}/generated_config.cmake) + +# TODO: Move the rest of this into files in ephemeral. See +# https://github.com/flutter/flutter/issues/57146. +set(WRAPPER_ROOT "${EPHEMERAL_DIR}/cpp_client_wrapper") + +# === Flutter Library === +set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/flutter_windows.dll") + +# Published to parent scope for install step. +set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) +set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) +set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) +set(AOT_LIBRARY "${PROJECT_DIR}/build/windows/app.so" PARENT_SCOPE) + +list(APPEND FLUTTER_LIBRARY_HEADERS + "flutter_export.h" + "flutter_windows.h" + "flutter_messenger.h" + "flutter_plugin_registrar.h" + "flutter_texture_registrar.h" +) +list(TRANSFORM FLUTTER_LIBRARY_HEADERS PREPEND "${EPHEMERAL_DIR}/") +add_library(flutter INTERFACE) +target_include_directories(flutter INTERFACE + "${EPHEMERAL_DIR}" +) +target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}.lib") +add_dependencies(flutter flutter_assemble) + +# === Wrapper === +list(APPEND CPP_WRAPPER_SOURCES_CORE + "core_implementations.cc" + "standard_codec.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_CORE PREPEND "${WRAPPER_ROOT}/") +list(APPEND CPP_WRAPPER_SOURCES_PLUGIN + "plugin_registrar.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_PLUGIN PREPEND "${WRAPPER_ROOT}/") +list(APPEND CPP_WRAPPER_SOURCES_APP + "flutter_engine.cc" + "flutter_view_controller.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_APP PREPEND "${WRAPPER_ROOT}/") + +# Wrapper sources needed for a plugin. +add_library(flutter_wrapper_plugin STATIC + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_PLUGIN} +) +apply_standard_settings(flutter_wrapper_plugin) +set_target_properties(flutter_wrapper_plugin PROPERTIES + POSITION_INDEPENDENT_CODE ON) +set_target_properties(flutter_wrapper_plugin PROPERTIES + CXX_VISIBILITY_PRESET hidden) +target_link_libraries(flutter_wrapper_plugin PUBLIC flutter) +target_include_directories(flutter_wrapper_plugin PUBLIC + "${WRAPPER_ROOT}/include" +) +add_dependencies(flutter_wrapper_plugin flutter_assemble) + +# Wrapper sources needed for the runner. +add_library(flutter_wrapper_app STATIC + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_APP} +) +apply_standard_settings(flutter_wrapper_app) +target_link_libraries(flutter_wrapper_app PUBLIC flutter) +target_include_directories(flutter_wrapper_app PUBLIC + "${WRAPPER_ROOT}/include" +) +add_dependencies(flutter_wrapper_app flutter_assemble) + +# === Flutter tool backend === +# _phony_ is a non-existent file to force this command to run every time, +# since currently there's no way to get a full input/output list from the +# flutter tool. +set(PHONY_OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/_phony_") +set_source_files_properties("${PHONY_OUTPUT}" PROPERTIES SYMBOLIC TRUE) +add_custom_command( + OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} + ${CPP_WRAPPER_SOURCES_CORE} ${CPP_WRAPPER_SOURCES_PLUGIN} + ${CPP_WRAPPER_SOURCES_APP} + ${PHONY_OUTPUT} + COMMAND ${CMAKE_COMMAND} -E env + ${FLUTTER_TOOL_ENVIRONMENT} + "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.bat" + windows-x64 $ + VERBATIM +) +add_custom_target(flutter_assemble DEPENDS + "${FLUTTER_LIBRARY}" + ${FLUTTER_LIBRARY_HEADERS} + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_PLUGIN} + ${CPP_WRAPPER_SOURCES_APP} +) diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/CMakeLists.txt b/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/CMakeLists.txt new file mode 100644 index 000000000000..394917c053a0 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/CMakeLists.txt @@ -0,0 +1,40 @@ +cmake_minimum_required(VERSION 3.14) +project(runner LANGUAGES CXX) + +# Define the application target. To change its name, change BINARY_NAME in the +# top-level CMakeLists.txt, not the value here, or `flutter run` will no longer +# work. +# +# Any new source files that you add to the application should be added here. +add_executable(${BINARY_NAME} WIN32 + "flutter_window.cpp" + "main.cpp" + "utils.cpp" + "win32_window.cpp" + "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" + "Runner.rc" + "runner.exe.manifest" +) + +# Apply the standard set of build settings. This can be removed for applications +# that need different build settings. +apply_standard_settings(${BINARY_NAME}) + +# Add preprocessor definitions for the build version. +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION=\"${FLUTTER_VERSION}\"") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MAJOR=${FLUTTER_VERSION_MAJOR}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MINOR=${FLUTTER_VERSION_MINOR}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_PATCH=${FLUTTER_VERSION_PATCH}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_BUILD=${FLUTTER_VERSION_BUILD}") + +# Disable Windows macros that collide with C++ standard library functions. +target_compile_definitions(${BINARY_NAME} PRIVATE "NOMINMAX") + +# Add dependency libraries and include directories. Add any application-specific +# dependencies here. +target_link_libraries(${BINARY_NAME} PRIVATE flutter flutter_wrapper_app) +target_link_libraries(${BINARY_NAME} PRIVATE "dwmapi.lib") +target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") + +# Run the Flutter tool portions of the build. This must not be removed. +add_dependencies(${BINARY_NAME} flutter_assemble) diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/Runner.rc b/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/Runner.rc new file mode 100644 index 000000000000..c0d7fe21c712 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/Runner.rc @@ -0,0 +1,121 @@ +// Microsoft Visual C++ generated resource script. +// +#pragma code_page(65001) +#include "resource.h" + +#define APSTUDIO_READONLY_SYMBOLS +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 2 resource. +// +#include "winres.h" + +///////////////////////////////////////////////////////////////////////////// +#undef APSTUDIO_READONLY_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +// English (United States) resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) +LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US + +#ifdef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// TEXTINCLUDE +// + +1 TEXTINCLUDE +BEGIN + "resource.h\0" +END + +2 TEXTINCLUDE +BEGIN + "#include ""winres.h""\r\n" + "\0" +END + +3 TEXTINCLUDE +BEGIN + "\r\n" + "\0" +END + +#endif // APSTUDIO_INVOKED + + +///////////////////////////////////////////////////////////////////////////// +// +// Icon +// + +// Icon with lowest ID value placed first to ensure application icon +// remains consistent on all systems. +IDI_APP_ICON ICON "resources\\app_icon.ico" + + +///////////////////////////////////////////////////////////////////////////// +// +// Version +// + +#if defined(FLUTTER_VERSION_MAJOR) && defined(FLUTTER_VERSION_MINOR) && defined(FLUTTER_VERSION_PATCH) && defined(FLUTTER_VERSION_BUILD) +#define VERSION_AS_NUMBER FLUTTER_VERSION_MAJOR,FLUTTER_VERSION_MINOR,FLUTTER_VERSION_PATCH,FLUTTER_VERSION_BUILD +#else +#define VERSION_AS_NUMBER 1,0,0,0 +#endif + +#if defined(FLUTTER_VERSION) +#define VERSION_AS_STRING FLUTTER_VERSION +#else +#define VERSION_AS_STRING "1.0.0" +#endif + +VS_VERSION_INFO VERSIONINFO + FILEVERSION VERSION_AS_NUMBER + PRODUCTVERSION VERSION_AS_NUMBER + FILEFLAGSMASK VS_FFI_FILEFLAGSMASK +#ifdef _DEBUG + FILEFLAGS VS_FF_DEBUG +#else + FILEFLAGS 0x0L +#endif + FILEOS VOS__WINDOWS32 + FILETYPE VFT_APP + FILESUBTYPE 0x0L +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "040904e4" + BEGIN + VALUE "CompanyName", "com.example" "\0" + VALUE "FileDescription", "firebase_core_example" "\0" + VALUE "FileVersion", VERSION_AS_STRING "\0" + VALUE "InternalName", "firebase_core_example" "\0" + VALUE "LegalCopyright", "Copyright (C) 2023 com.example. All rights reserved." "\0" + VALUE "OriginalFilename", "firebase_core_example.exe" "\0" + VALUE "ProductName", "firebase_core_example" "\0" + VALUE "ProductVersion", VERSION_AS_STRING "\0" + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x409, 1252 + END +END + +#endif // English (United States) resources +///////////////////////////////////////////////////////////////////////////// + + + +#ifndef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 3 resource. +// + + +///////////////////////////////////////////////////////////////////////////// +#endif // not APSTUDIO_INVOKED diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/flutter_window.cpp b/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/flutter_window.cpp new file mode 100644 index 000000000000..b25e363efa42 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/flutter_window.cpp @@ -0,0 +1,66 @@ +#include "flutter_window.h" + +#include + +#include "flutter/generated_plugin_registrant.h" + +FlutterWindow::FlutterWindow(const flutter::DartProject& project) + : project_(project) {} + +FlutterWindow::~FlutterWindow() {} + +bool FlutterWindow::OnCreate() { + if (!Win32Window::OnCreate()) { + return false; + } + + RECT frame = GetClientArea(); + + // The size here must match the window dimensions to avoid unnecessary surface + // creation / destruction in the startup path. + flutter_controller_ = std::make_unique( + frame.right - frame.left, frame.bottom - frame.top, project_); + // Ensure that basic setup of the controller was successful. + if (!flutter_controller_->engine() || !flutter_controller_->view()) { + return false; + } + RegisterPlugins(flutter_controller_->engine()); + SetChildContent(flutter_controller_->view()->GetNativeWindow()); + + flutter_controller_->engine()->SetNextFrameCallback([&]() { + this->Show(); + }); + + return true; +} + +void FlutterWindow::OnDestroy() { + if (flutter_controller_) { + flutter_controller_ = nullptr; + } + + Win32Window::OnDestroy(); +} + +LRESULT +FlutterWindow::MessageHandler(HWND hwnd, UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + // Give Flutter, including plugins, an opportunity to handle window messages. + if (flutter_controller_) { + std::optional result = + flutter_controller_->HandleTopLevelWindowProc(hwnd, message, wparam, + lparam); + if (result) { + return *result; + } + } + + switch (message) { + case WM_FONTCHANGE: + flutter_controller_->engine()->ReloadSystemFonts(); + break; + } + + return Win32Window::MessageHandler(hwnd, message, wparam, lparam); +} diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/flutter_window.h b/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/flutter_window.h new file mode 100644 index 000000000000..6da0652f05f2 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/flutter_window.h @@ -0,0 +1,33 @@ +#ifndef RUNNER_FLUTTER_WINDOW_H_ +#define RUNNER_FLUTTER_WINDOW_H_ + +#include +#include + +#include + +#include "win32_window.h" + +// A window that does nothing but host a Flutter view. +class FlutterWindow : public Win32Window { + public: + // Creates a new FlutterWindow hosting a Flutter view running |project|. + explicit FlutterWindow(const flutter::DartProject& project); + virtual ~FlutterWindow(); + + protected: + // Win32Window: + bool OnCreate() override; + void OnDestroy() override; + LRESULT MessageHandler(HWND window, UINT const message, WPARAM const wparam, + LPARAM const lparam) noexcept override; + + private: + // The project to run. + flutter::DartProject project_; + + // The Flutter instance hosted by this window. + std::unique_ptr flutter_controller_; +}; + +#endif // RUNNER_FLUTTER_WINDOW_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/main.cpp b/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/main.cpp new file mode 100644 index 000000000000..2b640e48b2b0 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/main.cpp @@ -0,0 +1,43 @@ +#include +#include +#include + +#include "flutter_window.h" +#include "utils.h" + +int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev, + _In_ wchar_t *command_line, _In_ int show_command) { + // Attach to console when present (e.g., 'flutter run') or create a + // new console when running with a debugger. + if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent()) { + CreateAndAttachConsole(); + } + + // Initialize COM, so that it is available for use in the library and/or + // plugins. + ::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED); + + flutter::DartProject project(L"data"); + + std::vector command_line_arguments = + GetCommandLineArguments(); + + project.set_dart_entrypoint_arguments(std::move(command_line_arguments)); + + FlutterWindow window(project); + Win32Window::Point origin(10, 10); + Win32Window::Size size(1280, 720); + if (!window.Create(L"firebase_core_example", origin, size)) { + return EXIT_FAILURE; + } + window.SetQuitOnClose(true); + + ::MSG msg; + while (::GetMessage(&msg, nullptr, 0, 0)) { + ::TranslateMessage(&msg); + ::DispatchMessage(&msg); + } + + ::CoUninitialize(); + return EXIT_SUCCESS; +} diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/resource.h b/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/resource.h new file mode 100644 index 000000000000..66a65d1e4a79 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/resource.h @@ -0,0 +1,16 @@ +//{{NO_DEPENDENCIES}} +// Microsoft Visual C++ generated include file. +// Used by Runner.rc +// +#define IDI_APP_ICON 101 + +// Next default values for new objects +// +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_NEXT_RESOURCE_VALUE 102 +#define _APS_NEXT_COMMAND_VALUE 40001 +#define _APS_NEXT_CONTROL_VALUE 1001 +#define _APS_NEXT_SYMED_VALUE 101 +#endif +#endif diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/resources/app_icon.ico b/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/resources/app_icon.ico new file mode 100644 index 0000000000000000000000000000000000000000..c04e20caf6370ebb9253ad831cc31de4a9c965f6 GIT binary patch literal 33772 zcmeHQc|26z|35SKE&G-*mXah&B~fFkXr)DEO&hIfqby^T&>|8^_Ub8Vp#`BLl3lbZ zvPO!8k!2X>cg~Elr=IVxo~J*a`+9wR=A83c-k-DFd(XM&UI1VKCqM@V;DDtJ09WB} zRaHKiW(GT00brH|0EeTeKVbpbGZg?nK6-j827q-+NFM34gXjqWxJ*a#{b_apGN<-L_m3#8Z26atkEn& ze87Bvv^6vVmM+p+cQ~{u%=NJF>#(d;8{7Q{^rWKWNtf14H}>#&y7$lqmY6xmZryI& z($uy?c5-+cPnt2%)R&(KIWEXww>Cnz{OUpT>W$CbO$h1= z#4BPMkFG1Y)x}Ui+WXr?Z!w!t_hjRq8qTaWpu}FH{MsHlU{>;08goVLm{V<&`itk~ zE_Ys=D(hjiy+5=?=$HGii=Y5)jMe9|wWoD_K07(}edAxh`~LBorOJ!Cf@f{_gNCC| z%{*04ViE!#>@hc1t5bb+NO>ncf@@Dv01K!NxH$3Eg1%)|wLyMDF8^d44lV!_Sr}iEWefOaL z8f?ud3Q%Sen39u|%00W<#!E=-RpGa+H8}{ulxVl4mwpjaU+%2pzmi{3HM)%8vb*~-M9rPUAfGCSos8GUXp02|o~0BTV2l#`>>aFV&_P$ejS;nGwSVP8 zMbOaG7<7eKD>c12VdGH;?2@q7535sa7MN*L@&!m?L`ASG%boY7(&L5imY#EQ$KrBB z4@_tfP5m50(T--qv1BJcD&aiH#b-QC>8#7Fx@3yXlonJI#aEIi=8&ChiVpc#N=5le zM*?rDIdcpawoc5kizv$GEjnveyrp3sY>+5_R5;>`>erS%JolimF=A^EIsAK zsPoVyyUHCgf0aYr&alx`<)eb6Be$m&`JYSuBu=p8j%QlNNp$-5C{b4#RubPb|CAIS zGE=9OFLP7?Hgc{?k45)84biT0k&-C6C%Q}aI~q<(7BL`C#<6HyxaR%!dFx7*o^laG z=!GBF^cwK$IA(sn9y6>60Rw{mYRYkp%$jH z*xQM~+bp)G$_RhtFPYx2HTsWk80+p(uqv9@I9)y{b$7NK53rYL$ezbmRjdXS?V}fj zWxX_feWoLFNm3MG7pMUuFPs$qrQWO9!l2B(SIuy2}S|lHNbHzoE+M2|Zxhjq9+Ws8c{*}x^VAib7SbxJ*Q3EnY5lgI9 z=U^f3IW6T=TWaVj+2N%K3<%Un;CF(wUp`TC&Y|ZjyFu6co^uqDDB#EP?DV5v_dw~E zIRK*BoY9y-G_ToU2V_XCX4nJ32~`czdjT!zwme zGgJ0nOk3U4@IE5JwtM}pwimLjk{ln^*4HMU%Fl4~n(cnsLB}Ja-jUM>xIB%aY;Nq8 z)Fp8dv1tkqKanv<68o@cN|%thj$+f;zGSO7H#b+eMAV8xH$hLggtt?O?;oYEgbq@= zV(u9bbd12^%;?nyk6&$GPI%|+<_mEpJGNfl*`!KV;VfmZWw{n{rnZ51?}FDh8we_L z8OI9nE31skDqJ5Oa_ybn7|5@ui>aC`s34p4ZEu6-s!%{uU45$Zd1=p$^^dZBh zu<*pDDPLW+c>iWO$&Z_*{VSQKg7=YEpS3PssPn1U!lSm6eZIho*{@&20e4Y_lRklKDTUCKI%o4Pc<|G^Xgu$J^Q|B87U;`c1zGwf^-zH*VQ^x+i^OUWE0yd z;{FJq)2w!%`x7yg@>uGFFf-XJl4H`YtUG%0slGKOlXV`q?RP>AEWg#x!b{0RicxGhS!3$p7 zij;{gm!_u@D4$Ox%>>bPtLJ> zwKtYz?T_DR1jN>DkkfGU^<#6sGz|~p*I{y`aZ>^Di#TC|Z!7j_O1=Wo8thuit?WxR zh9_S>kw^{V^|g}HRUF=dcq>?q(pHxw!8rx4dC6vbQVmIhmICF#zU!HkHpQ>9S%Uo( zMw{eC+`&pb=GZRou|3;Po1}m46H6NGd$t<2mQh}kaK-WFfmj_66_17BX0|j-E2fe3Jat}ijpc53 zJV$$;PC<5aW`{*^Z6e5##^`Ed#a0nwJDT#Qq~^e8^JTA=z^Kl>La|(UQ!bI@#ge{Dzz@61p-I)kc2?ZxFt^QQ}f%ldLjO*GPj(5)V9IyuUakJX=~GnTgZ4$5!3E=V#t`yOG4U z(gphZB6u2zsj=qNFLYShhg$}lNpO`P9xOSnO*$@@UdMYES*{jJVj|9z-}F^riksLK zbsU+4-{281P9e2UjY6tse^&a)WM1MFw;p#_dHhWI7p&U*9TR0zKdVuQed%6{otTsq z$f~S!;wg#Bd9kez=Br{m|66Wv z#g1xMup<0)H;c2ZO6su_ii&m8j&+jJz4iKnGZ&wxoQX|5a>v&_e#6WA!MB_4asTxLRGQCC5cI(em z%$ZfeqP>!*q5kU>a+BO&ln=4Jm>Ef(QE8o&RgLkk%2}4Tf}U%IFP&uS7}&|Q-)`5< z+e>;s#4cJ-z%&-^&!xsYx777Wt(wZY9(3(avmr|gRe4cD+a8&!LY`1^T?7x{E<=kdY9NYw>A;FtTvQ=Y&1M%lyZPl$ss1oY^Sl8we}n}Aob#6 zl4jERwnt9BlSoWb@3HxYgga(752Vu6Y)k4yk9u~Kw>cA5&LHcrvn1Y-HoIuFWg~}4 zEw4bR`mXZQIyOAzo)FYqg?$5W<;^+XX%Uz61{-L6@eP|lLH%|w?g=rFc;OvEW;^qh z&iYXGhVt(G-q<+_j}CTbPS_=K>RKN0&;dubh0NxJyDOHFF;<1k!{k#7b{|Qok9hac z;gHz}6>H6C6RnB`Tt#oaSrX0p-j-oRJ;_WvS-qS--P*8}V943RT6kou-G=A+7QPGQ z!ze^UGxtW3FC0$|(lY9^L!Lx^?Q8cny(rR`es5U;-xBhphF%_WNu|aO<+e9%6LuZq zt(0PoagJG<%hyuf;te}n+qIl_Ej;czWdc{LX^pS>77s9t*2b4s5dvP_!L^3cwlc)E!(!kGrg~FescVT zZCLeua3f4;d;Tk4iXzt}g}O@nlK3?_o91_~@UMIl?@77Qc$IAlLE95#Z=TES>2E%z zxUKpK{_HvGF;5%Q7n&vA?`{%8ohlYT_?(3A$cZSi)MvIJygXD}TS-3UwyUxGLGiJP znblO~G|*uA^|ac8E-w#}uBtg|s_~s&t>-g0X%zIZ@;o_wNMr_;{KDg^O=rg`fhDZu zFp(VKd1Edj%F zWHPl+)FGj%J1BO3bOHVfH^3d1F{)*PL&sRX`~(-Zy3&9UQX)Z;c51tvaI2E*E7!)q zcz|{vpK7bjxix(k&6=OEIBJC!9lTkUbgg?4-yE{9+pFS)$Ar@vrIf`D0Bnsed(Cf? zObt2CJ>BKOl>q8PyFO6w)+6Iz`LW%T5^R`U_NIW0r1dWv6OY=TVF?N=EfA(k(~7VBW(S;Tu5m4Lg8emDG-(mOSSs=M9Q&N8jc^Y4&9RqIsk(yO_P(mcCr}rCs%1MW1VBrn=0-oQN(Xj!k%iKV zb%ricBF3G4S1;+8lzg5PbZ|$Se$)I=PwiK=cDpHYdov2QO1_a-*dL4KUi|g&oh>(* zq$<`dQ^fat`+VW?m)?_KLn&mp^-@d=&7yGDt<=XwZZC=1scwxO2^RRI7n@g-1o8ps z)&+et_~)vr8aIF1VY1Qrq~Xe``KJrQSnAZ{CSq3yP;V*JC;mmCT6oRLSs7=GA?@6g zUooM}@tKtx(^|aKK8vbaHlUQqwE0}>j&~YlN3H#vKGm@u)xxS?n9XrOWUfCRa< z`20Fld2f&;gg7zpo{Adh+mqNntMc-D$N^yWZAZRI+u1T1zWHPxk{+?vcS1D>08>@6 zLhE@`gt1Y9mAK6Z4p|u(5I%EkfU7rKFSM=E4?VG9tI;a*@?6!ey{lzN5=Y-!$WFSe z&2dtO>^0@V4WRc#L&P%R(?@KfSblMS+N+?xUN$u3K4Ys%OmEh+tq}fnU}i>6YHM?< zlnL2gl~sF!j!Y4E;j3eIU-lfa`RsOL*Tt<%EFC0gPzoHfNWAfKFIKZN8}w~(Yi~=q z>=VNLO2|CjkxP}RkutxjV#4fWYR1KNrPYq5ha9Wl+u>ipsk*I(HS@iLnmGH9MFlTU zaFZ*KSR0px>o+pL7BbhB2EC1%PJ{67_ z#kY&#O4@P=OV#-79y_W>Gv2dxL*@G7%LksNSqgId9v;2xJ zrh8uR!F-eU$NMx@S*+sk=C~Dxr9Qn7TfWnTupuHKuQ$;gGiBcU>GF5sWx(~4IP3`f zWE;YFO*?jGwYh%C3X<>RKHC-DZ!*r;cIr}GLOno^3U4tFSSoJp%oHPiSa%nh=Zgn% z14+8v@ygy0>UgEN1bczD6wK45%M>psM)y^)IfG*>3ItX|TzV*0i%@>L(VN!zdKb8S?Qf7BhjNpziA zR}?={-eu>9JDcl*R=OP9B8N$IcCETXah9SUDhr{yrld{G;PnCWRsPD7!eOOFBTWUQ=LrA_~)mFf&!zJX!Oc-_=kT<}m|K52 z)M=G#;p;Rdb@~h5D{q^K;^fX-m5V}L%!wVC2iZ1uu401Ll}#rocTeK|7FAeBRhNdQ zCc2d^aQnQp=MpOmak60N$OgS}a;p(l9CL`o4r(e-nN}mQ?M&isv-P&d$!8|1D1I(3-z!wi zTgoo)*Mv`gC?~bm?S|@}I|m-E2yqPEvYybiD5azInexpK8?9q*$9Yy9-t%5jU8~ym zgZDx>!@ujQ=|HJnwp^wv-FdD{RtzO9SnyfB{mH_(c!jHL*$>0o-(h(eqe*ZwF6Lvu z{7rkk%PEqaA>o+f{H02tzZ@TWy&su?VNw43! z-X+rN`6llvpUms3ZiSt)JMeztB~>9{J8SPmYs&qohxdYFi!ra8KR$35Zp9oR)eFC4 zE;P31#3V)n`w$fZ|4X-|%MX`xZDM~gJyl2W;O$H25*=+1S#%|53>|LyH za@yh+;325%Gq3;J&a)?%7X%t@WXcWL*BaaR*7UEZad4I8iDt7^R_Fd`XeUo256;sAo2F!HcIQKk;h})QxEsPE5BcKc7WyerTchgKmrfRX z!x#H_%cL#B9TWAqkA4I$R^8{%do3Y*&(;WFmJ zU7Dih{t1<{($VtJRl9|&EB?|cJ)xse!;}>6mSO$o5XIx@V|AA8ZcoD88ZM?C*;{|f zZVmf94_l1OmaICt`2sTyG!$^UeTHx9YuUP!omj(r|7zpm5475|yXI=rR>>fteLI+| z)MoiGho0oEt=*J(;?VY0QzwCqw@cVm?d7Y!z0A@u#H?sCJ*ecvyhj& z-F77lO;SH^dmf?L>3i>?Z*U}Em4ZYV_CjgfvzYsRZ+1B!Uo6H6mbS<-FFL`ytqvb& zE7+)2ahv-~dz(Hs+f})z{*4|{)b=2!RZK;PWwOnO=hG7xG`JU5>bAvUbdYd_CjvtHBHgtGdlO+s^9ca^Bv3`t@VRX2_AD$Ckg36OcQRF zXD6QtGfHdw*hx~V(MV-;;ZZF#dJ-piEF+s27z4X1qi5$!o~xBnvf=uopcn7ftfsZc zy@(PuOk`4GL_n(H9(E2)VUjqRCk9kR?w)v@xO6Jm_Mx})&WGEl=GS0#)0FAq^J*o! zAClhvoTsNP*-b~rN{8Yym3g{01}Ep^^Omf=SKqvN?{Q*C4HNNAcrowIa^mf+3PRy! z*_G-|3i8a;+q;iP@~Of_$(vtFkB8yOyWt2*K)vAn9El>=D;A$CEx6b*XF@4y_6M+2 zpeW`RHoI_p(B{%(&jTHI->hmNmZjHUj<@;7w0mx3&koy!2$@cfX{sN19Y}euYJFn& z1?)+?HCkD0MRI$~uB2UWri})0bru_B;klFdwsLc!ne4YUE;t41JqfG# zZJq6%vbsdx!wYeE<~?>o4V`A3?lN%MnKQ`z=uUivQN^vzJ|C;sdQ37Qn?;lpzg})y z)_2~rUdH}zNwX;Tp0tJ78+&I=IwOQ-fl30R79O8@?Ub8IIA(6I`yHn%lARVL`%b8+ z4$8D-|MZZWxc_)vu6@VZN!HsI$*2NOV&uMxBNzIbRgy%ob_ zhwEH{J9r$!dEix9XM7n&c{S(h>nGm?el;gaX0@|QnzFD@bne`el^CO$yXC?BDJ|Qg z+y$GRoR`?ST1z^e*>;!IS@5Ovb7*RlN>BV_UC!7E_F;N#ky%1J{+iixp(dUJj93aK zzHNN>R-oN7>kykHClPnoPTIj7zc6KM(Pnlb(|s??)SMb)4!sMHU^-ntJwY5Big7xv zb1Ew`Xj;|D2kzGja*C$eS44(d&RMU~c_Y14V9_TLTz0J#uHlsx`S6{nhsA0dWZ#cG zJ?`fO50E>*X4TQLv#nl%3GOk*UkAgt=IY+u0LNXqeln3Z zv$~&Li`ZJOKkFuS)dJRA>)b_Da%Q~axwA_8zNK{BH{#}#m}zGcuckz}riDE-z_Ms> zR8-EqAMcfyGJCtvTpaUVQtajhUS%c@Yj}&6Zz;-M7MZzqv3kA7{SuW$oW#=0az2wQ zg-WG@Vb4|D`pl~Il54N7Hmsauc_ne-a!o5#j3WaBBh@Wuefb!QJIOn5;d)%A#s+5% zuD$H=VNux9bE-}1&bcYGZ+>1Fo;3Z@e&zX^n!?JK*adSbONm$XW9z;Q^L>9U!}Toj2WdafJ%oL#h|yWWwyAGxzfrAWdDTtaKl zK4`5tDpPg5>z$MNv=X0LZ0d6l%D{(D8oT@+w0?ce$DZ6pv>{1&Ok67Ix1 zH}3=IEhPJEhItCC8E=`T`N5(k?G=B4+xzZ?<4!~ ze~z6Wk9!CHTI(0rLJ4{JU?E-puc;xusR?>G?;4vt;q~iI9=kDL=z0Rr%O$vU`30X$ zDZRFyZ`(omOy@u|i6h;wtJlP;+}$|Ak|k2dea7n?U1*$T!sXqqOjq^NxLPMmk~&qI zYg0W?yK8T(6+Ea+$YyspKK?kP$+B`~t3^Pib_`!6xCs32!i@pqXfFV6PmBIR<-QW= zN8L{pt0Vap0x`Gzn#E@zh@H)0FfVfA_Iu4fjYZ+umO1LXIbVc$pY+E234u)ttcrl$ z>s92z4vT%n6cMb>=XT6;l0+9e(|CZG)$@C7t7Z7Ez@a)h)!hyuV&B5K%%)P5?Lk|C zZZSVzdXp{@OXSP0hoU-gF8s8Um(#xzjP2Vem zec#-^JqTa&Y#QJ>-FBxd7tf`XB6e^JPUgagB8iBSEps;92KG`!#mvVcPQ5yNC-GEG zTiHEDYfH+0O15}r^+ z#jxj=@x8iNHWALe!P3R67TwmhItn**0JwnzSV2O&KE8KcT+0hWH^OPD1pwiuyx=b@ zNf5Jh0{9X)8;~Es)$t@%(3!OnbY+`@?i{mGX7Yy}8T_*0a6g;kaFPq;*=px5EhO{Cp%1kI<0?*|h8v!6WnO3cCJRF2-CRrU3JiLJnj@6;L)!0kWYAc_}F{2P))3HmCrz zQ&N&gE70;`!6*eJ4^1IR{f6j4(-l&X!tjHxkbHA^Zhrnhr9g{exN|xrS`5Pq=#Xf& zG%P=#ra-TyVFfgW%cZo5OSIwFL9WtXAlFOa+ubmI5t*3=g#Y zF%;70p5;{ZeFL}&}yOY1N1*Q;*<(kTB!7vM$QokF)yr2FlIU@$Ph58$Bz z0J?xQG=MlS4L6jA22eS42g|9*9pX@$#*sUeM(z+t?hr@r5J&D1rx}2pW&m*_`VDCW zUYY@v-;bAO0HqoAgbbiGGC<=ryf96}3pouhy3XJrX+!!u*O_>Si38V{uJmQ&USptX zKp#l(?>%^7;2%h(q@YWS#9;a!JhKlkR#Vd)ERILlgu!Hr@jA@V;sk4BJ-H#p*4EqC zDGjC*tl=@3Oi6)Bn^QwFpul18fpkbpg0+peH$xyPBqb%`$OUhPKyWb32o7clB*9Z< zN=i~NLjavrLtwgJ01bufP+>p-jR2I95|TpmKpQL2!oV>g(4RvS2pK4*ou%m(h6r3A zX#s&`9LU1ZG&;{CkOK!4fLDTnBys`M!vuz>Q&9OZ0hGQl!~!jSDg|~s*w52opC{sB ze|Cf2luD(*G13LcOAGA!s2FjSK8&IE5#W%J25w!vM0^VyQM!t)inj&RTiJ!wXzFgz z3^IqzB7I0L$llljsGq})thBy9UOyjtFO_*hYM_sgcMk>44jeH0V1FDyELc{S1F-;A zS;T^k^~4biG&V*Irq}O;e}j$$+E_#G?HKIn05iP3j|87TkGK~SqG!-KBg5+mN(aLm z8ybhIM`%C19UX$H$KY6JgXbY$0AT%rEpHC;u`rQ$Y=rxUdsc5*Kvc8jaYaO$^)cI6){P6K0r)I6DY4Wr4&B zLQUBraey#0HV|&c4v7PVo3n$zHj99(TZO^3?Ly%C4nYvJTL9eLBLHsM3WKKD>5!B` zQ=BsR3aR6PD(Fa>327E2HAu5TM~Wusc!)>~(gM)+3~m;92Jd;FnSib=M5d6;;5{%R zb4V7DEJ0V!CP-F*oU?gkc>ksUtAYP&V4ND5J>J2^jt*vcFflQWCrB&fLdT%O59PVJ zhid#toR=FNgD!q3&r8#wEBr`!wzvQu5zX?Q>nlSJ4i@WC*CN*-xU66F^V5crWevQ9gsq$I@z1o(a=k7LL~ z7m_~`o;_Ozha1$8Q}{WBehvAlO4EL60y5}8GDrZ< zXh&F}71JbW2A~8KfEWj&UWV#4+Z4p`b{uAj4&WC zha`}X@3~+Iz^WRlOHU&KngK>#j}+_o@LdBC1H-`gT+krWX3-;!)6?{FBp~%20a}FL zFP9%Emqcwa#(`=G>BBZ0qZDQhmZKJg_g8<=bBFKWr!dyg(YkpE+|R*SGpDVU!+VlU zFC54^DLv}`qa%49T>nNiA9Q7Ips#!Xx90tCU2gvK`(F+GPcL=J^>No{)~we#o@&mUb6c$ zCc*<|NJBk-#+{j9xkQ&ujB zI~`#kN~7W!f*-}wkG~Ld!JqZ@tK}eeSnsS5J1fMFXm|`LJx&}5`@dK3W^7#Wnm+_P zBZkp&j1fa2Y=eIjJ0}gh85jt43kaIXXv?xmo@eHrka!Z|vQv12HN#+!I5E z`(fbuW>gFiJL|uXJ!vKt#z3e3HlVdboH7;e#i3(2<)Fg-I@BR!qY#eof3MFZ&*Y@l zI|KJf&ge@p2Dq09Vu$$Qxb7!}{m-iRk@!)%KL)txi3;~Z4Pb}u@GsW;ELiWeG9V51 znX#}B&4Y2E7-H=OpNE@q{%hFLxwIpBF2t{vPREa8_{linXT;#1vMRWjOzLOP$-hf( z>=?$0;~~PnkqY;~K{EM6Vo-T(0K{A0}VUGmu*hR z{tw3hvBN%N3G3Yw`X5Te+F{J`(3w1s3-+1EbnFQKcrgrX1Jqvs@ADGe%M0s$EbK$$ zK)=y=upBc6SjGYAACCcI=Y*6Fi8_jgwZlLxD26fnQfJmb8^gHRN5(TemhX@0e=vr> zg`W}6U>x6VhoA3DqsGGD9uL1DhB3!OXO=k}59TqD@(0Nb{)Ut_luTioK_>7wjc!5C zIr@w}b`Fez3)0wQfKl&bae7;PcTA7%?f2xucM0G)wt_KO!Ewx>F~;=BI0j=Fb4>pp zv}0R^xM4eti~+^+gE$6b81p(kwzuDti(-K9bc|?+pJEl@H+jSYuxZQV8rl8 zjp@M{#%qItIUFN~KcO9Hed*`$5A-2~pAo~K&<-Q+`9`$CK>rzqAI4w~$F%vs9s{~x zg4BP%Gy*@m?;D6=SRX?888Q6peF@_4Z->8wAH~Cn!R$|Hhq2cIzFYqT_+cDourHbY z0qroxJnrZ4Gh+Ay+F`_c%+KRT>y3qw{)89?=hJ@=KO=@ep)aBJ$c!JHfBMJpsP*3G za7|)VJJ8B;4?n{~ldJF7%jmb`-ftIvNd~ekoufG(`K(3=LNc;HBY& z(lp#q8XAD#cIf}k49zX_i`*fO+#!zKA&%T3j@%)R+#yag067CU%yUEe47>wzGU8^` z1EXFT^@I!{J!F8!X?S6ph8J=gUi5tl93*W>7}_uR<2N2~e}FaG?}KPyugQ=-OGEZs z!GBoyYY+H*ANn4?Z)X4l+7H%`17i5~zRlRIX?t)6_eu=g2Q`3WBhxSUeea+M-S?RL zX9oBGKn%a!H+*hx4d2(I!gsi+@SQK%<{X22M~2tMulJoa)0*+z9=-YO+;DFEm5eE1U9b^B(Z}2^9!Qk`!A$wUE z7$Ar5?NRg2&G!AZqnmE64eh^Anss3i!{}%6@Et+4rr!=}!SBF8eZ2*J3ujCWbl;3; z48H~goPSv(8X61fKKdpP!Z7$88NL^Z?j`!^*I?-P4X^pMxyWz~@$(UeAcTSDd(`vO z{~rc;9|GfMJcApU3k}22a!&)k4{CU!e_ny^Y3cO;tOvOMKEyWz!vG(Kp*;hB?d|R3`2X~=5a6#^o5@qn?J-bI8Ppip{-yG z!k|VcGsq!jF~}7DMr49Wap-s&>o=U^T0!Lcy}!(bhtYsPQy z4|EJe{12QL#=c(suQ89Mhw9<`bui%nx7Nep`C&*M3~vMEACmcRYYRGtANq$F%zh&V zc)cEVeHz*Z1N)L7k-(k3np#{GcDh2Q@ya0YHl*n7fl*ZPAsbU-a94MYYtA#&!c`xGIaV;yzsmrjfieTEtqB_WgZp2*NplHx=$O{M~2#i_vJ{ps-NgK zQsxKK_CBM2PP_je+Xft`(vYfXXgIUr{=PA=7a8`2EHk)Ym2QKIforz# tySWtj{oF3N9@_;i*Fv5S)9x^z=nlWP>jpp-9)52ZmLVA=i*%6g{{fxOO~wEK literal 0 HcmV?d00001 diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/runner.exe.manifest b/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/runner.exe.manifest new file mode 100644 index 000000000000..a42ea7687cb6 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/runner.exe.manifest @@ -0,0 +1,20 @@ + + + + + PerMonitorV2 + + + + + + + + + + + + + + + diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/utils.cpp b/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/utils.cpp new file mode 100644 index 000000000000..f5bf9fa0f536 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/utils.cpp @@ -0,0 +1,64 @@ +#include "utils.h" + +#include +#include +#include +#include + +#include + +void CreateAndAttachConsole() { + if (::AllocConsole()) { + FILE *unused; + if (freopen_s(&unused, "CONOUT$", "w", stdout)) { + _dup2(_fileno(stdout), 1); + } + if (freopen_s(&unused, "CONOUT$", "w", stderr)) { + _dup2(_fileno(stdout), 2); + } + std::ios::sync_with_stdio(); + FlutterDesktopResyncOutputStreams(); + } +} + +std::vector GetCommandLineArguments() { + // Convert the UTF-16 command line arguments to UTF-8 for the Engine to use. + int argc; + wchar_t** argv = ::CommandLineToArgvW(::GetCommandLineW(), &argc); + if (argv == nullptr) { + return std::vector(); + } + + std::vector command_line_arguments; + + // Skip the first argument as it's the binary name. + for (int i = 1; i < argc; i++) { + command_line_arguments.push_back(Utf8FromUtf16(argv[i])); + } + + ::LocalFree(argv); + + return command_line_arguments; +} + +std::string Utf8FromUtf16(const wchar_t* utf16_string) { + if (utf16_string == nullptr) { + return std::string(); + } + int target_length = ::WideCharToMultiByte( + CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, + -1, nullptr, 0, nullptr, nullptr); + std::string utf8_string; + if (target_length == 0 || target_length > utf8_string.max_size()) { + return utf8_string; + } + utf8_string.resize(target_length); + int converted_length = ::WideCharToMultiByte( + CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, + -1, utf8_string.data(), + target_length, nullptr, nullptr); + if (converted_length == 0) { + return std::string(); + } + return utf8_string; +} diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/utils.h b/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/utils.h new file mode 100644 index 000000000000..3879d5475579 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/utils.h @@ -0,0 +1,19 @@ +#ifndef RUNNER_UTILS_H_ +#define RUNNER_UTILS_H_ + +#include +#include + +// Creates a console for the process, and redirects stdout and stderr to +// it for both the runner and the Flutter library. +void CreateAndAttachConsole(); + +// Takes a null-terminated wchar_t* encoded in UTF-16 and returns a std::string +// encoded in UTF-8. Returns an empty std::string on failure. +std::string Utf8FromUtf16(const wchar_t* utf16_string); + +// Gets the command line arguments passed in as a std::vector, +// encoded in UTF-8. Returns an empty std::vector on failure. +std::vector GetCommandLineArguments(); + +#endif // RUNNER_UTILS_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/win32_window.cpp b/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/win32_window.cpp new file mode 100644 index 000000000000..041a38554745 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/win32_window.cpp @@ -0,0 +1,288 @@ +#include "win32_window.h" + +#include +#include + +#include "resource.h" + +namespace { + +/// Window attribute that enables dark mode window decorations. +/// +/// Redefined in case the developer's machine has a Windows SDK older than +/// version 10.0.22000.0. +/// See: https://docs.microsoft.com/windows/win32/api/dwmapi/ne-dwmapi-dwmwindowattribute +#ifndef DWMWA_USE_IMMERSIVE_DARK_MODE +#define DWMWA_USE_IMMERSIVE_DARK_MODE 20 +#endif + +constexpr const wchar_t kWindowClassName[] = L"FLUTTER_RUNNER_WIN32_WINDOW"; + +/// Registry key for app theme preference. +/// +/// A value of 0 indicates apps should use dark mode. A non-zero or missing +/// value indicates apps should use light mode. +constexpr const wchar_t kGetPreferredBrightnessRegKey[] = + L"Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize"; +constexpr const wchar_t kGetPreferredBrightnessRegValue[] = L"AppsUseLightTheme"; + +// The number of Win32Window objects that currently exist. +static int g_active_window_count = 0; + +using EnableNonClientDpiScaling = BOOL __stdcall(HWND hwnd); + +// Scale helper to convert logical scaler values to physical using passed in +// scale factor +int Scale(int source, double scale_factor) { + return static_cast(source * scale_factor); +} + +// Dynamically loads the |EnableNonClientDpiScaling| from the User32 module. +// This API is only needed for PerMonitor V1 awareness mode. +void EnableFullDpiSupportIfAvailable(HWND hwnd) { + HMODULE user32_module = LoadLibraryA("User32.dll"); + if (!user32_module) { + return; + } + auto enable_non_client_dpi_scaling = + reinterpret_cast( + GetProcAddress(user32_module, "EnableNonClientDpiScaling")); + if (enable_non_client_dpi_scaling != nullptr) { + enable_non_client_dpi_scaling(hwnd); + } + FreeLibrary(user32_module); +} + +} // namespace + +// Manages the Win32Window's window class registration. +class WindowClassRegistrar { + public: + ~WindowClassRegistrar() = default; + + // Returns the singleton registar instance. + static WindowClassRegistrar* GetInstance() { + if (!instance_) { + instance_ = new WindowClassRegistrar(); + } + return instance_; + } + + // Returns the name of the window class, registering the class if it hasn't + // previously been registered. + const wchar_t* GetWindowClass(); + + // Unregisters the window class. Should only be called if there are no + // instances of the window. + void UnregisterWindowClass(); + + private: + WindowClassRegistrar() = default; + + static WindowClassRegistrar* instance_; + + bool class_registered_ = false; +}; + +WindowClassRegistrar* WindowClassRegistrar::instance_ = nullptr; + +const wchar_t* WindowClassRegistrar::GetWindowClass() { + if (!class_registered_) { + WNDCLASS window_class{}; + window_class.hCursor = LoadCursor(nullptr, IDC_ARROW); + window_class.lpszClassName = kWindowClassName; + window_class.style = CS_HREDRAW | CS_VREDRAW; + window_class.cbClsExtra = 0; + window_class.cbWndExtra = 0; + window_class.hInstance = GetModuleHandle(nullptr); + window_class.hIcon = + LoadIcon(window_class.hInstance, MAKEINTRESOURCE(IDI_APP_ICON)); + window_class.hbrBackground = 0; + window_class.lpszMenuName = nullptr; + window_class.lpfnWndProc = Win32Window::WndProc; + RegisterClass(&window_class); + class_registered_ = true; + } + return kWindowClassName; +} + +void WindowClassRegistrar::UnregisterWindowClass() { + UnregisterClass(kWindowClassName, nullptr); + class_registered_ = false; +} + +Win32Window::Win32Window() { + ++g_active_window_count; +} + +Win32Window::~Win32Window() { + --g_active_window_count; + Destroy(); +} + +bool Win32Window::Create(const std::wstring& title, + const Point& origin, + const Size& size) { + Destroy(); + + const wchar_t* window_class = + WindowClassRegistrar::GetInstance()->GetWindowClass(); + + const POINT target_point = {static_cast(origin.x), + static_cast(origin.y)}; + HMONITOR monitor = MonitorFromPoint(target_point, MONITOR_DEFAULTTONEAREST); + UINT dpi = FlutterDesktopGetDpiForMonitor(monitor); + double scale_factor = dpi / 96.0; + + HWND window = CreateWindow( + window_class, title.c_str(), WS_OVERLAPPEDWINDOW, + Scale(origin.x, scale_factor), Scale(origin.y, scale_factor), + Scale(size.width, scale_factor), Scale(size.height, scale_factor), + nullptr, nullptr, GetModuleHandle(nullptr), this); + + if (!window) { + return false; + } + + UpdateTheme(window); + + return OnCreate(); +} + +bool Win32Window::Show() { + return ShowWindow(window_handle_, SW_SHOWNORMAL); +} + +// static +LRESULT CALLBACK Win32Window::WndProc(HWND const window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + if (message == WM_NCCREATE) { + auto window_struct = reinterpret_cast(lparam); + SetWindowLongPtr(window, GWLP_USERDATA, + reinterpret_cast(window_struct->lpCreateParams)); + + auto that = static_cast(window_struct->lpCreateParams); + EnableFullDpiSupportIfAvailable(window); + that->window_handle_ = window; + } else if (Win32Window* that = GetThisFromHandle(window)) { + return that->MessageHandler(window, message, wparam, lparam); + } + + return DefWindowProc(window, message, wparam, lparam); +} + +LRESULT +Win32Window::MessageHandler(HWND hwnd, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + switch (message) { + case WM_DESTROY: + window_handle_ = nullptr; + Destroy(); + if (quit_on_close_) { + PostQuitMessage(0); + } + return 0; + + case WM_DPICHANGED: { + auto newRectSize = reinterpret_cast(lparam); + LONG newWidth = newRectSize->right - newRectSize->left; + LONG newHeight = newRectSize->bottom - newRectSize->top; + + SetWindowPos(hwnd, nullptr, newRectSize->left, newRectSize->top, newWidth, + newHeight, SWP_NOZORDER | SWP_NOACTIVATE); + + return 0; + } + case WM_SIZE: { + RECT rect = GetClientArea(); + if (child_content_ != nullptr) { + // Size and position the child window. + MoveWindow(child_content_, rect.left, rect.top, rect.right - rect.left, + rect.bottom - rect.top, TRUE); + } + return 0; + } + + case WM_ACTIVATE: + if (child_content_ != nullptr) { + SetFocus(child_content_); + } + return 0; + + case WM_DWMCOLORIZATIONCOLORCHANGED: + UpdateTheme(hwnd); + return 0; + } + + return DefWindowProc(window_handle_, message, wparam, lparam); +} + +void Win32Window::Destroy() { + OnDestroy(); + + if (window_handle_) { + DestroyWindow(window_handle_); + window_handle_ = nullptr; + } + if (g_active_window_count == 0) { + WindowClassRegistrar::GetInstance()->UnregisterWindowClass(); + } +} + +Win32Window* Win32Window::GetThisFromHandle(HWND const window) noexcept { + return reinterpret_cast( + GetWindowLongPtr(window, GWLP_USERDATA)); +} + +void Win32Window::SetChildContent(HWND content) { + child_content_ = content; + SetParent(content, window_handle_); + RECT frame = GetClientArea(); + + MoveWindow(content, frame.left, frame.top, frame.right - frame.left, + frame.bottom - frame.top, true); + + SetFocus(child_content_); +} + +RECT Win32Window::GetClientArea() { + RECT frame; + GetClientRect(window_handle_, &frame); + return frame; +} + +HWND Win32Window::GetHandle() { + return window_handle_; +} + +void Win32Window::SetQuitOnClose(bool quit_on_close) { + quit_on_close_ = quit_on_close; +} + +bool Win32Window::OnCreate() { + // No-op; provided for subclasses. + return true; +} + +void Win32Window::OnDestroy() { + // No-op; provided for subclasses. +} + +void Win32Window::UpdateTheme(HWND const window) { + DWORD light_mode; + DWORD light_mode_size = sizeof(light_mode); + LSTATUS result = RegGetValue(HKEY_CURRENT_USER, kGetPreferredBrightnessRegKey, + kGetPreferredBrightnessRegValue, + RRF_RT_REG_DWORD, nullptr, &light_mode, + &light_mode_size); + + if (result == ERROR_SUCCESS) { + BOOL enable_dark_mode = light_mode == 0; + DwmSetWindowAttribute(window, DWMWA_USE_IMMERSIVE_DARK_MODE, + &enable_dark_mode, sizeof(enable_dark_mode)); + } +} diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/win32_window.h b/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/win32_window.h new file mode 100644 index 000000000000..c86632d8a6b9 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/win32_window.h @@ -0,0 +1,102 @@ +#ifndef RUNNER_WIN32_WINDOW_H_ +#define RUNNER_WIN32_WINDOW_H_ + +#include + +#include +#include +#include + +// A class abstraction for a high DPI-aware Win32 Window. Intended to be +// inherited from by classes that wish to specialize with custom +// rendering and input handling +class Win32Window { + public: + struct Point { + unsigned int x; + unsigned int y; + Point(unsigned int x, unsigned int y) : x(x), y(y) {} + }; + + struct Size { + unsigned int width; + unsigned int height; + Size(unsigned int width, unsigned int height) + : width(width), height(height) {} + }; + + Win32Window(); + virtual ~Win32Window(); + + // Creates a win32 window with |title| that is positioned and sized using + // |origin| and |size|. New windows are created on the default monitor. Window + // sizes are specified to the OS in physical pixels, hence to ensure a + // consistent size this function will scale the inputted width and height as + // as appropriate for the default monitor. The window is invisible until + // |Show| is called. Returns true if the window was created successfully. + bool Create(const std::wstring& title, const Point& origin, const Size& size); + + // Show the current window. Returns true if the window was successfully shown. + bool Show(); + + // Release OS resources associated with window. + void Destroy(); + + // Inserts |content| into the window tree. + void SetChildContent(HWND content); + + // Returns the backing Window handle to enable clients to set icon and other + // window properties. Returns nullptr if the window has been destroyed. + HWND GetHandle(); + + // If true, closing this window will quit the application. + void SetQuitOnClose(bool quit_on_close); + + // Return a RECT representing the bounds of the current client area. + RECT GetClientArea(); + + protected: + // Processes and route salient window messages for mouse handling, + // size change and DPI. Delegates handling of these to member overloads that + // inheriting classes can handle. + virtual LRESULT MessageHandler(HWND window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept; + + // Called when CreateAndShow is called, allowing subclass window-related + // setup. Subclasses should return false if setup fails. + virtual bool OnCreate(); + + // Called when Destroy is called. + virtual void OnDestroy(); + + private: + friend class WindowClassRegistrar; + + // OS callback called by message pump. Handles the WM_NCCREATE message which + // is passed when the non-client area is being created and enables automatic + // non-client DPI scaling so that the non-client area automatically + // responsponds to changes in DPI. All other messages are handled by + // MessageHandler. + static LRESULT CALLBACK WndProc(HWND const window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept; + + // Retrieves a class instance pointer for |window| + static Win32Window* GetThisFromHandle(HWND const window) noexcept; + + // Update the window frame's theme to match the system theme. + static void UpdateTheme(HWND const window); + + bool quit_on_close_ = false; + + // window handle for top level window. + HWND window_handle_ = nullptr; + + // window handle for hosted content. + HWND child_content_ = nullptr; +}; + +#endif // RUNNER_WIN32_WINDOW_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/pubspec.yaml b/packages/firebase_core/firebase_core/firebase_core/pubspec.yaml index ce38f84906e8..c942173c517b 100644 --- a/packages/firebase_core/firebase_core/firebase_core/pubspec.yaml +++ b/packages/firebase_core/firebase_core/firebase_core/pubspec.yaml @@ -24,6 +24,8 @@ flutter: platforms: linux: pluginClass: FirebaseCorePlugin + windows: + pluginClass: FirebaseCorePluginCApi ffigen: output: 'generated_bindings.dart' diff --git a/packages/firebase_core/firebase_core/firebase_core/windows/.gitignore b/packages/firebase_core/firebase_core/firebase_core/windows/.gitignore new file mode 100644 index 000000000000..b3eb2be169a5 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/windows/.gitignore @@ -0,0 +1,17 @@ +flutter/ + +# Visual Studio user-specific files. +*.suo +*.user +*.userosscache +*.sln.docstates + +# Visual Studio build-related files. +x64/ +x86/ + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!*.[Cc]ache/ diff --git a/packages/firebase_core/firebase_core/firebase_core/windows/CMakeLists.txt b/packages/firebase_core/firebase_core/firebase_core/windows/CMakeLists.txt new file mode 100644 index 000000000000..2f368229d6e9 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/windows/CMakeLists.txt @@ -0,0 +1,53 @@ +# The Flutter tooling requires that developers have a version of Visual Studio +# installed that includes CMake 3.14 or later. You should not increase this +# version, as doing so will cause the plugin to fail to compile for some +# customers of the plugin. +cmake_minimum_required(VERSION 3.14) + +# Project-level configuration. +set(PROJECT_NAME "firebase_core") +project(${PROJECT_NAME} LANGUAGES CXX) + +# This value is used when generating builds using this plugin, so it must +# not be changed +set(PLUGIN_NAME "firebase_core_plugin") + +# Any new source files that you add to the plugin should be added here. +list(APPEND PLUGIN_SOURCES + "firebase_core_plugin.cpp" + "firebase_core_plugin.h" +) + +# Define the plugin library target. Its name must not be changed (see comment +# on PLUGIN_NAME above). +add_library(${PLUGIN_NAME} SHARED + "include/firebase_core/firebase_core_plugin_c_api.h" + "firebase_core_plugin_c_api.cpp" + ${PLUGIN_SOURCES} +) + +# Apply a standard set of build settings that are configured in the +# application-level CMakeLists.txt. This can be removed for plugins that want +# full control over build settings. +apply_standard_settings(${PLUGIN_NAME}) + +# Symbols are hidden by default to reduce the chance of accidental conflicts +# between plugins. This should not be removed; any symbols that should be +# exported should be explicitly exported with the FLUTTER_PLUGIN_EXPORT macro. +set_target_properties(${PLUGIN_NAME} PROPERTIES + CXX_VISIBILITY_PRESET hidden) +target_compile_definitions(${PLUGIN_NAME} PRIVATE FLUTTER_PLUGIN_IMPL) + +# Source include directories and library dependencies. Add any plugin-specific +# dependencies here. +target_include_directories(${PLUGIN_NAME} INTERFACE + "${CMAKE_CURRENT_SOURCE_DIR}/include") +target_link_libraries(${PLUGIN_NAME} PRIVATE flutter flutter_wrapper_plugin) + +# List of absolute paths to libraries that should be bundled with the plugin. +# This list could contain prebuilt libraries, or libraries created by an +# external build triggered from this build file. +set(firebase_core_bundled_libraries + "" + PARENT_SCOPE +) diff --git a/packages/firebase_core/firebase_core/firebase_core/windows/firebase_core_plugin.cpp b/packages/firebase_core/firebase_core/firebase_core/windows/firebase_core_plugin.cpp new file mode 100644 index 000000000000..e92cfe868845 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/windows/firebase_core_plugin.cpp @@ -0,0 +1,59 @@ +#include "firebase_core_plugin.h" + +// This must be included before many other Windows headers. +#include + +// For getPlatformVersion; remove unless needed for your plugin implementation. +#include + +#include +#include +#include + +#include +#include + +namespace firebase_core { + +// static +void FirebaseCorePlugin::RegisterWithRegistrar( + flutter::PluginRegistrarWindows *registrar) { + auto channel = + std::make_unique>( + registrar->messenger(), "firebase_core", + &flutter::StandardMethodCodec::GetInstance()); + + auto plugin = std::make_unique(); + + channel->SetMethodCallHandler( + [plugin_pointer = plugin.get()](const auto &call, auto result) { + plugin_pointer->HandleMethodCall(call, std::move(result)); + }); + + registrar->AddPlugin(std::move(plugin)); +} + +FirebaseCorePlugin::FirebaseCorePlugin() {} + +FirebaseCorePlugin::~FirebaseCorePlugin() {} + +void FirebaseCorePlugin::HandleMethodCall( + const flutter::MethodCall &method_call, + std::unique_ptr> result) { + if (method_call.method_name().compare("getPlatformVersion") == 0) { + std::ostringstream version_stream; + version_stream << "Windows "; + if (IsWindows10OrGreater()) { + version_stream << "10+"; + } else if (IsWindows8OrGreater()) { + version_stream << "8"; + } else if (IsWindows7OrGreater()) { + version_stream << "7"; + } + result->Success(flutter::EncodableValue(version_stream.str())); + } else { + result->NotImplemented(); + } +} + +} // namespace firebase_core diff --git a/packages/firebase_core/firebase_core/firebase_core/windows/firebase_core_plugin.h b/packages/firebase_core/firebase_core/firebase_core/windows/firebase_core_plugin.h new file mode 100644 index 000000000000..fe99490af2c2 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/windows/firebase_core_plugin.h @@ -0,0 +1,32 @@ +#ifndef FLUTTER_PLUGIN_FIREBASE_CORE_PLUGIN_H_ +#define FLUTTER_PLUGIN_FIREBASE_CORE_PLUGIN_H_ + +#include +#include + +#include + +namespace firebase_core { + +class FirebaseCorePlugin : public flutter::Plugin { + public: + static void RegisterWithRegistrar(flutter::PluginRegistrarWindows *registrar); + + FirebaseCorePlugin(); + + virtual ~FirebaseCorePlugin(); + + // Disallow copy and assign. + FirebaseCorePlugin(const FirebaseCorePlugin&) = delete; + FirebaseCorePlugin& operator=(const FirebaseCorePlugin&) = delete; + + private: + // Called when a method is called on this plugin's channel from Dart. + void HandleMethodCall( + const flutter::MethodCall &method_call, + std::unique_ptr> result); +}; + +} // namespace firebase_core + +#endif // FLUTTER_PLUGIN_FIREBASE_CORE_PLUGIN_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/windows/firebase_core_plugin_c_api.cpp b/packages/firebase_core/firebase_core/firebase_core/windows/firebase_core_plugin_c_api.cpp new file mode 100644 index 000000000000..f0ca223fcf26 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/windows/firebase_core_plugin_c_api.cpp @@ -0,0 +1,12 @@ +#include "include/firebase_core/firebase_core_plugin_c_api.h" + +#include + +#include "firebase_core_plugin.h" + +void FirebaseCorePluginCApiRegisterWithRegistrar( + FlutterDesktopPluginRegistrarRef registrar) { + firebase_core::FirebaseCorePlugin::RegisterWithRegistrar( + flutter::PluginRegistrarManager::GetInstance() + ->GetRegistrar(registrar)); +} diff --git a/packages/firebase_core/firebase_core/firebase_core/windows/include/firebase_core/firebase_core_plugin_c_api.h b/packages/firebase_core/firebase_core/firebase_core/windows/include/firebase_core/firebase_core_plugin_c_api.h new file mode 100644 index 000000000000..4ef141db19bd --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/windows/include/firebase_core/firebase_core_plugin_c_api.h @@ -0,0 +1,23 @@ +#ifndef FLUTTER_PLUGIN_FIREBASE_CORE_PLUGIN_C_API_H_ +#define FLUTTER_PLUGIN_FIREBASE_CORE_PLUGIN_C_API_H_ + +#include + +#ifdef FLUTTER_PLUGIN_IMPL +#define FLUTTER_PLUGIN_EXPORT __declspec(dllexport) +#else +#define FLUTTER_PLUGIN_EXPORT __declspec(dllimport) +#endif + +#if defined(__cplusplus) +extern "C" { +#endif + +FLUTTER_PLUGIN_EXPORT void FirebaseCorePluginCApiRegisterWithRegistrar( + FlutterDesktopPluginRegistrarRef registrar); + +#if defined(__cplusplus) +} // extern "C" +#endif + +#endif // FLUTTER_PLUGIN_FIREBASE_CORE_PLUGIN_C_API_H_ From 73e93e21a9c3a33f35c15ef0a0695393525df82d Mon Sep 17 00:00:00 2001 From: Guillaume Bernos Date: Mon, 6 Mar 2023 15:24:46 +0100 Subject: [PATCH 10/65] add windows --- .../flutter/generated_plugin_registrant.cc | 14 +++++++++++ .../flutter/generated_plugin_registrant.h | 15 ++++++++++++ .../windows/flutter/generated_plugins.cmake | 24 +++++++++++++++++++ .../firebase_core/windows/CMakeLists.txt | 12 ++++++++++ 4 files changed, 65 insertions(+) create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/windows/flutter/generated_plugin_registrant.cc create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/windows/flutter/generated_plugin_registrant.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/windows/flutter/generated_plugins.cmake diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/flutter/generated_plugin_registrant.cc b/packages/firebase_core/firebase_core/firebase_core/example/windows/flutter/generated_plugin_registrant.cc new file mode 100644 index 000000000000..1a82e7d01dce --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/windows/flutter/generated_plugin_registrant.cc @@ -0,0 +1,14 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#include "generated_plugin_registrant.h" + +#include + +void RegisterPlugins(flutter::PluginRegistry* registry) { + FirebaseCorePluginCApiRegisterWithRegistrar( + registry->GetRegistrarForPlugin("FirebaseCorePluginCApi")); +} diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/flutter/generated_plugin_registrant.h b/packages/firebase_core/firebase_core/firebase_core/example/windows/flutter/generated_plugin_registrant.h new file mode 100644 index 000000000000..dc139d85a931 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/windows/flutter/generated_plugin_registrant.h @@ -0,0 +1,15 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#ifndef GENERATED_PLUGIN_REGISTRANT_ +#define GENERATED_PLUGIN_REGISTRANT_ + +#include + +// Registers Flutter plugins. +void RegisterPlugins(flutter::PluginRegistry* registry); + +#endif // GENERATED_PLUGIN_REGISTRANT_ diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/flutter/generated_plugins.cmake b/packages/firebase_core/firebase_core/firebase_core/example/windows/flutter/generated_plugins.cmake new file mode 100644 index 000000000000..fa8a39bab15e --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/windows/flutter/generated_plugins.cmake @@ -0,0 +1,24 @@ +# +# Generated file, do not edit. +# + +list(APPEND FLUTTER_PLUGIN_LIST + firebase_core +) + +list(APPEND FLUTTER_FFI_PLUGIN_LIST +) + +set(PLUGIN_BUNDLED_LIBRARIES) + +foreach(plugin ${FLUTTER_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/windows plugins/${plugin}) + target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) + list(APPEND PLUGIN_BUNDLED_LIBRARIES $) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) +endforeach(plugin) + +foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/windows plugins/${ffi_plugin}) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries}) +endforeach(ffi_plugin) diff --git a/packages/firebase_core/firebase_core/firebase_core/windows/CMakeLists.txt b/packages/firebase_core/firebase_core/firebase_core/windows/CMakeLists.txt index 2f368229d6e9..c6ef1ebf3727 100644 --- a/packages/firebase_core/firebase_core/firebase_core/windows/CMakeLists.txt +++ b/packages/firebase_core/firebase_core/firebase_core/windows/CMakeLists.txt @@ -26,6 +26,18 @@ add_library(${PLUGIN_NAME} SHARED ${PLUGIN_SOURCES} ) +# Add Firebase libraries to the target using the function from the SDK. +add_subdirectory(${FIREBASE_CPP_SDK_DIR} bin/ EXCLUDE_FROM_ALL) + +# The Firebase C++ library `firebase_app` is required, +# and it must always be listed last. + +# Add the Firebase SDKs for the products you want to use in your app +# For example, to use Firebase Authentication and Firebase Realtime Database +set(firebase_libs firebase_auth firebase_app) +target_link_libraries(${target_name} "${firebase_libs}") + + # Apply a standard set of build settings that are configured in the # application-level CMakeLists.txt. This can be removed for plugins that want # full control over build settings. From 29700cec9dbc56d5694cb9a5bbf3e5f3e3fccfa6 Mon Sep 17 00:00:00 2001 From: Guillaume Bernos Date: Mon, 6 Mar 2023 16:15:41 +0100 Subject: [PATCH 11/65] add windows --- .../firebase_core/windows/CMakeLists.txt | 18 +++++++----------- 1 file changed, 7 insertions(+), 11 deletions(-) diff --git a/packages/firebase_core/firebase_core/firebase_core/windows/CMakeLists.txt b/packages/firebase_core/firebase_core/firebase_core/windows/CMakeLists.txt index c6ef1ebf3727..bd3c3fdc2bdb 100644 --- a/packages/firebase_core/firebase_core/firebase_core/windows/CMakeLists.txt +++ b/packages/firebase_core/firebase_core/firebase_core/windows/CMakeLists.txt @@ -26,17 +26,6 @@ add_library(${PLUGIN_NAME} SHARED ${PLUGIN_SOURCES} ) -# Add Firebase libraries to the target using the function from the SDK. -add_subdirectory(${FIREBASE_CPP_SDK_DIR} bin/ EXCLUDE_FROM_ALL) - -# The Firebase C++ library `firebase_app` is required, -# and it must always be listed last. - -# Add the Firebase SDKs for the products you want to use in your app -# For example, to use Firebase Authentication and Firebase Realtime Database -set(firebase_libs firebase_auth firebase_app) -target_link_libraries(${target_name} "${firebase_libs}") - # Apply a standard set of build settings that are configured in the # application-level CMakeLists.txt. This can be removed for plugins that want @@ -52,6 +41,13 @@ target_compile_definitions(${PLUGIN_NAME} PRIVATE FLUTTER_PLUGIN_IMPL) # Source include directories and library dependencies. Add any plugin-specific # dependencies here. + +add_subdirectory(${FIREBASE_CPP_SDK_DIR} bin/ EXCLUDE_FROM_ALL) +target_include_directories(${PLUGIN_NAME} INTERFACE + "${FIREBASE_CPP_SDK_DIR}/include") +set(firebase_libs firebase_auth firebase_database firebase_app) +target_link_libraries(${PLUGIN_NAME} PRIVATE "${firebase_libs}") + target_include_directories(${PLUGIN_NAME} INTERFACE "${CMAKE_CURRENT_SOURCE_DIR}/include") target_link_libraries(${PLUGIN_NAME} PRIVATE flutter flutter_wrapper_plugin) From e9c3cbb74069c493e0a7c061bb3b340101b075bf Mon Sep 17 00:00:00 2001 From: Guillaume Bernos Date: Mon, 6 Mar 2023 17:09:15 +0100 Subject: [PATCH 12/65] add windows --- .../example/bin/CMakeFiles/generate.stamp | 1 + .../bin/CMakeFiles/generate.stamp.depend | 5 + .../firebase_core/example/bin/INSTALL.vcxproj | 165 ++++++++++++++++++ .../example/bin/INSTALL.vcxproj.filters | 13 ++ .../example/bin/cmake_install.cmake | 34 ++++ .../runner/google-services-desktop.json | 37 ++++ .../firebase_core/windows/CMakeLists.txt | 4 +- .../windows/firebase_core_plugin.cpp | 4 + 8 files changed, 261 insertions(+), 2 deletions(-) create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/bin/CMakeFiles/generate.stamp create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/bin/CMakeFiles/generate.stamp.depend create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/bin/INSTALL.vcxproj create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/bin/INSTALL.vcxproj.filters create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/bin/cmake_install.cmake create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/windows/runner/google-services-desktop.json diff --git a/packages/firebase_core/firebase_core/firebase_core/example/bin/CMakeFiles/generate.stamp b/packages/firebase_core/firebase_core/firebase_core/example/bin/CMakeFiles/generate.stamp new file mode 100644 index 000000000000..9b5f49fa9f14 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/bin/CMakeFiles/generate.stamp @@ -0,0 +1 @@ +# CMake generation timestamp file for this directory. diff --git a/packages/firebase_core/firebase_core/firebase_core/example/bin/CMakeFiles/generate.stamp.depend b/packages/firebase_core/firebase_core/firebase_core/example/bin/CMakeFiles/generate.stamp.depend new file mode 100644 index 000000000000..5b8da13f857a --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/bin/CMakeFiles/generate.stamp.depend @@ -0,0 +1,5 @@ +# CMake generation dependency list for this directory. +C:/Program Files/Microsoft Visual Studio/2022/Community/Common7/IDE/CommonExtensions/Microsoft/CMake/CMake/share/cmake-3.25/Modules/FindPackageHandleStandardArgs.cmake +C:/Program Files/Microsoft Visual Studio/2022/Community/Common7/IDE/CommonExtensions/Microsoft/CMake/CMake/share/cmake-3.25/Modules/FindPackageMessage.cmake +C:/Program Files/Microsoft Visual Studio/2022/Community/Common7/IDE/CommonExtensions/Microsoft/CMake/CMake/share/cmake-3.25/Modules/FindPkgConfig.cmake +C:/Users/guill/Downloads/firebase_cpp_sdk_10.5.0/firebase_cpp_sdk/CMakeLists.txt diff --git a/packages/firebase_core/firebase_core/firebase_core/example/bin/INSTALL.vcxproj b/packages/firebase_core/firebase_core/firebase_core/example/bin/INSTALL.vcxproj new file mode 100644 index 000000000000..05091bebad78 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/bin/INSTALL.vcxproj @@ -0,0 +1,165 @@ + + + + x64 + + + + Debug + x64 + + + Profile + x64 + + + Release + x64 + + + + {B2284ACE-B264-3C77-ADAD-5516EBC85159} + Win32Proj + 10.0.22000.0 + x64 + INSTALL + NoUpgrade + + + + Utility + MultiByte + v143 + + + Utility + MultiByte + v143 + + + Utility + MultiByte + v143 + + + + + + + + + + <_ProjectFileVersion>10.0.20506.1 + $(Platform)\$(Configuration)\$(ProjectName)\ + $(Platform)\$(Configuration)\$(ProjectName)\ + $(Platform)\$(Configuration)\$(ProjectName)\ + + + + Always + + setlocal +"C:\Program Files\Microsoft Visual Studio\2022\Community\Common7\IDE\CommonExtensions\Microsoft\CMake\CMake\bin\cmake.exe" -DBUILD_TYPE=$(Configuration) -P cmake_install.cmake +if %errorlevel% neq 0 goto :cmEnd +:cmEnd +endlocal & call :cmErrorLevel %errorlevel% & goto :cmDone +:cmErrorLevel +exit /b %1 +:cmDone +if %errorlevel% neq 0 goto :VCEnd + + + + + Always + + setlocal +"C:\Program Files\Microsoft Visual Studio\2022\Community\Common7\IDE\CommonExtensions\Microsoft\CMake\CMake\bin\cmake.exe" -DBUILD_TYPE=$(Configuration) -P cmake_install.cmake +if %errorlevel% neq 0 goto :cmEnd +:cmEnd +endlocal & call :cmErrorLevel %errorlevel% & goto :cmDone +:cmErrorLevel +exit /b %1 +:cmDone +if %errorlevel% neq 0 goto :VCEnd + + + + + Always + + setlocal +"C:\Program Files\Microsoft Visual Studio\2022\Community\Common7\IDE\CommonExtensions\Microsoft\CMake\CMake\bin\cmake.exe" -DBUILD_TYPE=$(Configuration) -P cmake_install.cmake +if %errorlevel% neq 0 goto :cmEnd +:cmEnd +endlocal & call :cmErrorLevel %errorlevel% & goto :cmDone +:cmErrorLevel +exit /b %1 +:cmDone +if %errorlevel% neq 0 goto :VCEnd + + + + + + setlocal +cd . +if %errorlevel% neq 0 goto :cmEnd +:cmEnd +endlocal & call :cmErrorLevel %errorlevel% & goto :cmDone +:cmErrorLevel +exit /b %1 +:cmDone +if %errorlevel% neq 0 goto :VCEnd + %(AdditionalInputs) + C:\Users\guill\Developer\flutterfire\packages\firebase_core\firebase_core\firebase_core\example\bin\CMakeFiles\INSTALL_force + false + false + + setlocal +cd . +if %errorlevel% neq 0 goto :cmEnd +:cmEnd +endlocal & call :cmErrorLevel %errorlevel% & goto :cmDone +:cmErrorLevel +exit /b %1 +:cmDone +if %errorlevel% neq 0 goto :VCEnd + %(AdditionalInputs) + C:\Users\guill\Developer\flutterfire\packages\firebase_core\firebase_core\firebase_core\example\bin\CMakeFiles\INSTALL_force + false + false + + setlocal +cd . +if %errorlevel% neq 0 goto :cmEnd +:cmEnd +endlocal & call :cmErrorLevel %errorlevel% & goto :cmDone +:cmErrorLevel +exit /b %1 +:cmDone +if %errorlevel% neq 0 goto :VCEnd + %(AdditionalInputs) + C:\Users\guill\Developer\flutterfire\packages\firebase_core\firebase_core\firebase_core\example\bin\CMakeFiles\INSTALL_force + false + false + + + + + {DC08768F-F57C-313C-94F0-E16194F54223} + ZERO_CHECK + false + Never + + + {DF648812-5598-379C-A5B5-8A3EAC6BC5B0} + ALL_BUILD + false + Never + + + + + + \ No newline at end of file diff --git a/packages/firebase_core/firebase_core/firebase_core/example/bin/INSTALL.vcxproj.filters b/packages/firebase_core/firebase_core/firebase_core/example/bin/INSTALL.vcxproj.filters new file mode 100644 index 000000000000..69fed1abf535 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/bin/INSTALL.vcxproj.filters @@ -0,0 +1,13 @@ + + + + + CMake Rules + + + + + {EAE753BC-CF7B-3081-8331-9EFFB2F8D8A5} + + + diff --git a/packages/firebase_core/firebase_core/firebase_core/example/bin/cmake_install.cmake b/packages/firebase_core/firebase_core/firebase_core/example/bin/cmake_install.cmake new file mode 100644 index 000000000000..8cf9b6c06b96 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/bin/cmake_install.cmake @@ -0,0 +1,34 @@ +# Install script for directory: C:/Users/guill/Downloads/firebase_cpp_sdk_10.5.0/firebase_cpp_sdk + +# Set the install prefix +if(NOT DEFINED CMAKE_INSTALL_PREFIX) + set(CMAKE_INSTALL_PREFIX "$") +endif() +string(REGEX REPLACE "/$" "" CMAKE_INSTALL_PREFIX "${CMAKE_INSTALL_PREFIX}") + +# Set the install configuration name. +if(NOT DEFINED CMAKE_INSTALL_CONFIG_NAME) + if(BUILD_TYPE) + string(REGEX REPLACE "^[^A-Za-z0-9_]+" "" + CMAKE_INSTALL_CONFIG_NAME "${BUILD_TYPE}") + else() + set(CMAKE_INSTALL_CONFIG_NAME "Release") + endif() + message(STATUS "Install configuration: \"${CMAKE_INSTALL_CONFIG_NAME}\"") +endif() + +# Set the component getting installed. +if(NOT CMAKE_INSTALL_COMPONENT) + if(COMPONENT) + message(STATUS "Install component: \"${COMPONENT}\"") + set(CMAKE_INSTALL_COMPONENT "${COMPONENT}") + else() + set(CMAKE_INSTALL_COMPONENT) + endif() +endif() + +# Is this installation the result of a crosscompile? +if(NOT DEFINED CMAKE_CROSSCOMPILING) + set(CMAKE_CROSSCOMPILING "FALSE") +endif() + diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/google-services-desktop.json b/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/google-services-desktop.json new file mode 100644 index 000000000000..a3bf216f4de0 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/google-services-desktop.json @@ -0,0 +1,37 @@ +{ + "project_info": { + "project_number": "406099696497", + "firebase_url": "https://flutterfire-e2e-tests-default-rtdb.europe-west1.firebasedatabase.app", + "project_id": "flutterfire-e2e-tests", + "storage_bucket": "flutterfire-e2e-tests.appspot.com" + }, + "client": [ + { + "client_info": { + "mobilesdk_app_id": "1:406099696497:ios:58cbc26aca8e5cf83574d0", + "android_client_info": { + "package_name": "io.flutter.plugins.firebase.auth.example" + } + }, + "oauth_client": [ + { + "client_id": "406099696497-134k3722m01rtrsklhf3b7k8sqa5r7in.apps.googleusercontent.com" + } + ], + "api_key": [ + { + "current_key": "AIzaSyDooSUGSf63Ghq02_iIhtnmwMDs4HlWS6c" + } + ], + "services": { + "analytics_service": { + "status": 0 + }, + "appinvite_service": { + "status": 1 + } + } + } + ], + "configuration_version": "1" +} \ No newline at end of file diff --git a/packages/firebase_core/firebase_core/firebase_core/windows/CMakeLists.txt b/packages/firebase_core/firebase_core/firebase_core/windows/CMakeLists.txt index bd3c3fdc2bdb..e75e1384506a 100644 --- a/packages/firebase_core/firebase_core/firebase_core/windows/CMakeLists.txt +++ b/packages/firebase_core/firebase_core/firebase_core/windows/CMakeLists.txt @@ -41,8 +41,8 @@ target_compile_definitions(${PLUGIN_NAME} PRIVATE FLUTTER_PLUGIN_IMPL) # Source include directories and library dependencies. Add any plugin-specific # dependencies here. - -add_subdirectory(${FIREBASE_CPP_SDK_DIR} bin/ EXCLUDE_FROM_ALL) +set(MSVC_RUNTIME_MODE MD) +add_subdirectory(C:/Users/guill/Downloads/firebase_cpp_sdk_10.5.0/firebase_cpp_sdk C:/Users/guill/Developer/flutterfire/packages/firebase_core/firebase_core/firebase_core/example/bin/ EXCLUDE_FROM_ALL) target_include_directories(${PLUGIN_NAME} INTERFACE "${FIREBASE_CPP_SDK_DIR}/include") set(firebase_libs firebase_auth firebase_database firebase_app) diff --git a/packages/firebase_core/firebase_core/firebase_core/windows/firebase_core_plugin.cpp b/packages/firebase_core/firebase_core/firebase_core/windows/firebase_core_plugin.cpp index e92cfe868845..7dd2b9945a72 100644 --- a/packages/firebase_core/firebase_core/firebase_core/windows/firebase_core_plugin.cpp +++ b/packages/firebase_core/firebase_core/firebase_core/windows/firebase_core_plugin.cpp @@ -2,6 +2,7 @@ // This must be included before many other Windows headers. #include +#include "firebase/app.h" // For getPlatformVersion; remove unless needed for your plugin implementation. #include @@ -12,6 +13,7 @@ #include #include +using ::firebase::App; namespace firebase_core { @@ -41,6 +43,8 @@ void FirebaseCorePlugin::HandleMethodCall( const flutter::MethodCall &method_call, std::unique_ptr> result) { if (method_call.method_name().compare("getPlatformVersion") == 0) { + App* app = App::Create(); + std::cout << static_cast(reinterpret_cast(app)); std::ostringstream version_stream; version_stream << "Windows "; if (IsWindows10OrGreater()) { From 9e7fdcf7b1e5d75a81a7d3291bece72159e5b837 Mon Sep 17 00:00:00 2001 From: Guillaume Bernos Date: Mon, 6 Mar 2023 17:19:28 +0100 Subject: [PATCH 13/65] right position for google service file --- .../example/google-services-desktop.json | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/google-services-desktop.json diff --git a/packages/firebase_core/firebase_core/firebase_core/example/google-services-desktop.json b/packages/firebase_core/firebase_core/firebase_core/example/google-services-desktop.json new file mode 100644 index 000000000000..a3bf216f4de0 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/google-services-desktop.json @@ -0,0 +1,37 @@ +{ + "project_info": { + "project_number": "406099696497", + "firebase_url": "https://flutterfire-e2e-tests-default-rtdb.europe-west1.firebasedatabase.app", + "project_id": "flutterfire-e2e-tests", + "storage_bucket": "flutterfire-e2e-tests.appspot.com" + }, + "client": [ + { + "client_info": { + "mobilesdk_app_id": "1:406099696497:ios:58cbc26aca8e5cf83574d0", + "android_client_info": { + "package_name": "io.flutter.plugins.firebase.auth.example" + } + }, + "oauth_client": [ + { + "client_id": "406099696497-134k3722m01rtrsklhf3b7k8sqa5r7in.apps.googleusercontent.com" + } + ], + "api_key": [ + { + "current_key": "AIzaSyDooSUGSf63Ghq02_iIhtnmwMDs4HlWS6c" + } + ], + "services": { + "analytics_service": { + "status": 0 + }, + "appinvite_service": { + "status": 1 + } + } + } + ], + "configuration_version": "1" +} \ No newline at end of file From f5517dc9bc119c926d5e7d714f34746e70e41804 Mon Sep 17 00:00:00 2001 From: Guillaume Bernos Date: Mon, 6 Mar 2023 17:21:03 +0100 Subject: [PATCH 14/65] add windows --- .../firebase_core/firebase_core/windows/CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/firebase_core/firebase_core/firebase_core/windows/CMakeLists.txt b/packages/firebase_core/firebase_core/firebase_core/windows/CMakeLists.txt index e75e1384506a..35c68f4a1910 100644 --- a/packages/firebase_core/firebase_core/firebase_core/windows/CMakeLists.txt +++ b/packages/firebase_core/firebase_core/firebase_core/windows/CMakeLists.txt @@ -42,7 +42,7 @@ target_compile_definitions(${PLUGIN_NAME} PRIVATE FLUTTER_PLUGIN_IMPL) # Source include directories and library dependencies. Add any plugin-specific # dependencies here. set(MSVC_RUNTIME_MODE MD) -add_subdirectory(C:/Users/guill/Downloads/firebase_cpp_sdk_10.5.0/firebase_cpp_sdk C:/Users/guill/Developer/flutterfire/packages/firebase_core/firebase_core/firebase_core/example/bin/ EXCLUDE_FROM_ALL) +add_subdirectory(${FIREBASE_CPP_SDK_DIR} bin/ EXCLUDE_FROM_ALL) target_include_directories(${PLUGIN_NAME} INTERFACE "${FIREBASE_CPP_SDK_DIR}/include") set(firebase_libs firebase_auth firebase_database firebase_app) From e1b75caa8541b464e5d2095fcce5744ecc41e0e2 Mon Sep 17 00:00:00 2001 From: Guillaume Bernos Date: Tue, 14 Mar 2023 11:04:55 +0100 Subject: [PATCH 15/65] feat(core, windows): add windows support to firebase_core --- .../example/google-services-desktop.json | 0 .../firebase_core/firebase_core/.gitignore | 30 - .../firebase_core/firebase_core/.metadata | 30 - .../firebase_core/.vscode/settings.json | 3 - .../firebase_core/firebase_core/CHANGELOG.md | 3 - .../firebase_core/GoogleService-Info.plist | 38 - .../firebase_core/firebase_core/LICENSE | 1 - .../firebase_core/firebase_core/README.md | 15 - .../firebase_core/analysis_options.yaml | 4 - .../firebase_core/example/.gitignore | 44 - .../firebase_core/example/README.md | 16 - .../example/analysis_options.yaml | 29 - .../example/bin/CMakeFiles/generate.stamp | 1 - .../bin/CMakeFiles/generate.stamp.depend | 5 - .../firebase_core/example/bin/INSTALL.vcxproj | 165 --- .../example/bin/INSTALL.vcxproj.filters | 13 - .../example/bin/cmake_install.cmake | 34 - .../firebase_core/example/lib/main.dart | 63 - .../firebase_core/example/linux/.gitignore | 1 - .../example/linux/CMakeLists.txt | 150 --- .../example/linux/flutter/CMakeLists.txt | 88 -- .../flutter/generated_plugin_registrant.cc | 15 - .../flutter/generated_plugin_registrant.h | 15 - .../linux/flutter/generated_plugins.cmake | 24 - .../firebase_core/example/linux/main.cc | 6 - .../example/linux/my_application.cc | 104 -- .../example/linux/my_application.h | 18 - .../firebase_core/example/pubspec.yaml | 83 -- .../example/test/widget_test.dart | 27 - .../firebase_core/example/windows/.gitignore | 17 - .../example/windows/CMakeLists.txt | 101 -- .../example/windows/flutter/CMakeLists.txt | 104 -- .../flutter/generated_plugin_registrant.cc | 14 - .../flutter/generated_plugin_registrant.h | 15 - .../windows/flutter/generated_plugins.cmake | 24 - .../example/windows/runner/CMakeLists.txt | 40 - .../example/windows/runner/Runner.rc | 121 -- .../example/windows/runner/flutter_window.cpp | 66 - .../example/windows/runner/flutter_window.h | 33 - .../runner/google-services-desktop.json | 37 - .../example/windows/runner/main.cpp | 43 - .../example/windows/runner/resource.h | 16 - .../windows/runner/resources/app_icon.ico | Bin 33772 -> 0 bytes .../windows/runner/runner.exe.manifest | 20 - .../example/windows/runner/utils.cpp | 64 - .../example/windows/runner/utils.h | 19 - .../example/windows/runner/win32_window.cpp | 288 ---- .../example/windows/runner/win32_window.h | 102 -- .../firebase_core/firebase/admob.h | 215 --- .../firebase/admob/banner_view.h | 427 ------ .../firebase/admob/interstitial_ad.h | 259 ---- .../firebase/admob/native_express_ad_view.h | 446 ------ .../firebase/admob/rewarded_video.h | 407 ------ .../firebase_core/firebase/admob/types.h | 244 ---- .../firebase_core/firebase/analytics.h | 569 -------- .../firebase/analytics/event_names.h | 472 ------- .../firebase/analytics/parameter_names.h | 755 ----------- .../firebase/analytics/user_property_names.h | 50 - .../firebase_core/firebase/app.h | 787 ----------- .../firebase_core/firebase/auth.h | 939 ------------- .../firebase_core/firebase/auth/credential.h | 633 --------- .../firebase_core/firebase/auth/types.h | 473 ------- .../firebase_core/firebase/auth/user.h | 501 ------- .../firebase_core/firebase/database.h | 199 --- .../firebase_core/firebase/database/common.h | 83 -- .../firebase/database/data_snapshot.h | 205 --- .../firebase/database/database_reference.h | 477 ------- .../firebase/database/disconnection.h | 156 --- .../firebase/database/listener.h | 112 -- .../firebase/database/mutable_data.h | 165 --- .../firebase_core/firebase/database/query.h | 358 ----- .../firebase/database/transaction.h | 102 -- .../firebase_core/firebase/dynamic_links.h | 117 -- .../firebase/dynamic_links/components.h | 336 ----- .../firebase_core/firebase/firestore.h | 458 ------- .../firebase/firestore/collection_reference.h | 183 --- .../firebase/firestore/document_change.h | 203 --- .../firebase/firestore/document_reference.h | 351 ----- .../firebase/firestore/document_snapshot.h | 297 ---- .../firebase/firestore/field_path.h | 205 --- .../firebase/firestore/field_value.h | 436 ------ .../firebase/firestore/firestore_errors.h | 116 -- .../firebase/firestore/firestore_version.h | 29 - .../firebase/firestore/geo_point.h | 120 -- .../firestore/listener_registration.h | 130 -- .../firestore/load_bundle_task_progress.h | 101 -- .../firebase/firestore/map_field_value.h | 37 - .../firebase/firestore/metadata_changes.h | 41 - .../firebase_core/firebase/firestore/query.h | 683 ---------- .../firebase/firestore/query_snapshot.h | 194 --- .../firebase/firestore/set_options.h | 161 --- .../firebase/firestore/settings.h | 247 ---- .../firebase/firestore/snapshot_metadata.h | 159 --- .../firebase_core/firebase/firestore/source.h | 59 - .../firebase/firestore/timestamp.h | 252 ---- .../firebase/firestore/transaction.h | 143 -- .../firebase/firestore/transaction_options.h | 137 -- .../firebase/firestore/write_batch.h | 188 --- .../firebase_core/firebase/functions.h | 115 -- .../firebase/functions/callable_reference.h | 124 -- .../firebase/functions/callable_result.h | 96 -- .../firebase_core/firebase/functions/common.h | 202 --- .../firebase_core/firebase/future.h | 533 -------- .../firebase_core/firebase/gma.h | 207 --- .../firebase_core/firebase/gma/ad_view.h | 267 ---- .../firebase/gma/interstitial_ad.h | 128 -- .../firebase_core/firebase/gma/rewarded_ad.h | 152 --- .../firebase_core/firebase/gma/types.h | 939 ------------- .../firebase_core/firebase/installations.h | 123 -- .../firebase_core/firebase/internal/common.h | 128 -- .../firebase/internal/future_impl.h | 359 ----- .../firebase_core/firebase/internal/mutex.h | 100 -- .../firebase/internal/platform.h | 110 -- .../firebase/internal/type_traits.h | 134 -- .../firebase_core/firebase/log.h | 54 - .../firebase_core/firebase/messaging.h | 728 ---------- .../firebase_core/firebase/remote_config.h | 526 -------- .../firebase_core/firebase/storage.h | 161 --- .../firebase_core/firebase/storage/common.h | 62 - .../firebase/storage/controller.h | 146 -- .../firebase_core/firebase/storage/listener.h | 74 - .../firebase_core/firebase/storage/metadata.h | 276 ---- .../firebase/storage/storage_reference.h | 361 ----- .../firebase_core/firebase/util.h | 101 -- .../firebase_core/firebase/variant.h | 1197 ----------------- .../firebase_core/firebase/version.h | 68 - .../generate_xml_from_google_services_json.py | 496 ------- .../firebase_core/generated_bindings.dart | 26 - .../google-services-desktop.json | 37 - .../firebase_core/lib/firebase_core.dart | 8 - .../lib/firebase_core_method_channel.dart | 17 - .../lib/firebase_core_platform_interface.dart | 29 - .../firebase_core/linux/CMakeLists.txt | 47 - .../linux/firebase_core_plugin.cc | 70 - .../firebase_core/firebase_core_plugin.h | 26 - .../firebase_core/firebase_core/pubspec.yaml | 36 - .../firebase_core_method_channel_test.dart | 24 - .../test/firebase_core_test.dart | 29 - .../firebase_core/firebase_core/pubspec.yaml | 3 + .../{firebase_core => }/windows/.gitignore | 0 .../windows/CMakeLists.txt | 0 .../windows/firebase_core_plugin.cpp | 0 .../windows/firebase_core_plugin.h | 0 .../windows/firebase_core_plugin_c_api.cpp | 0 .../firebase_core_plugin_c_api.h | 0 145 files changed, 3 insertions(+), 24882 deletions(-) rename packages/firebase_core/firebase_core/{firebase_core => }/example/google-services-desktop.json (100%) delete mode 100644 packages/firebase_core/firebase_core/firebase_core/.gitignore delete mode 100644 packages/firebase_core/firebase_core/firebase_core/.metadata delete mode 100644 packages/firebase_core/firebase_core/firebase_core/.vscode/settings.json delete mode 100644 packages/firebase_core/firebase_core/firebase_core/CHANGELOG.md delete mode 100644 packages/firebase_core/firebase_core/firebase_core/GoogleService-Info.plist delete mode 100644 packages/firebase_core/firebase_core/firebase_core/LICENSE delete mode 100644 packages/firebase_core/firebase_core/firebase_core/README.md delete mode 100644 packages/firebase_core/firebase_core/firebase_core/analysis_options.yaml delete mode 100644 packages/firebase_core/firebase_core/firebase_core/example/.gitignore delete mode 100644 packages/firebase_core/firebase_core/firebase_core/example/README.md delete mode 100644 packages/firebase_core/firebase_core/firebase_core/example/analysis_options.yaml delete mode 100644 packages/firebase_core/firebase_core/firebase_core/example/bin/CMakeFiles/generate.stamp delete mode 100644 packages/firebase_core/firebase_core/firebase_core/example/bin/CMakeFiles/generate.stamp.depend delete mode 100644 packages/firebase_core/firebase_core/firebase_core/example/bin/INSTALL.vcxproj delete mode 100644 packages/firebase_core/firebase_core/firebase_core/example/bin/INSTALL.vcxproj.filters delete mode 100644 packages/firebase_core/firebase_core/firebase_core/example/bin/cmake_install.cmake delete mode 100644 packages/firebase_core/firebase_core/firebase_core/example/lib/main.dart delete mode 100644 packages/firebase_core/firebase_core/firebase_core/example/linux/.gitignore delete mode 100644 packages/firebase_core/firebase_core/firebase_core/example/linux/CMakeLists.txt delete mode 100644 packages/firebase_core/firebase_core/firebase_core/example/linux/flutter/CMakeLists.txt delete mode 100644 packages/firebase_core/firebase_core/firebase_core/example/linux/flutter/generated_plugin_registrant.cc delete mode 100644 packages/firebase_core/firebase_core/firebase_core/example/linux/flutter/generated_plugin_registrant.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/example/linux/flutter/generated_plugins.cmake delete mode 100644 packages/firebase_core/firebase_core/firebase_core/example/linux/main.cc delete mode 100644 packages/firebase_core/firebase_core/firebase_core/example/linux/my_application.cc delete mode 100644 packages/firebase_core/firebase_core/firebase_core/example/linux/my_application.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/example/pubspec.yaml delete mode 100644 packages/firebase_core/firebase_core/firebase_core/example/test/widget_test.dart delete mode 100644 packages/firebase_core/firebase_core/firebase_core/example/windows/.gitignore delete mode 100644 packages/firebase_core/firebase_core/firebase_core/example/windows/CMakeLists.txt delete mode 100644 packages/firebase_core/firebase_core/firebase_core/example/windows/flutter/CMakeLists.txt delete mode 100644 packages/firebase_core/firebase_core/firebase_core/example/windows/flutter/generated_plugin_registrant.cc delete mode 100644 packages/firebase_core/firebase_core/firebase_core/example/windows/flutter/generated_plugin_registrant.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/example/windows/flutter/generated_plugins.cmake delete mode 100644 packages/firebase_core/firebase_core/firebase_core/example/windows/runner/CMakeLists.txt delete mode 100644 packages/firebase_core/firebase_core/firebase_core/example/windows/runner/Runner.rc delete mode 100644 packages/firebase_core/firebase_core/firebase_core/example/windows/runner/flutter_window.cpp delete mode 100644 packages/firebase_core/firebase_core/firebase_core/example/windows/runner/flutter_window.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/example/windows/runner/google-services-desktop.json delete mode 100644 packages/firebase_core/firebase_core/firebase_core/example/windows/runner/main.cpp delete mode 100644 packages/firebase_core/firebase_core/firebase_core/example/windows/runner/resource.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/example/windows/runner/resources/app_icon.ico delete mode 100644 packages/firebase_core/firebase_core/firebase_core/example/windows/runner/runner.exe.manifest delete mode 100644 packages/firebase_core/firebase_core/firebase_core/example/windows/runner/utils.cpp delete mode 100644 packages/firebase_core/firebase_core/firebase_core/example/windows/runner/utils.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/example/windows/runner/win32_window.cpp delete mode 100644 packages/firebase_core/firebase_core/firebase_core/example/windows/runner/win32_window.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/admob.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/admob/banner_view.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/admob/interstitial_ad.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/admob/native_express_ad_view.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/admob/rewarded_video.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/admob/types.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/analytics.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/analytics/event_names.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/analytics/parameter_names.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/analytics/user_property_names.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/app.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/auth.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/auth/credential.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/auth/types.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/auth/user.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/database.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/database/common.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/database/data_snapshot.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/database/database_reference.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/database/disconnection.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/database/listener.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/database/mutable_data.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/database/query.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/database/transaction.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/dynamic_links.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/dynamic_links/components.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/collection_reference.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/document_change.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/document_reference.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/document_snapshot.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/field_path.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/field_value.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/firestore_errors.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/firestore_version.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/geo_point.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/listener_registration.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/load_bundle_task_progress.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/map_field_value.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/metadata_changes.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/query.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/query_snapshot.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/set_options.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/settings.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/snapshot_metadata.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/source.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/timestamp.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/transaction.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/transaction_options.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/write_batch.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/functions.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/functions/callable_reference.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/functions/callable_result.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/functions/common.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/future.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/gma.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/gma/ad_view.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/gma/interstitial_ad.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/gma/rewarded_ad.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/gma/types.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/installations.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/internal/common.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/internal/future_impl.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/internal/mutex.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/internal/platform.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/internal/type_traits.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/log.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/messaging.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/remote_config.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/storage.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/storage/common.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/storage/controller.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/storage/listener.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/storage/metadata.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/storage/storage_reference.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/util.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/variant.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/version.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/generate_xml_from_google_services_json.py delete mode 100644 packages/firebase_core/firebase_core/firebase_core/generated_bindings.dart delete mode 100644 packages/firebase_core/firebase_core/firebase_core/google-services-desktop.json delete mode 100644 packages/firebase_core/firebase_core/firebase_core/lib/firebase_core.dart delete mode 100644 packages/firebase_core/firebase_core/firebase_core/lib/firebase_core_method_channel.dart delete mode 100644 packages/firebase_core/firebase_core/firebase_core/lib/firebase_core_platform_interface.dart delete mode 100644 packages/firebase_core/firebase_core/firebase_core/linux/CMakeLists.txt delete mode 100644 packages/firebase_core/firebase_core/firebase_core/linux/firebase_core_plugin.cc delete mode 100644 packages/firebase_core/firebase_core/firebase_core/linux/include/firebase_core/firebase_core_plugin.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/pubspec.yaml delete mode 100644 packages/firebase_core/firebase_core/firebase_core/test/firebase_core_method_channel_test.dart delete mode 100644 packages/firebase_core/firebase_core/firebase_core/test/firebase_core_test.dart rename packages/firebase_core/firebase_core/{firebase_core => }/windows/.gitignore (100%) rename packages/firebase_core/firebase_core/{firebase_core => }/windows/CMakeLists.txt (100%) rename packages/firebase_core/firebase_core/{firebase_core => }/windows/firebase_core_plugin.cpp (100%) rename packages/firebase_core/firebase_core/{firebase_core => }/windows/firebase_core_plugin.h (100%) rename packages/firebase_core/firebase_core/{firebase_core => }/windows/firebase_core_plugin_c_api.cpp (100%) rename packages/firebase_core/firebase_core/{firebase_core => }/windows/include/firebase_core/firebase_core_plugin_c_api.h (100%) diff --git a/packages/firebase_core/firebase_core/firebase_core/example/google-services-desktop.json b/packages/firebase_core/firebase_core/example/google-services-desktop.json similarity index 100% rename from packages/firebase_core/firebase_core/firebase_core/example/google-services-desktop.json rename to packages/firebase_core/firebase_core/example/google-services-desktop.json diff --git a/packages/firebase_core/firebase_core/firebase_core/.gitignore b/packages/firebase_core/firebase_core/firebase_core/.gitignore deleted file mode 100644 index 96486fd93024..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/.gitignore +++ /dev/null @@ -1,30 +0,0 @@ -# Miscellaneous -*.class -*.log -*.pyc -*.swp -.DS_Store -.atom/ -.buildlog/ -.history -.svn/ -migrate_working_dir/ - -# IntelliJ related -*.iml -*.ipr -*.iws -.idea/ - -# The .vscode folder contains launch configuration and tasks you configure in -# VS Code which you may wish to be included in version control, so this line -# is commented out by default. -#.vscode/ - -# Flutter/Dart/Pub related -# Libraries should not include pubspec.lock, per https://dart.dev/guides/libraries/private-files#pubspeclock. -/pubspec.lock -**/doc/api/ -.dart_tool/ -.packages -build/ diff --git a/packages/firebase_core/firebase_core/firebase_core/.metadata b/packages/firebase_core/firebase_core/firebase_core/.metadata deleted file mode 100644 index 97ef0fff36d0..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/.metadata +++ /dev/null @@ -1,30 +0,0 @@ -# This file tracks properties of this Flutter project. -# Used by Flutter tool to assess capabilities and perform upgrades etc. -# -# This file should be version controlled. - -version: - revision: 12cb4eb7a009f52b347b62ade7cb4854b926af72 - channel: stable - -project_type: plugin - -# Tracks metadata for the flutter migrate command -migration: - platforms: - - platform: root - create_revision: 12cb4eb7a009f52b347b62ade7cb4854b926af72 - base_revision: 12cb4eb7a009f52b347b62ade7cb4854b926af72 - - platform: windows - create_revision: 12cb4eb7a009f52b347b62ade7cb4854b926af72 - base_revision: 12cb4eb7a009f52b347b62ade7cb4854b926af72 - - # User provided section - - # List of Local paths (relative to this file) that should be - # ignored by the migrate tool. - # - # Files that are not part of the templates will be ignored by default. - unmanaged_files: - - 'lib/main.dart' - - 'ios/Runner.xcodeproj/project.pbxproj' diff --git a/packages/firebase_core/firebase_core/firebase_core/.vscode/settings.json b/packages/firebase_core/firebase_core/firebase_core/.vscode/settings.json deleted file mode 100644 index deec1e1d3994..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/.vscode/settings.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "cmake.sourceDirectory": "${workspaceFolder}/linux" -} diff --git a/packages/firebase_core/firebase_core/firebase_core/CHANGELOG.md b/packages/firebase_core/firebase_core/firebase_core/CHANGELOG.md deleted file mode 100644 index 41cc7d8192ec..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/CHANGELOG.md +++ /dev/null @@ -1,3 +0,0 @@ -## 0.0.1 - -* TODO: Describe initial release. diff --git a/packages/firebase_core/firebase_core/firebase_core/GoogleService-Info.plist b/packages/firebase_core/firebase_core/firebase_core/GoogleService-Info.plist deleted file mode 100644 index f325ead98dbc..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/GoogleService-Info.plist +++ /dev/null @@ -1,38 +0,0 @@ - - - - - CLIENT_ID - 406099696497-134k3722m01rtrsklhf3b7k8sqa5r7in.apps.googleusercontent.com - REVERSED_CLIENT_ID - com.googleusercontent.apps.406099696497-134k3722m01rtrsklhf3b7k8sqa5r7in - ANDROID_CLIENT_ID - 406099696497-17qn06u8a0dc717u8ul7s49ampk13lul.apps.googleusercontent.com - API_KEY - AIzaSyDooSUGSf63Ghq02_iIhtnmwMDs4HlWS6c - GCM_SENDER_ID - 406099696497 - PLIST_VERSION - 1 - BUNDLE_ID - io.flutter.plugins.firebase.auth.example - PROJECT_ID - flutterfire-e2e-tests - STORAGE_BUCKET - flutterfire-e2e-tests.appspot.com - IS_ADS_ENABLED - - IS_ANALYTICS_ENABLED - - IS_APPINVITE_ENABLED - - IS_GCM_ENABLED - - IS_SIGNIN_ENABLED - - GOOGLE_APP_ID - 1:406099696497:ios:58cbc26aca8e5cf83574d0 - DATABASE_URL - https://flutterfire-e2e-tests-default-rtdb.europe-west1.firebasedatabase.app - - \ No newline at end of file diff --git a/packages/firebase_core/firebase_core/firebase_core/LICENSE b/packages/firebase_core/firebase_core/firebase_core/LICENSE deleted file mode 100644 index ba75c69f7f21..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/LICENSE +++ /dev/null @@ -1 +0,0 @@ -TODO: Add your license here. diff --git a/packages/firebase_core/firebase_core/firebase_core/README.md b/packages/firebase_core/firebase_core/firebase_core/README.md deleted file mode 100644 index b373aba55a5f..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/README.md +++ /dev/null @@ -1,15 +0,0 @@ -# firebase_core - -A new Flutter plugin project. - -## Getting Started - -This project is a starting point for a Flutter -[plug-in package](https://flutter.dev/developing-packages/), -a specialized package that includes platform-specific implementation code for -Android and/or iOS. - -For help getting started with Flutter development, view the -[online documentation](https://flutter.dev/docs), which offers tutorials, -samples, guidance on mobile development, and a full API reference. - diff --git a/packages/firebase_core/firebase_core/firebase_core/analysis_options.yaml b/packages/firebase_core/firebase_core/firebase_core/analysis_options.yaml deleted file mode 100644 index a5744c1cfbe7..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/analysis_options.yaml +++ /dev/null @@ -1,4 +0,0 @@ -include: package:flutter_lints/flutter.yaml - -# Additional information about this file can be found at -# https://dart.dev/guides/language/analysis-options diff --git a/packages/firebase_core/firebase_core/firebase_core/example/.gitignore b/packages/firebase_core/firebase_core/firebase_core/example/.gitignore deleted file mode 100644 index 24476c5d1eb5..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/example/.gitignore +++ /dev/null @@ -1,44 +0,0 @@ -# Miscellaneous -*.class -*.log -*.pyc -*.swp -.DS_Store -.atom/ -.buildlog/ -.history -.svn/ -migrate_working_dir/ - -# IntelliJ related -*.iml -*.ipr -*.iws -.idea/ - -# The .vscode folder contains launch configuration and tasks you configure in -# VS Code which you may wish to be included in version control, so this line -# is commented out by default. -#.vscode/ - -# Flutter/Dart/Pub related -**/doc/api/ -**/ios/Flutter/.last_build_id -.dart_tool/ -.flutter-plugins -.flutter-plugins-dependencies -.packages -.pub-cache/ -.pub/ -/build/ - -# Symbolication related -app.*.symbols - -# Obfuscation related -app.*.map.json - -# Android Studio will place build artifacts here -/android/app/debug -/android/app/profile -/android/app/release diff --git a/packages/firebase_core/firebase_core/firebase_core/example/README.md b/packages/firebase_core/firebase_core/firebase_core/example/README.md deleted file mode 100644 index d1f452146bce..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/example/README.md +++ /dev/null @@ -1,16 +0,0 @@ -# firebase_core_example - -Demonstrates how to use the firebase_core plugin. - -## Getting Started - -This project is a starting point for a Flutter application. - -A few resources to get you started if this is your first Flutter project: - -- [Lab: Write your first Flutter app](https://docs.flutter.dev/get-started/codelab) -- [Cookbook: Useful Flutter samples](https://docs.flutter.dev/cookbook) - -For help getting started with Flutter development, view the -[online documentation](https://docs.flutter.dev/), which offers tutorials, -samples, guidance on mobile development, and a full API reference. diff --git a/packages/firebase_core/firebase_core/firebase_core/example/analysis_options.yaml b/packages/firebase_core/firebase_core/firebase_core/example/analysis_options.yaml deleted file mode 100644 index 61b6c4de17c9..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/example/analysis_options.yaml +++ /dev/null @@ -1,29 +0,0 @@ -# This file configures the analyzer, which statically analyzes Dart code to -# check for errors, warnings, and lints. -# -# The issues identified by the analyzer are surfaced in the UI of Dart-enabled -# IDEs (https://dart.dev/tools#ides-and-editors). The analyzer can also be -# invoked from the command line by running `flutter analyze`. - -# The following line activates a set of recommended lints for Flutter apps, -# packages, and plugins designed to encourage good coding practices. -include: package:flutter_lints/flutter.yaml - -linter: - # The lint rules applied to this project can be customized in the - # section below to disable rules from the `package:flutter_lints/flutter.yaml` - # included above or to enable additional rules. A list of all available lints - # and their documentation is published at - # https://dart-lang.github.io/linter/lints/index.html. - # - # Instead of disabling a lint rule for the entire project in the - # section below, it can also be suppressed for a single line of code - # or a specific dart file by using the `// ignore: name_of_lint` and - # `// ignore_for_file: name_of_lint` syntax on the line or in the file - # producing the lint. - rules: - # avoid_print: false # Uncomment to disable the `avoid_print` rule - # prefer_single_quotes: true # Uncomment to enable the `prefer_single_quotes` rule - -# Additional information about this file can be found at -# https://dart.dev/guides/language/analysis-options diff --git a/packages/firebase_core/firebase_core/firebase_core/example/bin/CMakeFiles/generate.stamp b/packages/firebase_core/firebase_core/firebase_core/example/bin/CMakeFiles/generate.stamp deleted file mode 100644 index 9b5f49fa9f14..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/example/bin/CMakeFiles/generate.stamp +++ /dev/null @@ -1 +0,0 @@ -# CMake generation timestamp file for this directory. diff --git a/packages/firebase_core/firebase_core/firebase_core/example/bin/CMakeFiles/generate.stamp.depend b/packages/firebase_core/firebase_core/firebase_core/example/bin/CMakeFiles/generate.stamp.depend deleted file mode 100644 index 5b8da13f857a..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/example/bin/CMakeFiles/generate.stamp.depend +++ /dev/null @@ -1,5 +0,0 @@ -# CMake generation dependency list for this directory. -C:/Program Files/Microsoft Visual Studio/2022/Community/Common7/IDE/CommonExtensions/Microsoft/CMake/CMake/share/cmake-3.25/Modules/FindPackageHandleStandardArgs.cmake -C:/Program Files/Microsoft Visual Studio/2022/Community/Common7/IDE/CommonExtensions/Microsoft/CMake/CMake/share/cmake-3.25/Modules/FindPackageMessage.cmake -C:/Program Files/Microsoft Visual Studio/2022/Community/Common7/IDE/CommonExtensions/Microsoft/CMake/CMake/share/cmake-3.25/Modules/FindPkgConfig.cmake -C:/Users/guill/Downloads/firebase_cpp_sdk_10.5.0/firebase_cpp_sdk/CMakeLists.txt diff --git a/packages/firebase_core/firebase_core/firebase_core/example/bin/INSTALL.vcxproj b/packages/firebase_core/firebase_core/firebase_core/example/bin/INSTALL.vcxproj deleted file mode 100644 index 05091bebad78..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/example/bin/INSTALL.vcxproj +++ /dev/null @@ -1,165 +0,0 @@ - - - - x64 - - - - Debug - x64 - - - Profile - x64 - - - Release - x64 - - - - {B2284ACE-B264-3C77-ADAD-5516EBC85159} - Win32Proj - 10.0.22000.0 - x64 - INSTALL - NoUpgrade - - - - Utility - MultiByte - v143 - - - Utility - MultiByte - v143 - - - Utility - MultiByte - v143 - - - - - - - - - - <_ProjectFileVersion>10.0.20506.1 - $(Platform)\$(Configuration)\$(ProjectName)\ - $(Platform)\$(Configuration)\$(ProjectName)\ - $(Platform)\$(Configuration)\$(ProjectName)\ - - - - Always - - setlocal -"C:\Program Files\Microsoft Visual Studio\2022\Community\Common7\IDE\CommonExtensions\Microsoft\CMake\CMake\bin\cmake.exe" -DBUILD_TYPE=$(Configuration) -P cmake_install.cmake -if %errorlevel% neq 0 goto :cmEnd -:cmEnd -endlocal & call :cmErrorLevel %errorlevel% & goto :cmDone -:cmErrorLevel -exit /b %1 -:cmDone -if %errorlevel% neq 0 goto :VCEnd - - - - - Always - - setlocal -"C:\Program Files\Microsoft Visual Studio\2022\Community\Common7\IDE\CommonExtensions\Microsoft\CMake\CMake\bin\cmake.exe" -DBUILD_TYPE=$(Configuration) -P cmake_install.cmake -if %errorlevel% neq 0 goto :cmEnd -:cmEnd -endlocal & call :cmErrorLevel %errorlevel% & goto :cmDone -:cmErrorLevel -exit /b %1 -:cmDone -if %errorlevel% neq 0 goto :VCEnd - - - - - Always - - setlocal -"C:\Program Files\Microsoft Visual Studio\2022\Community\Common7\IDE\CommonExtensions\Microsoft\CMake\CMake\bin\cmake.exe" -DBUILD_TYPE=$(Configuration) -P cmake_install.cmake -if %errorlevel% neq 0 goto :cmEnd -:cmEnd -endlocal & call :cmErrorLevel %errorlevel% & goto :cmDone -:cmErrorLevel -exit /b %1 -:cmDone -if %errorlevel% neq 0 goto :VCEnd - - - - - - setlocal -cd . -if %errorlevel% neq 0 goto :cmEnd -:cmEnd -endlocal & call :cmErrorLevel %errorlevel% & goto :cmDone -:cmErrorLevel -exit /b %1 -:cmDone -if %errorlevel% neq 0 goto :VCEnd - %(AdditionalInputs) - C:\Users\guill\Developer\flutterfire\packages\firebase_core\firebase_core\firebase_core\example\bin\CMakeFiles\INSTALL_force - false - false - - setlocal -cd . -if %errorlevel% neq 0 goto :cmEnd -:cmEnd -endlocal & call :cmErrorLevel %errorlevel% & goto :cmDone -:cmErrorLevel -exit /b %1 -:cmDone -if %errorlevel% neq 0 goto :VCEnd - %(AdditionalInputs) - C:\Users\guill\Developer\flutterfire\packages\firebase_core\firebase_core\firebase_core\example\bin\CMakeFiles\INSTALL_force - false - false - - setlocal -cd . -if %errorlevel% neq 0 goto :cmEnd -:cmEnd -endlocal & call :cmErrorLevel %errorlevel% & goto :cmDone -:cmErrorLevel -exit /b %1 -:cmDone -if %errorlevel% neq 0 goto :VCEnd - %(AdditionalInputs) - C:\Users\guill\Developer\flutterfire\packages\firebase_core\firebase_core\firebase_core\example\bin\CMakeFiles\INSTALL_force - false - false - - - - - {DC08768F-F57C-313C-94F0-E16194F54223} - ZERO_CHECK - false - Never - - - {DF648812-5598-379C-A5B5-8A3EAC6BC5B0} - ALL_BUILD - false - Never - - - - - - \ No newline at end of file diff --git a/packages/firebase_core/firebase_core/firebase_core/example/bin/INSTALL.vcxproj.filters b/packages/firebase_core/firebase_core/firebase_core/example/bin/INSTALL.vcxproj.filters deleted file mode 100644 index 69fed1abf535..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/example/bin/INSTALL.vcxproj.filters +++ /dev/null @@ -1,13 +0,0 @@ - - - - - CMake Rules - - - - - {EAE753BC-CF7B-3081-8331-9EFFB2F8D8A5} - - - diff --git a/packages/firebase_core/firebase_core/firebase_core/example/bin/cmake_install.cmake b/packages/firebase_core/firebase_core/firebase_core/example/bin/cmake_install.cmake deleted file mode 100644 index 8cf9b6c06b96..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/example/bin/cmake_install.cmake +++ /dev/null @@ -1,34 +0,0 @@ -# Install script for directory: C:/Users/guill/Downloads/firebase_cpp_sdk_10.5.0/firebase_cpp_sdk - -# Set the install prefix -if(NOT DEFINED CMAKE_INSTALL_PREFIX) - set(CMAKE_INSTALL_PREFIX "$") -endif() -string(REGEX REPLACE "/$" "" CMAKE_INSTALL_PREFIX "${CMAKE_INSTALL_PREFIX}") - -# Set the install configuration name. -if(NOT DEFINED CMAKE_INSTALL_CONFIG_NAME) - if(BUILD_TYPE) - string(REGEX REPLACE "^[^A-Za-z0-9_]+" "" - CMAKE_INSTALL_CONFIG_NAME "${BUILD_TYPE}") - else() - set(CMAKE_INSTALL_CONFIG_NAME "Release") - endif() - message(STATUS "Install configuration: \"${CMAKE_INSTALL_CONFIG_NAME}\"") -endif() - -# Set the component getting installed. -if(NOT CMAKE_INSTALL_COMPONENT) - if(COMPONENT) - message(STATUS "Install component: \"${COMPONENT}\"") - set(CMAKE_INSTALL_COMPONENT "${COMPONENT}") - else() - set(CMAKE_INSTALL_COMPONENT) - endif() -endif() - -# Is this installation the result of a crosscompile? -if(NOT DEFINED CMAKE_CROSSCOMPILING) - set(CMAKE_CROSSCOMPILING "FALSE") -endif() - diff --git a/packages/firebase_core/firebase_core/firebase_core/example/lib/main.dart b/packages/firebase_core/firebase_core/firebase_core/example/lib/main.dart deleted file mode 100644 index 4e2b473ad9e0..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/example/lib/main.dart +++ /dev/null @@ -1,63 +0,0 @@ -import 'package:flutter/material.dart'; -import 'dart:async'; - -import 'package:flutter/services.dart'; -import 'package:firebase_core/firebase_core.dart'; - -void main() { - runApp(const MyApp()); -} - -class MyApp extends StatefulWidget { - const MyApp({super.key}); - - @override - State createState() => _MyAppState(); -} - -class _MyAppState extends State { - String _platformVersion = 'Unknown'; - final _firebaseCorePlugin = FirebaseCore(); - - @override - void initState() { - super.initState(); - initPlatformState(); - } - - // Platform messages are asynchronous, so we initialize in an async method. - Future initPlatformState() async { - String platformVersion; - // Platform messages may fail, so we use a try/catch PlatformException. - // We also handle the message potentially returning null. - try { - platformVersion = - await _firebaseCorePlugin.getPlatformVersion() ?? 'Unknown platform version'; - } on PlatformException { - platformVersion = 'Failed to get platform version.'; - } - - // If the widget was removed from the tree while the asynchronous platform - // message was in flight, we want to discard the reply rather than calling - // setState to update our non-existent appearance. - if (!mounted) return; - - setState(() { - _platformVersion = platformVersion; - }); - } - - @override - Widget build(BuildContext context) { - return MaterialApp( - home: Scaffold( - appBar: AppBar( - title: const Text('Plugin example app'), - ), - body: Center( - child: Text('Running on: $_platformVersion\n'), - ), - ), - ); - } -} diff --git a/packages/firebase_core/firebase_core/firebase_core/example/linux/.gitignore b/packages/firebase_core/firebase_core/firebase_core/example/linux/.gitignore deleted file mode 100644 index d3896c98444f..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/example/linux/.gitignore +++ /dev/null @@ -1 +0,0 @@ -flutter/ephemeral diff --git a/packages/firebase_core/firebase_core/firebase_core/example/linux/CMakeLists.txt b/packages/firebase_core/firebase_core/firebase_core/example/linux/CMakeLists.txt deleted file mode 100644 index 9ae42276201e..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/example/linux/CMakeLists.txt +++ /dev/null @@ -1,150 +0,0 @@ -# Project-level configuration. -cmake_minimum_required(VERSION 3.10) -project(runner LANGUAGES CXX) - -# The name of the executable created for the application. Change this to change -# the on-disk name of your application. -set(BINARY_NAME "firebase_core_example") -# The unique GTK application identifier for this application. See: -# https://wiki.gnome.org/HowDoI/ChooseApplicationID -set(APPLICATION_ID "com.example.firebase_core") - -# Explicitly opt in to modern CMake behaviors to avoid warnings with recent -# versions of CMake. -cmake_policy(SET CMP0063 NEW) - -# Load bundled libraries from the lib/ directory relative to the binary. -set(CMAKE_INSTALL_RPATH "$ORIGIN/lib") - -# Root filesystem for cross-building. -if(FLUTTER_TARGET_PLATFORM_SYSROOT) - set(CMAKE_SYSROOT ${FLUTTER_TARGET_PLATFORM_SYSROOT}) - set(CMAKE_FIND_ROOT_PATH ${CMAKE_SYSROOT}) - set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) - set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY) - set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) - set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) -endif() - -# Define build configuration options. -if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) - set(CMAKE_BUILD_TYPE "Debug" CACHE - STRING "Flutter build mode" FORCE) - set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS - "Debug" "Profile" "Release") -endif() - -# Compilation settings that should be applied to most targets. -# -# Be cautious about adding new options here, as plugins use this function by -# default. In most cases, you should add new options to specific targets instead -# of modifying this function. -function(APPLY_STANDARD_SETTINGS TARGET) - target_compile_features(${TARGET} PUBLIC cxx_std_14) - target_compile_options(${TARGET} PRIVATE -Wall -Werror) - target_compile_options(${TARGET} PRIVATE "$<$>:-O3>") - target_compile_definitions(${TARGET} PRIVATE "$<$>:NDEBUG>") -endfunction() - -# Flutter library and tool build rules. -set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") -add_subdirectory(${FLUTTER_MANAGED_DIR}) - -# Add Firebase libraries to the target using the function from the SDK. -add_subdirectory(${FIREBASE_CPP_SDK_DIR} bin/ EXCLUDE_FROM_ALL) - -# The Firebase C++ library `firebase_app` is required, -# and it must always be listed last. - -# Add the Firebase SDKs for the products you want to use in your app -# For example, to use Firebase Authentication and Firebase Realtime Database -set(firebase_libs firebase_auth firebase_database firebase_app) -target_link_libraries(${target_name} "${firebase_libs}") - - -# System-level dependencies. -find_package(PkgConfig REQUIRED) -pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) - -add_definitions(-DAPPLICATION_ID="${APPLICATION_ID}") - -# Define the application target. To change its name, change BINARY_NAME above, -# not the value here, or `flutter run` will no longer work. -# -# Any new source files that you add to the application should be added here. -add_executable(${BINARY_NAME} - "main.cc" - "my_application.cc" - "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" -) - -# Apply the standard set of build settings. This can be removed for applications -# that need different build settings. -apply_standard_settings(${BINARY_NAME}) - -# Add dependency libraries. Add any application-specific dependencies here. -target_link_libraries(${BINARY_NAME} PRIVATE flutter) -target_link_libraries(${BINARY_NAME} PRIVATE PkgConfig::GTK) - -# Run the Flutter tool portions of the build. This must not be removed. -add_dependencies(${BINARY_NAME} flutter_assemble) - -# Only the install-generated bundle's copy of the executable will launch -# correctly, since the resources must in the right relative locations. To avoid -# people trying to run the unbundled copy, put it in a subdirectory instead of -# the default top-level location. -set_target_properties(${BINARY_NAME} - PROPERTIES - RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/intermediates_do_not_run" -) - -# Generated plugin build rules, which manage building the plugins and adding -# them to the application. -include(flutter/generated_plugins.cmake) - - -# === Installation === -# By default, "installing" just makes a relocatable bundle in the build -# directory. -set(BUILD_BUNDLE_DIR "${PROJECT_BINARY_DIR}/bundle") -if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) - set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) -endif() - -# Start with a clean build bundle directory every time. -install(CODE " - file(REMOVE_RECURSE \"${BUILD_BUNDLE_DIR}/\") - " COMPONENT Runtime) - -set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") -set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}/lib") - -install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" - COMPONENT Runtime) - -install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" - COMPONENT Runtime) - -install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" - COMPONENT Runtime) - -foreach(bundled_library ${PLUGIN_BUNDLED_LIBRARIES}) - install(FILES "${bundled_library}" - DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" - COMPONENT Runtime) -endforeach(bundled_library) - -# Fully re-copy the assets directory on each build to avoid having stale files -# from a previous install. -set(FLUTTER_ASSET_DIR_NAME "flutter_assets") -install(CODE " - file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") - " COMPONENT Runtime) -install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" - DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) - -# Install the AOT library on non-Debug builds only. -if(NOT CMAKE_BUILD_TYPE MATCHES "Debug") - install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" - COMPONENT Runtime) -endif() diff --git a/packages/firebase_core/firebase_core/firebase_core/example/linux/flutter/CMakeLists.txt b/packages/firebase_core/firebase_core/firebase_core/example/linux/flutter/CMakeLists.txt deleted file mode 100644 index d5bd01648a96..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/example/linux/flutter/CMakeLists.txt +++ /dev/null @@ -1,88 +0,0 @@ -# This file controls Flutter-level build steps. It should not be edited. -cmake_minimum_required(VERSION 3.10) - -set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") - -# Configuration provided via flutter tool. -include(${EPHEMERAL_DIR}/generated_config.cmake) - -# TODO: Move the rest of this into files in ephemeral. See -# https://github.com/flutter/flutter/issues/57146. - -# Serves the same purpose as list(TRANSFORM ... PREPEND ...), -# which isn't available in 3.10. -function(list_prepend LIST_NAME PREFIX) - set(NEW_LIST "") - foreach(element ${${LIST_NAME}}) - list(APPEND NEW_LIST "${PREFIX}${element}") - endforeach(element) - set(${LIST_NAME} "${NEW_LIST}" PARENT_SCOPE) -endfunction() - -# === Flutter Library === -# System-level dependencies. -find_package(PkgConfig REQUIRED) -pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) -pkg_check_modules(GLIB REQUIRED IMPORTED_TARGET glib-2.0) -pkg_check_modules(GIO REQUIRED IMPORTED_TARGET gio-2.0) - -set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/libflutter_linux_gtk.so") - -# Published to parent scope for install step. -set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) -set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) -set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) -set(AOT_LIBRARY "${PROJECT_DIR}/build/lib/libapp.so" PARENT_SCOPE) - -list(APPEND FLUTTER_LIBRARY_HEADERS - "fl_basic_message_channel.h" - "fl_binary_codec.h" - "fl_binary_messenger.h" - "fl_dart_project.h" - "fl_engine.h" - "fl_json_message_codec.h" - "fl_json_method_codec.h" - "fl_message_codec.h" - "fl_method_call.h" - "fl_method_channel.h" - "fl_method_codec.h" - "fl_method_response.h" - "fl_plugin_registrar.h" - "fl_plugin_registry.h" - "fl_standard_message_codec.h" - "fl_standard_method_codec.h" - "fl_string_codec.h" - "fl_value.h" - "fl_view.h" - "flutter_linux.h" -) -list_prepend(FLUTTER_LIBRARY_HEADERS "${EPHEMERAL_DIR}/flutter_linux/") -add_library(flutter INTERFACE) -target_include_directories(flutter INTERFACE - "${EPHEMERAL_DIR}" -) -target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}") -target_link_libraries(flutter INTERFACE - PkgConfig::GTK - PkgConfig::GLIB - PkgConfig::GIO -) -add_dependencies(flutter flutter_assemble) - -# === Flutter tool backend === -# _phony_ is a non-existent file to force this command to run every time, -# since currently there's no way to get a full input/output list from the -# flutter tool. -add_custom_command( - OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} - ${CMAKE_CURRENT_BINARY_DIR}/_phony_ - COMMAND ${CMAKE_COMMAND} -E env - ${FLUTTER_TOOL_ENVIRONMENT} - "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.sh" - ${FLUTTER_TARGET_PLATFORM} ${CMAKE_BUILD_TYPE} - VERBATIM -) -add_custom_target(flutter_assemble DEPENDS - "${FLUTTER_LIBRARY}" - ${FLUTTER_LIBRARY_HEADERS} -) diff --git a/packages/firebase_core/firebase_core/firebase_core/example/linux/flutter/generated_plugin_registrant.cc b/packages/firebase_core/firebase_core/firebase_core/example/linux/flutter/generated_plugin_registrant.cc deleted file mode 100644 index 15034725064f..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/example/linux/flutter/generated_plugin_registrant.cc +++ /dev/null @@ -1,15 +0,0 @@ -// -// Generated file. Do not edit. -// - -// clang-format off - -#include "generated_plugin_registrant.h" - -#include - -void fl_register_plugins(FlPluginRegistry* registry) { - g_autoptr(FlPluginRegistrar) firebase_core_registrar = - fl_plugin_registry_get_registrar_for_plugin(registry, "FirebaseCorePlugin"); - firebase_core_plugin_register_with_registrar(firebase_core_registrar); -} diff --git a/packages/firebase_core/firebase_core/firebase_core/example/linux/flutter/generated_plugin_registrant.h b/packages/firebase_core/firebase_core/firebase_core/example/linux/flutter/generated_plugin_registrant.h deleted file mode 100644 index e0f0a47bc08f..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/example/linux/flutter/generated_plugin_registrant.h +++ /dev/null @@ -1,15 +0,0 @@ -// -// Generated file. Do not edit. -// - -// clang-format off - -#ifndef GENERATED_PLUGIN_REGISTRANT_ -#define GENERATED_PLUGIN_REGISTRANT_ - -#include - -// Registers Flutter plugins. -void fl_register_plugins(FlPluginRegistry* registry); - -#endif // GENERATED_PLUGIN_REGISTRANT_ diff --git a/packages/firebase_core/firebase_core/firebase_core/example/linux/flutter/generated_plugins.cmake b/packages/firebase_core/firebase_core/firebase_core/example/linux/flutter/generated_plugins.cmake deleted file mode 100644 index 1d55b5b0bf79..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/example/linux/flutter/generated_plugins.cmake +++ /dev/null @@ -1,24 +0,0 @@ -# -# Generated file, do not edit. -# - -list(APPEND FLUTTER_PLUGIN_LIST - firebase_core -) - -list(APPEND FLUTTER_FFI_PLUGIN_LIST -) - -set(PLUGIN_BUNDLED_LIBRARIES) - -foreach(plugin ${FLUTTER_PLUGIN_LIST}) - add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/linux plugins/${plugin}) - target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) - list(APPEND PLUGIN_BUNDLED_LIBRARIES $) - list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) -endforeach(plugin) - -foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST}) - add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/linux plugins/${ffi_plugin}) - list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries}) -endforeach(ffi_plugin) diff --git a/packages/firebase_core/firebase_core/firebase_core/example/linux/main.cc b/packages/firebase_core/firebase_core/firebase_core/example/linux/main.cc deleted file mode 100644 index e7c5c5437037..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/example/linux/main.cc +++ /dev/null @@ -1,6 +0,0 @@ -#include "my_application.h" - -int main(int argc, char** argv) { - g_autoptr(MyApplication) app = my_application_new(); - return g_application_run(G_APPLICATION(app), argc, argv); -} diff --git a/packages/firebase_core/firebase_core/firebase_core/example/linux/my_application.cc b/packages/firebase_core/firebase_core/firebase_core/example/linux/my_application.cc deleted file mode 100644 index b699538ff8ee..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/example/linux/my_application.cc +++ /dev/null @@ -1,104 +0,0 @@ -#include "my_application.h" - -#include -#ifdef GDK_WINDOWING_X11 -#include -#endif - -#include "flutter/generated_plugin_registrant.h" - -struct _MyApplication { - GtkApplication parent_instance; - char** dart_entrypoint_arguments; -}; - -G_DEFINE_TYPE(MyApplication, my_application, GTK_TYPE_APPLICATION) - -// Implements GApplication::activate. -static void my_application_activate(GApplication* application) { - MyApplication* self = MY_APPLICATION(application); - GtkWindow* window = - GTK_WINDOW(gtk_application_window_new(GTK_APPLICATION(application))); - - // Use a header bar when running in GNOME as this is the common style used - // by applications and is the setup most users will be using (e.g. Ubuntu - // desktop). - // If running on X and not using GNOME then just use a traditional title bar - // in case the window manager does more exotic layout, e.g. tiling. - // If running on Wayland assume the header bar will work (may need changing - // if future cases occur). - gboolean use_header_bar = TRUE; -#ifdef GDK_WINDOWING_X11 - GdkScreen* screen = gtk_window_get_screen(window); - if (GDK_IS_X11_SCREEN(screen)) { - const gchar* wm_name = gdk_x11_screen_get_window_manager_name(screen); - if (g_strcmp0(wm_name, "GNOME Shell") != 0) { - use_header_bar = FALSE; - } - } -#endif - if (use_header_bar) { - GtkHeaderBar* header_bar = GTK_HEADER_BAR(gtk_header_bar_new()); - gtk_widget_show(GTK_WIDGET(header_bar)); - gtk_header_bar_set_title(header_bar, "firebase_core_example"); - gtk_header_bar_set_show_close_button(header_bar, TRUE); - gtk_window_set_titlebar(window, GTK_WIDGET(header_bar)); - } else { - gtk_window_set_title(window, "firebase_core_example"); - } - - gtk_window_set_default_size(window, 1280, 720); - gtk_widget_show(GTK_WIDGET(window)); - - g_autoptr(FlDartProject) project = fl_dart_project_new(); - fl_dart_project_set_dart_entrypoint_arguments(project, self->dart_entrypoint_arguments); - - FlView* view = fl_view_new(project); - gtk_widget_show(GTK_WIDGET(view)); - gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(view)); - - fl_register_plugins(FL_PLUGIN_REGISTRY(view)); - - gtk_widget_grab_focus(GTK_WIDGET(view)); -} - -// Implements GApplication::local_command_line. -static gboolean my_application_local_command_line(GApplication* application, gchar*** arguments, int* exit_status) { - MyApplication* self = MY_APPLICATION(application); - // Strip out the first argument as it is the binary name. - self->dart_entrypoint_arguments = g_strdupv(*arguments + 1); - - g_autoptr(GError) error = nullptr; - if (!g_application_register(application, nullptr, &error)) { - g_warning("Failed to register: %s", error->message); - *exit_status = 1; - return TRUE; - } - - g_application_activate(application); - *exit_status = 0; - - return TRUE; -} - -// Implements GObject::dispose. -static void my_application_dispose(GObject* object) { - MyApplication* self = MY_APPLICATION(object); - g_clear_pointer(&self->dart_entrypoint_arguments, g_strfreev); - G_OBJECT_CLASS(my_application_parent_class)->dispose(object); -} - -static void my_application_class_init(MyApplicationClass* klass) { - G_APPLICATION_CLASS(klass)->activate = my_application_activate; - G_APPLICATION_CLASS(klass)->local_command_line = my_application_local_command_line; - G_OBJECT_CLASS(klass)->dispose = my_application_dispose; -} - -static void my_application_init(MyApplication* self) {} - -MyApplication* my_application_new() { - return MY_APPLICATION(g_object_new(my_application_get_type(), - "application-id", APPLICATION_ID, - "flags", G_APPLICATION_NON_UNIQUE, - nullptr)); -} diff --git a/packages/firebase_core/firebase_core/firebase_core/example/linux/my_application.h b/packages/firebase_core/firebase_core/firebase_core/example/linux/my_application.h deleted file mode 100644 index 72271d5e4170..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/example/linux/my_application.h +++ /dev/null @@ -1,18 +0,0 @@ -#ifndef FLUTTER_MY_APPLICATION_H_ -#define FLUTTER_MY_APPLICATION_H_ - -#include - -G_DECLARE_FINAL_TYPE(MyApplication, my_application, MY, APPLICATION, - GtkApplication) - -/** - * my_application_new: - * - * Creates a new Flutter-based application. - * - * Returns: a new #MyApplication. - */ -MyApplication* my_application_new(); - -#endif // FLUTTER_MY_APPLICATION_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/example/pubspec.yaml b/packages/firebase_core/firebase_core/firebase_core/example/pubspec.yaml deleted file mode 100644 index dd3d2b2c7b7e..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/example/pubspec.yaml +++ /dev/null @@ -1,83 +0,0 @@ -name: firebase_core_example -description: Demonstrates how to use the firebase_core plugin. -# The following line prevents the package from being accidentally published to -# pub.dev using `flutter pub publish`. This is preferred for private packages. -publish_to: 'none' # Remove this line if you wish to publish to pub.dev - -environment: - sdk: '>=2.19.2 <3.0.0' - -# Dependencies specify other packages that your package needs in order to work. -# To automatically upgrade your package dependencies to the latest versions -# consider running `flutter pub upgrade --major-versions`. Alternatively, -# dependencies can be manually updated by changing the version numbers below to -# the latest version available on pub.dev. To see which dependencies have newer -# versions available, run `flutter pub outdated`. -dependencies: - flutter: - sdk: flutter - - firebase_core: - # When depending on this package from a real application you should use: - # firebase_core: ^x.y.z - # See https://dart.dev/tools/pub/dependencies#version-constraints - # The example app is bundled with the plugin so we use a path dependency on - # the parent directory to use the current plugin's version. - path: ../ - - # The following adds the Cupertino Icons font to your application. - # Use with the CupertinoIcons class for iOS style icons. - cupertino_icons: ^1.0.2 - -dev_dependencies: - flutter_test: - sdk: flutter - - # The "flutter_lints" package below contains a set of recommended lints to - # encourage good coding practices. The lint set provided by the package is - # activated in the `analysis_options.yaml` file located at the root of your - # package. See that file for information about deactivating specific lint - # rules and activating additional ones. - flutter_lints: ^2.0.0 - -# For information on the generic Dart part of this file, see the -# following page: https://dart.dev/tools/pub/pubspec - -# The following section is specific to Flutter packages. -flutter: - - # The following line ensures that the Material Icons font is - # included with your application, so that you can use the icons in - # the material Icons class. - uses-material-design: true - - # To add assets to your application, add an assets section, like this: - # assets: - # - images/a_dot_burr.jpeg - # - images/a_dot_ham.jpeg - - # An image asset can refer to one or more resolution-specific "variants", see - # https://flutter.dev/assets-and-images/#resolution-aware - - # For details regarding adding assets from package dependencies, see - # https://flutter.dev/assets-and-images/#from-packages - - # To add custom fonts to your application, add a fonts section here, - # in this "flutter" section. Each entry in this list should have a - # "family" key with the font family name, and a "fonts" key with a - # list giving the asset and other descriptors for the font. For - # example: - # fonts: - # - family: Schyler - # fonts: - # - asset: fonts/Schyler-Regular.ttf - # - asset: fonts/Schyler-Italic.ttf - # style: italic - # - family: Trajan Pro - # fonts: - # - asset: fonts/TrajanPro.ttf - # - asset: fonts/TrajanPro_Bold.ttf - # weight: 700 - # - # For details regarding fonts from package dependencies, - # see https://flutter.dev/custom-fonts/#from-packages diff --git a/packages/firebase_core/firebase_core/firebase_core/example/test/widget_test.dart b/packages/firebase_core/firebase_core/firebase_core/example/test/widget_test.dart deleted file mode 100644 index d343f68407e8..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/example/test/widget_test.dart +++ /dev/null @@ -1,27 +0,0 @@ -// This is a basic Flutter widget test. -// -// To perform an interaction with a widget in your test, use the WidgetTester -// utility in the flutter_test package. For example, you can send tap and scroll -// gestures. You can also use WidgetTester to find child widgets in the widget -// tree, read text, and verify that the values of widget properties are correct. - -import 'package:flutter/material.dart'; -import 'package:flutter_test/flutter_test.dart'; - -import 'package:firebase_core_example/main.dart'; - -void main() { - testWidgets('Verify Platform version', (WidgetTester tester) async { - // Build our app and trigger a frame. - await tester.pumpWidget(const MyApp()); - - // Verify that platform version is retrieved. - expect( - find.byWidgetPredicate( - (Widget widget) => widget is Text && - widget.data!.startsWith('Running on:'), - ), - findsOneWidget, - ); - }); -} diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/.gitignore b/packages/firebase_core/firebase_core/firebase_core/example/windows/.gitignore deleted file mode 100644 index d492d0d98c8f..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/example/windows/.gitignore +++ /dev/null @@ -1,17 +0,0 @@ -flutter/ephemeral/ - -# Visual Studio user-specific files. -*.suo -*.user -*.userosscache -*.sln.docstates - -# Visual Studio build-related files. -x64/ -x86/ - -# Visual Studio cache files -# files ending in .cache can be ignored -*.[Cc]ache -# but keep track of directories ending in .cache -!*.[Cc]ache/ diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/CMakeLists.txt b/packages/firebase_core/firebase_core/firebase_core/example/windows/CMakeLists.txt deleted file mode 100644 index ddf92aa378e1..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/example/windows/CMakeLists.txt +++ /dev/null @@ -1,101 +0,0 @@ -# Project-level configuration. -cmake_minimum_required(VERSION 3.14) -project(firebase_core_example LANGUAGES CXX) - -# The name of the executable created for the application. Change this to change -# the on-disk name of your application. -set(BINARY_NAME "firebase_core_example") - -# Explicitly opt in to modern CMake behaviors to avoid warnings with recent -# versions of CMake. -cmake_policy(SET CMP0063 NEW) - -# Define build configuration option. -get_property(IS_MULTICONFIG GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG) -if(IS_MULTICONFIG) - set(CMAKE_CONFIGURATION_TYPES "Debug;Profile;Release" - CACHE STRING "" FORCE) -else() - if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) - set(CMAKE_BUILD_TYPE "Debug" CACHE - STRING "Flutter build mode" FORCE) - set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS - "Debug" "Profile" "Release") - endif() -endif() -# Define settings for the Profile build mode. -set(CMAKE_EXE_LINKER_FLAGS_PROFILE "${CMAKE_EXE_LINKER_FLAGS_RELEASE}") -set(CMAKE_SHARED_LINKER_FLAGS_PROFILE "${CMAKE_SHARED_LINKER_FLAGS_RELEASE}") -set(CMAKE_C_FLAGS_PROFILE "${CMAKE_C_FLAGS_RELEASE}") -set(CMAKE_CXX_FLAGS_PROFILE "${CMAKE_CXX_FLAGS_RELEASE}") - -# Use Unicode for all projects. -add_definitions(-DUNICODE -D_UNICODE) - -# Compilation settings that should be applied to most targets. -# -# Be cautious about adding new options here, as plugins use this function by -# default. In most cases, you should add new options to specific targets instead -# of modifying this function. -function(APPLY_STANDARD_SETTINGS TARGET) - target_compile_features(${TARGET} PUBLIC cxx_std_17) - target_compile_options(${TARGET} PRIVATE /W4 /WX /wd"4100") - target_compile_options(${TARGET} PRIVATE /EHsc) - target_compile_definitions(${TARGET} PRIVATE "_HAS_EXCEPTIONS=0") - target_compile_definitions(${TARGET} PRIVATE "$<$:_DEBUG>") -endfunction() - -# Flutter library and tool build rules. -set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") -add_subdirectory(${FLUTTER_MANAGED_DIR}) - -# Application build; see runner/CMakeLists.txt. -add_subdirectory("runner") - -# Generated plugin build rules, which manage building the plugins and adding -# them to the application. -include(flutter/generated_plugins.cmake) - - -# === Installation === -# Support files are copied into place next to the executable, so that it can -# run in place. This is done instead of making a separate bundle (as on Linux) -# so that building and running from within Visual Studio will work. -set(BUILD_BUNDLE_DIR "$") -# Make the "install" step default, as it's required to run. -set(CMAKE_VS_INCLUDE_INSTALL_TO_DEFAULT_BUILD 1) -if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) - set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) -endif() - -set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") -set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}") - -install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" - COMPONENT Runtime) - -install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" - COMPONENT Runtime) - -install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" - COMPONENT Runtime) - -if(PLUGIN_BUNDLED_LIBRARIES) - install(FILES "${PLUGIN_BUNDLED_LIBRARIES}" - DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" - COMPONENT Runtime) -endif() - -# Fully re-copy the assets directory on each build to avoid having stale files -# from a previous install. -set(FLUTTER_ASSET_DIR_NAME "flutter_assets") -install(CODE " - file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") - " COMPONENT Runtime) -install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" - DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) - -# Install the AOT library on non-Debug builds only. -install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" - CONFIGURATIONS Profile;Release - COMPONENT Runtime) diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/flutter/CMakeLists.txt b/packages/firebase_core/firebase_core/firebase_core/example/windows/flutter/CMakeLists.txt deleted file mode 100644 index 930d2071a324..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/example/windows/flutter/CMakeLists.txt +++ /dev/null @@ -1,104 +0,0 @@ -# This file controls Flutter-level build steps. It should not be edited. -cmake_minimum_required(VERSION 3.14) - -set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") - -# Configuration provided via flutter tool. -include(${EPHEMERAL_DIR}/generated_config.cmake) - -# TODO: Move the rest of this into files in ephemeral. See -# https://github.com/flutter/flutter/issues/57146. -set(WRAPPER_ROOT "${EPHEMERAL_DIR}/cpp_client_wrapper") - -# === Flutter Library === -set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/flutter_windows.dll") - -# Published to parent scope for install step. -set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) -set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) -set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) -set(AOT_LIBRARY "${PROJECT_DIR}/build/windows/app.so" PARENT_SCOPE) - -list(APPEND FLUTTER_LIBRARY_HEADERS - "flutter_export.h" - "flutter_windows.h" - "flutter_messenger.h" - "flutter_plugin_registrar.h" - "flutter_texture_registrar.h" -) -list(TRANSFORM FLUTTER_LIBRARY_HEADERS PREPEND "${EPHEMERAL_DIR}/") -add_library(flutter INTERFACE) -target_include_directories(flutter INTERFACE - "${EPHEMERAL_DIR}" -) -target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}.lib") -add_dependencies(flutter flutter_assemble) - -# === Wrapper === -list(APPEND CPP_WRAPPER_SOURCES_CORE - "core_implementations.cc" - "standard_codec.cc" -) -list(TRANSFORM CPP_WRAPPER_SOURCES_CORE PREPEND "${WRAPPER_ROOT}/") -list(APPEND CPP_WRAPPER_SOURCES_PLUGIN - "plugin_registrar.cc" -) -list(TRANSFORM CPP_WRAPPER_SOURCES_PLUGIN PREPEND "${WRAPPER_ROOT}/") -list(APPEND CPP_WRAPPER_SOURCES_APP - "flutter_engine.cc" - "flutter_view_controller.cc" -) -list(TRANSFORM CPP_WRAPPER_SOURCES_APP PREPEND "${WRAPPER_ROOT}/") - -# Wrapper sources needed for a plugin. -add_library(flutter_wrapper_plugin STATIC - ${CPP_WRAPPER_SOURCES_CORE} - ${CPP_WRAPPER_SOURCES_PLUGIN} -) -apply_standard_settings(flutter_wrapper_plugin) -set_target_properties(flutter_wrapper_plugin PROPERTIES - POSITION_INDEPENDENT_CODE ON) -set_target_properties(flutter_wrapper_plugin PROPERTIES - CXX_VISIBILITY_PRESET hidden) -target_link_libraries(flutter_wrapper_plugin PUBLIC flutter) -target_include_directories(flutter_wrapper_plugin PUBLIC - "${WRAPPER_ROOT}/include" -) -add_dependencies(flutter_wrapper_plugin flutter_assemble) - -# Wrapper sources needed for the runner. -add_library(flutter_wrapper_app STATIC - ${CPP_WRAPPER_SOURCES_CORE} - ${CPP_WRAPPER_SOURCES_APP} -) -apply_standard_settings(flutter_wrapper_app) -target_link_libraries(flutter_wrapper_app PUBLIC flutter) -target_include_directories(flutter_wrapper_app PUBLIC - "${WRAPPER_ROOT}/include" -) -add_dependencies(flutter_wrapper_app flutter_assemble) - -# === Flutter tool backend === -# _phony_ is a non-existent file to force this command to run every time, -# since currently there's no way to get a full input/output list from the -# flutter tool. -set(PHONY_OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/_phony_") -set_source_files_properties("${PHONY_OUTPUT}" PROPERTIES SYMBOLIC TRUE) -add_custom_command( - OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} - ${CPP_WRAPPER_SOURCES_CORE} ${CPP_WRAPPER_SOURCES_PLUGIN} - ${CPP_WRAPPER_SOURCES_APP} - ${PHONY_OUTPUT} - COMMAND ${CMAKE_COMMAND} -E env - ${FLUTTER_TOOL_ENVIRONMENT} - "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.bat" - windows-x64 $ - VERBATIM -) -add_custom_target(flutter_assemble DEPENDS - "${FLUTTER_LIBRARY}" - ${FLUTTER_LIBRARY_HEADERS} - ${CPP_WRAPPER_SOURCES_CORE} - ${CPP_WRAPPER_SOURCES_PLUGIN} - ${CPP_WRAPPER_SOURCES_APP} -) diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/flutter/generated_plugin_registrant.cc b/packages/firebase_core/firebase_core/firebase_core/example/windows/flutter/generated_plugin_registrant.cc deleted file mode 100644 index 1a82e7d01dce..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/example/windows/flutter/generated_plugin_registrant.cc +++ /dev/null @@ -1,14 +0,0 @@ -// -// Generated file. Do not edit. -// - -// clang-format off - -#include "generated_plugin_registrant.h" - -#include - -void RegisterPlugins(flutter::PluginRegistry* registry) { - FirebaseCorePluginCApiRegisterWithRegistrar( - registry->GetRegistrarForPlugin("FirebaseCorePluginCApi")); -} diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/flutter/generated_plugin_registrant.h b/packages/firebase_core/firebase_core/firebase_core/example/windows/flutter/generated_plugin_registrant.h deleted file mode 100644 index dc139d85a931..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/example/windows/flutter/generated_plugin_registrant.h +++ /dev/null @@ -1,15 +0,0 @@ -// -// Generated file. Do not edit. -// - -// clang-format off - -#ifndef GENERATED_PLUGIN_REGISTRANT_ -#define GENERATED_PLUGIN_REGISTRANT_ - -#include - -// Registers Flutter plugins. -void RegisterPlugins(flutter::PluginRegistry* registry); - -#endif // GENERATED_PLUGIN_REGISTRANT_ diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/flutter/generated_plugins.cmake b/packages/firebase_core/firebase_core/firebase_core/example/windows/flutter/generated_plugins.cmake deleted file mode 100644 index fa8a39bab15e..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/example/windows/flutter/generated_plugins.cmake +++ /dev/null @@ -1,24 +0,0 @@ -# -# Generated file, do not edit. -# - -list(APPEND FLUTTER_PLUGIN_LIST - firebase_core -) - -list(APPEND FLUTTER_FFI_PLUGIN_LIST -) - -set(PLUGIN_BUNDLED_LIBRARIES) - -foreach(plugin ${FLUTTER_PLUGIN_LIST}) - add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/windows plugins/${plugin}) - target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) - list(APPEND PLUGIN_BUNDLED_LIBRARIES $) - list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) -endforeach(plugin) - -foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST}) - add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/windows plugins/${ffi_plugin}) - list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries}) -endforeach(ffi_plugin) diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/CMakeLists.txt b/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/CMakeLists.txt deleted file mode 100644 index 394917c053a0..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/CMakeLists.txt +++ /dev/null @@ -1,40 +0,0 @@ -cmake_minimum_required(VERSION 3.14) -project(runner LANGUAGES CXX) - -# Define the application target. To change its name, change BINARY_NAME in the -# top-level CMakeLists.txt, not the value here, or `flutter run` will no longer -# work. -# -# Any new source files that you add to the application should be added here. -add_executable(${BINARY_NAME} WIN32 - "flutter_window.cpp" - "main.cpp" - "utils.cpp" - "win32_window.cpp" - "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" - "Runner.rc" - "runner.exe.manifest" -) - -# Apply the standard set of build settings. This can be removed for applications -# that need different build settings. -apply_standard_settings(${BINARY_NAME}) - -# Add preprocessor definitions for the build version. -target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION=\"${FLUTTER_VERSION}\"") -target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MAJOR=${FLUTTER_VERSION_MAJOR}") -target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MINOR=${FLUTTER_VERSION_MINOR}") -target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_PATCH=${FLUTTER_VERSION_PATCH}") -target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_BUILD=${FLUTTER_VERSION_BUILD}") - -# Disable Windows macros that collide with C++ standard library functions. -target_compile_definitions(${BINARY_NAME} PRIVATE "NOMINMAX") - -# Add dependency libraries and include directories. Add any application-specific -# dependencies here. -target_link_libraries(${BINARY_NAME} PRIVATE flutter flutter_wrapper_app) -target_link_libraries(${BINARY_NAME} PRIVATE "dwmapi.lib") -target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") - -# Run the Flutter tool portions of the build. This must not be removed. -add_dependencies(${BINARY_NAME} flutter_assemble) diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/Runner.rc b/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/Runner.rc deleted file mode 100644 index c0d7fe21c712..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/Runner.rc +++ /dev/null @@ -1,121 +0,0 @@ -// Microsoft Visual C++ generated resource script. -// -#pragma code_page(65001) -#include "resource.h" - -#define APSTUDIO_READONLY_SYMBOLS -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 2 resource. -// -#include "winres.h" - -///////////////////////////////////////////////////////////////////////////// -#undef APSTUDIO_READONLY_SYMBOLS - -///////////////////////////////////////////////////////////////////////////// -// English (United States) resources - -#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) -LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US - -#ifdef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// TEXTINCLUDE -// - -1 TEXTINCLUDE -BEGIN - "resource.h\0" -END - -2 TEXTINCLUDE -BEGIN - "#include ""winres.h""\r\n" - "\0" -END - -3 TEXTINCLUDE -BEGIN - "\r\n" - "\0" -END - -#endif // APSTUDIO_INVOKED - - -///////////////////////////////////////////////////////////////////////////// -// -// Icon -// - -// Icon with lowest ID value placed first to ensure application icon -// remains consistent on all systems. -IDI_APP_ICON ICON "resources\\app_icon.ico" - - -///////////////////////////////////////////////////////////////////////////// -// -// Version -// - -#if defined(FLUTTER_VERSION_MAJOR) && defined(FLUTTER_VERSION_MINOR) && defined(FLUTTER_VERSION_PATCH) && defined(FLUTTER_VERSION_BUILD) -#define VERSION_AS_NUMBER FLUTTER_VERSION_MAJOR,FLUTTER_VERSION_MINOR,FLUTTER_VERSION_PATCH,FLUTTER_VERSION_BUILD -#else -#define VERSION_AS_NUMBER 1,0,0,0 -#endif - -#if defined(FLUTTER_VERSION) -#define VERSION_AS_STRING FLUTTER_VERSION -#else -#define VERSION_AS_STRING "1.0.0" -#endif - -VS_VERSION_INFO VERSIONINFO - FILEVERSION VERSION_AS_NUMBER - PRODUCTVERSION VERSION_AS_NUMBER - FILEFLAGSMASK VS_FFI_FILEFLAGSMASK -#ifdef _DEBUG - FILEFLAGS VS_FF_DEBUG -#else - FILEFLAGS 0x0L -#endif - FILEOS VOS__WINDOWS32 - FILETYPE VFT_APP - FILESUBTYPE 0x0L -BEGIN - BLOCK "StringFileInfo" - BEGIN - BLOCK "040904e4" - BEGIN - VALUE "CompanyName", "com.example" "\0" - VALUE "FileDescription", "firebase_core_example" "\0" - VALUE "FileVersion", VERSION_AS_STRING "\0" - VALUE "InternalName", "firebase_core_example" "\0" - VALUE "LegalCopyright", "Copyright (C) 2023 com.example. All rights reserved." "\0" - VALUE "OriginalFilename", "firebase_core_example.exe" "\0" - VALUE "ProductName", "firebase_core_example" "\0" - VALUE "ProductVersion", VERSION_AS_STRING "\0" - END - END - BLOCK "VarFileInfo" - BEGIN - VALUE "Translation", 0x409, 1252 - END -END - -#endif // English (United States) resources -///////////////////////////////////////////////////////////////////////////// - - - -#ifndef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 3 resource. -// - - -///////////////////////////////////////////////////////////////////////////// -#endif // not APSTUDIO_INVOKED diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/flutter_window.cpp b/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/flutter_window.cpp deleted file mode 100644 index b25e363efa42..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/flutter_window.cpp +++ /dev/null @@ -1,66 +0,0 @@ -#include "flutter_window.h" - -#include - -#include "flutter/generated_plugin_registrant.h" - -FlutterWindow::FlutterWindow(const flutter::DartProject& project) - : project_(project) {} - -FlutterWindow::~FlutterWindow() {} - -bool FlutterWindow::OnCreate() { - if (!Win32Window::OnCreate()) { - return false; - } - - RECT frame = GetClientArea(); - - // The size here must match the window dimensions to avoid unnecessary surface - // creation / destruction in the startup path. - flutter_controller_ = std::make_unique( - frame.right - frame.left, frame.bottom - frame.top, project_); - // Ensure that basic setup of the controller was successful. - if (!flutter_controller_->engine() || !flutter_controller_->view()) { - return false; - } - RegisterPlugins(flutter_controller_->engine()); - SetChildContent(flutter_controller_->view()->GetNativeWindow()); - - flutter_controller_->engine()->SetNextFrameCallback([&]() { - this->Show(); - }); - - return true; -} - -void FlutterWindow::OnDestroy() { - if (flutter_controller_) { - flutter_controller_ = nullptr; - } - - Win32Window::OnDestroy(); -} - -LRESULT -FlutterWindow::MessageHandler(HWND hwnd, UINT const message, - WPARAM const wparam, - LPARAM const lparam) noexcept { - // Give Flutter, including plugins, an opportunity to handle window messages. - if (flutter_controller_) { - std::optional result = - flutter_controller_->HandleTopLevelWindowProc(hwnd, message, wparam, - lparam); - if (result) { - return *result; - } - } - - switch (message) { - case WM_FONTCHANGE: - flutter_controller_->engine()->ReloadSystemFonts(); - break; - } - - return Win32Window::MessageHandler(hwnd, message, wparam, lparam); -} diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/flutter_window.h b/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/flutter_window.h deleted file mode 100644 index 6da0652f05f2..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/flutter_window.h +++ /dev/null @@ -1,33 +0,0 @@ -#ifndef RUNNER_FLUTTER_WINDOW_H_ -#define RUNNER_FLUTTER_WINDOW_H_ - -#include -#include - -#include - -#include "win32_window.h" - -// A window that does nothing but host a Flutter view. -class FlutterWindow : public Win32Window { - public: - // Creates a new FlutterWindow hosting a Flutter view running |project|. - explicit FlutterWindow(const flutter::DartProject& project); - virtual ~FlutterWindow(); - - protected: - // Win32Window: - bool OnCreate() override; - void OnDestroy() override; - LRESULT MessageHandler(HWND window, UINT const message, WPARAM const wparam, - LPARAM const lparam) noexcept override; - - private: - // The project to run. - flutter::DartProject project_; - - // The Flutter instance hosted by this window. - std::unique_ptr flutter_controller_; -}; - -#endif // RUNNER_FLUTTER_WINDOW_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/google-services-desktop.json b/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/google-services-desktop.json deleted file mode 100644 index a3bf216f4de0..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/google-services-desktop.json +++ /dev/null @@ -1,37 +0,0 @@ -{ - "project_info": { - "project_number": "406099696497", - "firebase_url": "https://flutterfire-e2e-tests-default-rtdb.europe-west1.firebasedatabase.app", - "project_id": "flutterfire-e2e-tests", - "storage_bucket": "flutterfire-e2e-tests.appspot.com" - }, - "client": [ - { - "client_info": { - "mobilesdk_app_id": "1:406099696497:ios:58cbc26aca8e5cf83574d0", - "android_client_info": { - "package_name": "io.flutter.plugins.firebase.auth.example" - } - }, - "oauth_client": [ - { - "client_id": "406099696497-134k3722m01rtrsklhf3b7k8sqa5r7in.apps.googleusercontent.com" - } - ], - "api_key": [ - { - "current_key": "AIzaSyDooSUGSf63Ghq02_iIhtnmwMDs4HlWS6c" - } - ], - "services": { - "analytics_service": { - "status": 0 - }, - "appinvite_service": { - "status": 1 - } - } - } - ], - "configuration_version": "1" -} \ No newline at end of file diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/main.cpp b/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/main.cpp deleted file mode 100644 index 2b640e48b2b0..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/main.cpp +++ /dev/null @@ -1,43 +0,0 @@ -#include -#include -#include - -#include "flutter_window.h" -#include "utils.h" - -int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev, - _In_ wchar_t *command_line, _In_ int show_command) { - // Attach to console when present (e.g., 'flutter run') or create a - // new console when running with a debugger. - if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent()) { - CreateAndAttachConsole(); - } - - // Initialize COM, so that it is available for use in the library and/or - // plugins. - ::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED); - - flutter::DartProject project(L"data"); - - std::vector command_line_arguments = - GetCommandLineArguments(); - - project.set_dart_entrypoint_arguments(std::move(command_line_arguments)); - - FlutterWindow window(project); - Win32Window::Point origin(10, 10); - Win32Window::Size size(1280, 720); - if (!window.Create(L"firebase_core_example", origin, size)) { - return EXIT_FAILURE; - } - window.SetQuitOnClose(true); - - ::MSG msg; - while (::GetMessage(&msg, nullptr, 0, 0)) { - ::TranslateMessage(&msg); - ::DispatchMessage(&msg); - } - - ::CoUninitialize(); - return EXIT_SUCCESS; -} diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/resource.h b/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/resource.h deleted file mode 100644 index 66a65d1e4a79..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/resource.h +++ /dev/null @@ -1,16 +0,0 @@ -//{{NO_DEPENDENCIES}} -// Microsoft Visual C++ generated include file. -// Used by Runner.rc -// -#define IDI_APP_ICON 101 - -// Next default values for new objects -// -#ifdef APSTUDIO_INVOKED -#ifndef APSTUDIO_READONLY_SYMBOLS -#define _APS_NEXT_RESOURCE_VALUE 102 -#define _APS_NEXT_COMMAND_VALUE 40001 -#define _APS_NEXT_CONTROL_VALUE 1001 -#define _APS_NEXT_SYMED_VALUE 101 -#endif -#endif diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/resources/app_icon.ico b/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/resources/app_icon.ico deleted file mode 100644 index c04e20caf6370ebb9253ad831cc31de4a9c965f6..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 33772 zcmeHQc|26z|35SKE&G-*mXah&B~fFkXr)DEO&hIfqby^T&>|8^_Ub8Vp#`BLl3lbZ zvPO!8k!2X>cg~Elr=IVxo~J*a`+9wR=A83c-k-DFd(XM&UI1VKCqM@V;DDtJ09WB} zRaHKiW(GT00brH|0EeTeKVbpbGZg?nK6-j827q-+NFM34gXjqWxJ*a#{b_apGN<-L_m3#8Z26atkEn& ze87Bvv^6vVmM+p+cQ~{u%=NJF>#(d;8{7Q{^rWKWNtf14H}>#&y7$lqmY6xmZryI& z($uy?c5-+cPnt2%)R&(KIWEXww>Cnz{OUpT>W$CbO$h1= z#4BPMkFG1Y)x}Ui+WXr?Z!w!t_hjRq8qTaWpu}FH{MsHlU{>;08goVLm{V<&`itk~ zE_Ys=D(hjiy+5=?=$HGii=Y5)jMe9|wWoD_K07(}edAxh`~LBorOJ!Cf@f{_gNCC| z%{*04ViE!#>@hc1t5bb+NO>ncf@@Dv01K!NxH$3Eg1%)|wLyMDF8^d44lV!_Sr}iEWefOaL z8f?ud3Q%Sen39u|%00W<#!E=-RpGa+H8}{ulxVl4mwpjaU+%2pzmi{3HM)%8vb*~-M9rPUAfGCSos8GUXp02|o~0BTV2l#`>>aFV&_P$ejS;nGwSVP8 zMbOaG7<7eKD>c12VdGH;?2@q7535sa7MN*L@&!m?L`ASG%boY7(&L5imY#EQ$KrBB z4@_tfP5m50(T--qv1BJcD&aiH#b-QC>8#7Fx@3yXlonJI#aEIi=8&ChiVpc#N=5le zM*?rDIdcpawoc5kizv$GEjnveyrp3sY>+5_R5;>`>erS%JolimF=A^EIsAK zsPoVyyUHCgf0aYr&alx`<)eb6Be$m&`JYSuBu=p8j%QlNNp$-5C{b4#RubPb|CAIS zGE=9OFLP7?Hgc{?k45)84biT0k&-C6C%Q}aI~q<(7BL`C#<6HyxaR%!dFx7*o^laG z=!GBF^cwK$IA(sn9y6>60Rw{mYRYkp%$jH z*xQM~+bp)G$_RhtFPYx2HTsWk80+p(uqv9@I9)y{b$7NK53rYL$ezbmRjdXS?V}fj zWxX_feWoLFNm3MG7pMUuFPs$qrQWO9!l2B(SIuy2}S|lHNbHzoE+M2|Zxhjq9+Ws8c{*}x^VAib7SbxJ*Q3EnY5lgI9 z=U^f3IW6T=TWaVj+2N%K3<%Un;CF(wUp`TC&Y|ZjyFu6co^uqDDB#EP?DV5v_dw~E zIRK*BoY9y-G_ToU2V_XCX4nJ32~`czdjT!zwme zGgJ0nOk3U4@IE5JwtM}pwimLjk{ln^*4HMU%Fl4~n(cnsLB}Ja-jUM>xIB%aY;Nq8 z)Fp8dv1tkqKanv<68o@cN|%thj$+f;zGSO7H#b+eMAV8xH$hLggtt?O?;oYEgbq@= zV(u9bbd12^%;?nyk6&$GPI%|+<_mEpJGNfl*`!KV;VfmZWw{n{rnZ51?}FDh8we_L z8OI9nE31skDqJ5Oa_ybn7|5@ui>aC`s34p4ZEu6-s!%{uU45$Zd1=p$^^dZBh zu<*pDDPLW+c>iWO$&Z_*{VSQKg7=YEpS3PssPn1U!lSm6eZIho*{@&20e4Y_lRklKDTUCKI%o4Pc<|G^Xgu$J^Q|B87U;`c1zGwf^-zH*VQ^x+i^OUWE0yd z;{FJq)2w!%`x7yg@>uGFFf-XJl4H`YtUG%0slGKOlXV`q?RP>AEWg#x!b{0RicxGhS!3$p7 zij;{gm!_u@D4$Ox%>>bPtLJ> zwKtYz?T_DR1jN>DkkfGU^<#6sGz|~p*I{y`aZ>^Di#TC|Z!7j_O1=Wo8thuit?WxR zh9_S>kw^{V^|g}HRUF=dcq>?q(pHxw!8rx4dC6vbQVmIhmICF#zU!HkHpQ>9S%Uo( zMw{eC+`&pb=GZRou|3;Po1}m46H6NGd$t<2mQh}kaK-WFfmj_66_17BX0|j-E2fe3Jat}ijpc53 zJV$$;PC<5aW`{*^Z6e5##^`Ed#a0nwJDT#Qq~^e8^JTA=z^Kl>La|(UQ!bI@#ge{Dzz@61p-I)kc2?ZxFt^QQ}f%ldLjO*GPj(5)V9IyuUakJX=~GnTgZ4$5!3E=V#t`yOG4U z(gphZB6u2zsj=qNFLYShhg$}lNpO`P9xOSnO*$@@UdMYES*{jJVj|9z-}F^riksLK zbsU+4-{281P9e2UjY6tse^&a)WM1MFw;p#_dHhWI7p&U*9TR0zKdVuQed%6{otTsq z$f~S!;wg#Bd9kez=Br{m|66Wv z#g1xMup<0)H;c2ZO6su_ii&m8j&+jJz4iKnGZ&wxoQX|5a>v&_e#6WA!MB_4asTxLRGQCC5cI(em z%$ZfeqP>!*q5kU>a+BO&ln=4Jm>Ef(QE8o&RgLkk%2}4Tf}U%IFP&uS7}&|Q-)`5< z+e>;s#4cJ-z%&-^&!xsYx777Wt(wZY9(3(avmr|gRe4cD+a8&!LY`1^T?7x{E<=kdY9NYw>A;FtTvQ=Y&1M%lyZPl$ss1oY^Sl8we}n}Aob#6 zl4jERwnt9BlSoWb@3HxYgga(752Vu6Y)k4yk9u~Kw>cA5&LHcrvn1Y-HoIuFWg~}4 zEw4bR`mXZQIyOAzo)FYqg?$5W<;^+XX%Uz61{-L6@eP|lLH%|w?g=rFc;OvEW;^qh z&iYXGhVt(G-q<+_j}CTbPS_=K>RKN0&;dubh0NxJyDOHFF;<1k!{k#7b{|Qok9hac z;gHz}6>H6C6RnB`Tt#oaSrX0p-j-oRJ;_WvS-qS--P*8}V943RT6kou-G=A+7QPGQ z!ze^UGxtW3FC0$|(lY9^L!Lx^?Q8cny(rR`es5U;-xBhphF%_WNu|aO<+e9%6LuZq zt(0PoagJG<%hyuf;te}n+qIl_Ej;czWdc{LX^pS>77s9t*2b4s5dvP_!L^3cwlc)E!(!kGrg~FescVT zZCLeua3f4;d;Tk4iXzt}g}O@nlK3?_o91_~@UMIl?@77Qc$IAlLE95#Z=TES>2E%z zxUKpK{_HvGF;5%Q7n&vA?`{%8ohlYT_?(3A$cZSi)MvIJygXD}TS-3UwyUxGLGiJP znblO~G|*uA^|ac8E-w#}uBtg|s_~s&t>-g0X%zIZ@;o_wNMr_;{KDg^O=rg`fhDZu zFp(VKd1Edj%F zWHPl+)FGj%J1BO3bOHVfH^3d1F{)*PL&sRX`~(-Zy3&9UQX)Z;c51tvaI2E*E7!)q zcz|{vpK7bjxix(k&6=OEIBJC!9lTkUbgg?4-yE{9+pFS)$Ar@vrIf`D0Bnsed(Cf? zObt2CJ>BKOl>q8PyFO6w)+6Iz`LW%T5^R`U_NIW0r1dWv6OY=TVF?N=EfA(k(~7VBW(S;Tu5m4Lg8emDG-(mOSSs=M9Q&N8jc^Y4&9RqIsk(yO_P(mcCr}rCs%1MW1VBrn=0-oQN(Xj!k%iKV zb%ricBF3G4S1;+8lzg5PbZ|$Se$)I=PwiK=cDpHYdov2QO1_a-*dL4KUi|g&oh>(* zq$<`dQ^fat`+VW?m)?_KLn&mp^-@d=&7yGDt<=XwZZC=1scwxO2^RRI7n@g-1o8ps z)&+et_~)vr8aIF1VY1Qrq~Xe``KJrQSnAZ{CSq3yP;V*JC;mmCT6oRLSs7=GA?@6g zUooM}@tKtx(^|aKK8vbaHlUQqwE0}>j&~YlN3H#vKGm@u)xxS?n9XrOWUfCRa< z`20Fld2f&;gg7zpo{Adh+mqNntMc-D$N^yWZAZRI+u1T1zWHPxk{+?vcS1D>08>@6 zLhE@`gt1Y9mAK6Z4p|u(5I%EkfU7rKFSM=E4?VG9tI;a*@?6!ey{lzN5=Y-!$WFSe z&2dtO>^0@V4WRc#L&P%R(?@KfSblMS+N+?xUN$u3K4Ys%OmEh+tq}fnU}i>6YHM?< zlnL2gl~sF!j!Y4E;j3eIU-lfa`RsOL*Tt<%EFC0gPzoHfNWAfKFIKZN8}w~(Yi~=q z>=VNLO2|CjkxP}RkutxjV#4fWYR1KNrPYq5ha9Wl+u>ipsk*I(HS@iLnmGH9MFlTU zaFZ*KSR0px>o+pL7BbhB2EC1%PJ{67_ z#kY&#O4@P=OV#-79y_W>Gv2dxL*@G7%LksNSqgId9v;2xJ zrh8uR!F-eU$NMx@S*+sk=C~Dxr9Qn7TfWnTupuHKuQ$;gGiBcU>GF5sWx(~4IP3`f zWE;YFO*?jGwYh%C3X<>RKHC-DZ!*r;cIr}GLOno^3U4tFSSoJp%oHPiSa%nh=Zgn% z14+8v@ygy0>UgEN1bczD6wK45%M>psM)y^)IfG*>3ItX|TzV*0i%@>L(VN!zdKb8S?Qf7BhjNpziA zR}?={-eu>9JDcl*R=OP9B8N$IcCETXah9SUDhr{yrld{G;PnCWRsPD7!eOOFBTWUQ=LrA_~)mFf&!zJX!Oc-_=kT<}m|K52 z)M=G#;p;Rdb@~h5D{q^K;^fX-m5V}L%!wVC2iZ1uu401Ll}#rocTeK|7FAeBRhNdQ zCc2d^aQnQp=MpOmak60N$OgS}a;p(l9CL`o4r(e-nN}mQ?M&isv-P&d$!8|1D1I(3-z!wi zTgoo)*Mv`gC?~bm?S|@}I|m-E2yqPEvYybiD5azInexpK8?9q*$9Yy9-t%5jU8~ym zgZDx>!@ujQ=|HJnwp^wv-FdD{RtzO9SnyfB{mH_(c!jHL*$>0o-(h(eqe*ZwF6Lvu z{7rkk%PEqaA>o+f{H02tzZ@TWy&su?VNw43! z-X+rN`6llvpUms3ZiSt)JMeztB~>9{J8SPmYs&qohxdYFi!ra8KR$35Zp9oR)eFC4 zE;P31#3V)n`w$fZ|4X-|%MX`xZDM~gJyl2W;O$H25*=+1S#%|53>|LyH za@yh+;325%Gq3;J&a)?%7X%t@WXcWL*BaaR*7UEZad4I8iDt7^R_Fd`XeUo256;sAo2F!HcIQKk;h})QxEsPE5BcKc7WyerTchgKmrfRX z!x#H_%cL#B9TWAqkA4I$R^8{%do3Y*&(;WFmJ zU7Dih{t1<{($VtJRl9|&EB?|cJ)xse!;}>6mSO$o5XIx@V|AA8ZcoD88ZM?C*;{|f zZVmf94_l1OmaICt`2sTyG!$^UeTHx9YuUP!omj(r|7zpm5475|yXI=rR>>fteLI+| z)MoiGho0oEt=*J(;?VY0QzwCqw@cVm?d7Y!z0A@u#H?sCJ*ecvyhj& z-F77lO;SH^dmf?L>3i>?Z*U}Em4ZYV_CjgfvzYsRZ+1B!Uo6H6mbS<-FFL`ytqvb& zE7+)2ahv-~dz(Hs+f})z{*4|{)b=2!RZK;PWwOnO=hG7xG`JU5>bAvUbdYd_CjvtHBHgtGdlO+s^9ca^Bv3`t@VRX2_AD$Ckg36OcQRF zXD6QtGfHdw*hx~V(MV-;;ZZF#dJ-piEF+s27z4X1qi5$!o~xBnvf=uopcn7ftfsZc zy@(PuOk`4GL_n(H9(E2)VUjqRCk9kR?w)v@xO6Jm_Mx})&WGEl=GS0#)0FAq^J*o! zAClhvoTsNP*-b~rN{8Yym3g{01}Ep^^Omf=SKqvN?{Q*C4HNNAcrowIa^mf+3PRy! z*_G-|3i8a;+q;iP@~Of_$(vtFkB8yOyWt2*K)vAn9El>=D;A$CEx6b*XF@4y_6M+2 zpeW`RHoI_p(B{%(&jTHI->hmNmZjHUj<@;7w0mx3&koy!2$@cfX{sN19Y}euYJFn& z1?)+?HCkD0MRI$~uB2UWri})0bru_B;klFdwsLc!ne4YUE;t41JqfG# zZJq6%vbsdx!wYeE<~?>o4V`A3?lN%MnKQ`z=uUivQN^vzJ|C;sdQ37Qn?;lpzg})y z)_2~rUdH}zNwX;Tp0tJ78+&I=IwOQ-fl30R79O8@?Ub8IIA(6I`yHn%lARVL`%b8+ z4$8D-|MZZWxc_)vu6@VZN!HsI$*2NOV&uMxBNzIbRgy%ob_ zhwEH{J9r$!dEix9XM7n&c{S(h>nGm?el;gaX0@|QnzFD@bne`el^CO$yXC?BDJ|Qg z+y$GRoR`?ST1z^e*>;!IS@5Ovb7*RlN>BV_UC!7E_F;N#ky%1J{+iixp(dUJj93aK zzHNN>R-oN7>kykHClPnoPTIj7zc6KM(Pnlb(|s??)SMb)4!sMHU^-ntJwY5Big7xv zb1Ew`Xj;|D2kzGja*C$eS44(d&RMU~c_Y14V9_TLTz0J#uHlsx`S6{nhsA0dWZ#cG zJ?`fO50E>*X4TQLv#nl%3GOk*UkAgt=IY+u0LNXqeln3Z zv$~&Li`ZJOKkFuS)dJRA>)b_Da%Q~axwA_8zNK{BH{#}#m}zGcuckz}riDE-z_Ms> zR8-EqAMcfyGJCtvTpaUVQtajhUS%c@Yj}&6Zz;-M7MZzqv3kA7{SuW$oW#=0az2wQ zg-WG@Vb4|D`pl~Il54N7Hmsauc_ne-a!o5#j3WaBBh@Wuefb!QJIOn5;d)%A#s+5% zuD$H=VNux9bE-}1&bcYGZ+>1Fo;3Z@e&zX^n!?JK*adSbONm$XW9z;Q^L>9U!}Toj2WdafJ%oL#h|yWWwyAGxzfrAWdDTtaKl zK4`5tDpPg5>z$MNv=X0LZ0d6l%D{(D8oT@+w0?ce$DZ6pv>{1&Ok67Ix1 zH}3=IEhPJEhItCC8E=`T`N5(k?G=B4+xzZ?<4!~ ze~z6Wk9!CHTI(0rLJ4{JU?E-puc;xusR?>G?;4vt;q~iI9=kDL=z0Rr%O$vU`30X$ zDZRFyZ`(omOy@u|i6h;wtJlP;+}$|Ak|k2dea7n?U1*$T!sXqqOjq^NxLPMmk~&qI zYg0W?yK8T(6+Ea+$YyspKK?kP$+B`~t3^Pib_`!6xCs32!i@pqXfFV6PmBIR<-QW= zN8L{pt0Vap0x`Gzn#E@zh@H)0FfVfA_Iu4fjYZ+umO1LXIbVc$pY+E234u)ttcrl$ z>s92z4vT%n6cMb>=XT6;l0+9e(|CZG)$@C7t7Z7Ez@a)h)!hyuV&B5K%%)P5?Lk|C zZZSVzdXp{@OXSP0hoU-gF8s8Um(#xzjP2Vem zec#-^JqTa&Y#QJ>-FBxd7tf`XB6e^JPUgagB8iBSEps;92KG`!#mvVcPQ5yNC-GEG zTiHEDYfH+0O15}r^+ z#jxj=@x8iNHWALe!P3R67TwmhItn**0JwnzSV2O&KE8KcT+0hWH^OPD1pwiuyx=b@ zNf5Jh0{9X)8;~Es)$t@%(3!OnbY+`@?i{mGX7Yy}8T_*0a6g;kaFPq;*=px5EhO{Cp%1kI<0?*|h8v!6WnO3cCJRF2-CRrU3JiLJnj@6;L)!0kWYAc_}F{2P))3HmCrz zQ&N&gE70;`!6*eJ4^1IR{f6j4(-l&X!tjHxkbHA^Zhrnhr9g{exN|xrS`5Pq=#Xf& zG%P=#ra-TyVFfgW%cZo5OSIwFL9WtXAlFOa+ubmI5t*3=g#Y zF%;70p5;{ZeFL}&}yOY1N1*Q;*<(kTB!7vM$QokF)yr2FlIU@$Ph58$Bz z0J?xQG=MlS4L6jA22eS42g|9*9pX@$#*sUeM(z+t?hr@r5J&D1rx}2pW&m*_`VDCW zUYY@v-;bAO0HqoAgbbiGGC<=ryf96}3pouhy3XJrX+!!u*O_>Si38V{uJmQ&USptX zKp#l(?>%^7;2%h(q@YWS#9;a!JhKlkR#Vd)ERILlgu!Hr@jA@V;sk4BJ-H#p*4EqC zDGjC*tl=@3Oi6)Bn^QwFpul18fpkbpg0+peH$xyPBqb%`$OUhPKyWb32o7clB*9Z< zN=i~NLjavrLtwgJ01bufP+>p-jR2I95|TpmKpQL2!oV>g(4RvS2pK4*ou%m(h6r3A zX#s&`9LU1ZG&;{CkOK!4fLDTnBys`M!vuz>Q&9OZ0hGQl!~!jSDg|~s*w52opC{sB ze|Cf2luD(*G13LcOAGA!s2FjSK8&IE5#W%J25w!vM0^VyQM!t)inj&RTiJ!wXzFgz z3^IqzB7I0L$llljsGq})thBy9UOyjtFO_*hYM_sgcMk>44jeH0V1FDyELc{S1F-;A zS;T^k^~4biG&V*Irq}O;e}j$$+E_#G?HKIn05iP3j|87TkGK~SqG!-KBg5+mN(aLm z8ybhIM`%C19UX$H$KY6JgXbY$0AT%rEpHC;u`rQ$Y=rxUdsc5*Kvc8jaYaO$^)cI6){P6K0r)I6DY4Wr4&B zLQUBraey#0HV|&c4v7PVo3n$zHj99(TZO^3?Ly%C4nYvJTL9eLBLHsM3WKKD>5!B` zQ=BsR3aR6PD(Fa>327E2HAu5TM~Wusc!)>~(gM)+3~m;92Jd;FnSib=M5d6;;5{%R zb4V7DEJ0V!CP-F*oU?gkc>ksUtAYP&V4ND5J>J2^jt*vcFflQWCrB&fLdT%O59PVJ zhid#toR=FNgD!q3&r8#wEBr`!wzvQu5zX?Q>nlSJ4i@WC*CN*-xU66F^V5crWevQ9gsq$I@z1o(a=k7LL~ z7m_~`o;_Ozha1$8Q}{WBehvAlO4EL60y5}8GDrZ< zXh&F}71JbW2A~8KfEWj&UWV#4+Z4p`b{uAj4&WC zha`}X@3~+Iz^WRlOHU&KngK>#j}+_o@LdBC1H-`gT+krWX3-;!)6?{FBp~%20a}FL zFP9%Emqcwa#(`=G>BBZ0qZDQhmZKJg_g8<=bBFKWr!dyg(YkpE+|R*SGpDVU!+VlU zFC54^DLv}`qa%49T>nNiA9Q7Ips#!Xx90tCU2gvK`(F+GPcL=J^>No{)~we#o@&mUb6c$ zCc*<|NJBk-#+{j9xkQ&ujB zI~`#kN~7W!f*-}wkG~Ld!JqZ@tK}eeSnsS5J1fMFXm|`LJx&}5`@dK3W^7#Wnm+_P zBZkp&j1fa2Y=eIjJ0}gh85jt43kaIXXv?xmo@eHrka!Z|vQv12HN#+!I5E z`(fbuW>gFiJL|uXJ!vKt#z3e3HlVdboH7;e#i3(2<)Fg-I@BR!qY#eof3MFZ&*Y@l zI|KJf&ge@p2Dq09Vu$$Qxb7!}{m-iRk@!)%KL)txi3;~Z4Pb}u@GsW;ELiWeG9V51 znX#}B&4Y2E7-H=OpNE@q{%hFLxwIpBF2t{vPREa8_{linXT;#1vMRWjOzLOP$-hf( z>=?$0;~~PnkqY;~K{EM6Vo-T(0K{A0}VUGmu*hR z{tw3hvBN%N3G3Yw`X5Te+F{J`(3w1s3-+1EbnFQKcrgrX1Jqvs@ADGe%M0s$EbK$$ zK)=y=upBc6SjGYAACCcI=Y*6Fi8_jgwZlLxD26fnQfJmb8^gHRN5(TemhX@0e=vr> zg`W}6U>x6VhoA3DqsGGD9uL1DhB3!OXO=k}59TqD@(0Nb{)Ut_luTioK_>7wjc!5C zIr@w}b`Fez3)0wQfKl&bae7;PcTA7%?f2xucM0G)wt_KO!Ewx>F~;=BI0j=Fb4>pp zv}0R^xM4eti~+^+gE$6b81p(kwzuDti(-K9bc|?+pJEl@H+jSYuxZQV8rl8 zjp@M{#%qItIUFN~KcO9Hed*`$5A-2~pAo~K&<-Q+`9`$CK>rzqAI4w~$F%vs9s{~x zg4BP%Gy*@m?;D6=SRX?888Q6peF@_4Z->8wAH~Cn!R$|Hhq2cIzFYqT_+cDourHbY z0qroxJnrZ4Gh+Ay+F`_c%+KRT>y3qw{)89?=hJ@=KO=@ep)aBJ$c!JHfBMJpsP*3G za7|)VJJ8B;4?n{~ldJF7%jmb`-ftIvNd~ekoufG(`K(3=LNc;HBY& z(lp#q8XAD#cIf}k49zX_i`*fO+#!zKA&%T3j@%)R+#yag067CU%yUEe47>wzGU8^` z1EXFT^@I!{J!F8!X?S6ph8J=gUi5tl93*W>7}_uR<2N2~e}FaG?}KPyugQ=-OGEZs z!GBoyYY+H*ANn4?Z)X4l+7H%`17i5~zRlRIX?t)6_eu=g2Q`3WBhxSUeea+M-S?RL zX9oBGKn%a!H+*hx4d2(I!gsi+@SQK%<{X22M~2tMulJoa)0*+z9=-YO+;DFEm5eE1U9b^B(Z}2^9!Qk`!A$wUE z7$Ar5?NRg2&G!AZqnmE64eh^Anss3i!{}%6@Et+4rr!=}!SBF8eZ2*J3ujCWbl;3; z48H~goPSv(8X61fKKdpP!Z7$88NL^Z?j`!^*I?-P4X^pMxyWz~@$(UeAcTSDd(`vO z{~rc;9|GfMJcApU3k}22a!&)k4{CU!e_ny^Y3cO;tOvOMKEyWz!vG(Kp*;hB?d|R3`2X~=5a6#^o5@qn?J-bI8Ppip{-yG z!k|VcGsq!jF~}7DMr49Wap-s&>o=U^T0!Lcy}!(bhtYsPQy z4|EJe{12QL#=c(suQ89Mhw9<`bui%nx7Nep`C&*M3~vMEACmcRYYRGtANq$F%zh&V zc)cEVeHz*Z1N)L7k-(k3np#{GcDh2Q@ya0YHl*n7fl*ZPAsbU-a94MYYtA#&!c`xGIaV;yzsmrjfieTEtqB_WgZp2*NplHx=$O{M~2#i_vJ{ps-NgK zQsxKK_CBM2PP_je+Xft`(vYfXXgIUr{=PA=7a8`2EHk)Ym2QKIforz# tySWtj{oF3N9@_;i*Fv5S)9x^z=nlWP>jpp-9)52ZmLVA=i*%6g{{fxOO~wEK diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/runner.exe.manifest b/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/runner.exe.manifest deleted file mode 100644 index a42ea7687cb6..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/runner.exe.manifest +++ /dev/null @@ -1,20 +0,0 @@ - - - - - PerMonitorV2 - - - - - - - - - - - - - - - diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/utils.cpp b/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/utils.cpp deleted file mode 100644 index f5bf9fa0f536..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/utils.cpp +++ /dev/null @@ -1,64 +0,0 @@ -#include "utils.h" - -#include -#include -#include -#include - -#include - -void CreateAndAttachConsole() { - if (::AllocConsole()) { - FILE *unused; - if (freopen_s(&unused, "CONOUT$", "w", stdout)) { - _dup2(_fileno(stdout), 1); - } - if (freopen_s(&unused, "CONOUT$", "w", stderr)) { - _dup2(_fileno(stdout), 2); - } - std::ios::sync_with_stdio(); - FlutterDesktopResyncOutputStreams(); - } -} - -std::vector GetCommandLineArguments() { - // Convert the UTF-16 command line arguments to UTF-8 for the Engine to use. - int argc; - wchar_t** argv = ::CommandLineToArgvW(::GetCommandLineW(), &argc); - if (argv == nullptr) { - return std::vector(); - } - - std::vector command_line_arguments; - - // Skip the first argument as it's the binary name. - for (int i = 1; i < argc; i++) { - command_line_arguments.push_back(Utf8FromUtf16(argv[i])); - } - - ::LocalFree(argv); - - return command_line_arguments; -} - -std::string Utf8FromUtf16(const wchar_t* utf16_string) { - if (utf16_string == nullptr) { - return std::string(); - } - int target_length = ::WideCharToMultiByte( - CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, - -1, nullptr, 0, nullptr, nullptr); - std::string utf8_string; - if (target_length == 0 || target_length > utf8_string.max_size()) { - return utf8_string; - } - utf8_string.resize(target_length); - int converted_length = ::WideCharToMultiByte( - CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, - -1, utf8_string.data(), - target_length, nullptr, nullptr); - if (converted_length == 0) { - return std::string(); - } - return utf8_string; -} diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/utils.h b/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/utils.h deleted file mode 100644 index 3879d5475579..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/utils.h +++ /dev/null @@ -1,19 +0,0 @@ -#ifndef RUNNER_UTILS_H_ -#define RUNNER_UTILS_H_ - -#include -#include - -// Creates a console for the process, and redirects stdout and stderr to -// it for both the runner and the Flutter library. -void CreateAndAttachConsole(); - -// Takes a null-terminated wchar_t* encoded in UTF-16 and returns a std::string -// encoded in UTF-8. Returns an empty std::string on failure. -std::string Utf8FromUtf16(const wchar_t* utf16_string); - -// Gets the command line arguments passed in as a std::vector, -// encoded in UTF-8. Returns an empty std::vector on failure. -std::vector GetCommandLineArguments(); - -#endif // RUNNER_UTILS_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/win32_window.cpp b/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/win32_window.cpp deleted file mode 100644 index 041a38554745..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/win32_window.cpp +++ /dev/null @@ -1,288 +0,0 @@ -#include "win32_window.h" - -#include -#include - -#include "resource.h" - -namespace { - -/// Window attribute that enables dark mode window decorations. -/// -/// Redefined in case the developer's machine has a Windows SDK older than -/// version 10.0.22000.0. -/// See: https://docs.microsoft.com/windows/win32/api/dwmapi/ne-dwmapi-dwmwindowattribute -#ifndef DWMWA_USE_IMMERSIVE_DARK_MODE -#define DWMWA_USE_IMMERSIVE_DARK_MODE 20 -#endif - -constexpr const wchar_t kWindowClassName[] = L"FLUTTER_RUNNER_WIN32_WINDOW"; - -/// Registry key for app theme preference. -/// -/// A value of 0 indicates apps should use dark mode. A non-zero or missing -/// value indicates apps should use light mode. -constexpr const wchar_t kGetPreferredBrightnessRegKey[] = - L"Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize"; -constexpr const wchar_t kGetPreferredBrightnessRegValue[] = L"AppsUseLightTheme"; - -// The number of Win32Window objects that currently exist. -static int g_active_window_count = 0; - -using EnableNonClientDpiScaling = BOOL __stdcall(HWND hwnd); - -// Scale helper to convert logical scaler values to physical using passed in -// scale factor -int Scale(int source, double scale_factor) { - return static_cast(source * scale_factor); -} - -// Dynamically loads the |EnableNonClientDpiScaling| from the User32 module. -// This API is only needed for PerMonitor V1 awareness mode. -void EnableFullDpiSupportIfAvailable(HWND hwnd) { - HMODULE user32_module = LoadLibraryA("User32.dll"); - if (!user32_module) { - return; - } - auto enable_non_client_dpi_scaling = - reinterpret_cast( - GetProcAddress(user32_module, "EnableNonClientDpiScaling")); - if (enable_non_client_dpi_scaling != nullptr) { - enable_non_client_dpi_scaling(hwnd); - } - FreeLibrary(user32_module); -} - -} // namespace - -// Manages the Win32Window's window class registration. -class WindowClassRegistrar { - public: - ~WindowClassRegistrar() = default; - - // Returns the singleton registar instance. - static WindowClassRegistrar* GetInstance() { - if (!instance_) { - instance_ = new WindowClassRegistrar(); - } - return instance_; - } - - // Returns the name of the window class, registering the class if it hasn't - // previously been registered. - const wchar_t* GetWindowClass(); - - // Unregisters the window class. Should only be called if there are no - // instances of the window. - void UnregisterWindowClass(); - - private: - WindowClassRegistrar() = default; - - static WindowClassRegistrar* instance_; - - bool class_registered_ = false; -}; - -WindowClassRegistrar* WindowClassRegistrar::instance_ = nullptr; - -const wchar_t* WindowClassRegistrar::GetWindowClass() { - if (!class_registered_) { - WNDCLASS window_class{}; - window_class.hCursor = LoadCursor(nullptr, IDC_ARROW); - window_class.lpszClassName = kWindowClassName; - window_class.style = CS_HREDRAW | CS_VREDRAW; - window_class.cbClsExtra = 0; - window_class.cbWndExtra = 0; - window_class.hInstance = GetModuleHandle(nullptr); - window_class.hIcon = - LoadIcon(window_class.hInstance, MAKEINTRESOURCE(IDI_APP_ICON)); - window_class.hbrBackground = 0; - window_class.lpszMenuName = nullptr; - window_class.lpfnWndProc = Win32Window::WndProc; - RegisterClass(&window_class); - class_registered_ = true; - } - return kWindowClassName; -} - -void WindowClassRegistrar::UnregisterWindowClass() { - UnregisterClass(kWindowClassName, nullptr); - class_registered_ = false; -} - -Win32Window::Win32Window() { - ++g_active_window_count; -} - -Win32Window::~Win32Window() { - --g_active_window_count; - Destroy(); -} - -bool Win32Window::Create(const std::wstring& title, - const Point& origin, - const Size& size) { - Destroy(); - - const wchar_t* window_class = - WindowClassRegistrar::GetInstance()->GetWindowClass(); - - const POINT target_point = {static_cast(origin.x), - static_cast(origin.y)}; - HMONITOR monitor = MonitorFromPoint(target_point, MONITOR_DEFAULTTONEAREST); - UINT dpi = FlutterDesktopGetDpiForMonitor(monitor); - double scale_factor = dpi / 96.0; - - HWND window = CreateWindow( - window_class, title.c_str(), WS_OVERLAPPEDWINDOW, - Scale(origin.x, scale_factor), Scale(origin.y, scale_factor), - Scale(size.width, scale_factor), Scale(size.height, scale_factor), - nullptr, nullptr, GetModuleHandle(nullptr), this); - - if (!window) { - return false; - } - - UpdateTheme(window); - - return OnCreate(); -} - -bool Win32Window::Show() { - return ShowWindow(window_handle_, SW_SHOWNORMAL); -} - -// static -LRESULT CALLBACK Win32Window::WndProc(HWND const window, - UINT const message, - WPARAM const wparam, - LPARAM const lparam) noexcept { - if (message == WM_NCCREATE) { - auto window_struct = reinterpret_cast(lparam); - SetWindowLongPtr(window, GWLP_USERDATA, - reinterpret_cast(window_struct->lpCreateParams)); - - auto that = static_cast(window_struct->lpCreateParams); - EnableFullDpiSupportIfAvailable(window); - that->window_handle_ = window; - } else if (Win32Window* that = GetThisFromHandle(window)) { - return that->MessageHandler(window, message, wparam, lparam); - } - - return DefWindowProc(window, message, wparam, lparam); -} - -LRESULT -Win32Window::MessageHandler(HWND hwnd, - UINT const message, - WPARAM const wparam, - LPARAM const lparam) noexcept { - switch (message) { - case WM_DESTROY: - window_handle_ = nullptr; - Destroy(); - if (quit_on_close_) { - PostQuitMessage(0); - } - return 0; - - case WM_DPICHANGED: { - auto newRectSize = reinterpret_cast(lparam); - LONG newWidth = newRectSize->right - newRectSize->left; - LONG newHeight = newRectSize->bottom - newRectSize->top; - - SetWindowPos(hwnd, nullptr, newRectSize->left, newRectSize->top, newWidth, - newHeight, SWP_NOZORDER | SWP_NOACTIVATE); - - return 0; - } - case WM_SIZE: { - RECT rect = GetClientArea(); - if (child_content_ != nullptr) { - // Size and position the child window. - MoveWindow(child_content_, rect.left, rect.top, rect.right - rect.left, - rect.bottom - rect.top, TRUE); - } - return 0; - } - - case WM_ACTIVATE: - if (child_content_ != nullptr) { - SetFocus(child_content_); - } - return 0; - - case WM_DWMCOLORIZATIONCOLORCHANGED: - UpdateTheme(hwnd); - return 0; - } - - return DefWindowProc(window_handle_, message, wparam, lparam); -} - -void Win32Window::Destroy() { - OnDestroy(); - - if (window_handle_) { - DestroyWindow(window_handle_); - window_handle_ = nullptr; - } - if (g_active_window_count == 0) { - WindowClassRegistrar::GetInstance()->UnregisterWindowClass(); - } -} - -Win32Window* Win32Window::GetThisFromHandle(HWND const window) noexcept { - return reinterpret_cast( - GetWindowLongPtr(window, GWLP_USERDATA)); -} - -void Win32Window::SetChildContent(HWND content) { - child_content_ = content; - SetParent(content, window_handle_); - RECT frame = GetClientArea(); - - MoveWindow(content, frame.left, frame.top, frame.right - frame.left, - frame.bottom - frame.top, true); - - SetFocus(child_content_); -} - -RECT Win32Window::GetClientArea() { - RECT frame; - GetClientRect(window_handle_, &frame); - return frame; -} - -HWND Win32Window::GetHandle() { - return window_handle_; -} - -void Win32Window::SetQuitOnClose(bool quit_on_close) { - quit_on_close_ = quit_on_close; -} - -bool Win32Window::OnCreate() { - // No-op; provided for subclasses. - return true; -} - -void Win32Window::OnDestroy() { - // No-op; provided for subclasses. -} - -void Win32Window::UpdateTheme(HWND const window) { - DWORD light_mode; - DWORD light_mode_size = sizeof(light_mode); - LSTATUS result = RegGetValue(HKEY_CURRENT_USER, kGetPreferredBrightnessRegKey, - kGetPreferredBrightnessRegValue, - RRF_RT_REG_DWORD, nullptr, &light_mode, - &light_mode_size); - - if (result == ERROR_SUCCESS) { - BOOL enable_dark_mode = light_mode == 0; - DwmSetWindowAttribute(window, DWMWA_USE_IMMERSIVE_DARK_MODE, - &enable_dark_mode, sizeof(enable_dark_mode)); - } -} diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/win32_window.h b/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/win32_window.h deleted file mode 100644 index c86632d8a6b9..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/win32_window.h +++ /dev/null @@ -1,102 +0,0 @@ -#ifndef RUNNER_WIN32_WINDOW_H_ -#define RUNNER_WIN32_WINDOW_H_ - -#include - -#include -#include -#include - -// A class abstraction for a high DPI-aware Win32 Window. Intended to be -// inherited from by classes that wish to specialize with custom -// rendering and input handling -class Win32Window { - public: - struct Point { - unsigned int x; - unsigned int y; - Point(unsigned int x, unsigned int y) : x(x), y(y) {} - }; - - struct Size { - unsigned int width; - unsigned int height; - Size(unsigned int width, unsigned int height) - : width(width), height(height) {} - }; - - Win32Window(); - virtual ~Win32Window(); - - // Creates a win32 window with |title| that is positioned and sized using - // |origin| and |size|. New windows are created on the default monitor. Window - // sizes are specified to the OS in physical pixels, hence to ensure a - // consistent size this function will scale the inputted width and height as - // as appropriate for the default monitor. The window is invisible until - // |Show| is called. Returns true if the window was created successfully. - bool Create(const std::wstring& title, const Point& origin, const Size& size); - - // Show the current window. Returns true if the window was successfully shown. - bool Show(); - - // Release OS resources associated with window. - void Destroy(); - - // Inserts |content| into the window tree. - void SetChildContent(HWND content); - - // Returns the backing Window handle to enable clients to set icon and other - // window properties. Returns nullptr if the window has been destroyed. - HWND GetHandle(); - - // If true, closing this window will quit the application. - void SetQuitOnClose(bool quit_on_close); - - // Return a RECT representing the bounds of the current client area. - RECT GetClientArea(); - - protected: - // Processes and route salient window messages for mouse handling, - // size change and DPI. Delegates handling of these to member overloads that - // inheriting classes can handle. - virtual LRESULT MessageHandler(HWND window, - UINT const message, - WPARAM const wparam, - LPARAM const lparam) noexcept; - - // Called when CreateAndShow is called, allowing subclass window-related - // setup. Subclasses should return false if setup fails. - virtual bool OnCreate(); - - // Called when Destroy is called. - virtual void OnDestroy(); - - private: - friend class WindowClassRegistrar; - - // OS callback called by message pump. Handles the WM_NCCREATE message which - // is passed when the non-client area is being created and enables automatic - // non-client DPI scaling so that the non-client area automatically - // responsponds to changes in DPI. All other messages are handled by - // MessageHandler. - static LRESULT CALLBACK WndProc(HWND const window, - UINT const message, - WPARAM const wparam, - LPARAM const lparam) noexcept; - - // Retrieves a class instance pointer for |window| - static Win32Window* GetThisFromHandle(HWND const window) noexcept; - - // Update the window frame's theme to match the system theme. - static void UpdateTheme(HWND const window); - - bool quit_on_close_ = false; - - // window handle for top level window. - HWND window_handle_ = nullptr; - - // window handle for hosted content. - HWND child_content_ = nullptr; -}; - -#endif // RUNNER_WIN32_WINDOW_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/admob.h b/packages/firebase_core/firebase_core/firebase_core/firebase/admob.h deleted file mode 100644 index 957c86b7e168..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/admob.h +++ /dev/null @@ -1,215 +0,0 @@ -/* - * Copyright 2016 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_H_ -#define FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_H_ - -#include "firebase/internal/platform.h" - -#if FIREBASE_PLATFORM_ANDROID -#include -#endif // FIREBASE_PLATFORM_ANDROID - -#include "firebase/admob/banner_view.h" -#include "firebase/admob/interstitial_ad.h" -#include "firebase/admob/rewarded_video.h" -#include "firebase/admob/types.h" -#include "firebase/app.h" -#include "firebase/internal/common.h" - -#if !defined(DOXYGEN) && !defined(SWIG) -FIREBASE_APP_REGISTER_CALLBACKS_REFERENCE(admob) -#endif // !defined(DOXYGEN) && !defined(SWIG) - -namespace firebase { - -/// @deprecated The functionality in the firebase::admob namespace -/// has been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the new -/// SDK in our migration guide. -/// -/// @brief API for AdMob with Firebase. -/// -/// The AdMob API allows you to load and display mobile ads using the Google -/// Mobile Ads SDK. Each ad format has its own header file. -namespace admob { - -/// @deprecated -/// @brief Initializes AdMob via Firebase. -/// -/// The functionality in the firebase::admob namespace has -/// been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the -/// new SDK in our migration -/// guide. -/// -/// @param app The Firebase app for which to initialize mobile ads. -/// -/// @return kInitResultSuccess if initialization succeeded, or -/// kInitResultFailedMissingDependency on Android if Google Play services is not -/// available on the current device and the Google Mobile Ads SDK requires -/// Google Play services (for example, when using 'play-services-ads-lite'). -FIREBASE_DEPRECATED InitResult Initialize(const ::firebase::App& app); - -/// @deprecated -/// @brief Initializes AdMob via Firebase with the publisher's AdMob app ID. -/// -/// The functionality in the firebase::admob namespace has -/// been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the -/// new SDK in our migration -/// guide. -/// -/// Initializing the Google Mobile Ads SDK with the AdMob app ID at app launch -/// allows the SDK to fetch app-level settings and perform configuration tasks -/// as early as possible. This can help reduce latency for the initial ad -/// request. AdMob app IDs are unique identifiers given to mobile apps when -/// they're registered in the AdMob console. To find your app ID in the AdMob -/// console, click the App management (https://apps.admob.com/#account/appmgmt:) -/// option under the settings dropdown (located in the upper right-hand corner). -/// App IDs have the form ca-app-pub-XXXXXXXXXXXXXXXX~NNNNNNNNNN. -/// -/// @param[in] app The Firebase app for which to initialize mobile ads. -/// @param[in] admob_app_id The publisher's AdMob app ID. -/// -/// @return kInitResultSuccess if initialization succeeded, or -/// kInitResultFailedMissingDependency on Android if Google Play services is not -/// available on the current device and the Google Mobile Ads SDK requires -/// Google Play services (for example, when using 'play-services-ads-lite'). -FIREBASE_DEPRECATED InitResult Initialize(const ::firebase::App& app, - const char* admob_app_id); - -#if FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) -/// @deprecated -/// @brief Initializes AdMob without Firebase for Android. -/// -/// The functionality in the firebase::admob namespace has -/// been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the -/// new SDK in our migration -/// guide. -/// -/// The arguments to @ref Initialize are platform-specific so the caller must do -/// something like this: -/// @code -/// #if defined(__ANDROID__) -/// firebase::admob::Initialize(jni_env, activity); -/// #else -/// firebase::admob::Initialize(); -/// #endif -/// @endcode -/// -/// @param[in] jni_env JNIEnv pointer. -/// @param[in] activity Activity used to start the application. -/// -/// @return kInitResultSuccess if initialization succeeded, or -/// kInitResultFailedMissingDependency on Android if Google Play services is not -/// available on the current device and the AdMob SDK requires -/// Google Play services (for example when using 'play-services-ads-lite'). -FIREBASE_DEPRECATED InitResult Initialize(JNIEnv* jni_env, jobject activity); - -/// @deprecated -/// @brief Initializes AdMob via Firebase with the publisher's AdMob app ID. -/// -/// The functionality in the firebase::admob namespace has -/// been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the -/// new SDK in our migration -/// guide. -/// -/// Initializing the Google Mobile Ads SDK with the AdMob app ID at app launch -/// allows the SDK to fetch app-level settings and perform configuration tasks -/// as early as possible. This can help reduce latency for the initial ad -/// request. AdMob app IDs are unique identifiers given to mobile apps when -/// they're registered in the AdMob console. To find your app ID in the AdMob -/// console, click the App management (https://apps.admob.com/#account/appmgmt:) -/// option under the settings dropdown (located in the upper right-hand corner). -/// App IDs have the form ca-app-pub-XXXXXXXXXXXXXXXX~NNNNNNNNNN. -/// -/// The arguments to @ref Initialize are platform-specific so the caller must do -/// something like this: -/// @code -/// #if defined(__ANDROID__) -/// firebase::admob::Initialize(jni_env, activity, admob_app_id); -/// #else -/// firebase::admob::Initialize(admob_app_id); -/// #endif -/// @endcode -/// -/// @param[in] jni_env JNIEnv pointer. -/// @param[in] activity Activity used to start the application. -/// @param[in] admob_app_id The publisher's AdMob app ID. -/// -/// @return kInitResultSuccess if initialization succeeded, or -/// kInitResultFailedMissingDependency on Android if Google Play services is not -/// available on the current device and the AdMob SDK requires -/// Google Play services (for example when using 'play-services-ads-lite'). -FIREBASE_DEPRECATED InitResult Initialize(JNIEnv* jni_env, jobject activity, - const char* admob_app_id); -#endif // defined(__ANDROID__) || defined(DOXYGEN) -#if !FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) -/// @deprecated -/// @brief Initializes AdMob without Firebase for iOS. -/// -/// The functionality in the firebase::admob namespace has -/// been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the -/// new SDK in our migration -/// guide. -FIREBASE_DEPRECATED InitResult Initialize(); - -/// @deprecated -/// @brief Initializes AdMob with the publisher's AdMob app ID and without -/// Firebase for iOS. -/// -/// The functionality in the firebase::admob namespace has -/// been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the -/// new SDK in our migration -/// guide. -/// -/// Initializing the Google Mobile Ads SDK with the AdMob app ID at app launch -/// allows the SDK to fetch app-level settings and perform configuration tasks -/// as early as possible. This can help reduce latency for the initial ad -/// request. AdMob app IDs are unique identifiers given to mobile apps when -/// they're registered in the AdMob console. To find your app ID in the AdMob -/// console, click the App management (https://apps.admob.com/#account/appmgmt:) -/// option under the settings dropdown (located in the upper right-hand corner). -/// App IDs have the form ca-app-pub-XXXXXXXXXXXXXXXX~NNNNNNNNNN. -/// -/// @param[in] admob_app_id The publisher's AdMob app ID. -/// -/// @return kInitResultSuccess if initialization succeeded -FIREBASE_DEPRECATED InitResult Initialize(const char* admob_app_id); -#endif // !defined(__ANDROID__) || defined(DOXYGEN) - -/// @deprecated -/// @brief Terminate AdMob. -/// -/// The functionality in the firebase::admob namespace has -/// been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the -/// new SDK in our migration -/// guide. -/// -/// Frees resources associated with AdMob that were allocated during -/// @ref firebase::admob::Initialize(). -FIREBASE_DEPRECATED void Terminate(); - -} // namespace admob -} // namespace firebase - -#endif // FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/admob/banner_view.h b/packages/firebase_core/firebase_core/firebase_core/firebase/admob/banner_view.h deleted file mode 100644 index 2d691f2d3a77..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/admob/banner_view.h +++ /dev/null @@ -1,427 +0,0 @@ -/* - * Copyright 2016 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_BANNER_VIEW_H_ -#define FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_BANNER_VIEW_H_ - -#include "firebase/admob/types.h" -#include "firebase/future.h" -#include "firebase/internal/common.h" - -namespace firebase { -namespace admob { - -namespace internal { -// Forward declaration for platform-specific data, implemented in each library. -class BannerViewInternal; -} // namespace internal - -/// @deprecated The functionality in the firebase::admob namespace -/// has been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the new -/// SDK in our migration guide. -/// -/// @brief Loads and displays AdMob banner ads. -/// -/// Each BannerView object corresponds to a single AdMob banner placement. There -/// are methods to load an ad, move it, show it and hide it, and retrieve the -/// bounds of the ad onscreen. -/// -/// BannerView objects maintain a presentation state that indicates whether -/// or not they're currently onscreen, as well as a set of bounds (stored in a -/// @ref BoundingBox struct), but otherwise provide information about -/// their current state through Futures. Methods like @ref Initialize, -/// @ref LoadAd, and @ref Hide each have a corresponding @ref Future from which -/// the result of the last call can be determined. The two variants of -/// @ref MoveTo share a single result @ref Future, since they're essentially the -/// same action. -/// -/// In addition, applications can create their own subclasses of -/// @ref BannerView::Listener, pass an instance to the @ref SetListener method, -/// and receive callbacks whenever the presentation state or bounding box of the -/// ad changes. -/// -/// For example, you could initialize, load, and show a banner view while -/// checking the result of the previous action at each step as follows: -/// -/// @code -/// namespace admob = ::firebase::admob; -/// admob::BannerView* banner_view = new admob::BannerView(); -/// banner_view->Initialize(ad_parent, "YOUR_AD_UNIT_ID", desired_ad_size) -/// @endcode -/// -/// Then, later: -/// -/// @code -/// if (banner_view->InitializeLastResult().status() == -/// ::firebase::kFutureStatusComplete && -/// banner_view->InitializeLastResult().error() == -/// firebase::admob::kAdMobErrorNone) { -/// banner_view->LoadAd(your_ad_request); -/// } -/// @endcode -/// -class BannerView { - public: -#ifdef INTERNAL_EXPERIMENTAL -// LINT.IfChange -#endif // INTERNAL_EXPERIMENTAL - /// @deprecated - /// @brief The presentation state of a @ref BannerView. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - enum PresentationState { - /// BannerView is currently hidden. - kPresentationStateHidden = 0, - /// BannerView is visible, but does not contain an ad. - kPresentationStateVisibleWithoutAd, - /// BannerView is visible and contains an ad. - kPresentationStateVisibleWithAd, - /// BannerView is visible and has opened a partial overlay on the screen. - kPresentationStateOpenedPartialOverlay, - /// BannerView is completely covering the screen or has caused focus to - /// leave the application (for example, when opening an external browser - /// during a clickthrough). - kPresentationStateCoveringUI, - }; -#ifdef INTERNAL_EXPERIMENTAL -// LINT.ThenChange(//depot_firebase_cpp/admob/client/cpp/src_java/com/google/firebase/admob/internal/cpp/ConstantsHelper.java) -#endif // INTERNAL_EXPERIMENTAL - -#ifdef INTERNAL_EXPERIMENTAL -// LINT.IfChange -#endif // INTERNAL_EXPERIMENTAL - /// @deprecated - /// @brief The possible screen positions for a @ref BannerView. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - enum Position { - /// Top of the screen, horizontally centered. - kPositionTop = 0, - /// Bottom of the screen, horizontally centered. - kPositionBottom, - /// Top-left corner of the screen. - kPositionTopLeft, - /// Top-right corner of the screen. - kPositionTopRight, - /// Bottom-left corner of the screen. - kPositionBottomLeft, - /// Bottom-right corner of the screen. - kPositionBottomRight, - }; -#ifdef INTERNAL_EXPERIMENTAL -// LINT.ThenChange(//depot_firebase_cpp/admob/client/cpp/src_java/com/google/firebase/admob/internal/cpp/ConstantsHelper.java) -#endif // INTERNAL_EXPERIMENTAL - - /// @deprecated - /// @brief A listener class that developers can extend and pass to a @ref - /// BannerView object's @ref SetListener method to be notified of changes to - /// the presentation state and bounding box. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - class Listener { - public: - /// @deprecated - /// @brief This method is called when the @ref BannerView object's - /// presentation state changes. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - /// @param[in] banner_view The banner view whose presentation state changed. - /// @param[in] state The new presentation state. - virtual void OnPresentationStateChanged(BannerView* banner_view, - PresentationState state) = 0; - /// @deprecated - /// @brief This method is called when the @ref BannerView object's bounding - /// box changes. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - /// @param[in] banner_view The banner view whose bounding box changed. - /// @param[in] box The new bounding box. - virtual void OnBoundingBoxChanged(BannerView* banner_view, - BoundingBox box) = 0; - virtual ~Listener(); - }; - - /// @deprecated - /// @brief Creates an uninitialized @ref BannerView object. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - /// - /// @ref Initialize must be called before the object is used. - FIREBASE_DEPRECATED BannerView(); - - ~BannerView(); - - /// @deprecated - /// @brief Initializes the @ref BannerView object. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - /// @param[in] parent The platform-specific UI element that will host the ad. - /// @param[in] ad_unit_id The ad unit ID to use when requesting ads. - /// @param[in] size The desired ad size for the banner. - FIREBASE_DEPRECATED Future Initialize(AdParent parent, - const char* ad_unit_id, - AdSize size); - - /// @deprecated - /// @brief Returns a @ref Future that has the status of the last call to - /// @ref Initialize. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - FIREBASE_DEPRECATED Future InitializeLastResult() const; - - /// @deprecated - /// @brief Begins an asynchronous request for an ad. If successful, the ad - /// will automatically be displayed in the BannerView. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - /// @param[in] request An AdRequest struct with information about the request - /// to be made (such as targeting info). - FIREBASE_DEPRECATED Future LoadAd(const AdRequest& request); - - /// @deprecated - /// @brief Returns a @ref Future containing the status of the last call to - /// @ref LoadAd. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - FIREBASE_DEPRECATED Future LoadAdLastResult() const; - - /// @deprecated - /// @brief Hides the BannerView. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - FIREBASE_DEPRECATED Future Hide(); - - /// @deprecated - /// @brief Returns a @ref Future containing the status of the last call to - /// @ref Hide. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - FIREBASE_DEPRECATED Future HideLastResult() const; - - /// @deprecated - /// @brief Shows the @ref BannerView. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - FIREBASE_DEPRECATED Future Show(); - - /// @deprecated - /// @brief Returns a @ref Future containing the status of the last call to - /// @ref Show. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - FIREBASE_DEPRECATED Future ShowLastResult() const; - - /// @deprecated - /// @brief Pauses the @ref BannerView. Should be called whenever the C++ - /// engine pauses or the application loses focus. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - FIREBASE_DEPRECATED Future Pause(); - - /// @deprecated - /// @brief Returns a @ref Future containing the status of the last call to - /// @ref Pause. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - FIREBASE_DEPRECATED Future PauseLastResult() const; - - /// @deprecated - /// @brief Resumes the @ref BannerView after pausing. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - FIREBASE_DEPRECATED Future Resume(); - - /// @deprecated - /// @brief Returns a @ref Future containing the status of the last call to - /// @ref Resume. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - FIREBASE_DEPRECATED Future ResumeLastResult() const; - - /// @deprecated - /// @brief Cleans up and deallocates any resources used by the @ref - /// BannerView. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - FIREBASE_DEPRECATED Future Destroy(); - - /// @deprecated - /// @brief Returns a @ref Future containing the status of the last call to - /// @ref Destroy. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - FIREBASE_DEPRECATED Future DestroyLastResult() const; - - /// @deprecated - /// @brief Moves the @ref BannerView so that its top-left corner is located at - /// (x, y). Coordinates are in pixels from the top-left corner of the screen. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - /// @param[in] x The desired horizontal coordinate. - /// @param[in] y The desired vertical coordinate. - FIREBASE_DEPRECATED Future MoveTo(int x, int y); - - /// @deprecated - /// @brief Moves the @ref BannerView so that it's located at the given - /// pre-defined position. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - /// @param[in] position The pre-defined position to which to move the - /// @ref BannerView. - FIREBASE_DEPRECATED Future MoveTo(Position position); - - /// @deprecated - /// @brief Returns a @ref Future containing the status of the last call to - /// either version of @ref MoveTo. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - FIREBASE_DEPRECATED Future MoveToLastResult() const; - - /// @deprecated - /// @brief Returns the current presentation state of the @ref BannerView. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - /// @return The current presentation state. - FIREBASE_DEPRECATED PresentationState presentation_state() const; - - /// @deprecated - /// @brief Retrieves the @ref BannerView's current onscreen size and location. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - FIREBASE_DEPRECATED BoundingBox bounding_box() const; - - /// @deprecated - /// @brief Sets the @ref Listener for this object. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - /// @param[in] listener A valid BannerView::Listener to receive callbacks. - FIREBASE_DEPRECATED void SetListener(Listener* listener); - - private: - // An internal, platform-specific implementation object that this class uses - // to interact with the Google Mobile Ads SDKs for iOS and Android. - internal::BannerViewInternal* internal_; -}; - -} // namespace admob -} // namespace firebase - -#endif // FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_BANNER_VIEW_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/admob/interstitial_ad.h b/packages/firebase_core/firebase_core/firebase_core/firebase/admob/interstitial_ad.h deleted file mode 100644 index b201ab7c3487..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/admob/interstitial_ad.h +++ /dev/null @@ -1,259 +0,0 @@ -/* - * Copyright 2016 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_INTERSTITIAL_AD_H_ -#define FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_INTERSTITIAL_AD_H_ - -#include "firebase/admob/types.h" -#include "firebase/future.h" -#include "firebase/internal/common.h" - -namespace firebase { -namespace admob { - -namespace internal { -// Forward declaration for platform-specific data, implemented in each library. -class InterstitialAdInternal; -} // namespace internal - -/// @deprecated The functionality in the firebase::admob namespace -/// has been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the new -/// SDK in our migration guide. -/// -/// @brief Loads and displays AdMob interstitial ads. -/// -/// @ref InterstitialAd is a single-use object that can load and show a -/// single AdMob interstitial ad. -/// -/// InterstitialAd objects maintain a presentation state that indicates whether -/// or not they're currently onscreen, but otherwise provide information about -/// their current state through Futures. @ref Initialize, @ref LoadAd, and -/// @ref Show each have a corresponding @ref Future from which you can determine -/// result of the previous call. -/// -/// In addition, applications can create their own subclasses of -/// @ref InterstitialAd::Listener, pass an instance to the @ref SetListener -/// method, and receive callbacks whenever the presentation state changes. -/// -/// Here's how one might initialize, load, and show an interstitial ad while -/// checking against the result of the previous action at each step: -/// -/// @code -/// namespace admob = ::firebase::admob; -/// admob::InterstitialAd* interstitial = new admob::InterstitialAd(); -/// interstitial->Initialize(ad_parent, "YOUR_AD_UNIT_ID") -/// @endcode -/// -/// Then, later: -/// -/// @code -/// if (interstitial->InitializeLastResult().status() == -/// ::firebase::kFutureStatusComplete && -/// interstitial->InitializeLastResult().error() == -/// firebase::admob::kAdMobErrorNone) { -/// interstitial->LoadAd(my_ad_request); -/// } -/// @endcode -/// -/// And after that: -/// -/// @code -/// if (interstitial->LoadAdLastResult().status() == -/// ::firebase::kFutureStatusComplete && -/// interstitial->LoadAdLastResult().error() == -/// firebase::admob::kAdMobErrorNone)) { -/// interstitial->Show(); -/// } -/// @endcode -/// -class InterstitialAd { - public: -#ifdef INTERNAL_EXPERIMENTAL -// LINT.IfChange -#endif // INTERNAL_EXPERIMENTAL - /// @deprecated - /// @brief The presentation states of an @ref InterstitialAd. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - enum PresentationState { - /// InterstitialAd is not currently being shown. - kPresentationStateHidden = 0, - /// InterstitialAd is being shown or has caused focus to leave the - /// application (for example, when opening an external browser during a - /// clickthrough). - kPresentationStateCoveringUI, - }; -#ifdef INTERNAL_EXPERIMENTAL -// LINT.ThenChange(//depot_firebase_cpp/admob/client/cpp/src_java/com/google/firebase/admob/internal/cpp/InterstitialAdHelper.java) -#endif // INTERNAL_EXPERIMENTAL - - /// @deprecated - /// @brief A listener class that developers can extend and pass to an - /// @ref InterstitialAd object's @ref SetListener method to be notified of - /// presentation state changes. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - /// @param[in] interstitial_ad The interstitial ad whose presentation state - /// changed. - /// @param[in] state The new presentation state. - virtual void OnPresentationStateChanged(InterstitialAd* interstitial_ad, - PresentationState state) = 0; - virtual ~Listener(); - }; - - /// @deprecated - /// @brief Creates an uninitialized @ref InterstitialAd object. - /// @ref Initialize must be called before the object is used. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - FIREBASE_DEPRECATED InterstitialAd(); - - ~InterstitialAd(); - - /// @deprecated - /// @brief Initialize the @ref InterstitialAd object. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - /// @param[in] parent The platform-specific UI element that will host the ad. - /// @param[in] ad_unit_id The ad unit ID to use in loading the ad. - FIREBASE_DEPRECATED Future Initialize(AdParent parent, - const char* ad_unit_id); - - /// @deprecated - /// @brief Returns a @ref Future containing the status of the last call to - /// @ref Initialize. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - FIREBASE_DEPRECATED Future InitializeLastResult() const; - - /// @deprecated - /// @brief Begins an asynchronous request for an ad. - /// - /// The @ref InterstitialAd::presentation_state method can be used to track - /// the progress of the request. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - /// @param[in] request An AdRequest struct with information about the request - /// to be made (such as targeting info). - FIREBASE_DEPRECATED Future LoadAd(const AdRequest& request); - - /// @deprecated - /// @brief Returns a @ref Future containing the status of the last call to - /// @ref LoadAd. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - FIREBASE_DEPRECATED Future LoadAdLastResult() const; - - /// @deprecated - /// @brief Shows the @ref InterstitialAd. This should not be called unless an - /// ad has already been loaded. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - FIREBASE_DEPRECATED Future Show(); - - /// @deprecated - /// @brief Returns a @ref Future containing the status of the last call to - /// @ref Show. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - FIREBASE_DEPRECATED Future ShowLastResult() const; - - /// @deprecated - /// @brief Returns the current presentation state of the @ref InterstitialAd. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - /// @return The current presentation state. - FIREBASE_DEPRECATED PresentationState presentation_state() const; - - /// @deprecated - /// @brief Sets the @ref Listener for this @ref InterstitialAd. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - /// @param[in] listener A valid InterstititalAd::Listener to receive - /// callbacks. - FIREBASE_DEPRECATED void SetListener(Listener* listener); - - private: - // An internal, platform-specific implementation object that this class uses - // to interact with the Google Mobile Ads SDKs for iOS and Android. - internal::InterstitialAdInternal* internal_; -}; - -} // namespace admob -} // namespace firebase - -#endif // FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_INTERSTITIAL_AD_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/admob/native_express_ad_view.h b/packages/firebase_core/firebase_core/firebase_core/firebase/admob/native_express_ad_view.h deleted file mode 100644 index 7e571967825e..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/admob/native_express_ad_view.h +++ /dev/null @@ -1,446 +0,0 @@ -/* - * Copyright 2016 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_NATIVE_EXPRESS_AD_VIEW_H_ -#define FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_NATIVE_EXPRESS_AD_VIEW_H_ - -#include "firebase/admob/types.h" -#include "firebase/future.h" -#include "firebase/internal/common.h" - -namespace firebase { -namespace admob { - -namespace internal { -// Forward declaration for platform-specific data, implemented in each library. -class NativeExpressAdViewInternal; -} // namespace internal - -/// @deprecated The functionality in the firebase::admob namespace -/// has been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the new -/// SDK in our migration guide. -/// Native Express Ads has been discontinued, and are no longer served. -/// -/// @brief Loads and displays ads from AdMob Native Ads Express. -/// -/// Each NativeExpressAdView object corresponds to a single AdMob Native Express -/// ad placement. There are methods to load an ad, move it, show it and hide it, -/// and retrieve the bounds of the ad onscreen. -/// -/// NativeExpressAdView objects maintain a presentation state that indicates -/// whether or not they're currently onscreen, as well as a set of bounds -/// (stored in a @ref BoundingBox struct), but otherwise provide information -/// about their current state through Futures. Methods like @ref Initialize, -/// @ref LoadAd, and @ref Hide each have a corresponding @ref Future from which -/// the result of the last call can be determined. The two variants of -/// @ref MoveTo share a single result @ref Future, since they're essentially the -/// same action. -/// -/// In addition, applications can create their own subclasses of -/// @ref NativeExpressAdView::Listener, pass an instance to the @ref SetListener -/// method, and receive callbacks whenever the presentation state or bounding -/// box of the ad changes. -/// -/// For example, you could initialize, load, and show a native express ad view -/// while checking the result of the previous action at each step as follows: -/// -/// @code -/// namespace admob = ::firebase::admob; -/// admob::NativeExpressAdView* ad_view = new admob::NativeExpressAdView(); -/// ad_view->Initialize(ad_parent, "YOUR_AD_UNIT_ID", desired_ad_size) -/// @endcode -/// -/// Then, later: -/// -/// @code -/// if (ad_view->InitializeLastResult().Status() == -/// ::firebase::kFutureStatusComplete && -/// ad_view->InitializeLastResult().Error() == -/// firebase::admob::kAdMobErrorNone) { -/// ad_view->LoadAd(your_ad_request); -/// } -/// @endcode -class NativeExpressAdView { - public: -#ifdef INTERNAL_EXPERIMENTAL -// LINT.IfChange -#endif // INTERNAL_EXPERIMENTAL - /// @deprecated - /// @brief The presentation state of a @ref NativeExpressAdView. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - enum PresentationState { - /// NativeExpressAdView is currently hidden. - kPresentationStateHidden = 0, - /// NativeExpressAdView is visible, but does not contain an ad. - kPresentationStateVisibleWithoutAd, - /// NativeExpressAdView is visible and contains an ad. - kPresentationStateVisibleWithAd, - /// NativeExpressAdView is visible and has opened a partial overlay on the - /// screen. - kPresentationStateOpenedPartialOverlay, - /// NativeExpressAdView is completely covering the screen or has caused - /// focus to leave the application (for example, when opening an external - /// browser during a clickthrough). - kPresentationStateCoveringUI, - }; -#ifdef INTERNAL_EXPERIMENTAL -// LINT.ThenChange(//depot_firebase_cpp/admob/client/cpp/src_java/com/google/firebase/admob/internal/cpp/ConstantsHelper.java) -#endif // INTERNAL_EXPERIMENTAL - -#ifdef INTERNAL_EXPERIMENTAL -// LINT.IfChange -#endif // INTERNAL_EXPERIMENTAL - /// @deprecated - /// @brief The possible screen positions for a @ref NativeExpressAdView. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - enum Position { - /// Top of the screen, horizontally centered. - kPositionTop = 0, - /// Bottom of the screen, horizontally centered. - kPositionBottom, - /// Top-left corner of the screen. - kPositionTopLeft, - /// Top-right corner of the screen. - kPositionTopRight, - /// Bottom-left corner of the screen. - kPositionBottomLeft, - /// Bottom-right corner of the screen. - kPositionBottomRight, - }; -#ifdef INTERNAL_EXPERIMENTAL -// LINT.ThenChange(//depot_firebase_cpp/admob/client/cpp/src_java/com/google/firebase/admob/internal/cpp/ConstantsHelper.java) -#endif // INTERNAL_EXPERIMENTAL - - /// @deprecated - /// @brief A listener class that developers can extend and pass to a - /// @ref NativeExpressAdView object's @ref SetListener method to be notified - /// of changes to the presentation state and bounding box. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - class Listener { - public: - /// @deprecated - /// @brief This method is called when the @ref NativeExpressAdView object's - /// presentation state changes. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - /// @param[in] ad_view The native express ad view whose presentation state - /// changed. - /// @param[in] state The new presentation state. - FIREBASE_DEPRECATED virtual void OnPresentationStateChanged( - NativeExpressAdView* ad_view, PresentationState state) = 0; - - /// @deprecated - /// @brief This method is called when the @ref NativeExpressAdView object's - /// bounding box changes. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - /// - /// @ref Initialize must be called before the object is used. - FIREBASE_DEPRECATED NativeExpressAdView(); - - ~NativeExpressAdView(); - - /// @deprecated - /// @brief Initializes the @ref NativeExpressAdView object. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - /// @param[in] parent The platform-specific UI element that will host the ad. - /// @param[in] ad_unit_id The ad unit ID to use when requesting ads. - /// @param[in] size The desired ad size for the native express ad. - FIREBASE_DEPRECATED Future Initialize(AdParent parent, - const char* ad_unit_id, - AdSize size); - - /// @deprecated - /// @brief Returns a @ref Future that has the status of the last call to - /// @ref Initialize. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - FIREBASE_DEPRECATED Future InitializeLastResult() const; - - /// @deprecated - /// @brief Begins an asynchronous request for an ad. If successful, the ad - /// will automatically be displayed in the NativeExpressAdView. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - /// @param[in] request An AdRequest struct with information about the request - /// to be made (such as targeting info). - FIREBASE_DEPRECATED Future LoadAd(const AdRequest& request); - - /// @deprecated - /// @brief Returns a @ref Future containing the status of the last call to - /// @ref LoadAd. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - FIREBASE_DEPRECATED Future LoadAdLastResult() const; - - /// @deprecated - /// @brief Hides the NativeExpressAdView. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - FIREBASE_DEPRECATED Future Hide(); - - /// @deprecated - /// @brief Returns a @ref Future containing the status of the last call to - /// @ref Hide. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - FIREBASE_DEPRECATED Future HideLastResult() const; - - /// @deprecated - /// @brief Shows the @ref NativeExpressAdView. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - FIREBASE_DEPRECATED Future Show(); - - /// @deprecated - /// @brief Returns a @ref Future containing the status of the last call to - /// @ref Show. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - FIREBASE_DEPRECATED Future ShowLastResult() const; - - /// @deprecated - /// @brief Pauses the @ref NativeExpressAdView. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - /// - /// Should be called whenever the C++ engine pauses or the application loses - /// focus. - FIREBASE_DEPRECATED Future Pause(); - - /// @deprecated - /// @brief Returns a @ref Future containing the status of the last call to - /// @ref Pause. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - FIREBASE_DEPRECATED Future PauseLastResult() const; - - /// @deprecated - /// @brief Resumes the @ref NativeExpressAdView after pausing. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - FIREBASE_DEPRECATED Future Resume(); - - /// @deprecated - /// @brief Returns a @ref Future containing the status of the last call to - /// @ref Resume. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - FIREBASE_DEPRECATED Future ResumeLastResult() const; - - /// @deprecated - /// @brief Cleans up and deallocates any resources used by the - /// @ref NativeExpressAdView. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - FIREBASE_DEPRECATED Future Destroy(); - - /// @deprecated - /// @brief Returns a @ref Future containing the status of the last call to - /// @ref Destroy. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - FIREBASE_DEPRECATED Future DestroyLastResult() const; - - /// @deprecated - /// @brief Moves the @ref NativeExpressAdView so that its top-left corner is - /// located at (x, y). Coordinates are in pixels from the top-left corner of - /// the screen. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - /// - /// When built for Android, the library will not display an ad on top of or - /// beneath an Activity's status bar. If a call to MoveTo would result in an - /// overlap, the @ref NativeExpressAdView is placed just below the status bar, - /// so no overlap occurs. - /// @param[in] x The desired horizontal coordinate. - /// @param[in] y The desired vertical coordinate. - FIREBASE_DEPRECATED Future MoveTo(int x, int y); - - /// @deprecated - /// @brief Moves the @ref NativeExpressAdView so that it's located at the - /// given pre-defined position. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - /// @param[in] position The pre-defined position to which to move the - /// @ref NativeExpressAdView. - FIREBASE_DEPRECATED Future MoveTo(Position position); - - /// @deprecated - /// @brief Returns a @ref Future containing the status of the last call to - /// either version of @ref MoveTo. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - FIREBASE_DEPRECATED Future MoveToLastResult() const; - - /// @deprecated - /// @brief Returns the current presentation state of the - /// @ref NativeExpressAdView. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - /// @return The current presentation state. - FIREBASE_DEPRECATED PresentationState GetPresentationState() const; - - /// @deprecated - /// @brief Retrieves the @ref NativeExpressAdView's current onscreen size and - /// location. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - /// @return The current size and location. Values are in pixels, and location - /// coordinates originate from the top-left corner of the screen. - FIREBASE_DEPRECATED BoundingBox GetBoundingBox() const; - - /// @deprecated - /// @brief Sets the @ref Listener for this object. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - /// @param[in] listener A valid NativeExpressAdView::Listener to receive - /// callbacks. - FIREBASE_DEPRECATED void SetListener(Listener* listener); - - private: - // An internal, platform-specific implementation object that this class uses - // to interact with the Google Mobile Ads SDKs for iOS and Android. - internal::NativeExpressAdViewInternal* internal_; -}; - -} // namespace admob -} // namespace firebase - -#endif // FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_NATIVE_EXPRESS_AD_VIEW_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/admob/rewarded_video.h b/packages/firebase_core/firebase_core/firebase_core/firebase/admob/rewarded_video.h deleted file mode 100644 index 32bea80b5550..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/admob/rewarded_video.h +++ /dev/null @@ -1,407 +0,0 @@ -/* - * Copyright 2016 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_REWARDED_VIDEO_H_ -#define FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_REWARDED_VIDEO_H_ - -#include -#include - -#include "firebase/admob/types.h" -#include "firebase/future.h" - -namespace firebase { - -// Forward declaration of Firebase's internal Mutex. -class Mutex; - -namespace admob { - -/// @deprecated The functionality in the firebase::admob namespace -/// has been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the new -/// SDK in our migration guide. -/// -/// @brief Loads and displays rewarded video ads via AdMob mediation. -/// -/// The rewarded_video namespace contains methods to load and display rewarded -/// video ads via the Google Mobile Ads SDK. The underlying SDK objects for -/// rewarded video on Android and iOS are singletons, so there are no objects -/// to represent individual ads here. Instead, methods in the rewarded_video -/// namespace are invoked to initialize, load, and show. -/// -/// The basic steps for loading and displaying an ad are: -/// -/// 1. Call @ref Initialize to init the library and mediation adapters. -/// 2. Call @ref LoadAd to load an ad (some SDKs may have cached an ad at init -/// time). -/// 3. Call @ref Show to show the ad to the user. -/// 4. Repeat steps 2 and 3 as desired. -/// 5. Call @ref Destroy when your app is completely finished showing rewarded -/// video ads. -/// -/// Note that Initialize must be the very first thing called, and @ref Destroy -/// must be the very last. -/// -/// The library maintains a presentation state that indicates whether or not an -/// ad is currently onscreen, but otherwise provides information about its -/// current state through Futures. @ref Initialize, @ref LoadAd, and so on each -/// have a corresponding @ref Future from which apps can determine the result of -/// the previous call. -/// -/// In addition, applications can create their own subclasses of @ref Listener, -/// pass an instance to the @ref SetListener method, and receive callbacks -/// whenever the presentation state changes or an ad has been viewed in full and -/// the user is due a reward. -/// -/// Here's how one might initialize, load, and show a rewarded video ad while -/// checking against the result of the previous action at each step: -/// -/// @code -/// firebase::admob::rewarded_video::Initialize(); -/// @endcode -/// -/// Then, later: -/// -/// @code -/// if (firebase::admob::rewarded_video::InitializeLastResult().status() == -/// firebase::kFutureStatusComplete && -/// firebase::admob::rewarded_video::InitializeLastResult().error() == -/// firebase::admob::kAdMobErrorNone) { -/// firebase::admob::rewarded_video::LoadAd(my_ad_unit_str, my_ad_request); -/// } -/// @endcode -/// -/// And after that: -/// -/// @code -/// if (firebase::admob::rewarded_video::LoadAdLastResult().status() == -/// firebase::kFutureStatusComplete && -/// firebase::admob::rewarded_video::LoadAdLastResult().error() == -/// firebase::admob::kAdMobErrorNone) { -/// firebase::admob::rewarded_video::Show(my_ad_parent); -/// } -/// @endcode -namespace rewarded_video { -#ifdef INTERNAL_EXPERIMENTAL -// LINT.IfChange -#endif // INTERNAL_EXPERIMENTAL -/// @deprecated -/// @brief The possible presentation states for rewarded video. -/// -/// The functionality in the firebase::admob namespace has -/// been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the -/// new SDK in our migration -/// guide. -enum PresentationState { - /// No ad is currently being shown. - kPresentationStateHidden = 0, - /// A rewarded video ad is completely covering the screen or has caused - /// focus to leave the application (for example, when opening an external - /// browser during a clickthrough), but the video associated with the ad has - /// yet to begin playing. - kPresentationStateCoveringUI, - /// All of the above conditions are true *except* that the video associated - /// with the ad began playing at some point in the past. - kPresentationStateVideoHasStarted, - /// The rewarded video has played and completed. - kPresentationStateVideoHasCompleted, -}; -#ifdef INTERNAL_EXPERIMENTAL -// LINT.ThenChange(//depot_firebase_cpp/admob/client/cpp/src_java/com/google/firebase/admob/internal/cpp/RewardedVideoHelper.java) -#endif // INTERNAL_EXPERIMENTAL - -/// @deprecated -/// @brief A reward to be given to the user in exchange for watching a rewarded -/// video ad. -/// -/// The functionality in the firebase::admob namespace has -/// been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the -/// new SDK in our migration -/// guide. -struct RewardItem { - /// The reward amount. - float amount; - /// A string description of the type of reward (such as "coins" or "points"). - std::string reward_type; -}; - -/// @deprecated -/// @brief A listener class that developers can extend and pass to @ref -/// SetListener to be notified of rewards and changes to the presentation state. -/// -/// The functionality in the firebase::admob namespace has -/// been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the -/// new SDK in our migration -/// guide. -class Listener { - public: - /// @deprecated - /// @brief Invoked when the user should be given a reward for watching an ad. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - /// @param[in] reward The user's reward. - FIREBASE_DEPRECATED virtual void OnRewarded(RewardItem reward) = 0; - - /// @deprecated - /// @brief Invoked when the presentation state of the ad changes. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - /// @param[in] state The new presentation state. - FIREBASE_DEPRECATED virtual void OnPresentationStateChanged( - PresentationState state) = 0; - - virtual ~Listener(); -}; - -/// @deprecated -/// @brief A polling-based listener that developers can instantiate and pass to -/// @ref SetListener in order to queue rewards for later retrieval. -/// -/// The functionality in the firebase::admob namespace has -/// been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the -/// new SDK in our migration -/// guide. -/// -/// The @ref PollReward method should be used to retrieve awards granted by the -/// Mobile Ads SDK and queued by this class. -/// @ref rewarded_video::presentation_state can be used to poll the current -/// presentation state, so no additional method has been added for it. -class PollableRewardListener : public Listener { - public: - /// @deprecated - /// @brief Default constructor. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - FIREBASE_DEPRECATED PollableRewardListener(); - ~PollableRewardListener(); - - /// @deprecated - /// @brief Invoked when the user should be given a reward for watching an ad. - /// - /// Deprecated. The functionality in the firebase::admob - /// namespace has been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the new - /// SDK in our migration - /// guide. - FIREBASE_DEPRECATED void OnRewarded(RewardItem reward); - - /// @deprecated - /// @brief nvoked when the presentation state of the ad changes. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - FIREBASE_DEPRECATED void OnPresentationStateChanged(PresentationState state); - - /// @deprecated - /// @brief Pop the oldest queued reward, and copy its data into the provided - /// RewardItem. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - /// - /// If no reward is available, the struct is unchanged. - /// @param reward Pointer to a struct that reward data can be copied into. - /// @returns true if a reward was popped and data was copied, false otherwise. - FIREBASE_DEPRECATED bool PollReward(RewardItem* reward); - - private: - Mutex* mutex_; - - // Rewards granted by the Mobile Ads SDK. - std::queue rewards_; -}; - -/// @deprecated -/// @brief Initializes rewarded video. This must be the first method invoked in -/// this namespace. -/// -/// The functionality in the firebase::admob namespace has -/// been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the -/// new SDK in our migration -/// guide. -FIREBASE_DEPRECATED Future Initialize(); - -/// @deprecated -/// @brief Returns a @ref Future that has the status of the last call to -/// @ref Initialize. -/// -/// The functionality in the firebase::admob namespace has -/// been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the -/// new SDK in our migration -/// guide. -FIREBASE_DEPRECATED Future InitializeLastResult(); - -/// @deprecated -/// @brief Begins an asynchronous request for an ad. -/// -/// The functionality in the firebase::admob namespace has -/// been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the -/// new SDK in our migration -/// guide. -/// @param[in] ad_unit_id The ad unit ID to use in the request. -/// @param[in] request An AdRequest struct with information about the request -/// to be made (such as targeting info). -FIREBASE_DEPRECATED Future LoadAd(const char* ad_unit_id, - const AdRequest& request); - -/// @deprecated -/// @brief Returns a @ref Future containing the status of the last call to -/// @ref LoadAd. -/// -/// The functionality in the firebase::admob namespace has -/// been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the -/// new SDK in our migration -/// guide. -FIREBASE_DEPRECATED Future LoadAdLastResult(); - -/// @deprecated -/// @brief Shows an ad, assuming one has loaded. -/// -/// The functionality in the firebase::admob namespace has -/// been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the -/// new SDK in our migration -/// guide. -/// -/// @ref LoadAd must be called before this method. -/// @param[in] parent An @ref AdParent that is a reference to an iOS -/// UIView or an Android Activity. -FIREBASE_DEPRECATED Future Show(AdParent parent); - -/// @deprecated -/// @brief Returns a @ref Future containing the status of the last call to -/// @ref Show. -/// -/// Deprecated. The functionality in the firebase::admob -/// namespace has been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the new -/// SDK in our migration -/// guide. -FIREBASE_DEPRECATED Future ShowLastResult(); - -/// @deprecated -/// @brief Pauses any background processing associated with rewarded video. -/// -/// The functionality in the firebase::admob namespace has -/// been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the -/// new SDK in our migration -/// guide. -/// -/// Should be called whenever the C++ engine pauses or the application loses -/// focus. -FIREBASE_DEPRECATED Future Pause(); - -/// @deprecated -/// @brief Returns a @ref Future containing the status of the last call to -/// @ref Pause. -/// -/// The functionality in the firebase::admob namespace has -/// been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the -/// new SDK in our migration -/// guide. -FIREBASE_DEPRECATED Future PauseLastResult(); - -/// @deprecated -/// @brief Resumes the rewarded video system after pausing. -/// -/// The functionality in the firebase::admob namespace has -/// been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the -/// new SDK in our migration -/// guide. -FIREBASE_DEPRECATED Future Resume(); - -/// @deprecated -/// @brief Returns a @ref Future containing the status of the last call to -/// @ref Resume. -/// -/// The functionality in the firebase::admob namespace has -/// been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the -/// new SDK in our migration -/// guide. -FIREBASE_DEPRECATED Future ResumeLastResult(); - -/// @deprecated -/// @brief Cleans up and deallocates any resources used by rewarded video. -/// -/// The functionality in the firebase::admob namespace has -/// been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the -/// new SDK in our migration -/// guide. -/// -/// No other methods in rewarded_video should be called once this method has -/// been invoked. The system is closed for business at that point. -FIREBASE_DEPRECATED void Destroy(); - -/// @deprecated -/// @brief Returns the current presentation state, indicating if an ad is -/// visible or if a video has started playing. -/// -/// The functionality in the firebase::admob namespace has -/// been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the -/// new SDK in our migration -/// guide. -/// @return The current presentation state. -FIREBASE_DEPRECATED PresentationState presentation_state(); - -/// @deprecated -/// @brief Sets the @ref Listener that should receive callbacks. -/// -/// The functionality in the firebase::admob namespace has -/// been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the -/// new SDK in our migration -/// guide. -/// @param[in] listener A valid Listener. -FIREBASE_DEPRECATED void SetListener(Listener* listener); - -} // namespace rewarded_video -} // namespace admob -} // namespace firebase - -#endif // FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_REWARDED_VIDEO_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/admob/types.h b/packages/firebase_core/firebase_core/firebase_core/firebase/admob/types.h deleted file mode 100644 index 21a8379f2d96..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/admob/types.h +++ /dev/null @@ -1,244 +0,0 @@ -/* - * Copyright 2016 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_TYPES_H_ -#define FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_TYPES_H_ - -#include "firebase/internal/platform.h" - -#if FIREBASE_PLATFORM_ANDROID -#include -#elif FIREBASE_PLATFORM_IOS || FIREBASE_PLATFORM_TVOS -extern "C" { -#include -} // extern "C" -#endif // FIREBASE_PLATFORM_ANDROID, FIREBASE_PLATFORM_IOS, - // FIREBASE_PLATFORM_TVOS - -namespace firebase { -namespace admob { - -/// @deprecated The functionality in the firebase::admob namespace -/// has been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the new -/// SDK in our migration guide. -/// -/// @brief This is a platform specific datatype that is required to create an -/// AdMob ad. -/// -/// The following defines the datatype on each platform: -///

    -///
  • Android: A `jobject` which references an Android Activity.
  • -///
  • iOS: An `id` which references an iOS UIView.
  • -///
-/// -#if FIREBASE_PLATFORM_ANDROID -/// An Android Activity from Java. -typedef jobject AdParent; -#elif FIREBASE_PLATFORM_IOS || FIREBASE_PLATFORM_TVOS -/// A pointer to an iOS UIView. -typedef id AdParent; -#else -/// A void pointer for stub classes. -typedef void *AdParent; -#endif // FIREBASE_PLATFORM_ANDROID, FIREBASE_PLATFORM_IOS, - // FIREBASE_PLATFORM_TVOS - -#ifdef INTERNAL_EXPERIMENTAL -// LINT.IfChange -#endif // INTERNAL_EXPERIMENTAL -/// @deprecated -/// @brief Error codes returned by Future::error(). -/// -/// The functionality in the firebase::admob namespace has -/// been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the -/// new SDK in our migration -/// guide. -enum AdMobError { - /// Call completed successfully. - kAdMobErrorNone, - /// The ad has not been fully initialized. - kAdMobErrorUninitialized, - /// The ad is already initialized (repeat call). - kAdMobErrorAlreadyInitialized, - /// A call has failed because an ad is currently loading. - kAdMobErrorLoadInProgress, - /// A call to load an ad has failed due to an internal SDK error. - kAdMobErrorInternalError, - /// A call to load an ad has failed due to an invalid request. - kAdMobErrorInvalidRequest, - /// A call to load an ad has failed due to a network error. - kAdMobErrorNetworkError, - /// A call to load an ad has failed because no ad was available to serve. - kAdMobErrorNoFill, - /// An attempt has been made to show an ad on an Android Activity that has - /// no window token (such as one that's not done initializing). - kAdMobErrorNoWindowToken, - /// Fallback error for any unidentified cases. - kAdMobErrorUnknown, -}; -#ifdef INTERNAL_EXPERIMENTAL -// LINT.ThenChange(//depot_firebase_cpp/admob/client/cpp/src_java/com/google/firebase/admob/internal/cpp/ConstantsHelper.java) -#endif // INTERNAL_EXPERIMENTAL - -/// @deprecated -/// @brief Types of ad sizes. -/// -/// The functionality in the firebase::admob namespace has -/// been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the -/// new SDK in our migration -/// guide. -enum AdSizeType { kAdSizeStandard = 0 }; - -/// @deprecated -/// @brief An ad size value to be used in requesting ads. -/// -/// The functionality in the firebase::admob namespace has -/// been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the -/// new SDK in our migration -/// guide. -struct AdSize { - /// The type of ad size. - AdSizeType ad_size_type; - /// Height of the ad (in points or dp). - int height; - /// Width of the ad (in points or dp). - int width; -}; - -/// @deprecated -/// @brief Gender information used as part of the -/// @ref firebase::admob::AdRequest struct. -/// -/// The functionality in the firebase::admob namespace has -/// been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the -/// new SDK in our migration -/// guide. -enum Gender { - /// The gender of the current user is unknown or unspecified by the - /// publisher. - kGenderUnknown = 0, - /// The current user is known to be male. - kGenderMale, - /// The current user is known to be female. - kGenderFemale -}; - -/// @deprecated -/// @brief Indicates whether an ad request is considered tagged for -/// child-directed treatment. -/// -/// The functionality in the firebase::admob namespace has -/// been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the -/// new SDK in our migration -/// guide. -enum ChildDirectedTreatmentState { - /// The child-directed status for the request is not indicated. - kChildDirectedTreatmentStateUnknown = 0, - /// The request is tagged for child-directed treatment. - kChildDirectedTreatmentStateTagged, - /// The request is not tagged for child-directed treatment. - kChildDirectedTreatmentStateNotTagged -}; - -/// @deprecated -/// @brief Generic Key-Value container used for the "extras" values in an -/// @ref firebase::admob::AdRequest. -/// -/// The functionality in the firebase::admob namespace has -/// been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the -/// new SDK in our migration -/// guide. -struct KeyValuePair { - /// The name for an "extra." - const char *key; - /// The value for an "extra." - const char *value; -}; - -/// @deprecated -/// @brief The information needed to request an ad. -/// -/// The functionality in the firebase::admob namespace has -/// been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the -/// new SDK in our migration -/// guide. -struct AdRequest { - /// An array of test device IDs specifying devices that test ads will be - /// returned for. - const char **test_device_ids; - /// The number of entries in the array referenced by test_device_ids. - unsigned int test_device_id_count; - /// An array of keywords or phrases describing the current user activity, such - /// as "Sports Scores" or "Football." - const char **keywords; - /// The number of entries in the array referenced by keywords. - unsigned int keyword_count; - /// A @ref KeyValuePair specifying additional parameters accepted by an ad - /// network. - const KeyValuePair *extras; - /// The number of entries in the array referenced by extras. - unsigned int extras_count; - /// The day the user was born. Specify the user's birthday to increase ad - /// relevancy. - int birthday_day; - /// The month the user was born. Specify the user's birthday to increase ad - /// relevancy. - int birthday_month; - /// The year the user was born. Specify the user's birthday to increase ad - /// relevancy. - int birthday_year; - /// The user's @ref Gender. Specify the user's gender to increase ad - /// relevancy. - Gender gender; - /// Specifies whether the request should be considered as child-directed for - /// purposes of the Children’s Online Privacy Protection Act (COPPA). - ChildDirectedTreatmentState tagged_for_child_directed_treatment; -}; - -/// @deprecated -/// @brief The screen location and dimensions of an ad view once it has been -/// initialized. -/// -/// The functionality in the firebase::admob namespace has -/// been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the -/// new SDK in our migration -/// guide. -struct BoundingBox { - /// Default constructor which initializes all member variables to 0. - BoundingBox() : height(0), width(0), x(0), y(0) {} - /// Height of the ad in pixels. - int height; - /// Width of the ad in pixels. - int width; - /// Horizontal position of the ad in pixels from the left. - int x; - /// Vertical position of the ad in pixels from the top. - int y; -}; - -} // namespace admob -} // namespace firebase - -#endif // FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_TYPES_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/analytics.h b/packages/firebase_core/firebase_core/firebase_core/firebase/analytics.h deleted file mode 100644 index 973890b20fce..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/analytics.h +++ /dev/null @@ -1,569 +0,0 @@ -/* - * Copyright 2016 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_ANALYTICS_SRC_INCLUDE_FIREBASE_ANALYTICS_H_ -#define FIREBASE_ANALYTICS_SRC_INCLUDE_FIREBASE_ANALYTICS_H_ - -#include -#include -#include -#include - -#include "firebase/app.h" -#include "firebase/future.h" -#include "firebase/internal/common.h" -#include "firebase/variant.h" - -#if !defined(DOXYGEN) && !defined(SWIG) -FIREBASE_APP_REGISTER_CALLBACKS_REFERENCE(analytics) -#endif // !defined(DOXYGEN) && !defined(SWIG) - -/// @brief Namespace that encompasses all Firebase APIs. -namespace firebase { - -/// @brief Firebase Analytics API. -/// -/// See the developer guides for general -/// information on using Firebase Analytics in your apps. -namespace analytics { - -/// @brief Event parameter. -/// -/// Parameters supply information that contextualize events (see @ref LogEvent). -/// You can associate up to 25 unique Parameters with each event type (name). -/// -/// -/// @if swig_examples -/// Common event types are provided as static properties of the -/// FirebaseAnalytics class (e.g FirebaseAnalytics.EventPostScore) where -/// parameters of these events are also provided in this FirebaseAnalytics -/// class (e.g FirebaseAnalytics.ParameterScore). -/// -/// You are not limited to the set of event types and parameter names -/// suggested in FirebaseAnalytics class properties. Additional Parameters can -/// be supplied for suggested event types or custom Parameters for custom event -/// types. -/// @endif -/// -/// @if cpp_examples -/// Common event types (names) are suggested in @ref event_names -/// (%event_names.h) with parameters of common event types defined in -/// @ref parameter_names (%parameter_names.h). -/// -/// You are not limited to the set of event types and parameter names suggested -/// in @ref event_names (%event_names.h) and %parameter_names.h respectively. -/// Additional Parameters can be supplied for suggested event types or custom -/// Parameters for custom event types. -/// @endif -/// -/// Parameter names must be a combination of letters and digits -/// (matching the regular expression [a-zA-Z0-9]) between 1 and 40 characters -/// long starting with a letter [a-zA-Z] character. The "firebase_", -/// "google_" and "ga_" prefixes are reserved and should not be used. -/// -/// Parameter string values can be up to 100 characters long. -/// -/// -/// @if swig_examples -/// An array of Parameter class instances can be passed to LogEvent in order -/// to associate parameters's of an event with values where each value can be -/// a double, 64-bit integer or string. -/// @endif -/// -/// @if cpp_examples -/// An array of this structure is passed to LogEvent in order to associate -/// parameter's of an event (Parameter::name) with values (Parameter::value) -/// where each value can be a double, 64-bit integer or string. -/// @endif -/// -/// For example, a game may log an achievement event along with the -/// character the player is using and the level they're currently on: -/// -/// -/// @if swig_examples -/// @code{.cs} -/// using Firebase.Analytics; -/// -/// int currentLevel = GetCurrentLevel(); -/// Parameter[] AchievementParameters = { -/// new Parameter(FirebaseAnalytics.ParameterAchievementID, -/// "ultimate_wizard"), -/// new Parameter(FirebaseAnalytics.ParameterCharacter, "mysterion"), -/// new Parameter(FirebaseAnalytics.ParameterLevel, currentLevel), -/// }; -/// FirebaseAnalytics.LogEvent(FirebaseAnalytics.EventLevelUp, -/// AchievementParameters); -/// @endcode -/// @endif -/// -/// @if cpp_examples -/// @code{.cpp} -/// using namespace firebase::analytics; -/// int64_t current_level = GetCurrentLevel(); -/// const Parameter achievement_parameters[] = { -/// Parameter(kParameterAchievementID, "ultimate_wizard"), -/// Parameter(kParameterCharacter, "mysterion"), -/// Parameter(kParameterLevel, current_level), -/// }; -/// LogEvent(kEventUnlockAchievement, achievement_parameters, -/// sizeof(achievement_parameters) / -/// sizeof(achievement_parameters[0])); -/// @endcode -/// @endif -/// -struct Parameter { -#ifndef SWIG - /// Construct an empty parameter. - /// - /// This is provided to allow initialization after construction. - Parameter() : name(nullptr) {} -#endif // !SWIG - -// -// We don't want to pull in Variant in the C# interface. -// -#ifndef SWIG - /// Construct a parameter. - /// - /// @param parameter_name Name of the parameter (see Parameter::name). - /// @param parameter_value Value for the parameter. Variants can - /// hold numbers and strings. - Parameter(const char* parameter_name, Variant parameter_value) - : name(parameter_name) { - value = parameter_value; - } -#endif // !SWIG - - /// Construct a 64-bit integer parameter. - /// - /// @param parameter_name Name of the parameter. - /// @if cpp_examples - /// (see Parameter::name). - /// @endif - /// - /// @if swig_examples - /// Parameter names must be a combination of letters and digits - /// (matching the regular expression [a-zA-Z0-9]) between 1 and 40 characters - /// long starting with a letter [a-zA-Z] character. - /// @endif - /// - /// @param parameter_value Integer value for the parameter. - Parameter(const char* parameter_name, int parameter_value) - : name(parameter_name) { - value = parameter_value; - } - - /// Construct a 64-bit integer parameter. - /// - /// @param parameter_name Name of the parameter. - /// @if cpp_examples - /// (see Parameter::name). - /// @endif - /// - /// @if swig_examples - /// Parameter names must be a combination of letters and digits - /// (matching the regular expression [a-zA-Z0-9]) between 1 and 40 characters - /// long starting with a letter [a-zA-Z] character. - /// @endif - /// - /// @param parameter_value Integer value for the parameter. - Parameter(const char* parameter_name, int64_t parameter_value) - : name(parameter_name) { - value = parameter_value; - } - - /// Construct a floating point parameter. - /// - /// @param parameter_name Name of the parameter. - /// @if cpp_examples - /// (see Parameter::name). - /// @endif - /// - /// @if swig_examples - /// Parameter names must be a combination of letters and digits - /// (matching the regular expression [a-zA-Z0-9]) between 1 and 40 characters - /// long starting with a letter [a-zA-Z] character. - /// @endif - /// - /// @param parameter_value Floating point value for the parameter. - Parameter(const char* parameter_name, double parameter_value) - : name(parameter_name) { - value = parameter_value; - } - - /// Construct a string parameter. - /// - /// @param parameter_name Name of the parameter. - /// @if cpp_examples - /// (see Parameter::name). - /// @endif - /// - /// @if swig_examples - /// Parameter names must be a combination of letters and digits - /// (matching the regular expression [a-zA-Z0-9]) between 1 and 40 characters - /// long starting with a letter [a-zA-Z] character. - /// @endif - /// - /// @param parameter_value String value for the parameter, can be up to 100 - /// characters long. - Parameter(const char* parameter_name, const char* parameter_value) - : name(parameter_name) { - value = parameter_value; - } - -#ifndef SWIG - // - // Skipping implementation values because the C# API members are - // immutable, and there's no other need to read these values in - // C#. The class just needs to be passed to the C++ layers. - // This also avoids having to solve the nested union, which is - // unsupported in swig. - // - - /// @brief Name of the parameter. - /// - /// Parameter names must be a combination of letters and digits - /// (matching the regular expression [a-zA-Z0-9]) between 1 and 40 characters - /// long starting with a letter [a-zA-Z] character. The "firebase_", - /// "google_" and "ga_" prefixes are reserved and should not be used. - const char* name; - /// @brief Value of the parameter. - /// - /// See firebase::Variant for usage information. - /// @note String values can be up to 100 characters long. - Variant value; -#endif // SWIG -}; - -/// @brief Initialize the Analytics API. -/// -/// This must be called prior to calling any other methods in the -/// firebase::analytics namespace. -/// -/// @param[in] app Default @ref firebase::App instance. -/// -/// @see firebase::App::GetInstance(). -void Initialize(const App& app); - -/// @brief Terminate the Analytics API. -/// -/// Cleans up resources associated with the API. -void Terminate(); - -/// @brief Sets whether analytics collection is enabled for this app on this -/// device. -/// -/// This setting is persisted across app sessions. By default it is enabled. -/// -/// @param[in] enabled true to enable analytics collection, false to disable. -void SetAnalyticsCollectionEnabled(bool enabled); - -/// @brief The type of consent to set. -/// -/// Supported consent types are kConsentTypeAdStorage and -/// kConsentTypeAnalyticsStorage. Omitting a type retains its previous status. -enum ConsentType { kConsentTypeAdStorage = 0, kConsentTypeAnalyticsStorage }; - -/// @brief The status value of the consent type. -/// -/// Supported statuses are kConsentStatusGranted and kConsentStatusDenied. -enum ConsentStatus { kConsentStatusGranted = 0, kConsentStatusDenied }; - -/// @brief Sets the applicable end user consent state (e.g., for device -/// identifiers) for this app on this device. -/// -/// Use the consent map to specify individual consent type values. Settings are -/// persisted across app sessions. By default consent types are set to -/// "granted". -void SetConsent(const std::map& consent_settings); - -/// @brief Log an event with one string parameter. -/// -/// @param[in] name Name of the event to log. Should contain 1 to 40 -/// alphanumeric characters or underscores. The name must start with an -/// alphabetic character. Some event names are reserved. -/// -/// @if swig_examples -/// See the FirebaseAnalytics.Event properties for the list of reserved event -/// names. -/// @endif -/// -/// @if cpp_examples -/// See @ref event_names (%event_names.h) for the list of reserved event names. -/// @endif -/// The "firebase_" prefix is reserved and should not be used. Note that event -/// names are case-sensitive and that logging two events whose names differ -/// only in case will result in two distinct events. -/// @param[in] parameter_name Name of the parameter to log. -/// For more information, see @ref Parameter. -/// @param[in] parameter_value Value of the parameter to log. -/// -/// -/// @if swig_examples -/// @see LogEvent(string, Parameter[]) -/// @endif -/// -/// @if cpp_examples -/// @see LogEvent(const char*, const Parameter*, size_t) -/// @endif -void LogEvent(const char* name, const char* parameter_name, - const char* parameter_value); - -/// @brief Log an event with one float parameter. -/// -/// @param[in] name Name of the event to log. Should contain 1 to 40 -/// alphanumeric characters or underscores. The name must start with an -/// alphabetic character. Some event names are reserved. -/// -/// @if swig_examples -/// See the FirebaseAnalytics.Event properties for the list of reserved event -/// names. -/// @endif -/// -/// @if cpp_examples -/// See @ref event_names (%event_names.h) for the list of reserved event names. -/// @endif -/// The "firebase_" prefix is reserved and should not be used. Note that event -/// names are case-sensitive and that logging two events whose names differ -/// only in case will result in two distinct events. -/// @param[in] parameter_name Name of the parameter to log. -/// For more information, see @ref Parameter. -/// @param[in] parameter_value Value of the parameter to log. -/// -/// -/// @if swig_examples -/// @see LogEvent(string, Parameter[]) -/// @endif -/// -/// @if cpp_examples -/// @see LogEvent(const char*, const Parameter*, size_t) -/// @endif -void LogEvent(const char* name, const char* parameter_name, - const double parameter_value); - -/// @brief Log an event with one 64-bit integer parameter. -/// -/// @param[in] name Name of the event to log. Should contain 1 to 40 -/// alphanumeric characters or underscores. The name must start with an -/// alphabetic character. Some event names are reserved. -/// -/// @if swig_examples -/// See the FirebaseAnalytics.Event properties for the list of reserved event -/// names. -/// @endif -/// -/// @if cpp_examples -/// See @ref event_names (%event_names.h) for the list of reserved event names. -/// @endif -/// The "firebase_" prefix is reserved and should not be used. Note that event -/// names are case-sensitive and that logging two events whose names differ -/// only in case will result in two distinct events. -/// @param[in] parameter_name Name of the parameter to log. -/// For more information, see @ref Parameter. -/// @param[in] parameter_value Value of the parameter to log. -/// -/// -/// @if swig_examples -/// @see LogEvent(string, Parameter[]) -/// @endif -/// -/// @if cpp_examples -/// @see LogEvent(const char*, const Parameter*, size_t) -/// @endif -void LogEvent(const char* name, const char* parameter_name, - const int64_t parameter_value); - -/// @brief Log an event with one integer parameter -/// (stored as a 64-bit integer). -/// -/// @param[in] name Name of the event to log. Should contain 1 to 40 -/// alphanumeric characters or underscores. The name must start with an -/// alphabetic character. Some event names are reserved. -/// -/// @if swig_examples -/// See the FirebaseAnalytics.Event properties for the list of reserved event -/// names. -/// @endif -/// -/// @if cpp_examples -/// See @ref event_names (%event_names.h) for the list of reserved event names. -/// @endif -/// The "firebase_" prefix is reserved and should not be used. Note that event -/// names are case-sensitive and that logging two events whose names differ -/// only in case will result in two distinct events. -/// @param[in] parameter_name Name of the parameter to log. -/// For more information, see @ref Parameter. -/// @param[in] parameter_value Value of the parameter to log. -/// -/// -/// @if swig_examples -/// @see LogEvent(string, Parameter[]) -/// @endif -/// -/// @if cpp_examples -/// @see LogEvent(const char*, const Parameter*, size_t) -/// @endif -void LogEvent(const char* name, const char* parameter_name, - const int parameter_value); - -/// @brief Log an event with no parameters. -/// -/// @param[in] name Name of the event to log. Should contain 1 to 40 -/// alphanumeric characters or underscores. The name must start with an -/// alphabetic character. Some event names are reserved. -/// -/// @if swig_examples -/// See the FirebaseAnalytics.Event properties for the list of reserved event -/// names. -/// @endif -/// -/// @if cpp_examples -/// See @ref event_names (%event_names.h) for the list of reserved event names. -/// @endif -/// The "firebase_" prefix is reserved and should not be used. Note that event -/// names are case-sensitive and that logging two events whose names differ -/// only in case will result in two distinct events. -/// -/// -/// @if swig_examples -/// @see LogEvent(string, Parameter[]) -/// @endif -/// -/// @if cpp_examples -/// @see LogEvent(const char*, const Parameter*, size_t) -/// @endif -void LogEvent(const char* name); - -// clang-format off -#ifdef SWIG -// Modify the following overload with unsafe, so that we can do some pinning -// in the C# code. -%csmethodmodifiers LogEvent "public unsafe" -#endif // SWIG -// clang-format on - -/// @brief Log an event with associated parameters. -/// -/// An Event is an important occurrence in your app that you want to -/// measure. You can report up to 500 different types of events per app and -/// you can associate up to 25 unique parameters with each Event type. -/// -/// Some common events are documented in @ref event_names (%event_names.h), -/// but you may also choose to specify custom event types that are associated -/// with your specific app. -/// -/// @param[in] name Name of the event to log. Should contain 1 to 40 -/// alphanumeric characters or underscores. The name must start with an -/// alphabetic character. Some event names are reserved. See @ref event_names -/// (%event_names.h) for the list of reserved event names. The "firebase_" -/// prefix is reserved and should not be used. Note that event names are -/// case-sensitive and that logging two events whose names differ only in -/// case will result in two distinct events. -/// @param[in] parameters Array of Parameter structures. -/// @param[in] number_of_parameters Number of elements in the parameters -/// array. -void LogEvent(const char* name, const Parameter* parameters, - size_t number_of_parameters); - -/// Initiates on-device conversion measurement given a user email address on iOS -/// and tvOS (no-op on Android). On iOS and tvOS, this method requires the -/// dependency GoogleAppMeasurementOnDeviceConversion to be linked in, -/// otherwise the invocation results in a no-op. -/// @param[in] email_address User email address. Include a domain name for all -/// email addresses (e.g. gmail.com or hotmail.co.jp). -void InitiateOnDeviceConversionMeasurementWithEmailAddress( - const char* email_address); - -/// @brief Set a user property to the given value. -/// -/// Properties associated with a user allow a developer to segment users -/// into groups that are useful to their application. Up to 25 properties -/// can be associated with a user. -/// -/// Suggested property names are listed @ref user_property_names -/// (%user_property_names.h) but you're not limited to this set. For example, -/// the "gamertype" property could be used to store the type of player where -/// a range of values could be "casual", "mid_core", or "core". -/// -/// @param[in] name Name of the user property to set. This must be a -/// combination of letters and digits (matching the regular expression -/// [a-zA-Z0-9] between 1 and 40 characters long starting with a letter -/// [a-zA-Z] character. -/// @param[in] property Value to set the user property to. Set this -/// argument to NULL or nullptr to remove the user property. The value can be -/// between 1 to 100 characters long. -void SetUserProperty(const char* name, const char* property); - -/// @brief Sets the user ID property. -/// -/// This feature must be used in accordance with -/// Google's Privacy -/// Policy -/// -/// @param[in] user_id The user ID associated with the user of this app on this -/// device. The user ID must be non-empty and no more than 256 characters long. -/// Setting user_id to NULL or nullptr removes the user ID. -void SetUserId(const char* user_id); - -/// @brief Sets the duration of inactivity that terminates the current session. -/// -/// @note The default value is 1800000 (30 minutes). -/// -/// @param milliseconds The duration of inactivity that terminates the current -/// session. -void SetSessionTimeoutDuration(int64_t milliseconds); - -/// Clears all analytics data for this app from the device and resets the app -/// instance id. -void ResetAnalyticsData(); - -/// Get the instance ID from the analytics service. -/// -/// @note This is *not* the same ID as the ID returned by -/// @if cpp_examples -/// firebase::instance_id::InstanceId. -/// @else -/// Firebase.InstanceId.FirebaseInstanceId. -/// @endif -/// -/// @returns Object which can be used to retrieve the analytics instance ID. -Future GetAnalyticsInstanceId(); - -/// Get the result of the most recent GetAnalyticsInstanceId() call. -/// -/// @returns Object which can be used to retrieve the analytics instance ID. -Future GetAnalyticsInstanceIdLastResult(); - -/// Asynchronously retrieves the identifier of the current app -/// session. -/// -/// The session ID retrieval could fail due to Analytics collection -/// disabled, or if the app session was expired. -/// -/// @returns Object which can be used to retrieve the identifier of the current -/// app session. -Future GetSessionId(); - -/// Get the result of the most recent GetSessionId() call. -/// -/// @returns Object which can be used to retrieve the identifier of the current -/// app session. -Future GetSessionIdLastResult(); - -} // namespace analytics -} // namespace firebase - -#endif // FIREBASE_ANALYTICS_SRC_INCLUDE_FIREBASE_ANALYTICS_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/analytics/event_names.h b/packages/firebase_core/firebase_core/firebase_core/firebase/analytics/event_names.h deleted file mode 100644 index 4f1d4e5a0e2b..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/analytics/event_names.h +++ /dev/null @@ -1,472 +0,0 @@ -// Copyright 2023 Google Inc. All Rights Reserved. - -#ifndef FIREBASE_ANALYTICS_CLIENT_CPP_INCLUDE_FIREBASE_ANALYTICS_EVENT_NAMES_H_ -#define FIREBASE_ANALYTICS_CLIENT_CPP_INCLUDE_FIREBASE_ANALYTICS_EVENT_NAMES_H_ - -/// @brief Namespace that encompasses all Firebase APIs. -namespace firebase { -/// @brief Firebase Analytics API. -namespace analytics { - - - -/// @defgroup event_names Analytics Events -/// -/// Predefined event names. -/// -/// An Event is an important occurrence in your app that you want to -/// measure. You can report up to 500 different types of Events per app -/// and you can associate up to 25 unique parameters with each Event type. -/// Some common events are suggested below, but you may also choose to -/// specify custom Event types that are associated with your specific app. -/// Each event type is identified by a unique name. Event names can be up -/// to 40 characters long, may only contain alphanumeric characters and -/// underscores ("_"), and must start with an alphabetic character. The -/// "firebase_", "google_", and "ga_" prefixes are reserved and should not -/// be used. -/// @{ - - -/// Ad Impression event. This event signifies when a user sees an ad -/// impression. Note: If you supply the @c AnalyticsParameterValue -/// parameter, you must also supply the @c AnalyticsParameterCurrency -/// parameter so that revenue metrics can be computed accurately. Params: -/// -///
    -///
  • @c AnalyticsParameterAdPlatform (String) (optional)
  • -///
  • @c AnalyticsParameterAdFormat (String) (optional)
  • -///
  • @c AnalyticsParameterAdSource (String) (optional)
  • -///
  • @c AnalyticsParameterAdUnitName (String) (optional)
  • -///
  • @c AnalyticsParameterCurrency (String) (optional)
  • -///
  • @c AnalyticsParameterValue (Double) (optional)
  • -///
-static const char*const kEventAdImpression = - "ad_impression"; - -/// Add Payment Info event. This event signifies that a user has submitted -/// their payment information. Note: If you supply the @c -/// AnalyticsParameterValue parameter, you must also supply the @c -/// AnalyticsParameterCurrency parameter so that revenue metrics can be -/// computed accurately. Params: -/// -///
    -///
  • @c AnalyticsParameterCoupon (String) (optional)
  • -///
  • @c AnalyticsParameterCurrency (String) (optional)
  • -///
  • @c AnalyticsParameterItems ([[String: Any]]) (optional)
  • -///
  • @c AnalyticsParameterPaymentType (String) (optional)
  • -///
  • @c AnalyticsParameterValue (Double) (optional)
  • -///
-static const char*const kEventAddPaymentInfo = - "add_payment_info"; - -/// Add Shipping Info event. This event signifies that a user has -/// submitted their shipping information. Note: If you supply the @c -/// AnalyticsParameterValue parameter, you must also supply the @c -/// AnalyticsParameterCurrency parameter so that revenue metrics can be -/// computed accurately. Params: -/// -///
    -///
  • @c AnalyticsParameterCoupon (String) (optional)
  • -///
  • @c AnalyticsParameterCurrency (String) (optional)
  • -///
  • @c AnalyticsParameterItems ([[String: Any]]) (optional)
  • -///
  • @c AnalyticsParameterShippingTier (String) (optional)
  • -///
  • @c AnalyticsParameterValue (Double) (optional)
  • -///
-static const char*const kEventAddShippingInfo = - "add_shipping_info"; - -/// E-Commerce Add To Cart event. This event signifies that an item(s) was -/// added to a cart for purchase. Add this event to a funnel with @c -/// AnalyticsEventPurchase to gauge the effectiveness of your -/// checParameter(kout, If you supply the @c AnalyticsParameterValue -/// parameter), you must also supply the @c AnalyticsParameterCurrency -/// parameter so that revenue metrics can be computed accurately. Params: -/// -///
    -///
  • @c AnalyticsParameterCurrency (String) (optional)
  • -///
  • @c AnalyticsParameterItems ([[String: Any]]) (optional)
  • -///
  • @c AnalyticsParameterValue (Double) (optional)
  • -///
-static const char*const kEventAddToCart = "add_to_cart"; - -/// E-Commerce Add To Wishlist event. This event signifies that an item -/// was added to a wishlist. Use this event to identify popular gift -/// items. Note: If you supply the @c AnalyticsParameterValue parameter, -/// you must also supply the @c AnalyticsParameterCurrency parameter so -/// that revenue metrics can be computed accurately. Params: -/// -///
    -///
  • @c AnalyticsParameterCurrency (String) (optional)
  • -///
  • @c AnalyticsParameterItems ([[String: Any]]) (optional)
  • -///
  • @c AnalyticsParameterValue (Double) (optional)
  • -///
-static const char*const kEventAddToWishlist = - "add_to_wishlist"; - -/// App Open event. By logging this event when an App becomes active, -/// developers can understand how often users leave and return during the -/// course of a Session. Although Sessions are automatically reported, -/// this event can provide further clarification around the continuous -/// engagement of app-users. -static const char*const kEventAppOpen = "app_open"; - -/// E-Commerce Begin Checkout event. This event signifies that a user has -/// begun the process of checking out. Add this event to a funnel with -/// your @c AnalyticsEventPurchase event to gauge the effectiveness of -/// your checkout process. Note: If you supply the @c -/// AnalyticsParameterValue parameter, you must also supply the @c -/// AnalyticsParameterCurrency parameter so that revenue metrics can be -/// computed accurately. Params: -/// -///
    -///
  • @c AnalyticsParameterCoupon (String) (optional)
  • -///
  • @c AnalyticsParameterCurrency (String) (optional)
  • -///
  • @c AnalyticsParameterItems ([[String: Any]]) (optional)
  • -///
  • @c AnalyticsParameterValue (Double) (optional)
  • -///
-static const char*const kEventBeginCheckout = - "begin_checkout"; - -/// Campaign Detail event. Log this event to supply the referral details -/// of a re-engagement campaign. Note: you must supply at least one of the -/// required parameters AnalyticsParameterSource, AnalyticsParameterMedium -/// or AnalyticsParameterCampaign. Params: -/// -///
    -///
  • @c AnalyticsParameterSource (String)
  • -///
  • @c AnalyticsParameterMedium (String)
  • -///
  • @c AnalyticsParameterCampaign (String)
  • -///
  • @c AnalyticsParameterTerm (String) (optional)
  • -///
  • @c AnalyticsParameterContent (String) (optional)
  • -///
  • @c AnalyticsParameterAdNetworkClickID (String) (optional)
  • -///
  • @c AnalyticsParameterCP1 (String) (optional)
  • -///
  • @c AnalyticsParameterCampaignID (String) (optional)
  • -///
  • @c AnalyticsParameterCreativeFormat (String) (optional)
  • -///
  • @c AnalyticsParameterMarketingTactic (String) (optional)
  • -///
  • @c AnalyticsParameterSourcePlatform (String) (optional)
  • -///
-static const char*const kEventCampaignDetails = - "campaign_details"; - -/// Earn Virtual Currency event. This event tracks the awarding of virtual -/// currency in your app. Log this along with @c -/// AnalyticsEventSpendVirtualCurrency to better understand your virtual -/// economy. Params: -/// -///
    -///
  • @c AnalyticsParameterVirtualCurrencyName (String)
  • -///
  • @c AnalyticsParameterValue (Int or Double)
  • -///
-static const char*const kEventEarnVirtualCurrency - = "earn_virtual_currency"; - -/// Generate Lead event. Log this event when a lead has been generated in -/// the app to understand the efficacy of your install and re-engagement -/// campaigns. Note: If you supply the @c AnalyticsParameterValue -/// parameter, you must also supply the @c AnalyticsParameterCurrency -/// parameter so that revenue metrics can be computed accurately. Params: -/// -///
    -///
  • @c AnalyticsParameterCurrency (String) (optional)
  • -///
  • @c AnalyticsParameterValue (Double) (optional)
  • -///
-static const char*const kEventGenerateLead = - "generate_lead"; - -/// Join Group event. Log this event when a user joins a group such as a -/// guild, team or family. Use this event to analyze how popular certain -/// groups or social features are in your app. Params: -/// -///
    -///
  • @c AnalyticsParameterGroupID (String)
  • -///
-static const char*const kEventJoinGroup = "join_group"; - -/// Level End event. Log this event when the user finishes a level. -/// Params: -/// -///
    -///
  • @c AnalyticsParameterLevelName (String)
  • -///
  • @c AnalyticsParameterSuccess (String)
  • -///
-static const char*const kEventLevelEnd = "level_end"; - -/// Level Start event. Log this event when the user starts a new level. -/// Params: -/// -///
    -///
  • @c AnalyticsParameterLevelName (String)
  • -///
-static const char*const kEventLevelStart = "level_start"; - -/// Level Up event. This event signifies that a player has leveled up in -/// your gaming app. It can help you gauge the level distribution of your -/// userbase and help you identify certain levels that are difficult to -/// pass. Params: -/// -///
    -///
  • @c AnalyticsParameterLevel (Int)
  • -///
  • @c AnalyticsParameterCharacter (String) (optional)
  • -///
-static const char*const kEventLevelUp = "level_up"; - -/// Login event. Apps with a login feature can report this event to -/// signify that a user has logged in. -static const char*const kEventLogin = "login"; - -/// Post Score event. Log this event when the user posts a score in your -/// gaming app. This event can help you understand how users are actually -/// performing in your game and it can help you correlate high scores with -/// certain audiences or behaviors. Params: -/// -///
    -///
  • @c AnalyticsParameterScore (Int)
  • -///
  • @c AnalyticsParameterLevel (Int) (optional)
  • -///
  • @c AnalyticsParameterCharacter (String) (optional)
  • -///
-static const char*const kEventPostScore = "post_score"; - -/// E-Commerce Purchase event. This event signifies that an item(s) was -/// purchased by a user. Note: This is different from the in-app purchase -/// event, which is reported automatically for App Store-based apps. Note: -/// If you supply the @c AnalyticsParameterValue parameter, you must also -/// supply the @c AnalyticsParameterCurrency parameter so that revenue -/// metrics can be computed accurately. Params: -/// -///
    -///
  • @c AnalyticsParameterAffiliation (String) (optional)
  • -///
  • @c AnalyticsParameterCoupon (String) (optional)
  • -///
  • @c AnalyticsParameterCurrency (String) (optional)
  • -///
  • @c AnalyticsParameterEndDate (String) (optional)
  • -///
  • @c AnalyticsParameterItemID (String) (optional)
  • -///
  • @c AnalyticsParameterItems ([[String: Any]]) (optional)
  • -///
  • @c AnalyticsParameterShipping (Double) (optional)
  • -///
  • @c AnalyticsParameterStartDate (String) (optional)
  • -///
  • @c AnalyticsParameterTax (Double) (optional)
  • -///
  • @c AnalyticsParameterTransactionID (String) (optional)
  • -///
  • @c AnalyticsParameterValue (Double) (optional)
  • -///
-static const char*const kEventPurchase = "purchase"; - -/// E-Commerce Refund event. This event signifies that a refund was -/// issued. Note: If you supply the @c AnalyticsParameterValue parameter, -/// you must also supply the @c AnalyticsParameterCurrency parameter so -/// that revenue metrics can be computed accurately. Params: -/// -///
    -///
  • @c AnalyticsParameterAffiliation (String) (optional)
  • -///
  • @c AnalyticsParameterCoupon (String) (optional)
  • -///
  • @c AnalyticsParameterCurrency (String) (optional)
  • -///
  • @c AnalyticsParameterItems ([[String: Any]]) (optional)
  • -///
  • @c AnalyticsParameterShipping (Double) (optional)
  • -///
  • @c AnalyticsParameterTax (Double) (optional)
  • -///
  • @c AnalyticsParameterTransactionID (String) (optional)
  • -///
  • @c AnalyticsParameterValue (Double) (optional)
  • -///
-static const char*const kEventRefund = "refund"; - -/// E-Commerce Remove from Cart event. This event signifies that an -/// item(s) was removed from a cart. Note: If you supply the @c -/// AnalyticsParameterValue parameter, you must also supply the @c -/// AnalyticsParameterCurrency parameter so that revenue metrics can be -/// computed accurately. Params: -/// -///
    -///
  • @c AnalyticsParameterCurrency (String) (optional)
  • -///
  • @c AnalyticsParameterItems ([[String: Any]]) (optional)
  • -///
  • @c AnalyticsParameterValue (Double) (optional)
  • -///
-static const char*const kEventRemoveFromCart = - "remove_from_cart"; - -/// Screen View event. This event signifies a screen view. Use this when a -/// screen transition occurs. This event can be logged irrespective of -/// whether automatic screen tracking is enabled. Params: -/// -///
    -///
  • @c AnalyticsParameterScreenClass (String) (optional)
  • -///
  • @c AnalyticsParameterScreenName (String) (optional)
  • -///
-static const char*const kEventScreenView = "screen_view"; - -/// Search event. Apps that support search features can use this event to -/// contextualize search operations by supplying the appropriate, -/// corresponding parameters. This event can help you identify the most -/// popular content in your app. Params: -/// -///
    -///
  • @c AnalyticsParameterSearchTerm (String)
  • -///
  • @c AnalyticsParameterStartDate (String) (optional)
  • -///
  • @c AnalyticsParameterEndDate (String) (optional)
  • -///
  • @c AnalyticsParameterNumberOfNights (Int) (optional) for hotel bookings
  • -///
  • @c AnalyticsParameterNumberOfRooms (Int) (optional) for hotel bookings
  • -///
  • @c AnalyticsParameterNumberOfPassengers (Int) (optional) for travel bookings
  • -///
  • @c AnalyticsParameterOrigin (String) (optional)
  • -///
  • @c AnalyticsParameterDestination (String) (optional)
  • -///
  • @c AnalyticsParameterTravelClass (String) (optional) for travel bookings
  • -///
-static const char*const kEventSearch = "search"; - -/// Select Content event. This general purpose event signifies that a user -/// has selected some content of a certain type in an app. The content can -/// be any object in your app. This event can help you identify popular -/// content and categories of content in your app. Params: -/// -///
    -///
  • @c AnalyticsParameterContentType (String)
  • -///
  • @c AnalyticsParameterItemID (String)
  • -///
-static const char*const kEventSelectContent = - "select_content"; - -/// Select Item event. This event signifies that an item was selected by a -/// user from a list. Use the appropriate parameters to contextualize the -/// event. Use this event to discover the most popular items selected. -/// Params: -/// -///
    -///
  • @c AnalyticsParameterItems ([[String: Any]]) (optional)
  • -///
  • @c AnalyticsParameterItemListID (String) (optional)
  • -///
  • @c AnalyticsParameterItemListName (String) (optional)
  • -///
-static const char*const kEventSelectItem = "select_item"; - -/// Select promotion event. This event signifies that a user has selected -/// a promotion offer. Use the appropriate parameters to contextualize the -/// event, such as the item(s) for which the promotion applies. Params: -/// -///
    -///
  • @c AnalyticsParameterCreativeName (String) (optional)
  • -///
  • @c AnalyticsParameterCreativeSlot (String) (optional)
  • -///
  • @c AnalyticsParameterItems ([[String: Any]]) (optional)
  • -///
  • @c AnalyticsParameterLocationID (String) (optional)
  • -///
  • @c AnalyticsParameterPromotionID (String) (optional)
  • -///
  • @c AnalyticsParameterPromotionName (String) (optional)
  • -///
-static const char*const kEventSelectPromotion = - "select_promotion"; - -/// Share event. Apps with social features can log the Share event to -/// identify the most viral content. Params: -/// -///
    -///
  • @c AnalyticsParameterContentType (String)
  • -///
  • @c AnalyticsParameterItemID (String)
  • -///
-static const char*const kEventShare = "share"; - -/// Sign Up event. This event indicates that a user has signed up for an -/// account in your app. The parameter signifies the method by which the -/// user signed up. Use this event to understand the different behaviors -/// between logged in and logged out users. Params: -/// -///
    -///
  • @c AnalyticsParameterMethod (String)
  • -///
-static const char*const kEventSignUp = "sign_up"; - -/// Spend Virtual Currency event. This event tracks the sale of virtual -/// goods in your app and can help you identify which virtual goods are -/// the most popular objects of purchase. Params: -/// -///
    -///
  • @c AnalyticsParameterItemName (String)
  • -///
  • @c AnalyticsParameterVirtualCurrencyName (String)
  • -///
  • @c AnalyticsParameterValue (Int or Double)
  • -///
-static const char*const kEventSpendVirtualCurrency - = "spend_virtual_currency"; - -/// Tutorial Begin event. This event signifies the start of the -/// on-boarding process in your app. Use this in a funnel with @c -/// AnalyticsEventTutorialComplete to understand how many users complete -/// this process and move on to the full app experience. -static const char*const kEventTutorialBegin = - "tutorial_begin"; - -/// Tutorial End event. Use this event to signify the user's completion of -/// your app's on-boarding process. Add this to a funnel with @c -/// AnalyticsEventTutorialBegin to gauge the completion rate of your -/// on-boarding process. -static const char*const kEventTutorialComplete = - "tutorial_complete"; - -/// Unlock Achievement event. Log this event when the user has unlocked an -/// achievement in your game. Since achievements generally represent the -/// breadth of a gaming experience, this event can help you understand how -/// many users are experiencing all that your game has to offer. Params: -/// -///
    -///
  • @c AnalyticsParameterAchievementID (String)
  • -///
-static const char*const kEventUnlockAchievement = - "unlock_achievement"; - -/// E-commerce View Cart event. This event signifies that a user has -/// viewed their cart. Use this to analyze your purchase funnel. Note: If -/// you supply the @c AnalyticsParameterValue parameter, you must also -/// supply the @c AnalyticsParameterCurrency parameter so that revenue -/// metrics can be computed accurately. Params: -/// -///
    -///
  • @c AnalyticsParameterCurrency (String) (optional)
  • -///
  • @c AnalyticsParameterItems ([[String: Any]]) (optional)
  • -///
  • @c AnalyticsParameterValue (Double) (optional)
  • -///
-static const char*const kEventViewCart = "view_cart"; - -/// View Item event. This event signifies that a user has viewed an item. -/// Use the appropriate parameters to contextualize the event. Use this -/// event to discover the most popular items viewed in your app. Note: If -/// you supply the @c AnalyticsParameterValue parameter, you must also -/// supply the @c AnalyticsParameterCurrency parameter so that revenue -/// metrics can be computed accurately. Params: -/// -///
    -///
  • @c AnalyticsParameterCurrency (String) (optional)
  • -///
  • @c AnalyticsParameterItems ([[String: Any]]) (optional)
  • -///
  • @c AnalyticsParameterValue (Double) (optional)
  • -///
-static const char*const kEventViewItem = "view_item"; - -/// View Item List event. Log this event when a user sees a list of items -/// or offerings. Params: -/// -///
    -///
  • @c AnalyticsParameterItems ([[String: Any]]) (optional)
  • -///
  • @c AnalyticsParameterItemListID (String) (optional)
  • -///
  • @c AnalyticsParameterItemListName (String) (optional)
  • -///
-static const char*const kEventViewItemList = - "view_item_list"; - -/// View Promotion event. This event signifies that a promotion was shown -/// to a user. Add this event to a funnel with the @c -/// AnalyticsEventAddToCart and @c AnalyticsEventPurchase to gauge your -/// conversion process. Params: -/// -///
    -///
  • @c AnalyticsParameterCreativeName (String) (optional)
  • -///
  • @c AnalyticsParameterCreativeSlot (String) (optional)
  • -///
  • @c AnalyticsParameterItems ([[String: Any]]) (optional)
  • -///
  • @c AnalyticsParameterLocationID (String) (optional)
  • -///
  • @c AnalyticsParameterPromotionID (String) (optional)
  • -///
  • @c AnalyticsParameterPromotionName (String) (optional)
  • -///
-static const char*const kEventViewPromotion = - "view_promotion"; - -/// View Search Results event. Log this event when the user has been -/// presented with the results of a search. Params: -/// -///
    -///
  • @c AnalyticsParameterSearchTerm (String)
  • -///
-static const char*const kEventViewSearchResults = - "view_search_results"; -/// @} - -} // namespace analytics -} // namespace firebase - -#endif // FIREBASE_ANALYTICS_CLIENT_CPP_INCLUDE_FIREBASE_ANALYTICS_EVENT_NAMES_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/analytics/parameter_names.h b/packages/firebase_core/firebase_core/firebase_core/firebase/analytics/parameter_names.h deleted file mode 100644 index fcc43c22fbc8..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/analytics/parameter_names.h +++ /dev/null @@ -1,755 +0,0 @@ -// Copyright 2023 Google Inc. All Rights Reserved. - -#ifndef FIREBASE_ANALYTICS_CLIENT_CPP_INCLUDE_FIREBASE_ANALYTICS_PARAMETER_NAMES_H_ -#define FIREBASE_ANALYTICS_CLIENT_CPP_INCLUDE_FIREBASE_ANALYTICS_PARAMETER_NAMES_H_ - -/// @brief Namespace that encompasses all Firebase APIs. -namespace firebase { -/// @brief Firebase Analytics API. -namespace analytics { - - - -/// @defgroup parameter_names Analytics Parameters -/// -/// Predefined event parameter names. -/// -/// Params supply information that contextualize Events. You can associate -/// up to 25 unique Params with each Event type. Some Params are suggested -/// below for certain common Events, but you are not limited to these. You -/// may supply extra Params for suggested Events or custom Params for -/// Custom events. Param names can be up to 40 characters long, may only -/// contain alphanumeric characters and underscores ("_"), and must start -/// with an alphabetic character. Param values can be up to 100 characters -/// long. The "firebase_", "google_", and "ga_" prefixes are reserved and -/// should not be used. -/// @{ - - -/// Game achievement ID (String). -/// @code -/// let params = [ -/// AnalyticsParameterAchievementID : "10_matches_won", -/// // ... -/// ] -/// @endcode -static const char*const kParameterAchievementID = - "achievement_id"; - -/// The ad format (e.g. Banner, Interstitial, Rewarded, Native, Rewarded -/// Interstitial, Instream). (String). -/// @code -/// let params = [ -/// AnalyticsParameterAdFormat : "Banner", -/// // ... -/// ] -/// @endcode -static const char*const kParameterAdFormat = - "ad_format"; - -/// Ad Network Click ID (String). Used for network-specific click IDs -/// which vary in format. -/// @code -/// let params = [ -/// AnalyticsParameterAdNetworParameter(kClickID, "1234567"), -/// // ... -/// ] -/// @endcode -static const char*const kParameterAdNetworkClickID - = "aclid"; - -/// The ad platform (e.g. MoPub, IronSource) (String). -/// @code -/// let params = [ -/// AnalyticsParameterAdPlatform : "MoPub", -/// // ... -/// ] -/// @endcode -static const char*const kParameterAdPlatform = - "ad_platform"; - -/// The ad source (e.g. AdColony) (String). -/// @code -/// let params = [ -/// AnalyticsParameterAdSource : "AdColony", -/// // ... -/// ] -/// @endcode -static const char*const kParameterAdSource = - "ad_source"; - -/// The ad unit name (e.g. Banner_03) (String). -/// @code -/// let params = [ -/// AnalyticsParameterAdUnitName : "Banner_03", -/// // ... -/// ] -/// @endcode -static const char*const kParameterAdUnitName = - "ad_unit_name"; - -/// A product affiliation to designate a supplying company or brick and -/// mortar store location -/// (String). @code -/// let params = [ -/// AnalyticsParameterAffiliation : "Google Store", -/// // ... -/// ] -/// @endcode -static const char*const kParameterAffiliation = - "affiliation"; - -/// Campaign custom parameter (String). Used as a method of capturing -/// custom data in a campaign. Use varies by network. -/// @code -/// let params = [ -/// AnalyticsParameterCP1 : "custom_data", -/// // ... -/// ] -/// @endcode -static const char*const kParameterCP1 = "cp1"; - -/// The individual campaign name, slogan, promo code, etc. Some networks -/// have pre-defined macro to capture campaign information, otherwise can -/// be populated by developer. Highly Recommended (String). -/// @code -/// let params = [ -/// AnalyticsParameterCampaign : "winter_promotion", -/// // ... -/// ] -/// @endcode -static const char*const kParameterCampaign = - "campaign"; - -/// Campaign ID (String). Used for keyword analysis to identify a specific -/// product promotion or strategic campaign. This is a required key for -/// GA4 data import. -/// @code -/// let params = [ -/// AnalyticsParameterCampaignID : "7877652710", -/// // ... -/// ] -/// @endcode -static const char*const kParameterCampaignID = - "campaign_id"; - -/// Character used in game (String). -/// @code -/// let params = [ -/// AnalyticsParameterCharacter : "beat_boss", -/// // ... -/// ] -/// @endcode -static const char*const kParameterCharacter = - "character"; - -/// Campaign content (String). -static const char*const kParameterContent = "content"; - -/// Type of content selected (String). -/// @code -/// let params = [ -/// AnalyticsParameterContentType : "news article", -/// // ... -/// ] -/// @endcode -static const char*const kParameterContentType = - "content_type"; - -/// Coupon code used for a purchase (String). -/// @code -/// let params = [ -/// AnalyticsParameterCoupon : "SUMMER_FUN", -/// // ... -/// ] -/// @endcode -static const char*const kParameterCoupon = "coupon"; - -/// Creative Format (String). Used to identify the high-level -/// classification of the type of ad served by a specific campaign. -/// @code -/// let params = [ -/// AnalyticsParameterCreativeFormat : "display", -/// // ... -/// ] -/// @endcode -static const char*const kParameterCreativeFormat = - "creative_format"; - -/// The name of a creative used in a promotional spot (String). -/// @code -/// let params = [ -/// AnalyticsParameterCreativeName : "Summer Sale", -/// // ... -/// ] -/// @endcode -static const char*const kParameterCreativeName = - "creative_name"; - -/// The name of a creative slot (String). -/// @code -/// let params = [ -/// AnalyticsParameterCreativeSlot : "summer_banner2", -/// // ... -/// ] -/// @endcode -static const char*const kParameterCreativeSlot = - "creative_slot"; - -/// Currency of the purchase or items associated with the event, in -/// 3-letter -/// ISO_4217 format (String). -/// @code -/// let params = [ -/// AnalyticsParameterCurrency : "USD", -/// // ... -/// ] -/// @endcode -static const char*const kParameterCurrency = - "currency"; - -/// Flight or Travel destination (String). -/// @code -/// let params = [ -/// AnalyticsParameterDestination : "Mountain View, CA", -/// // ... -/// ] -/// @endcode -static const char*const kParameterDestination = - "destination"; - -/// Monetary value of discount associated with a purchase (Double). -/// @code -/// let params = [ -/// AnalyticsParameterDiscount : 2.0, -/// AnalyticsParameterCurrency : "USD", // e.g. $2.00 USD -/// // ... -/// ] -/// @endcode -static const char*const kParameterDiscount = - "discount"; - -/// The arrival date, check-out date or rental end date for the item. This -/// should be in YYYY-MM-DD format (String). -/// @code -/// let params = [ -/// AnalyticsParameterEndDate : "2015-09-14", -/// // ... -/// ] -/// @endcode -static const char*const kParameterEndDate = "end_date"; - -/// Indicates that the associated event should either extend the current -/// session or start a new session if no session was active when the event -/// was logged. Specify 1 to extend the current session or to start a new -/// session; any other value will not extend or start a session. -/// @code -/// let params = [ -/// AnalyticsParameterExtendSession : 1, -/// // ... -/// ] -/// @endcode -static const char*const kParameterExtendSession = - "extend_session"; - -/// Flight number for travel events (String). -/// @code -/// let params = [ -/// AnalyticsParameterFlightNumber : "ZZ800", -/// // ... -/// ] -/// @endcode -static const char*const kParameterFlightNumber = - "flight_number"; - -/// Group/clan/guild ID (String). -/// @code -/// let params = [ -/// AnalyticsParameterGroupID : "g1", -/// // ... -/// ] -/// @endcode -static const char*const kParameterGroupID = "group_id"; - -/// The index of the item in a list (Int). -/// @code -/// let params = [ -/// AnalyticsParameterIndex : 5, -/// // ... -/// ] -/// @endcode -static const char*const kParameterIndex = "index"; - -/// Item brand (String). -/// @code -/// let params = [ -/// AnalyticsParameterItemBrand : "Google", -/// // ... -/// ] -/// @endcode -static const char*const kParameterItemBrand = - "item_brand"; - -/// Item category (context-specific) (String). -/// @code -/// let params = [ -/// AnalyticsParameterItemCategory : "pants", -/// // ... -/// ] -/// @endcode -static const char*const kParameterItemCategory = - "item_category"; - -/// Item Category (context-specific) (String). -/// @code -/// let params = [ -/// AnalyticsParameterItemCategory2 : "pants", -/// // ... -/// ] -/// @endcode -static const char*const kParameterItemCategory2 = - "item_category2"; - -/// Item Category (context-specific) (String). -/// @code -/// let params = [ -/// AnalyticsParameterItemCategory3 : "pants", -/// // ... -/// ] -/// @endcode -static const char*const kParameterItemCategory3 = - "item_category3"; - -/// Item Category (context-specific) (String). -/// @code -/// let params = [ -/// AnalyticsParameterItemCategory4 : "pants", -/// // ... -/// ] -/// @endcode -static const char*const kParameterItemCategory4 = - "item_category4"; - -/// Item Category (context-specific) (String). -/// @code -/// let params = [ -/// AnalyticsParameterItemCategory5 : "pants", -/// // ... -/// ] -/// @endcode -static const char*const kParameterItemCategory5 = - "item_category5"; - -/// Item ID (context-specific) (String). -/// @code -/// let params = [ -/// AnalyticsParameterItemID : "SKU_12345", -/// // ... -/// ] -/// @endcode -static const char*const kParameterItemID = "item_id"; - -/// The ID of the list in which the item was presented to the -/// user (String). -/// @code -/// let params = [ -/// AnalyticsParameterItemListID : "ABC123", -/// // ... -/// ] -/// @endcode -static const char*const kParameterItemListID = - "item_list_id"; - -/// The name of the list in which the item was presented to the user -/// (String). -/// @code -/// let params = [ -/// AnalyticsParameterItemListName : "Related products", -/// // ... -/// ] -/// @endcode -static const char*const kParameterItemListName = - "item_list_name"; - -/// Item Name (context-specific) (String). -/// @code -/// let params = [ -/// AnalyticsParameterItemName : "jeggings", -/// // ... -/// ] -/// @endcode -static const char*const kParameterItemName = - "item_name"; - -/// Item variant (String). -/// @code -/// let params = [ -/// AnalyticsParameterItemVariant : "Black", -/// // ... -/// ] -/// @endcode -static const char*const kParameterItemVariant = - "item_variant"; - -/// The list of items involved in the transaction expressed as `[[String: -/// Any]]`. -/// @code -/// let params = [ -/// AnalyticsParameterItems : [ -/// [AnalyticsParameterItemName : "jeggings", AnalyticsParameterItemCategory : "pants"], -/// [AnalyticsParameterItemName : "boots", AnalyticsParameterItemCategory : "shoes"], -/// ], -/// ] -/// @endcode -static const char*const kParameterItems = "items"; - -/// Level in game (Int). -/// @code -/// let params = [ -/// AnalyticsParameterLevel : 42, -/// // ... -/// ] -/// @endcode -static const char*const kParameterLevel = "level"; - -/// The name of a level in a game (String). -/// @code -/// let params = [ -/// AnalyticsParameterLevelName : "room_1", -/// // ... -/// ] -/// @endcode -static const char*const kParameterLevelName = - "level_name"; - -/// Location (String). The Google Place ID -/// that corresponds to the associated event. Alternatively, you can supply your own custom -/// Location ID. -/// @code -/// let params = [ -/// AnalyticsParameterLocation : "ChIJiyj437sx3YAR9kUWC8QkLzQ", -/// // ... -/// ] -/// @endcode -static const char*const kParameterLocation = - "location"; - -/// The location associated with the event. Preferred to be the Google -/// Place ID that corresponds to the -/// associated item but could be overridden to a custom location ID -/// string.(String). -/// @code -/// let params = [ -/// AnalyticsParameterLocationID : "ChIJiyj437sx3YAR9kUWC8QkLzQ", -/// // ... -/// ] -/// @endcode -static const char*const kParameterLocationID = - "location_id"; - -/// Marketing Tactic (String). Used to identify the targeting criteria -/// applied to a specific campaign. -/// @code -/// let params = [ -/// AnalyticsParameterMarParameter(ketingTactic, "Remarketing"), -/// // ... -/// ] -/// @endcode -static const char*const kParameterMarketingTactic - = "marketing_tactic"; - -/// The advertising or marParameter(keting, cpc, banner, email), push. -/// Highly recommended (String). -/// @code -/// let params = [ -/// AnalyticsParameterMedium : "email", -/// // ... -/// ] -/// @endcode -static const char*const kParameterMedium = "medium"; - -/// A particular approach used in an operation; for example, "facebook" or -/// "email" in the context of a sign_up or login event. (String). -/// @code -/// let params = [ -/// AnalyticsParameterMethod : "google", -/// // ... -/// ] -/// @endcode -static const char*const kParameterMethod = "method"; - -/// Number of nights staying at hotel (Int). -/// @code -/// let params = [ -/// AnalyticsParameterNumberOfNights : 3, -/// // ... -/// ] -/// @endcode -static const char*const kParameterNumberOfNights - = "number_of_nights"; - -/// Number of passengers traveling (Int). -/// @code -/// let params = [ -/// AnalyticsParameterNumberOfPassengers : 11, -/// // ... -/// ] -/// @endcode -static const char*const kParameterNumberOfPassengers - = "number_of_passengers"; - -/// Number of rooms for travel events (Int). -/// @code -/// let params = [ -/// AnalyticsParameterNumberOfRooms : 2, -/// // ... -/// ] -/// @endcode -static const char*const kParameterNumberOfRooms = - "number_of_rooms"; - -/// Flight or Travel origin (String). -/// @code -/// let params = [ -/// AnalyticsParameterOrigin : "Mountain View, CA", -/// // ... -/// ] -/// @endcode -static const char*const kParameterOrigin = "origin"; - -/// The chosen method of payment (String). -/// @code -/// let params = [ -/// AnalyticsParameterPaymentType : "Visa", -/// // ... -/// ] -/// @endcode -static const char*const kParameterPaymentType = - "payment_type"; - -/// Purchase price (Double). -/// @code -/// let params = [ -/// AnalyticsParameterPrice : 1.0, -/// AnalyticsParameterCurrency : "USD", // e.g. $1.00 USD -/// // ... -/// ] -/// @endcode -static const char*const kParameterPrice = "price"; - -/// The ID of a product promotion (String). -/// @code -/// let params = [ -/// AnalyticsParameterPromotionID : "ABC123", -/// // ... -/// ] -/// @endcode -static const char*const kParameterPromotionID = - "promotion_id"; - -/// The name of a product promotion (String). -/// @code -/// let params = [ -/// AnalyticsParameterPromotionName : "Summer Sale", -/// // ... -/// ] -/// @endcode -static const char*const kParameterPromotionName = - "promotion_name"; - -/// Purchase quantity (Int). -/// @code -/// let params = [ -/// AnalyticsParameterQuantity : 1, -/// // ... -/// ] -/// @endcode -static const char*const kParameterQuantity = - "quantity"; - -/// Score in game (Int). -/// @code -/// let params = [ -/// AnalyticsParameterScore : 4200, -/// // ... -/// ] -/// @endcode -static const char*const kParameterScore = "score"; - -/// Current screen class, such as the class name of the UIViewController, -/// logged with screen_view event and added to every event (String). -/// @code -/// let params = [ -/// AnalyticsParameterScreenClass : "LoginViewController", -/// // ... -/// ] -/// @endcode -static const char*const kParameterScreenClass = - "screen_class"; - -/// Current screen name, such as the name of the UIViewController, logged -/// with screen_view event and added to every event (String). -/// @code -/// let params = [ -/// AnalyticsParameterScreenName : "LoginView", -/// // ... -/// ] -/// @endcode -static const char*const kParameterScreenName = - "screen_name"; - -/// The search string/keywords used (String). -/// @code -/// let params = [ -/// AnalyticsParameterSearchTerm : "periodic table", -/// // ... -/// ] -/// @endcode -static const char*const kParameterSearchTerm = - "search_term"; - -/// Shipping cost associated with a transaction (Double). -/// @code -/// let params = [ -/// AnalyticsParameterShipping : 5.99, -/// AnalyticsParameterCurrency : "USD", // e.g. $5.99 USD -/// // ... -/// ] -/// @endcode -static const char*const kParameterShipping = - "shipping"; - -/// The shipping tier (e.g. Ground, Air, Next-day) selected for delivery -/// of the purchased item (String). -/// @code -/// let params = [ -/// AnalyticsParameterShippingTier : "Ground", -/// // ... -/// ] -/// @endcode -static const char*const kParameterShippingTier = - "shipping_tier"; - -/// The origin of your traffic, such as an Ad network (for example, -/// google) or partner (urban airship). Identify the advertiser, site, -/// publication, etc. that is sending traffic to your property. Highly -/// recommended (String). -/// @code -/// let params = [ -/// AnalyticsParameterSource : "InMobi", -/// // ... -/// ] -/// @endcode -static const char*const kParameterSource = "source"; - -/// Source Platform (String). Used to identify the platform responsible -/// for directing traffic to a given Analytics property (e.g., a buying -/// platform where budgets, targeting criteria, etc. are set, a platform -/// for managing organic traffic data, etc.). -/// @code -/// let params = [ -/// AnalyticsParameterSourcePlatform : "sa360", -/// // ... -/// ] -/// @endcode -static const char*const kParameterSourcePlatform = - "source_platform"; - -/// The departure date, check-in date or rental start date for the item. -/// This should be in YYYY-MM-DD format (String). -/// @code -/// let params = [ -/// AnalyticsParameterStartDate : "2015-09-14", -/// // ... -/// ] -/// @endcode -static const char*const kParameterStartDate = - "start_date"; - -/// The result of an operation. Specify 1 to indicate success and 0 to -/// indicate failure (Int). -/// @code -/// let params = [ -/// AnalyticsParameterSuccess : 1, -/// // ... -/// ] -/// @endcode -static const char*const kParameterSuccess = "success"; - -/// Tax cost associated with a transaction (Double). -/// @code -/// let params = [ -/// AnalyticsParameterTax : 2.43, -/// AnalyticsParameterCurrency : "USD", // e.g. $2.43 USD -/// // ... -/// ] -/// @endcode -static const char*const kParameterTax = "tax"; - -/// If you're manually tagging keyword campaigns, you should use utm_term -/// to specify the keyword (String). -/// @code -/// let params = [ -/// AnalyticsParameterTerm : "game", -/// // ... -/// ] -/// @endcode -static const char*const kParameterTerm = "term"; - -/// The unique identifier of a transaction (String). -/// @code -/// let params = [ -/// AnalyticsParameterTransactionID : "T12345", -/// // ... -/// ] -/// @endcode -static const char*const kParameterTransactionID = - "transaction_id"; - -/// Travel class (String). -/// @code -/// let params = [ -/// AnalyticsParameterTravelClass : "business", -/// // ... -/// ] -/// @endcode -static const char*const kParameterTravelClass = - "travel_class"; - -/// A context-specific numeric value which is accumulated automatically -/// for each event type. This is a general purpose parameter that is -/// useful for accumulating a key metric that pertains to an event. -/// Examples include revenue, distance, time and points. Value should be -/// specified as Int or Double. Notes: Values for pre-defined -/// currency-related events (such as @c AnalyticsEventAddToCart) should be -/// supplied using Double and must be accompanied by a @c -/// AnalyticsParameterCurrency parameter. The valid range of accumulated -/// values is [-9,223,372,036,854.77, 9,223,372,036,854.77]. Supplying a -/// non-numeric value, omitting the corresponding @c -/// AnalyticsParameterCurrency parameter, or supplying an invalid -/// currency code for conversion events will cause that -/// conversion to be omitted from reporting. -/// @code -/// let params = [ -/// AnalyticsParameterValue : 3.99, -/// AnalyticsParameterCurrency : "USD", // e.g. $3.99 USD -/// // ... -/// ] -/// @endcode -static const char*const kParameterValue = "value"; - -/// Name of virtual currency type (String). -/// @code -/// let params = [ -/// AnalyticsParameterVirtualCurrencyName : "virtual_currency_name", -/// // ... -/// ] -/// @endcode -static const char*const kParameterVirtualCurrencyName - = "virtual_currency_name"; -/// @} - -} // namespace analytics -} // namespace firebase - -#endif // FIREBASE_ANALYTICS_CLIENT_CPP_INCLUDE_FIREBASE_ANALYTICS_PARAMETER_NAMES_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/analytics/user_property_names.h b/packages/firebase_core/firebase_core/firebase_core/firebase/analytics/user_property_names.h deleted file mode 100644 index 155fea86e6f9..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/analytics/user_property_names.h +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright 2023 Google Inc. All Rights Reserved. - -#ifndef FIREBASE_ANALYTICS_CLIENT_CPP_INCLUDE_FIREBASE_ANALYTICS_USER_PROPERTY_NAMES_H_ -#define FIREBASE_ANALYTICS_CLIENT_CPP_INCLUDE_FIREBASE_ANALYTICS_USER_PROPERTY_NAMES_H_ - -/// @brief Namespace that encompasses all Firebase APIs. -namespace firebase { -/// @brief Firebase Analytics API. -namespace analytics { - - - -/// @defgroup user_property_names Analytics User Properties -/// -/// Predefined user property names. -/// -/// A UserProperty is an attribute that describes the app-user. By -/// supplying UserProperties, you can later analyze different behaviors of -/// various segments of your userbase. You may supply up to 25 unique -/// UserProperties per app, and you can use the name and value of your -/// choosing for each one. UserProperty names can be up to 24 characters -/// long, may only contain alphanumeric characters and underscores ("_"), -/// and must start with an alphabetic character. UserProperty values can -/// be up to 36 characters long. The "firebase_", "google_", and "ga_" -/// prefixes are reserved and should not be used. -/// @{ - - -/// Indicates whether events logged by Google Analytics can be used to -/// personalize ads for the user. Set to "YES" to enable, or "NO" to -/// disable. Default is enabled. See the -/// documentation for -/// more details and information about related settings. -/// -/// @code -/// Analytics.setUserProperty("NO", forName: AnalyticsUserPropertyAllowAdPersonalizationSignals) -/// @endcode -static const char*const kUserPropertyAllowAdPersonalizationSignals - = "allow_personalized_ads"; - -/// The method used to sign in. For example, "google", "facebook" or -/// "twitter". -static const char*const kUserPropertySignUpMethod - = "sign_up_method"; -/// @} - -} // namespace analytics -} // namespace firebase - -#endif // FIREBASE_ANALYTICS_CLIENT_CPP_INCLUDE_FIREBASE_ANALYTICS_USER_PROPERTY_NAMES_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/app.h b/packages/firebase_core/firebase_core/firebase_core/firebase/app.h deleted file mode 100644 index 0501f38ac0c8..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/app.h +++ /dev/null @@ -1,787 +0,0 @@ -/* - * Copyright 2016 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_APP_SRC_INCLUDE_FIREBASE_APP_H_ -#define FIREBASE_APP_SRC_INCLUDE_FIREBASE_APP_H_ - -#include "firebase/internal/platform.h" - -#if FIREBASE_PLATFORM_ANDROID -#include -#endif // FIREBASE_PLATFORM_ANDROID - -#include -#include -#include - -#if FIREBASE_PLATFORM_IOS || FIREBASE_PLATFORM_TVOS -#ifdef __OBJC__ -@class FIRApp; -#endif // __OBJC__ -#endif // FIREBASE_PLATFORM_IOS - -namespace firebase { - -#ifdef FIREBASE_LINUX_BUILD_CONFIG_STRING -// Check to see if the shared object compiler string matches the input -void CheckCompilerString(const char* input); -#endif // FIREBASE_LINUX_BUILD_CONFIG_STRING - -// Predeclarations. -#ifdef INTERNAL_EXPERIMENTAL -namespace internal { -class FunctionRegistry; -} // namespace internal -#endif // INTERNAL_EXPERIMENTAL - -#ifdef INTERNAL_EXPERIMENTAL -#if FIREBASE_PLATFORM_DESKTOP -namespace heartbeat { -class HeartbeatController; // forward declaration -} // namespace heartbeat -#endif // FIREBASE_PLATFORM_DESKTOP -#endif // INTERNAL_EXPERIMENTAL - -namespace internal { -class AppInternal; -} // namespace internal - -/// @brief Reports whether a Firebase module initialized successfully. -enum InitResult { - /// The given library was successfully initialized. - kInitResultSuccess = 0, - - /// The given library failed to initialize due to a missing dependency. - /// - /// On Android, this typically means that Google Play services is not - /// available and the library requires it. - /// @if cpp_examples - /// Use google_play_services::CheckAvailability() and - /// google_play_services::MakeAvailable() to resolve this issue. - /// @endif - /// - /// @if swig_examples - /// Use FirebaseApp.CheckDependencies() and - /// FirebaseApp.FixDependenciesAsync() to resolve this issue. - /// @endif - /// - /// - /// Also, on Android, this value can be returned if the Java dependencies of a - /// Firebase component are not included in the application, causing - /// initialization to fail. This means that the application's build - /// environment is not configured correctly. To resolve the problem, - /// see the SDK setup documentation for the set of Java dependencies (AARs) - /// required for the component that failed to initialize. - kInitResultFailedMissingDependency -}; - -/// @brief Default name for firebase::App() objects. -extern const char* const kDefaultAppName; - -/// @brief Options that control the creation of a Firebase App. -/// @if cpp_examples -/// @see firebase::App -/// @endif -/// -/// @if swig_examples -/// @see FirebaseApp -/// @endif -/// -class AppOptions { - friend class App; - - public: - /// @brief Create AppOptions. - /// - /// @if cpp_examples - /// To create a firebase::App object, the Firebase application identifier - /// and API key should be set using set_app_id() and set_api_key() - /// respectively. - /// - /// @see firebase::App::Create(). - /// @endif - /// - /// @if swig_examples - /// To create a FirebaseApp object, the Firebase application identifier - /// and API key should be set using AppId and ApiKey respectively. - /// - /// @see FirebaseApp.Create(). - /// @endif - /// - AppOptions() {} - - /// Set the Firebase app ID used to uniquely identify an instance of an app. - /// - /// This is the mobilesdk_app_id in the Android google-services.json config - /// file or GOOGLE_APP_ID in the GoogleService-Info.plist. - /// - /// This only needs to be specified if your application does not include - /// google-services.json or GoogleService-Info.plist in its resources. - void set_app_id(const char* id) { app_id_ = id; } - - /// Retrieves the app ID. - /// - /// @if cpp_examples - /// @see set_app_id(). - /// @endif - /// - /// - /// @xmlonly - /// - /// Gets or sets the App Id. - /// - /// This is the mobilesdk_app_id in the Android google-services.json config - /// file or GOOGLE_APP_ID in the GoogleService-Info.plist. - /// - /// This only needs to be specified if your application does not include - /// google-services.json or GoogleService-Info.plist in its resources. - /// - /// @endxmlonly - /// - const char* app_id() const { return app_id_.c_str(); } - - /// API key used to authenticate requests from your app. - /// - /// For example, "AIzaSyDdVgKwhZl0sTTTLZ7iTmt1r3N2cJLnaDk" used to identify - /// your app to Google servers. - /// - /// This only needs to be specified if your application does not include - /// google-services.json or GoogleService-Info.plist in its resources. - void set_api_key(const char* key) { api_key_ = key; } - - /// Get the API key. - /// - /// @if cpp_examples - /// @see set_api_key(). - /// @endif - /// - /// - /// @xmlonly - /// - /// Gets or sets the API key used to authenticate requests from your app. - /// - /// For example, \"AIzaSyDdVgKwhZl0sTTTLZ7iTmt1r3N2cJLnaDk\" used to identify - /// your app to Google servers. - /// - /// This only needs to be specified if your application does not include - /// google-services.json or GoogleService-Info.plist in its resources. - /// - /// @endxmlonly - /// - const char* api_key() const { return api_key_.c_str(); } - - /// Set the Firebase Cloud Messaging sender ID. - /// - /// For example "012345678901", used to configure Firebase Cloud Messaging. - /// - /// This only needs to be specified if your application does not include - /// google-services.json or GoogleService-Info.plist in its resources. - void set_messaging_sender_id(const char* sender_id) { - fcm_sender_id_ = sender_id; - } - - /// Get the Firebase Cloud Messaging sender ID. - /// - /// @if cpp_examples - /// @see set_messaging_sender_id(). - /// @endif - /// - /// - /// @xmlonly - /// - /// Gets or sets the messaging sender Id. - /// - /// This only needs to be specified if your application does not include - /// google-services.json or GoogleService-Info.plist in its resources. - /// - /// @endxmlonly - /// - const char* messaging_sender_id() const { return fcm_sender_id_.c_str(); } - - /// Set the database root URL, e.g. @"http://abc-xyz-123.firebaseio.com". - void set_database_url(const char* url) { database_url_ = url; } - - /// Get database root URL, e.g. @"http://abc-xyz-123.firebaseio.com". - /// - /// - /// @xmlonly - /// - /// Gets or sets the database root URL, e.g. - /// @\"http://abc-xyz-123.firebaseio.com\". - /// - /// @endxmlonly - /// - const char* database_url() const { return database_url_.c_str(); } - - /// @cond FIREBASE_APP_INTERNAL - - /// Set the tracking ID for Google Analytics, e.g. @"UA-12345678-1". - void set_ga_tracking_id(const char* id) { ga_tracking_id_ = id; } - - /// Get the tracking ID for Google Analytics, - /// - /// @if cpp_examples - /// @see set_ga_tracking_id(). - /// @endif - /// - const char* ga_tracking_id() const { return ga_tracking_id_.c_str(); } - - /// @endcond - - /// Set the Google Cloud Storage bucket name, - /// e.g. @\"abc-xyz-123.storage.firebase.com\". - void set_storage_bucket(const char* bucket) { storage_bucket_ = bucket; } - - /// Get the Google Cloud Storage bucket name, - /// @see set_storage_bucket(). - /// - /// @xmlonly - /// - /// Gets or sets the Google Cloud Storage bucket name, e.g. - /// @\"abc-xyz-123.storage.firebase.com\". - /// - /// @endxmlonly - /// - const char* storage_bucket() const { return storage_bucket_.c_str(); } - - /// Set the Google Cloud project ID. - void set_project_id(const char* project) { project_id_ = project; } - - /// Get the Google Cloud project ID. - /// - /// This is the project_id in the Android google-services.json config - /// file or PROJECT_ID in the GoogleService-Info.plist. - /// - /// @xmlonly - /// - /// Gets the Google Cloud project ID. - /// - /// This is the project_id in the Android google-services.json config - /// file or PROJECT_ID in the GoogleService-Info.plist. - /// - /// @endxmlonly - /// - const char* project_id() const { return project_id_.c_str(); } - -#ifdef INTERNAL_EXPERIMENTAL - /// @brief set the iOS client ID. - /// - /// This is the clientID in the GoogleService-Info.plist. - void set_client_id(const char* client_id) { client_id_ = client_id; } - - /// @brief Get the iOS client ID. - /// - /// This is the client_id in the GoogleService-Info.plist. - const char* client_id() const { return client_id_.c_str(); } -#endif // INTERNAL_EXPERIMENTAL - -#ifdef INTERNAL_EXPERIMENTAL - /// @brief Set the Android or iOS client project name. - /// - /// This is the project_name in the Android google-services.json config - /// file or BUNDLE_ID in the GoogleService-Info.plist. - void set_package_name(const char* package_name) { - package_name_ = package_name; - } - - /// @brief Get the Android or iOS client project name. - /// - /// This is the project_name in the Android google-services.json config - /// file or BUNDLE_ID in the GoogleService-Info.plist. - const char* package_name() const { return package_name_.c_str(); } -#endif // INTERNAL_EXPERIMENTAL - - /// @brief Load options from a config string. - /// - /// @param[in] config A JSON string that contains Firebase configuration i.e. - /// the content of the downloaded google-services.json file. - /// @param[out] options Optional: If provided, load options into it. - /// - /// @returns An instance containing the loaded options if successful. - /// If the options argument to this function is null, this method returns an - /// AppOptions instance allocated from the heap. - static AppOptions* LoadFromJsonConfig(const char* config, - AppOptions* options = nullptr); - -#if INTERNAL_EXPERIMENTAL - /// @brief Determine whether the specified options match this set of options. - /// - /// Fields of this object that are empty are ignored in the comparison. - /// - /// @param[in] options Options to compare with. - bool operator==(const AppOptions& options) const { - return (package_name_.empty() || package_name_ == options.package_name_) && - (api_key_.empty() || api_key_ == options.api_key_) && - (app_id_.empty() || app_id_ == options.app_id_) && - (database_url_.empty() || database_url_ == options.database_url_) && - (ga_tracking_id_.empty() || - ga_tracking_id_ == options.ga_tracking_id_) && - (fcm_sender_id_.empty() || - fcm_sender_id_ == options.fcm_sender_id_) && - (storage_bucket_.empty() || - storage_bucket_ == options.storage_bucket_) && - (project_id_.empty() || project_id_ == options.project_id_); - } -#endif // INTERNAL_EXPERIMENTAL - -#if INTERNAL_EXPERIMENTAL - /// @brief Determine whether the specified options don't match this set of - /// options. - /// - /// Fields of this object that are empty are ignored in the comparison. - /// - /// @param[in] options Options to compare with. - bool operator!=(const AppOptions& options) const { - return !operator==(options); - } -#endif // INTERNAL_EXPERIMENTAL - -#if INTERNAL_EXPERIMENTAL -#if FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) - /// @brief Load default options from the resource file. - /// - /// @param[in] jni_env JNI environment required to allow Firebase services - /// to interact with the Android framework. - /// @param[in] activity JNI reference to the Android activity, required to - /// allow Firebase services to interact with the Android application. - /// @param options Options to populate from a resource file. - /// - /// @return An instance containing the loaded options if successful. - /// If the options argument to this function is null, this method returns an - /// AppOptions instance allocated from the heap.. - static AppOptions* LoadDefault(AppOptions* options, JNIEnv* jni_env, - jobject activity); -#endif // FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) - -#if !FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) - /// @brief Load default options from the resource file. - /// - /// @param options Options to populate from a resource file. - /// - /// @return An instance containing the loaded options if successful. - /// If the options argument to this function is null, this method returns an - /// AppOptions instance allocated from the heap. - static AppOptions* LoadDefault(AppOptions* options); -#endif // !FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) -#endif // INTERNAL_EXPERIMENTAL - -#if INTERNAL_EXPERIMENTAL -#if FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) - /// @brief Attempt to populate required options with default values if not - /// specified. - /// - /// @param[in] jni_env JNI environment required to allow Firebase services - /// to interact with the Android framework. - /// @param[in] activity JNI reference to the Android activity, required to - /// allow Firebase services to interact with the Android application. - /// - /// @return true if successful, false otherwise. - bool PopulateRequiredWithDefaults(JNIEnv* jni_env, jobject activity); -#endif // FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) - -#if !FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) - /// @brief Attempt to populate required options with default values if not - /// specified. - /// - /// @return true if successful, false otherwise. - bool PopulateRequiredWithDefaults(); -#endif // !FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) -#endif // INTERNAL_EXPERIMENTAL - - /// @cond FIREBASE_APP_INTERNAL - private: - /// Application package name (e.g Android package name or iOS bundle ID). - std::string package_name_; - /// API key used to communicate with Google Servers. - std::string api_key_; - /// ID of the app. - std::string app_id_; - /// ClientID of the app. - std::string client_id_; - /// Database root URL. - std::string database_url_; - /// Google analytics tracking ID. - std::string ga_tracking_id_; - /// FCM sender ID. - std::string fcm_sender_id_; - /// Google Cloud Storage bucket name. - std::string storage_bucket_; - /// Google Cloud project ID. - std::string project_id_; - /// @endcond -}; - -/// @brief Firebase application object. -/// -/// @if cpp_examples -/// firebase::App acts as a conduit for communication between all Firebase -/// services used by an application. -/// -/// For example: -/// @code -/// #if defined(__ANDROID__) -/// firebase::App::Create(firebase::AppOptions(), jni_env, activity); -/// #else -/// firebase::App::Create(firebase::AppOptions()); -/// #endif // defined(__ANDROID__) -/// @endcode -/// @endif -/// -/// @if swig_examples -/// FirebaseApp acts as a conduit for communication between all Firebase -/// services used by an application. A default instance is created -/// automatically, based on settings in your Firebase configuration file, -/// and all of the Firebase APIs connect with it automatically. -/// @endif -class App { - public: - ~App(); - -#if !FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) - /// @brief Initializes the default firebase::App with default options. - /// - /// @note This method is specific to non-Android implementations. - /// - /// @return New App instance, the App should not be destroyed for the - /// lifetime of the application. If default options can't be loaded this - /// will return null. - static App* Create(); -#endif // !FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) - -#ifndef SWIG -// -// For Unity, we actually use the simpler, iOS version for both platforms -// -#if FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) - /// @brief Initializes the default firebase::App with default options. - /// - /// @note This method is specific to the Android implementation. - /// - /// @param[in] jni_env JNI environment required to allow Firebase services - /// to interact with the Android framework. - /// @param[in] activity JNI reference to the Android activity, required to - /// allow Firebase services to interact with the Android application. - /// - /// @return New App instance. The App should not be destroyed for the - /// lifetime of the application. If default options can't be loaded this - /// will return null. - static App* Create(JNIEnv* jni_env, jobject activity); -#endif // FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) -#endif // SWIG - -#if !FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) - /// @brief Initializes the default firebase::App with the given options. - /// - /// @note This method is specific to non-Android implementations. - /// - /// Options are copied at initialization time, so changes to the object are - /// ignored. - /// @param[in] options Options that control the creation of the App. - /// - /// @return New App instance, the App should not be destroyed for the - /// lifetime of the application. - static App* Create(const AppOptions& options); -#endif // !FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) - -#ifndef SWIG -// -// For Unity, we actually use the simpler, iOS version for both platforms -// -#if FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) - /// @brief Initializes the default firebase::App with the given options. - /// - /// @note This method is specific to the Android implementation. - /// - /// Options are copied at initialization time, so changes to the object are - /// ignored. - /// @param[in] options Options that control the creation of the App. - /// @param[in] jni_env JNI environment required to allow Firebase services - /// to interact with the Android framework. - /// @param[in] activity JNI reference to the Android activity, required to - /// allow Firebase services to interact with the Android application. - /// - /// @return New App instance. The App should not be destroyed for the - /// lifetime of the application. - static App* Create(const AppOptions& options, JNIEnv* jni_env, - jobject activity); -#endif // FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) -#endif // SWIG - -#if !FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) - /// @brief Initializes a firebase::App with the given options that operates - /// on the named app. - /// - /// @note This method is specific to non-Android implementations. - /// - /// Options are copied at initialization time, so changes to the object are - /// ignored. - /// @param[in] options Options that control the creation of the App. - /// @param[in] name Name of this App instance. This is only required when - /// one application uses multiple App instances. - /// - /// @return New App instance, the App should not be destroyed for the - /// lifetime of the application. - static App* Create(const AppOptions& options, const char* name); -#endif // !FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) - -#ifndef SWIG -// -// For Unity, we actually use the simpler iOS version for both platforms -// -#if FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) - /// @brief Initializes a firebase::App with the given options that operates - /// on the named app. - /// - /// @note This method is specific to the Android implementation. - /// - /// Options are copied at initialization time, so changes to the object are - /// ignored. - /// @param[in] options Options that control the creation of the App. - /// @param[in] name Name of this App instance. This is only required when - /// one application uses multiple App instances. - /// @param[in] jni_env JNI environment required to allow Firebase services - /// to interact with the Android framework. - /// @param[in] activity JNI reference to the Android activity, required to - /// allow Firebase services to interact with the Android application. - /// - /// @return New App instance. The App should not be destroyed for the - /// lifetime of the application. - static App* Create(const AppOptions& options, const char* name, - JNIEnv* jni_env, jobject activity); -#endif // FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) -#endif // SWIG - - /// Get the default App, or nullptr if none has been created. - static App* GetInstance(); - - /// Get the App with the given name, or nullptr if none have been created. - static App* GetInstance(const char* name); - -#ifndef SWIG -// -// Unity doesn't need the JNI from here, it has its method to access JNI. -// -#if FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) - /// Get Java virtual machine, retrieved from the initial JNI environment. - /// @note This method is specific to the Android implementation. - /// - /// @return JNI Java virtual machine object. - JavaVM* java_vm() const; - /// Get JNI environment, needed for performing JNI calls, set on creation. - /// This is not trivial as the correct environment needs to retrieved per - /// thread. - /// @note This method is specific to the Android implementation. - /// - /// @return JNI environment object. - JNIEnv* GetJNIEnv() const; - /// Get a global reference to the Android activity provided to the App on - /// creation. Also serves as the Context needed for Firebase calls. - /// @note This method is specific to the Android implementation. - /// - /// @return Global JNI reference to the Android activity used to create - /// the App. The reference count of the returned object is not increased. - jobject activity() const { return activity_; } -#endif // FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) -#endif // SWIG - - /// Get the name of this App instance. - /// - /// @return The name of this App instance. If a name wasn't provided via - /// Create(), this returns @ref kDefaultAppName. - /// - /// @xmlonly - /// - /// Get the name of this FirebaseApp instance. - /// If a name wasn't provided via Create(), this will match @ref DefaultName. - /// - /// @endxmlonly - /// - const char* name() const { return name_.c_str(); } - - /// Get options the App was created with. - /// - /// @return Options used to create the App. - /// - /// @xmlonly - /// - /// @brief Get the AppOptions the FirebaseApp was created with. - /// @return AppOptions used to create the FirebaseApp. - /// - /// @endxmlonly - /// - const AppOptions& options() const { return options_; } - -#ifdef INTERNAL_EXPERIMENTAL - /// Sets whether automatic data collection is enabled for all products. - /// - /// By default, automatic data collection is enabled. To disable automatic - /// data collection in your mobile app, add to your Android application's - /// manifest: - /// - /// @if NOT_DOXYGEN - /// - /// @else - /// @code - /// <meta-data android:name="firebase_data_collection_default_enabled" - /// android:value="false" /> - /// @endcode - /// @endif - /// - /// or on iOS to your Info.plist: - /// - /// @if NOT_DOXYGEN - /// FirebaseDataCollectionDefaultEnabled - /// - /// @else - /// @code - /// <key>FirebaseDataCollectionDefaultEnabled</key> - /// <false/> - /// @endcode - /// @endif - /// - /// Once your mobile app is set to disable automatic data collection, you can - /// ask users to consent to data collection, and then enable it after their - /// approval by calling this method. - /// - /// This value is persisted across runs of the app so that it can be set once - /// when users have consented to collection. - /// - /// @param enabled Whether or not to enable automatic data collection. - void SetDataCollectionDefaultEnabled(bool enabled); - - /// Gets whether automatic data collection is enabled for all - /// products. Defaults to true unless - /// "firebase_data_collection_default_enabled" is set to false in your - /// Android manifest and FirebaseDataCollectionDefaultEnabled is set to NO - /// in your iOS app's Info.plist. - /// - /// @return Whether or not automatic data collection is enabled for all - /// products. - bool IsDataCollectionDefaultEnabled() const; -#endif // INTERNAL_EXPERIMENTAL -#ifdef SWIG - void SetDataCollectionDefaultEnabled(bool enabled); - bool IsDataCollectionDefaultEnabled() const; -#endif // SWIG - -#ifdef INTERNAL_EXPERIMENTAL - // This is only visible to SWIG and internal users of firebase::App. - /// Get the initialization results of modules that were initialized when - /// creating this app. - /// - /// @return Initialization results of modules indexed by module name. - const std::map& init_results() const { - return init_results_; - } - - // Returns a pointer to the function registry, used by components to expose - // methods to one another without introducing linkage dependencies. - internal::FunctionRegistry* function_registry(); - - /// @brief Register a library which utilizes the Firebase C++ SDK. - /// - /// @param library Name of the library to register as a user of the Firebase - /// C++ SDK. - /// @param version Version of the library being registered. - static void RegisterLibrary(const char* library, const char* version); - - // Internal method to retrieve the combined string of registered libraries. - static const char* GetUserAgent(); - - // On desktop, when App.Create() is invoked without parameters, it looks for a - // file named 'google-services-desktop.json', to load parameters from. - // This function sets the location to search in. - // Note - when setting this, make sure to end the path with the appropriate - // path separator! - static void SetDefaultConfigPath(const char* path); -#endif // INTERNAL_EXPERIMENTAL - -#ifdef INTERNAL_EXPERIMENTAL -#if FIREBASE_PLATFORM_DESKTOP - // These methods are only visible to SWIG and internal users of firebase::App. - - /// Logs a heartbeat using the internal HeartbeatController. - void LogHeartbeat() const; - - /// Get a pointer to the HeartbeatController associated with this app. - std::shared_ptr GetHeartbeatController() - const; -#endif // FIREBASE_PLATFORM_DESKTOP -#endif // INTERNAL_EXPERIMENTAL - -#ifdef INTERNAL_EXPERIMENTAL -#if FIREBASE_PLATFORM_ANDROID - /// Get the platform specific app implementation referenced by this object. - /// - /// @return Global reference to the FirebaseApp. The returned reference - /// most be deleted after use. - jobject GetPlatformApp() const; -#elif FIREBASE_PLATFORM_IOS || FIREBASE_PLATFORM_TVOS -#ifdef __OBJC__ - /// Get the platform specific app implementation referenced by this object. - /// - /// @return Reference to the FIRApp object owned by this app. - FIRApp* GetPlatformApp() const; -#endif // __OBJC__ -#endif // FIREBASE_PLATFORM_ANDROID, FIREBASE_PLATFORM_IOS, - // FIREBASE_PLATFORM_TVOS -#endif // INTERNAL_EXPERIMENTAL - - private: - /// Construct the object. - App() - : -#if FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) - activity_(nullptr), -#endif - internal_(nullptr) { - Initialize(); - -#ifdef FIREBASE_LINUX_BUILD_CONFIG_STRING - CheckCompilerString(FIREBASE_LINUX_BUILD_CONFIG_STRING); -#endif // FIREBASE_LINUX_BUILD_CONFIG_STRING - } - - /// Initialize internal implementation - void Initialize(); - -#ifndef SWIG -// -// Unity doesn't need the JNI from here, it has its method to access JNI. -// -#if FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) - /// Android activity. - /// @note This is specific to Android. - jobject activity_; -#endif // FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) -#endif // SWIG - - /// Name of the App instance. - std::string name_; - /// Options used to create this App instance. - AppOptions options_; - /// Module initialization results. - std::map init_results_; - /// Pointer to other internal data used by this instance. - internal::AppInternal* internal_; - - /// @endcond -}; - -} // namespace firebase - -#endif // FIREBASE_APP_SRC_INCLUDE_FIREBASE_APP_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/auth.h b/packages/firebase_core/firebase_core/firebase_core/firebase/auth.h deleted file mode 100644 index 408c34ea9006..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/auth.h +++ /dev/null @@ -1,939 +0,0 @@ -/* - * Copyright 2016 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_AUTH_SRC_INCLUDE_FIREBASE_AUTH_H_ -#define FIREBASE_AUTH_SRC_INCLUDE_FIREBASE_AUTH_H_ - -#include - -#include "firebase/app.h" -#include "firebase/auth/user.h" -#include "firebase/future.h" -#include "firebase/internal/common.h" - -#if !defined(DOXYGEN) -#ifndef SWIG -FIREBASE_APP_REGISTER_CALLBACKS_REFERENCE(auth) -#endif // SWIG -#endif // !defined(DOXYGEN) - -namespace firebase { - -/// @brief Firebase Authentication API. -/// -/// Firebase Authentication provides backend services to securely authenticate -/// users. It can authenticate users using passwords and federated identity -/// provider credentials, and it can integrate with a custom auth backend. -namespace auth { - -// Predeclarations. -struct AuthData; -class AuthStateListener; -class IdTokenListener; -class PhoneAuthProvider; -struct AuthCompletionHandle; -class FederatedAuthProvider; -class FederatedOAuthProvider; -struct SignInResult; - -/// @brief Firebase authentication object. -/// -/// -/// @if swig_examples -/// Firebase.Auth.FirebaseAuth is the gateway to the Firebase authentication -/// API. With it, you can reference @ref Firebase.Auth.FirebaseAuth objects to -/// manage user accounts and credentials. -/// -/// Each @ref Firebase.FirebaseApp has up to one Firebase.Auth.FirebaseAuth -/// class. You acquire the Firebase.Auth.FirebaseAuth class through the static -/// function @ref Firebase.Auth.FirebaseAuth.GetAuth. -/// -/// For example: -/// @code{.cs} -/// // Get the Auth class for your App. -/// Firebase.Auth.FirebaseAuth auth = Firebase.Auth.FirebaseAuth.GetAuth(app); -/// -/// // Request anonymous sign-in and wait until asynchronous call completes. -/// auth.SignInAnonymouslyAsync().ContinueWith((authTask) => { -/// // Print sign in results. -/// if (authTask.IsCanceled) { -/// DebugLog("Sign-in canceled."); -/// } else if (authTask.IsFaulted) { -/// DebugLog("Sign-in encountered an error."); -/// DebugLog(authTask.Exception.ToString()); -/// } else if (authTask.IsCompleted) { -/// Firebase.Auth.User user = authTask.Result; -/// DebugLog(String.Format("Signed in as {0} user.", -/// user.Anonymous ? "an anonymous" : "a non-anonymous")); -/// DebugLog("Signing out."); -/// auth.SignOut(); -/// }); -/// @endcode -/// @endif -/// -/// @if cpp_examples -/// -/// firebase::auth::Auth is the gateway to the Firebase authentication API. -/// With it, you can reference @ref firebase::auth::User objects to manage user -/// accounts and credentials. -/// -/// Each @ref firebase::App has up to one firebase::auth::Auth class. You -/// acquire the firebase::auth::Auth class through the static function -/// @ref firebase::auth::Auth::GetAuth. -/// -/// For example: -/// @code{.cpp} -/// -/// // Get the Auth class for your App. -/// firebase::auth::Auth* auth = firebase::auth::Auth::GetAuth(app); -/// -/// // Request anonymous sign-in and wait until asynchronous call completes. -/// firebase::Future sign_in_future = -/// auth->SignInAnonymously(); -/// while(sign_in_future.status() == firebase::kFutureStatusPending) { -/// // when polling, like this, make sure you service your platform's -/// // message loop -/// // see https://github.com/firebase/quickstart-cpp for a sample -/// ProcessEvents(300); -/// std::cout << "Signing in...\n"; -/// } -/// -/// const firebase::auth::AuthError error = -/// static_cast(sign_in_future.error()); -/// if (error != firebase::auth::kAuthErrorNone) { -/// std::cout << "Sign in failed with error '" -/// << sign_in_future.error_message() << "'\n"; -/// } else { -/// firebase::auth::User* user = *sign_in_future.result(); -/// // is_anonymous from Anonymous -/// std::cout << "Signed in as " -/// << (user->is_anonymous() ? "an anonymous" : "a non-anonymous") -/// << " user\n"; -/// } -/// @endcode -/// @endif -class Auth { - public: - /// @brief Results of calls @ref FetchProvidersForEmail. - /// - /// - /// @if swig_examples - /// @see FirebaseAuth.FetchProvidersForEmailAsync(). - /// @endif - /// - struct FetchProvidersResult { - /// The IDPs (identity providers) that can be used for `email`. - /// An array of length `num_providers` of null-terminated strings. - /// - /// The C# doc string is in the SWIG file because nested structs are - /// causing problems b/35780150 - /// - std::vector providers; - }; - - ~Auth(); - - /// Synchronously gets the cached current user, or nullptr if there is none. - /// @note This function may block and wait until the Auth instance finishes - /// loading the saved user's state. This should only happen for a short - /// period of time after the Auth instance is created. - /// - /// @xmlonly - /// - /// Synchronously gets the cached current user, or null if there is none. - /// @note This function may block and wait until the Auth instance finishes - /// loading the saved user's state. This should only happen for a short - /// period of time after the Auth instance is created. - /// - /// @endxmlonly - /// - User* current_user(); - - /// The current user language code. This can be set to the app’s current - /// language by calling set_language_code. The string must be a language code - /// that follows BCP 47. This will return an empty string if the app default - /// language code is being used. - std::string language_code() const; - - /// Sets the user-facing language code for auth operations that can be - /// internationalized, such as FirebaseUser.sendEmailVerification(). This - /// language code should follow the conventions defined by the IETF in BCP 47. - void set_language_code(const char* language_code); - - /// Sets the user-facing language code to be the default app language. This - /// uses a language associated with the device's locale data. On desktop - /// this will set the language code to the Firebase service's default. You - /// may subsequently customize the language code again by invoking - /// set_language_code(). - void UseAppLanguage(); - - // ----- Providers ------------------------------------------------------- - /// Asynchronously requests the IDPs (identity providers) that can be used - /// for the given email address. - /// - /// Useful for an "identifier-first" login flow. - /// - /// @if cpp_examples - /// The following sample code illustrates a possible login screen - /// that allows the user to pick an identity provider. - /// @code{.cpp} - /// // This function is called every frame to display the login screen. - /// // Returns the identity provider name, or "" if none selected. - /// const char* DisplayIdentityProviders(firebase::auth::Auth& auth, - /// const char* email) { - /// // Get results of most recent call to FetchProvidersForEmail(). - /// firebase::Future future = - /// auth.FetchProvidersForEmailLastResult(); - /// const firebase::auth::Auth::FetchProvidersResult* result = - /// future.result(); - /// - /// // Header. - /// ShowTextBox("Sign in %s", email); - /// - /// // Fetch providers from the server if we need to. - /// const bool refetch = - /// future.status() == firebase::kFutureStatusInvalid || - /// (result != nullptr && strcmp(email, result->email.c_str()) != 0); - /// if (refetch) { - /// auth.FetchProvidersForEmail(email); - /// } - /// - /// // Show a waiting icon if we're waiting for the asynchronous call to - /// // complete. - /// if (future.status() != firebase::kFutureStatusComplete) { - /// ShowImage("waiting icon"); - /// return ""; - /// } - /// - /// // Show error code if the call failed. - /// if (future.error() != firebase::auth::kAuthErrorNone) { - /// ShowTextBox("Error fetching providers: %s", future.error_message()); - /// } - /// - /// // Show a button for each provider available to this email. - /// // Return the provider for the button that's pressed. - /// for (size_t i = 0; i < result->providers.size(); ++i) { - /// const bool selected = ShowTextButton(result->providers[i].c_str()); - /// if (selected) return result->providers[i].c_str(); - /// } - /// return ""; - /// } - /// @endcode - /// @endif - Future FetchProvidersForEmail(const char* email); - - /// Get results of the most recent call to @ref FetchProvidersForEmail. - Future FetchProvidersForEmailLastResult() const; - - // ----- Sign In --------------------------------------------------------- - /// Asynchronously logs into Firebase with the given Auth token. - /// - /// An error is returned, if the token is invalid, expired or otherwise - /// not accepted by the server. - Future SignInWithCustomToken(const char* token); - - /// Get results of the most recent call to @ref SignInWithCustomToken. - Future SignInWithCustomTokenLastResult() const; - - /// Convenience method for @ref SignInAndRetrieveDataWithCredential that - /// doesn't return additional identity provider data. - Future SignInWithCredential(const Credential& credential); - - /// Get results of the most recent call to @ref SignInWithCredential. - Future SignInWithCredentialLastResult() const; - - /// Sign-in a user authenticated via a federated auth provider. - /// - /// @param[in] provider Contains information on the provider to authenticate - /// with. - /// - /// @return A Future with the result of the sign-in request. - /// - /// @note: This operation is supported only on iOS, tvOS and Android - /// platforms. On other platforms this method will return a Future with a - /// preset error code: kAuthErrorUnimplemented. - Future SignInWithProvider(FederatedAuthProvider* provider); - - /// Asynchronously logs into Firebase with the given credentials. - /// - /// For example, the credential could wrap a Facebook login access token or - /// a Twitter token/token-secret pair. - /// - /// The SignInResult contains both a reference to the User (which can be null - /// if the sign in failed), and AdditionalUserInfo, which holds details - /// specific to the Identity Provider used to sign in. - /// - /// An error is returned if the token is invalid, expired, or otherwise not - /// accepted by the server. - Future SignInAndRetrieveDataWithCredential( - const Credential& credential); - - /// Get results of the most recent call to - /// @ref SignInAndRetrieveDataWithCredential. - Future SignInAndRetrieveDataWithCredentialLastResult() const; - - /// Asynchronously creates and becomes an anonymous user. - /// If there is already an anonymous user signed in, that user will be - /// returned instead. - /// If there is any other existing user, that user will be signed out. - /// - /// - /// @if swig_examples - /// @code{.cs} - /// bool SignIn(Firebase.Auth.FirebaseAuth auth) { - /// auth.SignInAnonymouslyAsync().ContinueWith((authTask) => { - /// if (authTask.IsCanceled) { - /// DebugLog("Anonymous sign in canceled."); - /// } else if (authTask.IsFaulted) { - /// DebugLog("Anonymous sign in encountered an error."); - /// DebugLog(authTask.Exception.ToString()); - /// } else if (authTask.IsCompleted) { - /// DebugLog("Anonymous sign in successful!"); - /// } - /// }); - /// } - /// @endcode - /// @endif - /// - /// @if cpp_examples - /// The following sample code illustrates the sign-in flow that might be - /// used by a game or some other program with a regular (for example, 30Hz) - /// update loop. - /// - /// The sample calls SignIn() every frame. We don’t maintain our own - /// Futures but instead call SignInAnonymouslyLastResult() to get the Future - /// of our most recent call. - /// - /// @code{.cpp} - /// // Try to ensure that we get logged in. - /// // This function is called every frame. - /// bool SignIn(firebase::auth::Auth& auth) { - /// // Grab the result of the latest sign-in attempt. - /// firebase::Future future = - /// auth.SignInAnonymouslyLastResult(); - /// - /// // If we're in a state where we can try to sign in, do so. - /// if (future.status() == firebase::kFutureStatusInvalid || - /// (future.status() == firebase::kFutureStatusComplete && - /// future.error() != firebase::auth::kAuthErrorNone)) { - /// auth.SignInAnonymously(); - /// } - /// - /// // We're signed in if the most recent result was successful. - /// return future.status() == firebase::kFutureStatusComplete && - /// future.error() == firebase::auth::kAuthErrorNone; - /// } - /// @endcode - /// @endif - Future SignInAnonymously(); - - /// Get results of the most recent call to @ref SignInAnonymously. - Future SignInAnonymouslyLastResult() const; - - /// Signs in using provided email address and password. - /// An error is returned if the password is wrong or otherwise not accepted - /// by the server. - Future SignInWithEmailAndPassword(const char* email, - const char* password); - - /// Get results of the most recent call to @ref SignInWithEmailAndPassword. - Future SignInWithEmailAndPasswordLastResult() const; - - /// Creates, and on success, logs in a user with the given email address - /// and password. - /// - /// An error is returned when account creation is unsuccessful - /// (due to another existing account, invalid password, etc.). - Future CreateUserWithEmailAndPassword(const char* email, - const char* password); - - /// Get results of the most recent call to - /// @ref CreateUserWithEmailAndPassword. - Future CreateUserWithEmailAndPasswordLastResult() const; - - /// Removes any existing authentication credentials from this client. - /// This function always succeeds. - void SignOut(); - - // ----- Password Reset ------------------------------------------------- - /// Initiates a password reset for the given email address. - /// - /// If the email address is not registered, then the returned task has a - /// status of IsFaulted. - /// - /// - /// @if swig_examples - /// @code{.cs} - /// void ResetPassword(string email) { - /// auth.SendPasswordResetEmail(email).ContinueWith((authTask) => { - /// if (authTask.IsCanceled) { - /// DebugLog("Password reset was canceled."); - /// } else if (authTask.IsFaulted) { - /// DebugLog("Password reset encountered an error."); - /// DebugLog(authTask.Exception.ToString()); - /// } else if (authTask.IsCompleted) { - /// DebugLog("Password reset successful!"); - /// } - /// }); - /// } - /// @endcode - /// @endif - /// - /// @if cpp_examples - /// The following sample code illustrating a possible password reset flow. - /// Like in the Anonymous Sign-In example above, the ResetPasswordScreen() - /// function is called once per frame (say 30 times per second). - /// - /// No state is persisted by the caller in this example. The state of the - /// most recent calls are instead accessed through calls to functions like - /// auth.SendPasswordResetEmailLastResult(). - /// @code{.cpp} - /// const char* ImageNameForStatus(const firebase::FutureBase& future) { - /// assert(future.status() != firebase::kFutureStatusInvalid); - /// return future.status() == firebase::kFutureStatusPending - /// ? "waiting icon" - /// : future.error() == firebase::auth::kAuthErrorNone - /// ? "checkmark icon" - /// : "x mark icon"; - /// } - /// - /// // This function is called once per frame. - /// void ResetPasswordScreen(firebase::auth::Auth& auth) { - /// // Gather email address. - /// // ShowInputBox() returns a value when `enter` is pressed. - /// const std::string email = ShowInputBox("Enter e-mail"); - /// if (email != "") { - /// auth.SendPasswordResetEmail(email.c_str()); - /// } - /// - /// // Show checkmark, X-mark, or waiting icon beside the - /// // email input box, to indicate if email has been sent. - /// firebase::Future send_future = - /// auth.SendPasswordResetEmailLastResult(); - /// ShowImage(ImageNameForStatus(send_future)); - /// - /// // Display error message if the e-mail could not be sent. - /// if (send_future.status() == firebase::kFutureStatusComplete && - /// send_future.error() != firebase::auth::kAuthErrorNone) { - /// ShowTextBox(send_future.error_message()); - /// } - /// } - /// @endcode - /// @endif - Future SendPasswordResetEmail(const char* email); - - /// Get results of the most recent call to @ref SendPasswordResetEmail. - Future SendPasswordResetEmailLastResult() const; - -#ifndef SWIG - /// @brief Registers a listener to changes in the authentication state. - /// - /// There can be more than one listener registered at the same time. - /// The listeners are called asynchronously, possibly on a different thread. - /// - /// Authentication state changes are: - /// - Right after the listener has been registered - /// - When a user signs in - /// - When the current user signs out - /// - When the current user changes - /// - /// It is a recommended practice to always listen to sign-out events, as you - /// may want to prompt the user to sign in again and maybe restrict the - /// information or actions they have access to. - /// - /// Use RemoveAuthStateListener to unregister a listener. - /// - /// @note The caller owns `listener` and is responsible for destroying it. - /// When `listener` is destroyed, or when @ref Auth is destroyed, - /// RemoveAuthStateListener is called automatically. - void AddAuthStateListener(AuthStateListener* listener); - - /// @brief Unregisters a listener of authentication changes. - /// - /// Listener must previously been added with AddAuthStateListener. - /// - /// Note that listeners unregister themselves automatically when they - /// are destroyed, and the Auth class unregisters its listeners when the - /// Auth class itself is destroyed, so this function does not normally need - /// to be called explicitly. - void RemoveAuthStateListener(AuthStateListener* listener); - - /// @brief Registers a listener to changes in the ID token state. - /// - /// There can be more than one listener registered at the same time. - /// The listeners are called asynchronously, possibly on a different thread. - /// - /// Authentication state changes are: - /// - Right after the listener has been registered - /// - When a user signs in - /// - When the current user signs out - /// - When the current user changes - /// - When there is a change in the current user's token - /// - /// Use RemoveIdTokenListener to unregister a listener. - /// - /// @note The caller owns `listener` and is responsible for destroying it. - /// When `listener` is destroyed, or when @ref Auth is destroyed, - /// RemoveIdTokenListener is called automatically. - void AddIdTokenListener(IdTokenListener* listener); - - /// @brief Unregisters a listener of ID token changes. - /// - /// Listener must previously been added with AddIdTokenListener. - /// - /// Note that listeners unregister themselves automatically when they - /// are destroyed, and the Auth class unregisters its listeners when the - /// Auth class itself is destroyed, so this function does not normally need - /// to be called explicitly. - void RemoveIdTokenListener(IdTokenListener* listener); -#endif // not SWIG - - /// Gets the App this auth object is connected to. - App& app(); - - /// Returns the Auth object for an App. Creates the Auth if required. - /// - /// To get the Auth object for the default app, use, - /// GetAuth(GetDefaultFirebaseApp()); - /// - /// If the library Auth fails to initialize, init_result_out will be - /// written with the result status (if a pointer is given). - /// - /// @param[in] app The App to use for the Auth object. - /// @param[out] init_result_out Optional: If provided, write the init result - /// here. Will be set to kInitResultSuccess if initialization succeeded, or - /// kInitResultFailedMissingDependency on Android if Google Play services is - /// not available on the current device. - static Auth* GetAuth(App* app, InitResult* init_result_out = nullptr); - - private: - /// @cond FIREBASE_APP_INTERNAL - friend class ::firebase::App; - friend class ::firebase::auth::PhoneAuthProvider; - friend class IdTokenRefreshListener; - friend class IdTokenRefreshThread; - friend class UserDataPersist; - friend class UserDesktopTest; - friend class AuthDesktopTest; - - friend void EnableTokenAutoRefresh(AuthData* authData); - friend void DisableTokenAutoRefresh(AuthData* authData); - friend void ResetTokenRefreshCounter(AuthData* authData); - friend void LogHeartbeat(Auth* auth); - /// @endcond - - // Find Auth instance using App. Return null if the instance does not exist. - static Auth* FindAuth(App* app); - - // Provides access to the auth token for the current user. Returns the - // current user's auth token, or an empty string, if there isn't one. - // Note that this can potentially return an expired token from the cache. - static bool GetAuthTokenForRegistry(App* app, void* /*unused*/, void* out); - - // Provides asynchronous access to the auth token for the current user. Allow - // the caller to force-refresh the token. Even without force-refresh, this - // ensure the future contain a fresh current user's auth token. This function - // returns invalid future if user data is not available. - static bool GetAuthTokenAsyncForRegistry(App* app, void* force_refresh, - void* out_future); - - // Provides access to the current user's uid, equivalent to calling - // this->current_user()->uid(). Returns the current user's uid or an empty - // string, if there isn't one. The out pointer is expected to point to an - // instance of std::string. - static bool GetCurrentUserUidForRegistry(App* app, void* /*unused*/, - void* out); - - // Starts and stops a thread to ensure that the cached auth token is never - // kept long enough for it to expire. Refcounted, so multiple classes can - // register this without causing problems. - static bool StartTokenRefreshThreadForRegistry(App* app, void* /*unused*/, - void* /*unused*/); - static bool StopTokenRefreshThreadForRegistry(App* app, void* /*unused*/, - void* /*unused*/); - - // Adds an indirect auth state listener implemented as a callback and a - // context object. - // - // @param callback a function pointer that takes a single void* argument and - // returns void (i.e. it has type void (*)(void*)). - // @param context a pointer to an arbitrary object that Auth will pass to - // the callback when the auth state changes. - static bool AddAuthStateListenerForRegistry(App* app, void* callback, - void* context); - - // Removes the indirect auth state listener that was added with the same - // arguments. - static bool RemoveAuthStateListenerForRegistry(App* app, void* callback, - void* context); - - // Init and Destroy the platform specific auth data. - void InitPlatformAuth(AuthData* const auth_data); - void DestroyPlatformAuth(AuthData* const auth_data); - - // Call GetAuth() to create an Auth object. - // Constructors and destructors don't make any external calls. - // They just initialize and deinitialize internal variables. - Auth(App* app, void* auth_impl); - - // Delete the internal AuthData object. - void DeleteInternal(); - - // This class uses the pimpl mechanism to avoid exposing platform-dependent - // implementation. - AuthData* auth_data_; -}; - -#ifndef SWIG -/// @brief Listener called when there is a change in the authentication state. -/// -/// Override base class method to handle authentication state changes. -/// Methods are invoked asynchronously and may be invoked on other threads. -class AuthStateListener { - public: - /// @note: Destruction of the listener automatically calls - /// RemoveAuthStateListener() from the Auths this listener is registered with, - /// if those Auths have not yet been destroyed. - virtual ~AuthStateListener(); - - /// Called when the authentication state of `auth` changes. - /// - Right after the listener has been registered - /// - When a user is signed in - /// - When the current user is signed out - /// - When the current user changes - /// - /// @param[in] auth Disambiguates which @ref Auth instance the event - /// corresponds to, in the case where you are using more than one at the same - /// time. - virtual void OnAuthStateChanged(Auth* auth) = 0; - - private: - /// @cond FIREBASE_APP_INTERNAL - friend class Auth; - /// @endcond - - /// The Auths with which this listener has been registered. - std::vector auths_; -}; -#endif // not SWIG - -#ifndef SWIG -/// @brief Listener called when there is a change in the ID token. -/// -/// Override base class method to handle ID token changes. -/// Methods are invoked asynchronously and may be invoked on other threads. -class IdTokenListener { - public: - /// @note: Destruction of the listener automatically calls - /// RemoveIdTokenListener() from the Auths this listener is registered with, - /// if those Auths have not yet been destroyed. - virtual ~IdTokenListener(); - - /// Called when there is a change in the current user's token. - /// - Right after the listener has been registered - /// - When a user signs in - /// - When the current user signs out - /// - When the current user changes - /// - When there is a change in the current user's token - /// - /// @param[in] auth Disambiguates which @ref Auth instance the event - /// corresponds to, in the case where you are using more than one at the same - /// time. - virtual void OnIdTokenChanged(Auth* auth) = 0; - - private: - /// @cond FIREBASE_APP_INTERNAL - friend class Auth; - /// @endcond - - /// The Auths with which this listener has been registered. - std::vector auths_; -}; - -#endif // not SWIG - -/// @brief Used to authenticate with Federated Auth Providers. -/// -/// The federated auth provider implementation may facilitate multiple provider -/// types in the future, with support for OAuth to start. -class FederatedAuthProvider { - public: -#ifdef INTERNAL_EXPERIMENTAL -#ifndef SWIG - /// @brief Contains resulting information of a user authenticated by a - /// Federated Auth Provider. This information will be used by the internal - /// implementation to construct a corresponding User object. - struct AuthenticatedUserData { - /// The unique ID identifies the IdP account. - const char* uid; - - /// [opt] The email of the account. - const char* email; - - /// Whether the sign-in email is verified. - bool is_email_verified; - - /// [opt] The display name for the account. - const char* display_name; - - /// [opt] The username for the account. - const char* user_name; - - /// [opt] The photo Url for the account, if one exists. - const char* photo_url; - - /// The linked provider ID (e.g. "google.com" for the Google provider). - const char* provider_id; - - /// A Firebase Auth ID token for the authenticated user. - const char* access_token; - - /// A Firebase Auth refresh token for the authenticated user. - const char* refresh_token; - - /// [opt] IdP user profile data corresponding to the provided credential. - std::map raw_user_info; - - /// The number of seconds in which the ID token expires. - uint64_t token_expires_in_seconds; - }; - - /// @brief Handlers for client applications to facilitate federated auth - /// requests on non-mobile systems. - template - class Handler { - public: - virtual ~Handler() {} - - /// @brief Application sign-in handler. - /// - /// The application must implement this method to handle federated auth user - /// sign-in requests on non-mobile systems. - /// - /// @param[in] provider_data Contains information on the provider to - /// authenticate with. - /// @param[in] completion_handle Internal data pertaining to this operation - /// which must be passed to SignInComplete once the handler has completed - /// the sign in operation. - /// - /// @see Auth#SignInWithProvider - /// @see SignInComplete - virtual void OnSignIn(const T& provider_data, - AuthCompletionHandle* completion_handle) = 0; - - /// Completion for OnSignIn events. - /// - /// Invoke this method once the corresponding OnSignIn has been fulfilled. - /// This method will trigger the associated Future previously - /// returned from the Auth::SignInWithProvider method. - /// - /// @param[in] completion_handle The handle provided to the application's - /// FederatedAuthProvider::Handler::OnSignIn method. - /// @param[in] user_data The application's resulting Firebase user - /// values following the authorization request. - /// @param[in] auth_error The enumerated status code of the authorization - /// request. - /// @param[in] error_message An optional error message to be set in the - /// Future. - /// - /// @see OnSignIn - /// @see Auth::SignInWithProvider - void SignInComplete(AuthCompletionHandle* completion_handle, - const AuthenticatedUserData& user_data, - AuthError auth_error, const char* error_message); - - /// @brief Application user account link handler. - /// - /// The application must implement this method to handle federated auth user - /// link requests on non-mobile systems. - /// - /// @param[in] provider_data Contains information on the provider to - /// authenticate with. - /// @param[in] completion_handle Internal data pertaining to this operation - /// which must be passed to LinkComplete once the handler has completed the - /// user link operation. - /// - /// @see User#LinkWithProvider - virtual void OnLink(const T& provider_data, - AuthCompletionHandle* completion_handle) = 0; - - /// Completion for non-mobile user authorization handlers. - /// - /// Invoke this method once the OnLine process has been fulfilled. This - /// method will trigger the associated Future previously - /// returned from an invocation of User::LinkWithProvider. - /// - /// @param[in] completion_handle The handle provided to the - /// application's FederatedAuthProvider::Handler::OnLink method. - /// @param[in] user_data The application's resulting Firebase user - /// values following the user link request. - /// @param[in] auth_error The enumerated status code of the user link - /// request. - /// @param[in] error_message An optional error message to be set in the - /// Future. - /// - /// @see OnLink - /// @see User#LinkWithProvider - void LinkComplete(AuthCompletionHandle* completion_handle, - const AuthenticatedUserData& user_data, - AuthError auth_error, const char* error_message); - - /// @brief Application user re-authentication handler. - /// - /// The application must implement this method to handle federated auth user - /// re-authentication requests on non-mobile systems. - /// - /// @param[in] provider_data Contains information on the provider to - /// authenticate with. - /// @param[in] completion_handle Internal data pertaining to this operation - /// which must be passed to ReauthenticateComplete once the handler has - /// completed the reauthentication operation. - /// - /// @see User#ReauthenticateWithProviderComplete - virtual void OnReauthenticate(const T& provider_data, - AuthCompletionHandle* completion_handle) = 0; - - /// Completion for non-mobile user authorization handlers. - /// - /// Invoke this method once the OnReauthenticate process has been - /// fulfilled. This method will trigger the associated Future - /// previously returned from an invocation of - /// User::ReauthenticateWithProvider. - /// - /// @param[in] completion_handle The handle provided to the application's - /// FederatedAuthProvider::Handler::OnReauthenticate method. - /// @param[in] user_data The application's resulting Firebase user - /// values following the user re-authentication request. - /// @param[in] auth_error The enumerated status code of the reauthentication - /// request. - /// @param[in] error_message An optional error message to be set in the - /// Future. - /// - /// @see OnReauthenticate - /// @see User#ReuthenticateWithProvider - void ReauthenticateComplete(AuthCompletionHandle* completion_handle, - const AuthenticatedUserData& user_data, - AuthError auth_error, - const char* error_message); - }; -#endif // not SWIG -#endif // INTERNAL_EXPERIMENTAL - - FederatedAuthProvider() {} - virtual ~FederatedAuthProvider() {} - - private: - friend class ::firebase::auth::Auth; - friend class ::firebase::auth::User; - virtual Future SignIn(AuthData* auth_data) = 0; - virtual Future Link(AuthData* auth_data) = 0; - virtual Future Reauthenticate(AuthData* auth_data) = 0; -}; - -/// @brief Authenticates with Federated OAuth Providers via the -/// firebase::auth::Auth and firebase::auth::User classes. -/// -/// Once configured with a provider id, and with OAuth scope and OAuth custom -/// parameters via an FedeartedOAuthProviderData structure, an object of -/// this class may be used via Auth::SignInWithProvider to sign-in users, or via -/// User::LinkWithProvider and User::ReauthenticateWithProvider for cross -/// account linking and user reauthentication, respectively. -class FederatedOAuthProvider : public FederatedAuthProvider { - public: -#ifdef INTERNAL_EXPERIMENTAL -#ifndef SWIG - /// @brief A FederatedAuthProvider typed specifically for OAuth Authentication - /// handling. - /// - /// To be used on non-mobile environments for custom OAuth implementations and - /// UI flows. - typedef FederatedAuthProvider::Handler - AuthHandler; -#endif // !SWIG -#endif // INTERNAL_EXPERIMENTAL - - /// Constructs an unconfigured provider. - FederatedOAuthProvider(); - - /// Constructs a FederatedOAuthProvider preconfigured with provider data. - /// - /// @param[in] provider_data Contains the federated provider id and OAuth - /// scopes and OAuth custom parameters required for user authentication and - /// user linking. - explicit FederatedOAuthProvider( - const FederatedOAuthProviderData& provider_data); - -#ifdef INTERNAL_EXPERIMENTAL -#ifndef SWIG - /// @brief Constructs a provider with the required information to authenticate - /// using an OAuth Provider. - /// - /// An AuthHandler is required on desktop platforms to facilitate custom - /// implementations of OAuth authentication. The AuthHandler must outlive the - /// instance of this OAuthProvider on desktop systems and is ignored on iOS, - /// tvOS, and Android platforms. - /// - /// @param[in] provider_data Contains information on the provider to - /// authenticate with. - /// @param[in] handler An FederatedOAuthProviderData typed - /// FederatedAuthProvider::Handler which be invoked on non-mobile systems - /// to handle authentication requests. - FederatedOAuthProvider(const FederatedOAuthProviderData& provider_data, - AuthHandler* handler); -#endif // !SWIG -#endif // INTERNAL_EXPERIMENTAL - - ~FederatedOAuthProvider() override; - - /// @brief Configures the provider with OAuth provider information. - /// - /// @param[in] provider_data Contains the federated provider id and OAuth - /// scopes and OAuth custom parameters required for user authentication and - /// user linking. - void SetProviderData(const FederatedOAuthProviderData& provider_data); - -#ifdef INTERNAL_EXPERIMENTAL -#ifndef SWIG - /// @brief Configures the use of an AuthHandler for non-mobile systems. - /// - /// The existence of a handler is required for non-mobile systems, and is - /// ignored on iOS, tvOS and Android platforms. - /// - /// @param[in] handler An FederatedOAuthProviderData typed - /// FederatedAuthProvider::Handler which be invoked on non-mobile systems - /// to handle authentication requests. The handler must outlive the instance - /// of this FederatedOAuthProvider. - void SetAuthHandler(AuthHandler* handler); -#endif // !SWIG -#endif // INTERNAL_EXPERIMENTAL - - private: - friend class ::firebase::auth::Auth; - - Future SignIn(AuthData* auth_data) override; - Future Link(AuthData* auth_data) override; - Future Reauthenticate(AuthData* auth_data) override; - - FederatedOAuthProviderData provider_data_; -#ifdef INTERNAL_EXPERIMENTAL - AuthHandler* handler_; -#endif // INTERNAL_EXPERIMENTAL -}; - -} // namespace auth -} // namespace firebase - -#endif // FIREBASE_AUTH_SRC_INCLUDE_FIREBASE_AUTH_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/auth/credential.h b/packages/firebase_core/firebase_core/firebase_core/firebase/auth/credential.h deleted file mode 100644 index a179d199b67a..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/auth/credential.h +++ /dev/null @@ -1,633 +0,0 @@ -/* - * Copyright 2016 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_AUTH_SRC_INCLUDE_FIREBASE_AUTH_CREDENTIAL_H_ -#define FIREBASE_AUTH_SRC_INCLUDE_FIREBASE_AUTH_CREDENTIAL_H_ - -#include - -#include - -#include "firebase/auth/types.h" -#include "firebase/internal/common.h" - -namespace firebase { - -// Predeclarations. -class App; - -/// @cond FIREBASE_APP_INTERNAL -template -class Future; -/// @endcond - -namespace auth { - -// Predeclarations. -class Auth; -class User; - -// Opaque internal types. -struct AuthData; -class ForceResendingTokenData; -struct PhoneAuthProviderData; -struct PhoneListenerData; - -/// @brief Authentication credentials for an authentication provider. -/// -/// An authentication provider is a service that allows you to authenticate -/// a user. Firebase provides email/password authentication, but there are also -/// external authentication providers such as Facebook. -class Credential { -#ifndef SWIG - /// @cond FIREBASE_APP_INTERNAL - friend class EmailAuthProvider; - friend class FacebookAuthProvider; - friend class GameCenterAuthProvider; - friend class GitHubAuthProvider; - friend class GoogleAuthProvider; - friend class JniAuthPhoneListener; - friend class MicrosoftAuthProvider; - friend class OAuthProvider; - friend class PhoneAuthProvider; - friend class PlayGamesAuthProvider; - friend class TwitterAuthProvider; - friend class YahooAuthProvider; - friend class ServiceUpdatedCredentialProvider; - /// @endcond -#endif // !SWIG - - private: - /// Should only be created by `Provider` classes. - /// - /// @see EmailAuthProvider::GetCredential() - /// @see FacebookAuthProvider::GetCredential() - /// @see GoogleAuthProvider::GetCredential() - explicit Credential(void* impl) : impl_(impl), error_code_(kAuthErrorNone) {} - - public: - Credential() : impl_(nullptr), error_code_(kAuthErrorNone) {} - ~Credential(); - - /// Copy constructor. - Credential(const Credential& rhs); - - /// Copy a Credential. - Credential& operator=(const Credential& rhs); - - /// Gets the name of the Identification Provider (IDP) for the credential. - /// - /// - /// @xmlonly - /// - /// Gets the name of the Identification Provider (IDP) for the credential. - /// - /// @endxmlonly - /// - std::string provider() const; - - /// Get whether this credential is valid. A credential can be - /// invalid in an error condition, e.g. empty username/password. - /// - /// @returns True if the credential is valid, false otherwise. - bool is_valid() const; - - protected: - /// @cond FIREBASE_APP_INTERNAL - friend class Auth; - friend class User; - - /// Platform-specific implementation. - /// For example, FIRAuthCredential* on iOS. - void* impl_; - - // If not kAuthErrorNone, then use this error code and string to override - // whatever error we would normally return when trying to sign-in with this - // credential. - AuthError error_code_; - std::string error_message_; - /// @endcond -}; - -/// @brief Use email and password to authenticate. -/// -/// Allows developers to use the email and password credentials as they could -/// other auth providers. For example, this can be used to change passwords, -/// log in, etc. -class EmailAuthProvider { - public: - /// Generate a credential from the given email and password. - /// - /// @param email E-mail to generate the credential from. - /// @param password Password to use for the new credential. - /// - /// @returns New Credential. - static Credential GetCredential(const char* email, const char* password); - - /// The string used to identify this provider. - static const char* const kProviderId; -}; - -/// @brief Use an access token provided by Facebook to authenticate. -class FacebookAuthProvider { - public: - /// Generate a credential from the given Facebook token. - /// - /// @param access_token Facebook token to generate the credential from. - /// - /// @returns New Credential. - static Credential GetCredential(const char* access_token); - - /// The string used to identify this provider. - static const char* const kProviderId; -}; - -/// @brief GameCenter (Apple) auth provider -class GameCenterAuthProvider { - public: - /// Generate a credential from GameCenter for the current user. - /// - /// @return a Future that will be fulfilled with the resulting credential. - static Future GetCredential(); - - /// Get the result of the most recent GetCredential() call. - /// - /// @return an object which can be used to retrieve the Credential. - static Future GetCredentialLastResult(); - - /// Tests to see if the current user is signed in to GameCenter. - /// - /// @return true if the user is signed in, false otherwise. - static bool IsPlayerAuthenticated(); - - /// The string used to identify this provider. - static const char* const kProviderId; -}; - -/// @brief Use an access token provided by GitHub to authenticate. -class GitHubAuthProvider { - public: - /// Generate a credential from the given GitHub token. - /// - /// @param token The GitHub OAuth access token. - /// - /// @returns New Credential. - static Credential GetCredential(const char* token); - - /// The string used to identify this provider. - static const char* const kProviderId; -}; - -/// @brief Use an ID token and access token provided by Google to authenticate. -class GoogleAuthProvider { - public: - /// Generate a credential from the given Google ID token and/or access token. - /// - /// @param id_token Google Sign-In ID token. - /// @param access_token Google Sign-In access token. - /// - /// @returns New Credential. - static Credential GetCredential(const char* id_token, - const char* access_token); - - /// The string used to identify this provider. - static const char* const kProviderId; -}; - -/// @brief Use an access token provided by Microsoft to authenticate. -class MicrosoftAuthProvider { - public: - /// The string used to identify this provider. - static const char* const kProviderId; -}; - -/// @brief OAuth2.0+UserInfo auth provider (OIDC compliant and non-compliant). -class OAuthProvider { - public: - /// Generate a credential for an OAuth2 provider. - /// - /// @param provider_id Name of the OAuth2 provider - /// TODO(jsanmiya) add examples. - /// @param id_token The authentication token (OIDC only). - /// @param access_token TODO(jsanmiya) add explanation (currently missing - /// from Android and iOS implementations). - static Credential GetCredential(const char* provider_id, const char* id_token, - const char* access_token); - - /// Generate a credential for an OAuth2 provider. - /// - /// @param provider_id Name of the OAuth2 provider. - /// @param id_token The authentication token (OIDC only). - /// @param raw_nonce The raw nonce associated with the Auth credential being - /// created. - /// @param access_token The access token associated with the Auth credential - /// to be created, if available. This value may be null. - static Credential GetCredential(const char* provider_id, const char* id_token, - const char* raw_nonce, - const char* access_token); -}; - -/// @brief Use phone number text messages to authenticate. -/// -/// Allows developers to use the phone number and SMS verification codes -/// to authenticate a user on a mobile device. -/// -/// This class is not supported on tvOS and Desktop platforms. -/// -/// The verification flow results in a Credential that can be used to, -/// * Sign in to an existing phone number account/sign up with a new -/// phone number -/// * Link a phone number to a current user. This provider will be added to -/// the user. -/// * Update a phone number on an existing user. -/// * Re-authenticate an existing user. This may be needed when a sensitive -/// operation requires the user to be recently logged in. -/// -/// Possible verification flows: -/// (1) User manually enters verification code. -/// @if cpp_examples -/// - App calls @ref VerifyPhoneNumber. -/// - Web verification page is displayed to user where they may need to -/// solve a CAPTCHA. [iOS only]. -/// - Auth server sends the verification code via SMS to the provided -/// phone number. App receives verification id via Listener::OnCodeSent(). -/// - User receives SMS and enters verification code in app's GUI. -/// - App uses user's verification code to call -/// @ref PhoneAuthProvider::GetCredential. -/// @endif -/// -/// @if swig_examples -/// - App calls @ref VerifyPhoneNumber. -/// - Web verification page is displayed to user where they may need to -/// solve a CAPTCHA. [iOS only]. -/// - Auth server sends the verification code via SMS to the provided -/// phone number. App receives verification id via @ref CodeSent. -/// - User receives SMS and enters verification code in app's GUI. -/// - App uses user's verification code to call -/// @ref PhoneAuthProvider::GetCredential. -/// @endif -/// -/// -/// (2) SMS is automatically retrieved (Android only). -/// - App calls @ref VerifyPhoneNumber with `timeout_ms` > 0. -/// - Auth server sends the verification code via SMS to the provided -/// phone number. -/// - SMS arrives and is automatically retrieved by the operating system. -/// Credential is automatically created and passed to the app via -/// @if cpp_examples -/// Listener::OnVerificationCompleted(). -/// @endif -/// -/// @if swig_examples -/// @ref VerificationCompleted. -/// @endif -/// -/// -/// (3) Phone number is instantly verified (Android only). -/// - App calls @ref VerifyPhoneNumber. -/// - The operating system validates the phone number without having to -/// send an SMS. Credential is automatically created and passed to -/// the app via -/// @if cpp_examples -/// Listener::OnVerificationCompleted(). -/// @endif -/// -/// @if swig_examples -/// @ref VerificationCompleted. -/// @endif -/// -/// -/// @if cpp_examples -/// All three flows can be handled with the example code below. -/// The flow is complete when PhoneVerifier::credential() returns non-NULL. -/// -/// @code{.cpp} -/// class PhoneVerifier : public PhoneAuthProvider::Listener { -/// public: -/// PhoneVerifier(const char* phone_number, -/// PhoneAuthProvider* phone_auth_provider) -/// : display_message_("Sending SMS with verification code"), -/// display_verification_code_input_box_(false), -/// display_resend_sms_button_(false), -/// phone_auth_provider_(phone_auth_provider), -/// phone_number_(phone_number) { -/// SendSms(); -/// } -/// -/// ~PhoneVerifier() override {} -/// -/// void OnVerificationCompleted(Credential credential) override { -/// // Grab `mutex_` for the scope of `lock`. Callbacks can be called on -/// // other threads, so this mutex ensures data access is atomic. -/// MutexLock lock(mutex_); -/// credential_ = credential; -/// } -/// -/// void OnVerificationFailed(const std::string& error) override { -/// MutexLock lock(mutex_); -/// display_message_ = "Verification failed with error: " + error; -/// } -/// -/// void OnCodeSent(const std::string& verification_id, -/// const PhoneAuthProvider::ForceResendingToken& -/// force_resending_token) override { -/// MutexLock lock(mutex_); -/// verification_id_ = verification_id; -/// force_resending_token_ = force_resending_token; -/// -/// display_verification_code_input_box_ = true; -/// display_message_ = "Waiting for SMS"; -/// } -/// -/// void OnCodeAutoRetrievalTimeOut( -/// const std::string& verification_id) override { -/// MutexLock lock(mutex_); -/// display_resend_sms_button_ = true; -/// } -/// -/// // Draw the verification GUI on screen and process input events. -/// void Draw() { -/// MutexLock lock(mutex_); -/// -/// // Draw an informative message describing what's currently happening. -/// ShowTextBox(display_message_.c_str()); -/// -/// // Once the time out expires, display a button to resend the SMS. -/// // If the button is pressed, call VerifyPhoneNumber again using the -/// // force_resending_token_. -/// if (display_resend_sms_button_ && !verification_id_.empty()) { -/// const bool resend_sms = ShowTextButton("Resend SMS"); -/// if (resend_sms) { -/// SendSms(); -/// } -/// } -/// -/// // Once the SMS has been sent, allow the user to enter the SMS -/// // verification code into a text box. When the user has completed -/// // entering it, call GetCredential() to complete the flow. -/// if (display_verification_code_input_box_) { -/// const std::string verification_code = -/// ShowInputBox("Verification code"); -/// if (!verification_code.empty()) { -/// credential_ = phone_auth_provider_->GetCredential( -/// verification_id_.c_str(), verification_code.c_str()); -/// } -/// } -/// } -/// -/// // The phone number verification flow is complete when this returns -/// // non-NULL. -/// Credential* credential() { -/// MutexLock lock(mutex_); -/// return credential_.is_valid() ? &credential_ : nullptr; -/// } -/// -/// private: -/// void SendSms() { -/// static const uint32_t kAutoVerifyTimeOut = 2000; -/// MutexLock lock(mutex_); -/// phone_auth_provider_->VerifyPhoneNumber( -/// phone_number_.c_str(), kAutoVerifyTimeOut, &force_resending_token_, -/// this); -/// display_resend_sms_button_ = false; -/// } -/// -/// // GUI-related variables. -/// std::string display_message_; -/// bool display_verification_code_input_box_; -/// bool display_resend_sms_button_; -/// -/// // Phone flow related variables. -/// PhoneAuthProvider* phone_auth_provider_; -/// std::string phone_number_; -/// std::string verification_id_; -/// PhoneAuthProvider::ForceResendingToken force_resending_token_; -/// Credential credential_; -/// -/// // Callbacks can be called on other threads, so guard them with a mutex. -/// Mutex mutex_; -/// }; -/// @endcode -/// @endif -class PhoneAuthProvider { - public: - /// @brief Token to maintain current phone number verification session. - /// Acquired via @ref Listener::OnCodeSent. Used in @ref VerifyPhoneNumber. - class ForceResendingToken { - public: - /// This token will be invalid until it is assigned a value sent via - /// @ref Listener::OnCodeSent. It can still be passed into - /// @ref VerifyPhoneNumber, but it will be ignored. - ForceResendingToken(); - - /// Make `this` token refer to the same phone session as `rhs`. - ForceResendingToken(const ForceResendingToken& rhs); - - /// Releases internal resources when destructing. - ~ForceResendingToken(); - - /// Make `this` token refer to the same phone session as `rhs`. - ForceResendingToken& operator=(const ForceResendingToken& rhs); - - /// Return true if `rhs` is refers to the same phone number session as - /// `this`. - bool operator==(const ForceResendingToken& rhs) const; - - /// Return true if `rhs` is refers to a different phone number session as - /// `this`. - bool operator!=(const ForceResendingToken& rhs) const; - - private: - friend class JniAuthPhoneListener; - friend class PhoneAuthProvider; - ForceResendingTokenData* data_; - }; - - /// @brief Receive callbacks from @ref VerifyPhoneNumber events. - /// - /// Please see @ref PhoneAuthProvider for a sample implementation. - class Listener { - public: - Listener(); - virtual ~Listener(); - - /// @brief Phone number auto-verification succeeded. - /// - /// Called when, - /// - auto-sms-retrieval has succeeded--flow (2) in @ref PhoneAuthProvider - /// - instant validation has succeeded--flow (3) in @ref PhoneAuthProvider - /// - /// @note This callback is never called on iOS, since iOS does not have - /// auto-validation. It is always called immediately in the stub desktop - /// implementation, however, since it fakes immediate success. - /// - /// @param[in] credential The completed credential from the phone number - /// verification flow. - virtual void OnVerificationCompleted(Credential credential) = 0; - - /// @brief Phone number verification failed with an error. - /// - /// Called when and error occurred doing phone number authentication. - /// For example, - /// - quota exceeded - /// - unknown phone number format - /// - /// @param[in] error A description of the failure. - virtual void OnVerificationFailed(const std::string& error) = 0; - - /// @brief SMS message with verification code sent to phone number. - /// - /// Called immediately after Auth server sends a verification SMS. - /// Once receiving this, you can allow users to manually input the - /// verification code (even if you're also performing auto-verification). - /// For user manual input case, get the SMS verification code from the user - /// and then call @ref GetCredential with the user's code. - /// - /// @param[in] verification_id Pass to @ref GetCredential along with the - /// user-input verification code to complete the phone number verification - /// flow. - /// @param[in] force_resending_token If the user requests that another SMS - /// message be sent, use this when you recall @ref VerifyPhoneNumber. - virtual void OnCodeSent(const std::string& verification_id, - const ForceResendingToken& force_resending_token); - - /// @brief The timeout specified in @ref VerifyPhoneNumber has expired. - /// - /// Called once `auto_verify_time_out_ms` has passed. - /// If using auto SMS retrieval, you can choose to block the UI (do not - /// allow manual input of the verification code) until timeout is hit. - /// - /// @note This callback is called immediately on iOS, since iOS does not - /// have auto-validation. - /// - /// @param[in] verification_id Identify the transaction that has timed out. - virtual void OnCodeAutoRetrievalTimeOut(const std::string& verification_id); - - private: - friend class PhoneAuthProvider; - - /// Back-pointer to the data of the PhoneAuthProvider that - /// @ref VerifyPhoneNumber was called with. Used internally. - PhoneListenerData* data_; - }; - - /// Maximum value of `auto_verify_time_out_ms` in @ref VerifyPhoneNumber. - /// Larger values will be clamped. - /// - /// @deprecated This value is no longer used to clamp - /// `auto_verify_time_out_ms` in VerifyPhoneNumber. The range is - /// determined by the underlying SDK, ex. PhoneAuthOptions.Build - /// in Android SDK - static const uint32_t kMaxTimeoutMs; - - /// Start the phone number authentication operation. - /// - /// @param[in] phone_number The phone number identifier supplied by the user. - /// Its format is normalized on the server, so it can be in any format - /// here. - /// @param[in] auto_verify_time_out_ms The time out for SMS auto retrieval, in - /// miliseconds. Currently SMS auto retrieval is only supported on Android. - /// If 0, do not do SMS auto retrieval. - /// If positive, try to auto-retrieve the SMS verification code. - /// When the time out is exceeded, listener->OnCodeAutoRetrievalTimeOut() - /// is called. - /// @param[in] force_resending_token If NULL, assume this is a new phone - /// number to verify. If not-NULL, bypass the verification session deduping - /// and force resending a new SMS. - /// This token is received in @ref Listener::OnCodeSent. - /// This should only be used when the user presses a Resend SMS button. - /// @param[in,out] listener Class that receives notification whenever an SMS - /// verification event occurs. See sample code at top of class. - void VerifyPhoneNumber(const char* phone_number, - uint32_t auto_verify_time_out_ms, - const ForceResendingToken* force_resending_token, - Listener* listener); - - /// Generate a credential for the given phone number. - /// - /// @param[in] verification_id The id returned when sending the verification - /// code. Sent to the caller via @ref Listener::OnCodeSent. - /// @param[in] verification_code The verification code supplied by the user, - /// most likely by a GUI where the user manually enters the code - /// received in the SMS sent by @ref VerifyPhoneNumber. - /// - /// @returns New Credential. - Credential GetCredential(const char* verification_id, - const char* verification_code); - - /// Return the PhoneAuthProvider for the specified `auth`. - /// - /// @param[in] auth The Auth session for which we want to get a - /// PhoneAuthProvider. - static PhoneAuthProvider& GetInstance(Auth* auth); - - /// The string used to identify this provider. - static const char* const kProviderId; - - private: - friend struct AuthData; - friend class JniAuthPhoneListener; - - // Use @ref GetInstance to access the PhoneAuthProvider. - PhoneAuthProvider(); - - // The PhoneAuthProvider is owned by the Auth class. - ~PhoneAuthProvider(); - - PhoneAuthProviderData* data_; -}; - -/// @brief Use a server auth code provided by Google Play Games to authenticate. -class PlayGamesAuthProvider { - public: - /// Generate a credential from the given Server Auth Code. - /// - /// @param server_auth_code Play Games Sign in Server Auth Code. - /// - /// @return New Credential. - static Credential GetCredential(const char* server_auth_code); - - /// The string used to identify this provider. - static const char* const kProviderId; -}; - -/// @brief Use a token and secret provided by Twitter to authenticate. -class TwitterAuthProvider { - public: - /// Generate a credential from the given Twitter token and password. - /// - /// @param token The Twitter OAuth token. - /// @param secret The Twitter OAuth secret. - /// - /// @return New Credential. - static Credential GetCredential(const char* token, const char* secret); - - /// The string used to identify this provider. - static const char* const kProviderId; -}; - -/// @brief Use an access token provided by Yahoo to authenticate. -class YahooAuthProvider { - public: - /// The string used to identify this provider. - static const char* const kProviderId; -}; - -} // namespace auth -} // namespace firebase - -#endif // FIREBASE_AUTH_SRC_INCLUDE_FIREBASE_AUTH_CREDENTIAL_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/auth/types.h b/packages/firebase_core/firebase_core/firebase_core/firebase/auth/types.h deleted file mode 100644 index 3f141ad3692c..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/auth/types.h +++ /dev/null @@ -1,473 +0,0 @@ -/* - * Copyright 2016 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_AUTH_SRC_INCLUDE_FIREBASE_AUTH_TYPES_H_ -#define FIREBASE_AUTH_SRC_INCLUDE_FIREBASE_AUTH_TYPES_H_ - -#include -#include -#include - -namespace firebase { -namespace auth { - -/// All possible error codes from asynchronous calls. -/// For error details, -/// @if cpp_examples -/// call Future::ErrorMessage(). -/// @endif -/// -/// @if swig_examples -/// use the FirebaseException.Message property. -/// @endif -/// -enum AuthError { - /// Success. - kAuthErrorNone = 0, - - /// Function will be implemented in a later revision of the API. - kAuthErrorUnimplemented = -1, - - /// This indicates an internal error. - /// Common error code for all API Methods. - kAuthErrorFailure = 1, - - /// Indicates a validation error with the custom token. - /// This error originates from "bring your own auth" methods. - kAuthErrorInvalidCustomToken, - - /// Indicates the service account and the API key belong to different - /// projects. - /// Caused by "Bring your own auth" methods. - kAuthErrorCustomTokenMismatch, - - /// Indicates the IDP token or requestUri is invalid. - /// Caused by "Sign in with credential" methods. - kAuthErrorInvalidCredential, - - /// Indicates the user’s account is disabled on the server. - /// Caused by "Sign in with credential" methods. - kAuthErrorUserDisabled, - - /// Indicates an account already exists with the same email address but using - /// different sign-in credentials. Account linking is required. - /// Caused by "Sign in with credential" methods. - kAuthErrorAccountExistsWithDifferentCredentials, - - /// Indicates the administrator disabled sign in with the specified identity - /// provider. - /// Caused by "Set account info" methods. - kAuthErrorOperationNotAllowed, - - /// Indicates the email used to attempt a sign up is already in use. - /// Caused by "Set account info" methods. - kAuthErrorEmailAlreadyInUse, - - /// Indicates the user has attemped to change email or password more than 5 - /// minutes after signing in, and will need to refresh the credentials. - /// Caused by "Set account info" methods. - kAuthErrorRequiresRecentLogin, - - /// Indicates an attempt to link with a credential that has already been - /// linked with a different Firebase account. - /// Caused by "Set account info" methods. - kAuthErrorCredentialAlreadyInUse, - - /// Indicates an invalid email address. - /// Caused by "Sign in with password" methods. - kAuthErrorInvalidEmail, - - /// Indicates the user attempted sign in with a wrong password. - /// Caused by "Sign in with password" methods. - kAuthErrorWrongPassword, - - /// Indicates that too many requests were made to a server method. - /// Common error code for all API methods. - kAuthErrorTooManyRequests, - - /// Indicates the user account was not found. - /// Send password request email error code. - /// Common error code for all API methods. - kAuthErrorUserNotFound, - - /// Indicates an attempt to link a provider to which the account is already - /// linked. - /// Caused by "Link credential" methods. - kAuthErrorProviderAlreadyLinked, - - /// Indicates an attempt to unlink a provider that is not linked. - /// Caused by "Link credential" methods. - kAuthErrorNoSuchProvider, - - /// Indicates user's saved auth credential is invalid, the user needs to sign - /// in again. - /// Caused by requests with an STS id token. - kAuthErrorInvalidUserToken, - - /// Indicates the saved token has expired. - /// For example, the user may have changed account password on another device. - /// The user needs to sign in again on the device that made this request. - /// Caused by requests with an STS id token. - kAuthErrorUserTokenExpired, - - /// Indicates a network error occurred (such as a timeout, interrupted - /// connection, or unreachable host). These types of errors are often - /// recoverable with a retry. - /// Common error code for all API Methods. - kAuthErrorNetworkRequestFailed, - - /// Indicates an invalid API key was supplied in the request. - /// For Android these should no longer occur (as of 2016 v3). - /// Common error code for all API Methods. - kAuthErrorInvalidApiKey, - - /// Indicates the App is not authorized to use Firebase Authentication with - /// the provided API Key. - /// Common error code for all API Methods. - /// On Android this error should no longer occur (as of 2016 v3). - /// Common error code for all API Methods. - kAuthErrorAppNotAuthorized, - - /// Indicates that an attempt was made to reauthenticate with a user which is - /// not the current user. - kAuthErrorUserMismatch, - - /// Indicates an attempt to set a password that is considered too weak. - kAuthErrorWeakPassword, - - /// Internal api usage error code when there is no signed-in user - /// and getAccessToken is called. - /// - /// @note This error is only reported on Android. - kAuthErrorNoSignedInUser, - - /// This can happen when certain methods on App are performed, when the auth - /// API is not loaded. - /// - /// @note This error is only reported on Android. - kAuthErrorApiNotAvailable, - - /// Indicates the out-of-band authentication code is expired. - kAuthErrorExpiredActionCode, - - /// Indicates the out-of-band authentication code is invalid. - kAuthErrorInvalidActionCode, - - /// Indicates that there are invalid parameters in the payload during a - /// "send password reset email" attempt. - kAuthErrorInvalidMessagePayload, - - /// Indicates that an invalid phone number was provided. - /// This is caused when the user is entering a phone number for verification. - kAuthErrorInvalidPhoneNumber, - - /// Indicates that a phone number was not provided during phone number - /// verification. - /// - /// @note This error is iOS-specific. - kAuthErrorMissingPhoneNumber, - - /// Indicates that the recipient email is invalid. - kAuthErrorInvalidRecipientEmail, - - /// Indicates that the sender email is invalid during a "send password reset - /// email" attempt. - kAuthErrorInvalidSender, - - /// Indicates that an invalid verification code was used in the - /// verifyPhoneNumber request. - kAuthErrorInvalidVerificationCode, - - /// Indicates that an invalid verification ID was used in the - /// verifyPhoneNumber request. - kAuthErrorInvalidVerificationId, - - /// Indicates that the phone auth credential was created with an empty - /// verification code. - kAuthErrorMissingVerificationCode, - - /// Indicates that the phone auth credential was created with an empty - /// verification ID. - kAuthErrorMissingVerificationId, - - /// Indicates that an email address was expected but one was not provided. - kAuthErrorMissingEmail, - - /// Represents the error code for when an application attempts to create an - /// email/password account with an empty/null password field. - /// - /// @note This error is only reported on Android. - kAuthErrorMissingPassword, - - /// Indicates that the project's quota for this operation (SMS messages, - /// sign-ins, account creation) has been exceeded. Try again later. - kAuthErrorQuotaExceeded, - - /// Thrown when one or more of the credentials passed to a method fail to - /// identify and/or authenticate the user subject of that operation. Inspect - /// the error message to find out the specific cause. - /// @note This error is only reported on Android. - kAuthErrorRetryPhoneAuth, - - /// Indicates that the SMS code has expired. - kAuthErrorSessionExpired, - - /// Indicates that the app could not be verified by Firebase during phone - /// number authentication. - /// - /// @note This error is iOS-specific. - kAuthErrorAppNotVerified, - - /// Indicates a general failure during the app verification flow. - /// - /// @note This error is iOS-specific. - kAuthErrorAppVerificationFailed, - - /// Indicates that the reCAPTCHA token is not valid. - /// - /// @note This error is iOS and tvOS-specific. - kAuthErrorCaptchaCheckFailed, - - /// Indicates that an invalid APNS device token was used in the verifyClient - /// request. - /// - /// @note This error is iOS and tvOS-specific. - kAuthErrorInvalidAppCredential, - - /// Indicates that the APNS device token is missing in the verifyClient - /// request. - /// - /// @note This error is iOS and tvOS-specific. - kAuthErrorMissingAppCredential, - - /// Indicates that the clientID used to invoke a web flow is invalid. - /// - /// @note This error is iOS and tvOS-specific. - kAuthErrorInvalidClientId, - - /// Indicates that the domain specified in the continue URI is not valid. - /// - /// @note This error is iOS and tvOS-specific. - kAuthErrorInvalidContinueUri, - - /// Indicates that a continue URI was not provided in a request to the backend - /// which requires one. - kAuthErrorMissingContinueUri, - - /// Indicates an error occurred while attempting to access the keychain. - /// Common error code for all API Methods. - /// - /// @note This error is iOS and tvOS-specific. - kAuthErrorKeychainError, - - /// Indicates that the APNs device token could not be obtained. The app may - /// not have set up remote notification correctly, or may have failed to - /// forward the APNs device token to FIRAuth if app delegate swizzling is - /// disabled. - /// - /// @note This error is iOS and tvOS-specific. - kAuthErrorMissingAppToken, - - /// Indicates that the iOS bundle ID is missing when an iOS App Store ID is - /// provided. - /// - /// @note This error is iOS and tvOS-specific. - kAuthErrorMissingIosBundleId, - - /// Indicates that the app fails to forward remote notification to FIRAuth. - /// - /// @note This error is iOS and tvOS-specific. - kAuthErrorNotificationNotForwarded, - - /// Indicates that the domain specified in the continue URL is not white- - /// listed in the Firebase console. - /// - /// @note This error is iOS and tvOS-specific. - kAuthErrorUnauthorizedDomain, - - /// Indicates that an attempt was made to present a new web context while one - /// was already being presented. - kAuthErrorWebContextAlreadyPresented, - - /// Indicates that the URL presentation was cancelled prematurely by the user. - kAuthErrorWebContextCancelled, - - /// Indicates that Dynamic Links in the Firebase Console is not activated. - kAuthErrorDynamicLinkNotActivated, - - /// Indicates that the operation was cancelled. - kAuthErrorCancelled, - - /// Indicates that the provider id given for the web operation is invalid. - kAuthErrorInvalidProviderId, - - /// Indicates that an internal error occurred during a web operation. - kAuthErrorWebInternalError, - - /// Indicates that 3rd party cookies or data are disabled, or that there was - /// a problem with the browser. - kAuthErrorWebStorateUnsupported, - - /// Indicates that the provided tenant ID does not match the Auth instance's - /// tenant ID. - kAuthErrorTenantIdMismatch, - - /// Indicates that a request was made to the backend with an associated tenant - /// ID for an operation that does not support multi-tenancy. - kAuthErrorUnsupportedTenantOperation, - - /// Indicates that an FDL domain used for an out of band code flow is either - /// not configured or is unauthorized for the current project. - kAuthErrorInvalidLinkDomain, - - /// Indicates that credential related request data is invalid. This can occur - /// when there is a project number mismatch (sessionInfo, spatula header, - /// temporary proof), - /// an incorrect temporary proof phone number, or during game center sign in - /// when the user is - /// already signed into a different game center account. - kAuthErrorRejectedCredential, - - /// Indicates that the phone number provided in the MFA sign in flow to be - /// verified does not correspond to a phone second factor for the user. - kAuthErrorPhoneNumberNotFound, - - /// Indicates that a request was made to the backend with an invalid tenant - /// ID. - kAuthErrorInvalidTenantId, - - /// Indicates that a request was made to the backend without a valid client - /// identifier. - kAuthErrorMissingClientIdentifier, - - /// Indicates that a second factor challenge request was made without proof of - /// a successful first factor sign-in. - kAuthErrorMissingMultiFactorSession, - - /// Indicates that a second factor challenge request was made where a second - /// factor identifier was not provided. - kAuthErrorMissingMultiFactorInfo, - - /// Indicates that a second factor challenge request was made containing an - /// invalid proof of first factor sign-in. - kAuthErrorInvalidMultiFactorSession, - - /// Indicates that the user does not have a second factor matching the - /// provided identifier. - kAuthErrorMultiFactorInfoNotFound, - - /// Indicates that a request was made that is restricted to administrators - /// only. - kAuthErrorAdminRestrictedOperation, - - /// Indicates that the user's email must be verified to perform that request. - kAuthErrorUnverifiedEmail, - - /// Indicates that the user is trying to enroll a second factor that already - /// exists on their account. - kAuthErrorSecondFactorAlreadyEnrolled, - - /// Indicates that the user has reached the maximum number of allowed second - /// factors and is attempting to enroll another one. - kAuthErrorMaximumSecondFactorCountExceeded, - - /// Indicates that a user either attempted to enroll in 2FA with an - /// unsupported first factor or is enrolled and attempts a first factor sign - /// in that is not supported for 2FA users. - kAuthErrorUnsupportedFirstFactor, - - /// Indicates that a second factor users attempted to change their email with - /// updateEmail instead of verifyBeforeUpdateEmail. - kAuthErrorEmailChangeNeedsVerification, - -#ifdef INTERNAL_EXPERIMENTAL - /// Indicates that the provided event handler is null or invalid. - kAuthErrorInvalidEventHandler, - - /// Indicates that the federated provider is busy with a previous - /// authorization request. Try again when the previous authorization request - /// completes. - kAuthErrorFederatedProviderAreadyInUse, - - /// Indicates that one or more fields of the provided AuthenticatedUserData - /// are invalid. - kAuthErrorInvalidAuthenticatedUserData, - - /// Indicates that an error occurred during a Federated Auth UI Flow when the - /// user was prompted to enter their credentials. - kAuthErrorFederatedSignInUserInteractionFailure, - - /// Indicates that a request was made with a missing or invalid nonce. - /// This can happen if the hash of the provided raw nonce did not match the - /// hashed nonce in the OIDC ID token payload. - kAuthErrorMissingOrInvalidNonce, - - /// Indicates that the user did not authorize the application during Generic - /// IDP sign-in. - kAuthErrorUserCancelled, - - /// Indicates that a request was made to an unsupported backend endpoint in - /// passthrough mode. - kAuthErrorUnsupportedPassthroughOperation, - - /// Indicates that a token refresh was requested, but neither a refresh token - /// nor a custom token provider is available. - kAuthErrorTokenRefreshUnavailable, - -#endif // INTERNAL_EXEPERIMENTAL -}; - -/// @brief Contains information required to authenticate with a third party -/// provider. -struct FederatedProviderData { - /// @brief contains the id of the provider to be used during sign-in, link, or - /// reauthentication requests. - std::string provider_id; -}; - -/// @brief Contains information to identify an OAuth povider. -struct FederatedOAuthProviderData : FederatedProviderData { - /// Initailizes an empty provider data structure. - FederatedOAuthProviderData() {} - - /// Initializes the provider data structure with a provider id. - explicit FederatedOAuthProviderData(const std::string& provider) { - this->provider_id = provider; - } - -#ifndef SWIG - /// @brief Initializes the provider data structure with the specified provider - /// id, scopes and custom parameters. - FederatedOAuthProviderData( - const std::string& provider, std::vector scopes, - std::map custom_parameters) { - this->provider_id = provider; - this->scopes = scopes; - this->custom_parameters = custom_parameters; - } -#endif - - /// OAuth parmeters which specify which rights of access are being requested. - std::vector scopes; - - /// OAuth parameters which are provided to the federated provider service. - std::map custom_parameters; -}; - -} // namespace auth -} // namespace firebase - -#endif // FIREBASE_AUTH_SRC_INCLUDE_FIREBASE_AUTH_TYPES_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/auth/user.h b/packages/firebase_core/firebase_core/firebase_core/firebase/auth/user.h deleted file mode 100644 index ddd1ba890687..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/auth/user.h +++ /dev/null @@ -1,501 +0,0 @@ -/* - * Copyright 2016 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_AUTH_SRC_INCLUDE_FIREBASE_AUTH_USER_H_ -#define FIREBASE_AUTH_SRC_INCLUDE_FIREBASE_AUTH_USER_H_ - -#include -#include - -#include "firebase/auth/credential.h" -#include "firebase/auth/types.h" -#include "firebase/future.h" -#include "firebase/internal/common.h" -#include "firebase/variant.h" - -namespace firebase { -namespace auth { - -// Predeclarations. -class Auth; -struct AuthData; - -class FederatedAuthProvider; - -/// @brief Interface implemented by each identity provider. -class UserInfoInterface { - public: - virtual ~UserInfoInterface(); - - /// Gets the unique Firebase user ID for the user. - /// - /// @note The user's ID, unique to the Firebase project. - /// Do NOT use this value to authenticate with your backend server, if you - /// have one. - /// @if cpp_examples - /// Use User::GetToken() instead. - /// @endif - /// - /// @if swig_examples - /// Use User.Token instead. - /// @endif - /// @xmlonly - /// - /// Gets the unique Firebase user ID for the user. - /// - /// @note The user's ID, unique to the Firebase project. - /// Do NOT use this value to authenticate with your backend server, if you - /// have one. Use User.Token instead. - /// - /// @endxmlonly - /// - virtual std::string uid() const = 0; - - /// Gets email associated with the user, if any. - /// - /// @xmlonly - /// - /// Gets email associated with the user, if any. - /// - /// @endxmlonly - /// - virtual std::string email() const = 0; - - /// Gets the display name associated with the user, if any. - /// - /// @xmlonly - /// - /// Gets the display name associated with the user, if any. - /// - /// @endxmlonly - /// - virtual std::string display_name() const = 0; - - /// Gets the photo url associated with the user, if any. - /// - /// @xmlonly - /// - /// Gets the photo url associated with the user, if any. - /// - /// @endxmlonly - /// - virtual std::string photo_url() const = 0; - - /// Gets the provider ID for the user (For example, "Facebook"). - /// - /// @xmlonly - /// - /// Gets the provider ID for the user (For example, \"Facebook\"). - /// - /// @endxmlonly - /// - virtual std::string provider_id() const = 0; - - /// Gets the phone number for the user, in E.164 format. - virtual std::string phone_number() const = 0; -}; - -/// @brief Additional user data returned from an identity provider. -struct AdditionalUserInfo { - /// The provider identifier. - std::string provider_id; - - /// The name of the user. - std::string user_name; - - /// Additional identity-provider specific information. - /// Most likely a hierarchical key-value mapping, like a parsed JSON file. - /// Note we use map instead of unordered_map to support older compilers. - std::map profile; - - /// On a nonce-based credential link failure where the user has already linked - /// to the provider, the Firebase auth service may provide an updated - /// Credential. If is_valid returns true on this credential, then it may be - /// passed to a new firebase::auth::Auth::SignInWithCredential request to sign - /// the user in with the provider. - Credential updated_credential; -}; - -/// @brief Metadata corresponding to a Firebase user. -struct UserMetadata { - UserMetadata() : last_sign_in_timestamp(0), creation_timestamp(0) {} - - /// The last sign in UTC timestamp in milliseconds. - /// See https://en.wikipedia.org/wiki/Unix_time for details of UTC. - uint64_t last_sign_in_timestamp; - - /// The Firebase user creation UTC timestamp in milliseconds. - uint64_t creation_timestamp; -}; - -/// @brief Result of operations that can affect authentication state. -struct SignInResult { - SignInResult() : user(NULL) {} - - /// The currently signed-in @ref User, or NULL if there isn't any (i.e. the - /// user is signed out). - User* user; - - /// Identity-provider specific information for the user, if the provider is - /// one of Facebook, GitHub, Google, or Twitter. - AdditionalUserInfo info; - - /// Metadata associated with the Firebase user. - UserMetadata meta; -}; - -/// @brief Firebase user account object. -/// -/// This class allows you to manipulate the profile of a user, link to and -/// unlink from authentication providers, and refresh authentication tokens. -class User : public UserInfoInterface { - public: - /// Parameters to the UpdateUserProfile() function. - /// - /// For fields you don't want to update, pass NULL. - /// For fields you want to reset, pass "". - struct UserProfile { - /// Construct a UserProfile with no display name or photo URL. - UserProfile() : display_name(NULL), photo_url(NULL) {} - - /// User display name. - const char* display_name; - - /// User photo URI. - const char* photo_url; - }; - - ~User(); - - /// The Java Web Token (JWT) that can be used to identify the user to - /// the backend. - /// - /// If a current ID token is still believed to be valid (i.e. it has not yet - /// expired), that token will be returned immediately. - /// A developer may set the optional force_refresh flag to get a new ID token, - /// whether or not the existing token has expired. For example, a developer - /// may use this when they have discovered that the token is invalid for some - /// other reason. - Future GetToken(bool force_refresh); - -#if defined(INTERNAL_EXPERIMENTAL) || defined(SWIG) - /// A "thread safer" version of GetToken. - /// If called by two threads simultaneously, GetToken can return the same - /// pending Future twice. This creates problems if both threads try to set - /// the OnCompletion callback, unaware that there's another copy. - /// GetTokenThreadSafe returns a proxy to the Future if it's still pending, - /// allowing each proxy to have their own callback. - Future GetTokenThreadSafe(bool force_refresh); -#endif // defined(INTERNAL_EXPERIMENTAL) || defined(SWIG) - - /// Get results of the most recent call to @ref GetToken. - Future GetTokenLastResult() const; - - /// Gets the third party profile data associated with this user returned by - /// the authentication server, if any. - /// - /// @xmlonly - /// - /// Gets the third party profile data associated with this user returned by - /// the authentication server, if any. - /// - /// @endxmlonly - /// - const std::vector& provider_data() const; - - /// Sets the email address for the user. - /// - /// May fail if there is already an email/password-based account for the same - /// email address. - Future UpdateEmail(const char* email); - - /// Get results of the most recent call to @ref UpdateEmail. - Future UpdateEmailLastResult() const; - - /// Attempts to change the password for the current user. - /// - /// For an account linked to an Identity Provider (IDP) with no password, - /// this will result in the account becoming an email/password-based account - /// while maintaining the IDP link. May fail if the password is invalid, - /// if there is a conflicting email/password-based account, or if the token - /// has expired. - /// To retrieve fresh tokens, - /// @if cpp_examples - /// call @ref Reauthenticate. - /// @endif - /// - /// @if swig_examples - /// call @ref ReauthenticateAsync. - /// @endif - /// - Future UpdatePassword(const char* password); - - /// Get results of the most recent call to @ref UpdatePassword. - Future UpdatePasswordLastResult() const; - - /// Convenience function for @ref ReauthenticateAndRetrieveData that discards - /// the returned AdditionalUserInfo data. - Future Reauthenticate(const Credential& credential); - - /// Get results of the most recent call to @ref Reauthenticate. - Future ReauthenticateLastResult() const; - - /// Reauthenticate using a credential. - /// - /// @if cpp_examples - /// Some APIs (for example, @ref UpdatePassword, @ref Delete) require that - /// the token used to invoke them be from a recent login attempt. - /// This API takes an existing credential for the user and retrieves fresh - /// tokens, ensuring that the operation can proceed. Developers can call - /// this method prior to calling @ref UpdatePassword() to ensure success. - /// @endif - /// - /// @if swig_examples - /// Some APIs (for example, @ref UpdatePasswordAsync, @ref DeleteAsync) - /// require that the token used to invoke them be from a recent login attempt. - /// This API takes an existing credential for the user and retrieves fresh - /// tokens, ensuring that the operation can proceed. Developers can call - /// this method prior to calling @ref UpdatePasswordAsync() to ensure success. - /// @endif - /// - /// - /// Data from the Identity Provider used to sign-in is returned in the - /// AdditionalUserInfo inside the returned SignInResult. - /// - /// Returns an error if the existing credential is not for this user - /// or if sign-in with that credential failed. - /// @note: The current user may be signed out if this operation fails on - /// Android and desktop platforms. - Future ReauthenticateAndRetrieveData( - const Credential& credential); - - /// Get results of the most recent call to @ref ReauthenticateAndRetrieveData. - Future ReauthenticateAndRetrieveDataLastResult() const; - - /// @brief Re-authenticates the user with a federated auth provider. - /// - /// @param[in] provider Contains information on the auth provider to - /// authenticate with. - /// @return A Future with the result of the re-authentication - /// request. - /// @note: This operation is supported only on iOS, tvOS and Android - /// platforms. On other platforms this method will return a Future with a - /// preset error code: kAuthErrorUnimplemented. - Future ReauthenticateWithProvider( - FederatedAuthProvider* provider) const; - - /// Initiates email verification for the user. - Future SendEmailVerification(); - - /// Get results of the most recent call to @ref SendEmailVerification. - Future SendEmailVerificationLastResult() const; - - /// Updates a subset of user profile information. - Future UpdateUserProfile(const UserProfile& profile); - - /// Get results of the most recent call to @ref UpdateUserProfile. - Future UpdateUserProfileLastResult() const; - - /// Convenience function for @ref ReauthenticateAndRetrieveData that discards - /// the returned @ref AdditionalUserInfo in @ref SignInResult. - Future LinkWithCredential(const Credential& credential); - - /// Get results of the most recent call to @ref LinkWithCredential. - Future LinkWithCredentialLastResult() const; - - /// Links the user with the given 3rd party credentials. - /// - /// For example, a Facebook login access token, a Twitter token/token-secret - /// pair. - /// Status will be an error if the token is invalid, expired, or otherwise - /// not accepted by the server as well as if the given 3rd party - /// user id is already linked with another user account or if the current user - /// is already linked with another id from the same provider. - /// - /// Data from the Identity Provider used to sign-in is returned in the - /// @ref AdditionalUserInfo inside @ref SignInResult. - Future LinkAndRetrieveDataWithCredential( - const Credential& credential); - - /// Get results of the most recent call to - /// @ref LinkAndRetrieveDataWithCredential. - Future LinkAndRetrieveDataWithCredentialLastResult() const; - - /// Links this user with a federated auth provider. - /// - /// @param[in] provider Contains information on the auth provider to link - /// with. - /// @return A Future with the user data result of the link - /// request. - /// - /// @note: This operation is supported only on iOS, tvOS and Android - /// platforms. On other platforms this method will return a Future with a - /// preset error code: kAuthErrorUnimplemented. - Future LinkWithProvider(FederatedAuthProvider* provider) const; - - /// Unlinks the current user from the provider specified. - /// Status will be an error if the user is not linked to the given provider. - Future Unlink(const char* provider); - - /// Get results of the most recent call to @ref Unlink. - Future UnlinkLastResult() const; - - /// Updates the currently linked phone number on the user. - /// This is useful when a user wants to change their phone number. It is a - /// shortcut to calling Unlink(phone_credential.provider().c_str()) and then - /// LinkWithCredential(phone_credential). - /// `credential` must have been created with @ref PhoneAuthProvider. - Future UpdatePhoneNumberCredential(const Credential& credential); - - /// Get results of the most recent call to @ref UpdatePhoneNumberCredential. - Future UpdatePhoneNumberCredentialLastResult() const; - - /// Refreshes the data for this user. - /// - /// For example, the attached providers, email address, display name, etc. - Future Reload(); - - /// Get results of the most recent call to @ref Reload. - Future ReloadLastResult() const; - - /// Deletes the user account. - Future Delete(); - - /// Get results of the most recent call to @ref Delete. - Future DeleteLastResult() const; - - /// Gets the metadata for this user account. - UserMetadata metadata() const; - - /// Returns true if the email address associated with this user has been - /// verified. - /// - /// @xmlonly - /// - /// True if the email address associated with this user has been verified. - /// - /// @endxmlonly - /// - bool is_email_verified() const; - - /// Returns true if user signed in anonymously. - /// - /// @xmlonly - /// - /// True if user signed in anonymously. - /// - /// @endxmlonly - /// - bool is_anonymous() const; - - /// Gets the unique Firebase user ID for the user. - /// - /// @note The user's ID, unique to the Firebase project. - /// Do NOT use this value to authenticate with your backend server, if you - /// have one. - /// @if cpp_examples - /// Use User::GetToken() instead. - /// @endif - /// - /// @if swig_examples - /// Use User.Token instead. - /// @endif - /// @xmlonly - /// - /// Gets the unique Firebase user ID for the user. - /// - /// @note The user's ID, unique to the Firebase project. - /// Do NOT use this value to authenticate with your backend server, if you - /// have one. Use User.Token instead. - /// - /// @endxmlonly - /// - virtual std::string uid() const; - - /// Gets email associated with the user, if any. - /// - /// @xmlonly - /// - /// Gets email associated with the user, if any. - /// - /// @endxmlonly - /// - virtual std::string email() const; - - /// Gets the display name associated with the user, if any. - /// - /// @xmlonly - /// - /// Gets the display name associated with the user, if any. - /// - /// @endxmlonly - /// - virtual std::string display_name() const; - - /// Gets the photo url associated with the user, if any. - /// - /// @xmlonly - /// - /// Gets the photo url associated with the user, if any. - /// - /// @endxmlonly - /// - virtual std::string photo_url() const; - - /// Gets the provider ID for the user (For example, "Facebook"). - /// - /// @xmlonly - /// - /// Gets the provider ID for the user (For example, \"Facebook\"). - /// - /// @endxmlonly - /// - virtual std::string provider_id() const; - - /// Gets the phone number for the user, in E.164 format. - virtual std::string phone_number() const; - - private: - /// @cond FIREBASE_APP_INTERNAL - friend struct AuthData; - // Only exists in AuthData. Access via @ref Auth::CurrentUser(). - explicit User(AuthData* auth_data) : auth_data_(auth_data) {} - - // Disable copy constructor. - User(const User&) = delete; - // Disable copy operator. - User& operator=(const User&) = delete; - /// @endcond - -#if defined(INTERNAL_EXPERIMENTAL) - // Doxygen should not make docs for this function. - /// @cond FIREBASE_APP_INTERNAL - friend class IdTokenRefreshThread; - friend class IdTokenRefreshListener; - friend class Auth; - Future GetTokenInternal(const bool force_refresh, - const int future_identifier); - /// @endcond -#endif // defined(INTERNAL_EXPERIMENTAL) - - // Use the pimpl mechanism to hide data details in the cpp files. - AuthData* auth_data_; -}; - -} // namespace auth -} // namespace firebase - -#endif // FIREBASE_AUTH_SRC_INCLUDE_FIREBASE_AUTH_USER_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/database.h b/packages/firebase_core/firebase_core/firebase_core/firebase/database.h deleted file mode 100644 index d0dc904c107b..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/database.h +++ /dev/null @@ -1,199 +0,0 @@ -// Copyright 2016 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_H_ -#define FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_H_ - -#include "firebase/app.h" -#include "firebase/database/common.h" -#include "firebase/database/data_snapshot.h" -#include "firebase/database/database_reference.h" -#include "firebase/database/disconnection.h" -#include "firebase/database/listener.h" -#include "firebase/database/mutable_data.h" -#include "firebase/database/query.h" -#include "firebase/database/transaction.h" -#include "firebase/internal/common.h" -#include "firebase/log.h" - -namespace firebase { - -/// Namespace for the Firebase Realtime Database C++ SDK. -namespace database { - -namespace internal { -class DatabaseInternal; -} // namespace internal - -class DatabaseReference; - -#ifndef SWIG -/// @brief Entry point for the Firebase Realtime Database C++ SDK. -/// -/// To use the SDK, call firebase::database::Database::GetInstance() to obtain -/// an instance of Database, then use GetReference() to obtain references to -/// child paths within the database. From there you can set data via -/// Query::SetValue(), get data via Query::GetValue(), attach listeners, and -/// more. -#endif // SWIG -class Database { - public: - /// @brief Get an instance of Database corresponding to the given App. - /// - /// Firebase Realtime Database uses firebase::App to communicate with Firebase - /// Authentication to authenticate users to the Database server backend. - /// - /// If you call GetInstance() multiple times with the same App, you will get - /// the same instance of Database. - /// - /// @param[in] app Your instance of firebase::App. Firebase Realtime Database - /// will use this to communicate with Firebase Authentication. - /// @param[out] init_result_out Optional: If provided, write the init result - /// here. Will be set to kInitResultSuccess if initialization succeeded, or - /// kInitResultFailedMissingDependency on Android if Google Play services is - /// not available on the current device. - /// - /// @returns An instance of Database corresponding to the given App. - static Database* GetInstance(::firebase::App* app, - InitResult* init_result_out = nullptr); - - /// @brief Gets an instance of FirebaseDatabase for the specified URL. - /// - /// If you call GetInstance() multiple times with the same App and URL, you - /// will get the same instance of Database. - /// - /// @param[in] app Your instance of firebase::App. Firebase Realtime Database - /// will use this to communicate with Firebase Authentication. - /// @param[in] url The URL of your Firebase Realtime Database. This overrides - /// any url specified in the App options. - /// @param[out] init_result_out Optional: If provided, write the init result - /// here. Will be set to kInitResultSuccess if initialization succeeded, or - /// kInitResultFailedMissingDependency on Android if Google Play services is - /// not available on the current device. - /// - /// @returns An instance of Database corresponding to the given App and URL. - static Database* GetInstance(::firebase::App* app, const char* url, - InitResult* init_result_out = nullptr); - - /// @brief Destructor for the Database object. - /// - /// When deleted, this instance will be removed from the cache of Database - /// objects. If you call GetInstance() in the future with the same App, a new - /// Database instance will be created. - ~Database(); - - /// @brief Get the firebase::App that this Database was created with. - /// - /// @returns The firebase::App this Database was created with. - App* app() const; - - /// @brief Get the URL that this Database was created with. - /// - /// @returns The URL this Database was created with, or an empty string if - /// this Database was created with default parameters. This string will remain - /// valid in memory for the lifetime of this Database. - const char* url() const; - - /// @brief Get a DatabaseReference to the root of the database. - /// - /// @returns A DatabaseReference to the root of the database. - DatabaseReference GetReference() const; - /// @brief Get a DatabaseReference for the specified path. - /// - /// @returns A DatabaseReference to the specified path in the database. - /// If you specified an invalid path, the reference's - /// DatabaseReference::IsValid() will return false. - DatabaseReference GetReference(const char* path) const; - /// @brief Get a DatabaseReference for the provided URL, which must belong to - /// the database URL this instance is already connected to. - /// - /// @returns A DatabaseReference to the specified path in the database. - /// If you specified an invalid path, the reference's - /// DatabaseReference::IsValid() will return false. - DatabaseReference GetReferenceFromUrl(const char* url) const; - - /// @brief Shuts down the connection to the Firebase Realtime Database - /// backend until GoOnline() is called. - void GoOffline(); - - /// @brief Resumes the connection to the Firebase Realtime Database backend - /// after a previous GoOffline() call. - void GoOnline(); - - /// @brief Purge all pending writes to the Firebase Realtime Database server. - /// - /// The Firebase Realtime Database client automatically queues writes and - /// sends them to the server at the earliest opportunity, depending on network - /// connectivity. In some cases (e.g. offline usage) there may be a large - /// number of writes waiting to be sent. Calling this method will purge all - /// outstanding writes so they are abandoned. All writes will be purged, - /// including transactions and onDisconnect() writes. The writes will be - /// rolled back locally, perhaps triggering events for affected event - /// listeners, and the client will not (re-)send them to the Firebase backend. - void PurgeOutstandingWrites(); - - /// @brief Sets whether pending write data will persist between application - /// exits. - /// - /// The Firebase Database client will cache synchronized data and keep track - /// of all writes you've initiated while your application is running. It - /// seamlessly handles intermittent network connections and re-sends write - /// operations when the network connection is restored. However by default - /// your write operations and cached data are only stored in-memory and will - /// be lost when your app restarts. By setting this value to `true`, the data - /// will be persisted to on-device (disk) storage and will thus be available - /// again when the app is restarted (even when there is no network - /// connectivity at that time). - /// - /// @note SetPersistenceEnabled should be called before creating any instances - /// of DatabaseReference, and only needs to be called once per application. - /// - /// @param[in] enabled Set this to true to persist write data to on-device - /// (disk) storage, or false to discard pending writes when the app exists. - void set_persistence_enabled(bool enabled); - - /// Set the log verbosity of this Database instance. - /// - /// The log filtering is cumulative with Firebase App. That is, this library's - /// log messages will only be displayed if they are not filtered out by this - /// library's log level setting and by Firebase App's log level setting. - /// - /// @note On Android this can only be set before any operations have been - /// performed with the object. - /// - /// @param[in] log_level Log level, by default this is set to kLogLevelInfo. - void set_log_level(LogLevel log_level); - - /// Get the log verbosity of this Database instance. - /// - /// @return Get the currently configured logging verbosity. - LogLevel log_level() const; - - private: - friend Database* GetDatabaseInstance(::firebase::App* app, const char* url, - InitResult* init_result_out); - Database(::firebase::App* app, internal::DatabaseInternal* internal); - Database(const Database& src); - Database& operator=(const Database& src); - - // Delete the internal_ data. - void DeleteInternal(); - - internal::DatabaseInternal* internal_; -}; - -} // namespace database -} // namespace firebase - -#endif // FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/database/common.h b/packages/firebase_core/firebase_core/firebase_core/firebase/database/common.h deleted file mode 100644 index 298972784631..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/database/common.h +++ /dev/null @@ -1,83 +0,0 @@ -// Copyright 2016 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_COMMON_H_ -#define FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_COMMON_H_ - -#include "firebase/variant.h" - -namespace firebase { -namespace database { - -/// Error code returned by Firebase Realtime Database C++ functions. -enum Error { - /// The operation was a success, no error occurred. - kErrorNone = 0, - /// The operation had to be aborted due to a network disconnect. - kErrorDisconnected, - /// The supplied auth token has expired. - kErrorExpiredToken, - /// The specified authentication token is invalid. - kErrorInvalidToken, - /// The transaction had too many retries. - kErrorMaxRetries, - /// The operation could not be performed due to a network error. - kErrorNetworkError, - /// The server indicated that this operation failed. - kErrorOperationFailed, - /// The transaction was overridden by a subsequent set. - kErrorOverriddenBySet, - /// This client does not have permission to perform this operation. - kErrorPermissionDenied, - /// The service is unavailable. - kErrorUnavailable, - /// An unknown error occurred. - kErrorUnknownError, - /// The write was canceled locally. - kErrorWriteCanceled, - /// You specified an invalid Variant type for a field. For example, - /// a DatabaseReference's Priority and the keys of a Map must be of - /// scalar type (MutableString, StaticString, Int64, Double). - kErrorInvalidVariantType, - /// An operation that conflicts with this one is already in progress. For - /// example, calling SetValue and SetValueAndPriority on a DatabaseReference - /// is not allowed. - kErrorConflictingOperationInProgress, - /// The transaction was aborted, because the user's DoTransaction function - /// returned kTransactionResultAbort instead of kTransactionResultSuccess. - kErrorTransactionAbortedByUser, -}; - -/// @brief Get the human-readable error message corresponding to an error code. -/// -/// @param[in] error Error code to get the error message for. -/// -/// @returns Statically-allocated string describing the error. -extern const char* GetErrorMessage(Error error); - -/// @brief Get a server-populated value corresponding to the current -/// timestamp. -/// -/// When inserting values into the database, you can use the special value -/// firebase::database::ServerTimestamp() to have the server auto-populate the -/// current timestamp, which is represented as millieconds since the Unix epoch, -/// into the field. -/// -/// @returns A special value that tells the server to use the current timestamp. -const Variant& ServerTimestamp(); - -} // namespace database -} // namespace firebase - -#endif // FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_COMMON_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/database/data_snapshot.h b/packages/firebase_core/firebase_core/firebase_core/firebase/database/data_snapshot.h deleted file mode 100644 index cb83292a792b..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/database/data_snapshot.h +++ /dev/null @@ -1,205 +0,0 @@ -// Copyright 2016 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_DATA_SNAPSHOT_H_ -#define FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_DATA_SNAPSHOT_H_ - -#include - -#include - -#include "firebase/internal/common.h" -#include "firebase/variant.h" - -namespace firebase { -namespace database { -namespace internal { -class Callbacks; -class ChildEventRegistration; -class DataSnapshotInternal; -class DatabaseInternal; -class DatabaseInternalTestMatcherTest; -class DatabaseReferenceInternal; -class QueryInternal; -class Repo; -class ValueEventRegistration; -} // namespace internal - -class Database; -class DatabaseReference; - -#ifndef SWIG -/// A DataSnapshot instance contains data from a Firebase Database location. Any -/// time you read Database data, you receive the data as a DataSnapshot. These -/// are efficiently-generated and cannot be changed. To modify data, -/// use DatabaseReference::SetValue() or DatabaseReference::RunTransaction(). -#endif // SWIG -class DataSnapshot { - public: - /// @brief Default constructor. - /// - /// This DataSnapshot contains nothing and is considered invalid (i.e. - /// is_valid() == false). Use this to construct an empty DataSnapshot that you - /// will later populate with data from a database callback. - DataSnapshot() : internal_(nullptr) {} - -#ifdef INTERNAL_EXPERIMENTAL - explicit DataSnapshot(internal::DataSnapshotInternal* internal); -#endif - - /// @brief Copy constructor. DataSnapshots are immutable, so they can be - /// efficiently copied. - /// - /// @param[in] snapshot DataSnapshot to copy. - DataSnapshot(const DataSnapshot& snapshot); - - /// @brief Copy assignment operator. DataSnapshots are immutable, so they can - /// be efficiently copied. - /// - /// @param[in] snapshot DataSnapshot to copy. - /// - /// @returns Reference to the destination DataSnapshot. - DataSnapshot& operator=(const DataSnapshot& snapshot); - -#if defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) - /// @brief Move constructor. DataSnapshots are immutable, so they can be - /// efficiently moved. - /// - /// @param[in] snapshot DataSnapshot to move into this one. - DataSnapshot(DataSnapshot&& snapshot); - - /// @brief Move assignment operator. DataSnapshots are immutable, so they can - /// be efficiently moved. - /// - /// @param[in] snapshot DataSnapshot to move into this one. - /// - /// @returns Reference to this destination DataSnapshot. - DataSnapshot& operator=(DataSnapshot&& snapshot); -#endif // defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) - - /// Destructor. - ~DataSnapshot(); - - /// @brief Returns true if the data is non-empty. - bool exists() const; - - /// @brief Get a DataSnapshot for the location at the specified relative path. - /// - /// @param[in] path Path relative to this snapshot's location. - /// It only needs to be valid during this call. - /// - /// @returns A DataSnapshot corresponding to specified child location. - DataSnapshot Child(const char* path) const; - - /// @brief Get a DataSnapshot for the location at the specified relative path. - /// - /// @param[in] path Path relative to this snapshot's location. - /// - /// @returns A DataSnapshot corresponding to specified child location. - DataSnapshot Child(const std::string& path) const; - - /// @brief Get all the immediate children of this location. - /// - /// @returns The immediate children of this snapshot. - std::vector children() const; - - /// @brief Get the number of children of this location. - /// - /// @returns The number of immediate children of this snapshot. - size_t children_count() const; - - /// @brief Does this DataSnapshot have any children at all? - /// - /// @returns True if the snapshot has any children, false otherwise. - bool has_children() const; - - /// @brief Get the key name of the source location of this snapshot. - /// - /// @note The returned pointer is only guaranteed to be valid while the - /// DataSnapshot is still in memory. - /// - /// @returns Key name of the source location of this snapshot. - const char* key() const; - - /// @brief Get the key name of the source location of this snapshot. - /// - /// @returns Key name of the source location of this snapshot. - std::string key_string() const; - - /// @brief Get the value of the data contained in this snapshot. - /// - /// @returns The value of the data contained in this location. - Variant value() const; - - /// @brief Get the priority of the data contained in this snapshot. - /// - /// @returns The value of this location's Priority relative to its siblings. - Variant priority() const; - - /// @brief Obtain a DatabaseReference to the source location for this - /// snapshot. - /// - /// @returns A DatabaseReference corresponding to same location as - /// this snapshot. - DatabaseReference GetReference() const; - - /// @brief Does this DataSnapshot have data at a particular location? - /// - /// @param[in] path Path relative to this snapshot's location. - /// The pointer only needs to be valid during this call. - /// - /// @returns True if the snapshot has data at the specified location, false if - /// not. - bool HasChild(const char* path) const; - - /// @brief Does this DataSnapshot have data at a particular location? - /// - /// @param[in] path Path relative to this snapshot's location. - /// - /// @returns True if the snapshot has data at the specified location, false if - /// not. - bool HasChild(const std::string& path) const; - - /// @brief Returns true if this snapshot is valid, false if it is not - /// valid. An invalid snapshot could be returned by a transaction where an - /// error has occurred. - /// - /// @returns true if this snapshot is valid, false if this snapshot is - /// invalid. - bool is_valid() const; - - private: - /// @cond FIREBASE_APP_INTERNAL - friend class internal::Callbacks; - friend class internal::ChildEventRegistration; - friend class internal::DataSnapshotInternal; - friend class internal::DatabaseInternal; - friend class internal::DatabaseInternalTestMatcherTest; - friend class internal::DatabaseReferenceInternal; - friend class internal::QueryInternal; - friend class internal::Repo; - friend class internal::ValueEventRegistration; - /// @endcond - -#ifndef INTERNAL_EXPERIMENTAL - explicit DataSnapshot(internal::DataSnapshotInternal* internal); -#endif - - internal::DataSnapshotInternal* internal_; -}; - -} // namespace database -} // namespace firebase - -#endif // FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_DATA_SNAPSHOT_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/database/database_reference.h b/packages/firebase_core/firebase_core/firebase_core/firebase/database/database_reference.h deleted file mode 100644 index 3e746541a1d5..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/database/database_reference.h +++ /dev/null @@ -1,477 +0,0 @@ -// Copyright 2016 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_DATABASE_REFERENCE_H_ -#define FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_DATABASE_REFERENCE_H_ - -#include -#include - -#include "firebase/database/disconnection.h" -#include "firebase/database/query.h" -#include "firebase/database/transaction.h" -#include "firebase/future.h" -#include "firebase/internal/common.h" -#include "firebase/variant.h" - -namespace firebase { -namespace database { -namespace internal { -class DatabaseInternal; -class DatabaseReferenceInternal; -class Repo; -} // namespace internal - -class DataSnapshot; - -#ifndef SWIG -/// DatabaseReference represents a particular location in your Database and can -/// be used for reading or writing data to that Database location. -/// -/// This class is the starting point for all Database operations. After you've -/// initialized it with a URL, you can use it to read data, write data, and to -/// create new DatabaseReference instances. -#endif // SWIG -class DatabaseReference : public Query { - public: - /// @brief Default constructor. This creates an invalid DatabaseReference. - /// Attempting to perform any operations on this reference will fail unless a - /// valid DatabaseReference has been assigned to it. - DatabaseReference() : Query(), internal_(nullptr) {} - - /// @brief Required virtual destructor. - virtual ~DatabaseReference(); - - /// @brief Copy constructor. It's totally okay (and efficient) to copy - /// DatabaseReference instances, as they simply point to the same location in - /// the database. - /// - /// @param[in] reference DatabaseReference to copy from. - DatabaseReference(const DatabaseReference& reference); - - /// @brief Copy assignment operator. It's totally okay (and efficient) to copy - /// DatabaseReference instances, as they simply point to the same location in - /// the database. - /// - /// @param[in] reference DatabaseReference to copy from. - /// - /// @returns Reference to the destination DatabaseReference. - DatabaseReference& operator=(const DatabaseReference& reference); - -#if defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) - /// @brief Move constructor. Moving is an efficient operation for - /// DatabaseReference instances. - /// - /// @param[in] reference DatabaseReference to move data from. - DatabaseReference(DatabaseReference&& reference); - - /// @brief Move assignment operator. Moving is an efficient operation for - /// DatabaseReference instances. - /// - /// @param[in] reference DatabaseReference to move data from. - /// - /// @returns Reference to the destination DatabaseReference. - DatabaseReference& operator=(DatabaseReference&& reference); -#endif // defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) - - /// @brief Gets the database to which we refer. - /// - /// The pointer will remain valid indefinitely. - /// - /// @returns Firebase Database instance that this DatabaseReference refers to. - Database* database() const; - - /// @brief Gets the string key of this database location. - /// - /// The pointer is only valid while the DatabaseReference remains in memory. - /// - /// @returns String key of this database location, which will remain valid in - /// memory until the DatabaseReference itself goes away. - const char* key() const; - - /// @brief Gets the string key of this database location. - /// - /// @returns String key of this database location. - std::string key_string() const; - - /// @brief Returns true if this reference refers to the root of the database. - /// - /// @returns true if this reference refers to the root of the database, false - /// otherwise. - bool is_root() const; - - /// @brief Returns true if this reference is valid, false if it is not - /// valid. DatabaseReferences constructed with the default constructor - /// are considered invalid. An invalid reference could be returned by - /// Database::GetReference() or Database::GetReferenceFromUrl() if you specify - /// an incorrect location, or calling Query::GetReference() on an invalid - /// query. - /// - /// @returns true if this reference is valid, false if this reference is - /// invalid. - bool is_valid() const override; - - /// @brief Gets the parent of this location, or get this location again if - /// IsRoot(). - /// - /// @returns Parent of this location in the database, unless this location is - /// the root, in which case it returns this same location again. - DatabaseReference GetParent() const; - - /// @brief Gets the root of the database. - /// - /// @returns Root of the database. - DatabaseReference GetRoot() const; - - /// @brief Gets a reference to a location relative to this one. - /// - /// @param[in] path Path relative to this snapshot's location. - /// The pointer only needs to be valid during this call. - /// - /// @returns Child relative to this location. - DatabaseReference Child(const char* path) const; - - /// @brief Gets a reference to a location relative to this one. - /// - /// @param[in] path Path relative to this snapshot's location. - /// - /// @returns Child relative to this location. - DatabaseReference Child(const std::string& path) const; - - /// @brief Automatically generates a child location, create a reference to it, - /// and returns that reference to it. - /// - /// @returns A newly created child, with a unique key. - DatabaseReference PushChild() const; - - /// @brief Removes the value at this location from the database. - /// - /// This is an asynchronous operation which takes time to execute, and uses - /// firebase::Future to return its result. - /// - /// @returns A Future result, which will complete when the operation either - /// succeeds or fails. When the Future is completed, if its Error is - /// kErrorNone, the operation succeeded. - /// - /// @note Only one RemoveValue() should be running on a given database - /// location at the same time. If you need to run multiple operations at once, - /// use RunTransaction(). - Future RemoveValue(); - - /// @brief Gets the result of the most recent call to RemoveValue(); - /// - /// @returns Result of the most recent call to RemoveValue(). - Future RemoveValueLastResult(); - - /// @brief Run a user-supplied callback function (passing in a context), - /// possibly multiple times, to perform an atomic transaction on the database. - /// - /// @see firebase::database::DoTransactionWithContext for more information. - /// - /// @param[in] transaction_function The user-supplied function that will be - /// called, possibly multiple times, to perform the database transaction. - /// @param[in] context User-supplied context that will be passed to the - /// transaction function. - /// @param[in] trigger_local_events If true, events will be triggered for - /// intermediate state changes during the transaction. If false, only the - /// final state will cause events to be triggered. - /// - /// @returns A Future result, which will complete when the transaction either - /// succeeds or fails. When the Future is completed, if its Error is - /// kErrorNone, the operation succeeded and the transaction was committed, and - /// the new value of the data will be returned in the DataSnapshot result. If - /// the Error is kErrorTransactionAbortedByUser, the transaction was aborted - /// because the transaction function returned kTransactionResultAbort, and the - /// old value will be returned in DataSnapshot. Otherwise, if some other error - /// occurred, Error and ErrorMessage will be set and DataSnapshot will be - /// invalid. - /// - /// @note Only one RunTransaction() should be running on a given database - /// location at the same time. - Future RunTransaction( - DoTransactionWithContext transaction_function, void* context, - bool trigger_local_events = true); - -#if defined(FIREBASE_USE_STD_FUNCTION) || defined(DOXYGEN) - /// @brief Run a user-supplied callback, possibly multiple times, to perform - /// an atomic transaction on the database. - /// - /// @see firebase::database::DoTransactionFunction for more information. - /// - /// @param[in] transaction_function The user-supplied function or lambda that - /// will be called, possibly multiple times, to perform the database - /// transaction. - /// @param[in] trigger_local_events If true, events will be triggered for - /// intermediate state changes during the transaction. If false, only the - /// final state will cause events to be triggered. - /// - /// @returns A Future result, which will complete when the transaction either - /// succeeds or fails. When the Future is completed, if its Error is - /// kErrorNone, the operation succeeded and the transaction was committed, and - /// the new value of the data will be returned in the DataSnapshot result. If - /// the Error is kErrorTransactionAbortedByUser, the transaction was aborted - /// because the transaction function returned kTransactionResultAbort, and the - /// old value will be returned in DataSnapshot. Otherwise, if some other error - /// occurred, Error and ErrorMessage will be set and DataSnapshot will be - /// invalid. - /// - /// @note Only one RunTransaction() should be running on a given database - /// location at the same time. - /// - /// @note This version (that accepts an std::function) is not available when - /// using stlport on Android. If you don't wish to use std::function, use the - /// overloaded method that accepts a simple function pointer with a context. - Future RunTransaction( - DoTransactionFunction transaction_function, - bool trigger_local_events = true); -#endif // defined(FIREBASE_USE_STD_FUNCTION) || defined(DOXYGEN) - -#if !defined(FIREBASE_USE_STD_FUNCTION) || defined(DOXYGEN) - /// @brief Run a user-supplied callback function, possibly multiple times, to - /// perform an atomic transaction on the database. - /// - /// @see firebase::database::DoTransaction for more information. - /// - /// @param[in] transaction_function The user-supplied function that will be - /// called, possibly multiple times, to perform the database transaction. - /// @param[in] trigger_local_events If true, events will be triggered for - /// intermediate state changes during the transaction. If false, only the - /// final state will cause events to be triggered. - /// - /// @returns A Future result, which will complete when the transaction either - /// succeeds or fails. When the Future is completed, if its Error is - /// kErrorNone, the operation succeeded and the transaction was committed, and - /// the new value of the data will be returned in the DataSnapshot result. If - /// the Error is kErrorTransactionAbortedByUser, the transaction was aborted - /// because the transaction function returned kTransactionResultAbort, and the - /// old value will be returned in DataSnapshot. Otherwise, if some other error - /// occurred, Error and ErrorMessage will be set and DataSnapshot will be - /// invalid. - /// - /// @note Only one RunTransaction() should be running on a given database - /// location at the same time. - /// - /// @note This version (that accepts a simple function pointer) is only - /// available when using stlport and std::function is not available. - Future RunTransaction(DoTransaction transaction_function, - bool trigger_local_events = true); -#endif // !defined(FIREBASE_USE_STD_FUNCTION) || defined(DOXYGEN) - - /// @brief Get the result of the most recent call to RunTransaction(). - /// - /// @returns Results of the most recent call to RunTransaction(). - Future RunTransactionLastResult(); - - /// @brief Sets the priority of this field, which controls its sort - /// order relative to its siblings. - /// - /// In Firebase, children are sorted in the following order: - /// 1. First, children with no priority. - /// 2. Then, children with numerical priority, sorted numerically in - /// ascending order. - /// 3. Then, remaining children, sorted lexicographically in ascending order - /// of their text priority. - /// - /// Children with the same priority (including no priority) are sorted by - /// key: - /// A. First, children with keys that can be parsed as 32-bit integers, - /// sorted in ascending numerical order of their keys. - /// B. Then, remaining children, sorted in ascending lexicographical order - /// of their keys. - /// - /// This is an asynchronous operation which takes time to execute, and uses - /// firebase::Future to return its result. - /// - /// @param[in] priority Sort priority for this child relative to its siblings. - /// The Variant types accepted are Null, Int64, Double, and String. Other - /// types will return kErrorInvalidVariantType. - /// - /// @returns A Future result, which will complete when the operation either - /// succeeds or fails. When the Future is completed, if its Error is - /// kErrorNone, the operation succeeded. - /// - /// @note Only one SetPriority() should be running on a given database - /// location - /// at the same time. If you need to run multiple operations at once, use - /// RunTransaction(). - Future SetPriority(Variant priority); - - /// @brief Gets the result of the most recent call to SetPriority(). - /// - /// @returns Result of the most recent call to SetPriority(). - Future SetPriorityLastResult(); - - /// @brief Sets the data at this location to the given value. - /// - /// This is an asynchronous operation which takes time to execute, and uses - /// firebase::Future to return its result. - /// - /// @param[in] value The value to set this location to. The Variant's type - /// corresponds to the types accepted by the database JSON: - /// Null: Deletes this location from the database. - /// Int64: Inserts an integer value into this location. - /// Double: Inserts a floating point value into this location. - /// String: Inserts a string into this location. - /// (Accepts both Mutable and Static strings) - /// Vector: Inserts a JSON array into this location. The elements can be any - /// Variant type, including Vector and Map. - /// Map: Inserts a JSON associative array into this location. The keys must - /// be of type String (or Int64/Double which are converted to String). - /// The values can be any Variant type, including Vector and Map. - /// - /// @returns A Future result, which will complete when the operation either - /// succeeds or fails. When the Future is completed, if its Error is - /// kErrorNone, the operation succeeded. - /// - /// @note Only one SetValue() should be running on a given database location - /// at the same time. If you need to run multiple operations at once, use - /// RunTransaction(). - Future SetValue(Variant value); - - /// @brief Gets the result of the most recent call to SetValue(). - /// - /// @returns Result of the most recent call to SetValue(). - Future SetValueLastResult(); - - /// @brief Sets both the data and priority of this location. See SetValue() - /// and SetPriority() for context on the parameters. - /// - /// This is an asynchronous operation which takes time to execute, and uses - /// firebase::Future to return its result. - /// - /// @param[in] value The value to set this location to. See SetValue() for - /// information on the types accepted. - /// @param[in] priority The priority to set this location to. See - /// SetPriority() for information on the types accepted. - /// - /// @returns A Future result, which will complete when the operation either - /// succeeds or fails. When the Future is completed, if its Error is - /// kErrorNone, the operation succeeded. - /// - /// @note Only one SetValueAndPriority() should be running on a given database - /// location at the same time. SetValueAndPriority() can't be used on the same - /// location at the same time as either SetValue() or SetPriority(), and will - /// return kErrorConflictingOperationInProgress if you try. If you need to run - /// multiple operations at once, use RunTransaction(). - Future SetValueAndPriority(Variant value, Variant priority); - - /// @brief Get the result of the most recent call to SetValueAndPriority(). - /// - /// @returns Result of the most recent call to SetValueAndPriority(). - Future SetValueAndPriorityLastResult(); - - /// @brief Updates the specified child keys to the given values. - /// - /// @param[in] values A variant of type Map. The keys are the paths to update - /// and must be of type String (or Int64/Double which are converted to - /// String). The values can be any Variant type. A value of Variant type Null - /// will delete the child. - /// - /// @returns A Future result, which will complete when the operation either - /// succeeds or fails. When the Future is completed, if its Error is - /// kErrorNone, the operation succeeded. - /// - /// @note This method will return kErrorConflictingOperationInProgress if it - /// is run at the same time as SetValue(), SetValueAndPriority(), or - /// RemoveValue() in the same location. - Future UpdateChildren(Variant values); - - /// @brief Updates the specified child keys to the given values. - /// - /// This is an asynchronous operation which takes time to execute, and uses - /// firebase::Future to return its result. - /// - /// @param[in] values The paths to update, and their new child values. A value - /// of type Null will delete that particular child. - /// - /// @returns A Future result, which will complete when the operation either - /// succeeds or fails. When the Future is completed, if its Error is - /// kErrorNone, the operation succeeded. - inline Future UpdateChildren( - const std::map& values) { - return UpdateChildren(Variant(values)); - } - - /// @brief Gets the result of the most recent call to either version of - /// UpdateChildren(). - /// - /// @returns Result of the most recent call to UpdateChildren(). - Future UpdateChildrenLastResult(); - - /// @brief Get the absolute URL of this reference. - /// - /// @returns The absolute URL of the location this reference refers to. - std::string url() const; - - /// @brief Get the disconnect handler, which controls what actions the server - /// will perform to this location's data when this client disconnects. - /// - /// @returns Disconnection handler for this location. You can use this to - /// queue up operations on the server to be performed when the client - /// disconnects. - DisconnectionHandler* OnDisconnect(); - - /// @brief Manually disconnect Firebase Realtime Database from the server, and - /// disable automatic reconnection. This will affect all other instances of - /// DatabaseReference as well. - void GoOffline(); - - /// @brief Manually reestablish connection to the Firebase Realtime Database - /// server and enable automatic reconnection. This will affect all other - /// instances of DatabaseReference as well. - void GoOnline(); - - protected: - /// @cond FIREBASE_APP_INTERNAL - explicit DatabaseReference(internal::DatabaseReferenceInternal* internal); - /// @endcond - - private: - /// @cond FIREBASE_APP_INTERNAL - - // Remove the "Query" cleanup registration (which the base class constructor - // already registered) and replace it with a "DatabaseReference" registration. - // - // This is necessary so that if the instance needs to be cleaned up, the - // correct pointer type will be used to access it. - void SwitchCleanupRegistrationToDatabaseReference(); - - // Remove the "DatabaseReference" cleanup registration and replace it with a - // "Query" one. ~Query() will unregister that one. - void SwitchCleanupRegistrationBackToQuery(); - - friend class DataSnapshot; - friend class Query; - friend class internal::DatabaseInternal; - friend class internal::Repo; - friend bool operator==(const DatabaseReference& lhs, - const DatabaseReference& rhs); - /// @endcond - - internal::DatabaseReferenceInternal* internal_; -}; - -/// @brief Compares two DatabaseReference instances. -/// -/// @param[in] lhs A DatabaseReference. -/// @param[in] rhs A DatabaseReference to compare against. -/// -/// @returns True if the DatabaseReference instances have the same URL. False -/// otherwise. -bool operator==(const DatabaseReference& lhs, const DatabaseReference& rhs); - -} // namespace database -} // namespace firebase - -#endif // FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_DATABASE_REFERENCE_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/database/disconnection.h b/packages/firebase_core/firebase_core/firebase_core/firebase/database/disconnection.h deleted file mode 100644 index b21fa472e629..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/database/disconnection.h +++ /dev/null @@ -1,156 +0,0 @@ -// Copyright 2016 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_DISCONNECTION_H_ -#define FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_DISCONNECTION_H_ - -#include "firebase/future.h" -#include "firebase/internal/common.h" -#include "firebase/variant.h" - -namespace firebase { -namespace database { -namespace internal { -class DatabaseReferenceInternal; -class DisconnectionHandlerInternal; -} // namespace internal - -/// Allows you to register server-side actions to occur when the client -/// disconnects. Each method you call (with the exception of Cancel) will queue -/// up an action on the data that will be performed by the server in the event -/// the client disconnects. To reset this queue, call Cancel(). -/// -/// A DisconnectionHandler is associated with a specific location in the -/// database, as they are obtained by calling DatabaseReference::OnDisconnect(). -class DisconnectionHandler { - public: - ~DisconnectionHandler(); - - /// @brief Cancel any Disconnection operations that are queued up by this - /// handler. When the Future returns, if its Error is kErrorNone, the queue - /// has been cleared on the server. - /// - /// @returns A Future result, which will complete when the operation either - /// succeeds or fails. When the Future is completed, if its Error is - /// kErrorNone, the operation succeeded. - Future Cancel(); - /// @brief Get the result of the most recent call to Cancel(). - /// - /// @returns Result of the most recent call to Cancel(). - Future CancelLastResult(); - - /// @brief Remove the value at the current location when the client - /// disconnects. When the Future returns, if its Error is kErrorNone, the - /// RemoveValue operation has been successfully queued up on the server. - /// - /// @returns A Future result, which will complete when the operation either - /// succeeds or fails. When the Future is completed, if its Error is - /// kErrorNone, the operation succeeded. - Future RemoveValue(); - /// @brief Get the result of the most recent call to RemoveValue(). - /// - /// @returns Result of the most recent call to RemoveValue(). - Future RemoveValueLastResult(); - - /// @brief Set the value of the data at the current location when the client - /// disconnects. When the Future returns, if its Error is kErrorNone, the - /// SetValue operation has been successfully queued up on the server. - /// - /// @param[in] value The value to set this location to when the client - /// disconnects. For information on how the Variant types are used, - /// see firebase::database::DatabaseReference::SetValue(). - /// - /// @returns A Future result, which will complete when the operation either - /// succeeds or fails. When the Future is completed, if its Error is - /// kErrorNone, the operation succeeded. - Future SetValue(Variant value); - /// Get the result of the most recent call to SetValue(). - /// - /// @returns Result of the most recent call to SetValue(). - Future SetValueLastResult(); - - /// @brief Set the value and priority of the data at the current location when - /// the client disconnects. When the Future returns, if its Error is - /// kErrorNone, the SetValue operation has been successfully queued up on the - /// server. - /// - /// @param[in] value The value to set this location to when the client - /// disconnects. For information on how the Variant types are used, - /// see firebase::database::DatabaseReference::SetValue(). - /// @param[in] priority The priority to set this location to when the client - /// disconnects. The Variant types accepted are Null, Int64, Double, and - /// String. For information about how priority is used, see - /// firebase::database::DatabaseReference::SetPriority(). - /// - /// @returns A Future result, which will complete when the operation either - /// succeeds or fails. When the Future is completed, if its Error is - /// kErrorNone, the operation succeeded. - Future SetValueAndPriority(Variant value, Variant priority); - /// @brief Get the result of the most recent call to SetValueAndPriority(). - /// - /// @returns Result of the most recent call to SetValueAndPriority(). - Future SetValueAndPriorityLastResult(); - - /// @brief Updates the specified child keys to the given values when the - /// client disconnects. When the Future returns, if its Error is kErrorNone, - /// the UpdateChildren operation has been successfully queued up by the - /// server. - /// - /// @param[in] values A variant of type Map. The keys are the paths to update - /// and must be of type String (or Int64/Double which are converted to - /// String). The values can be any Variant type. A value of Variant type Null - /// will delete the child. - /// - /// @returns A Future result, which will complete when the operation either - /// succeeds or fails. When the Future is completed, if its Error is - /// kErrorNone, the operation succeeded. - Future UpdateChildren(Variant values); - /// @brief Updates the specified child keys to the given values when the - /// client disconnects. When the Future returns, if its Error is kErrorNone, - /// the UpdateChildren operation has been successfully queued up by the - /// server. - /// - /// @param[in] values The paths to update, and their new child values. A value - /// of type Null will delete that particular child. - /// - /// @returns A Future result, which will complete when the operation either - /// succeeds or fails. When the Future is completed, if its Error is - /// kErrorNone, the operation succeeded. - Future UpdateChildren(const std::map& values) { - return UpdateChildren(Variant(values)); - } - /// @brief Gets the result of the most recent call to either version of - /// UpdateChildren(). - /// - /// @returns Result of the most recent call to UpdateChildren(). - Future UpdateChildrenLastResult(); - - private: - /// @cond FIREBASE_APP_INTERNAL - friend class internal::DatabaseReferenceInternal; - friend class internal::DisconnectionHandlerInternal; - /// @endcond - - /// Call DatabaseReference::OnDisconnect() to get an instance of this class. - explicit DisconnectionHandler( - internal::DisconnectionHandlerInternal* internal); - - /// You can only get the DisconnectHandler for a given reference. - internal::DisconnectionHandlerInternal* internal_; -}; - -} // namespace database -} // namespace firebase - -#endif // FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_DISCONNECTION_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/database/listener.h b/packages/firebase_core/firebase_core/firebase_core/firebase/database/listener.h deleted file mode 100644 index fe13d9299003..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/database/listener.h +++ /dev/null @@ -1,112 +0,0 @@ -// Copyright 2016 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_LISTENER_H_ -#define FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_LISTENER_H_ - -#include "firebase/database/common.h" - -namespace firebase { -namespace database { - -class DataSnapshot; - -/// Value listener interface. Subclasses of this listener class can be -/// used to receive events about data changes at a location. Attach -/// the listener to a location using -/// DatabaseReference::AddValueListener() or -/// Query::AddValueListener(), and OnValueChanged() will be called -/// once immediately, and again when the value changes. -class ValueListener { - public: - virtual ~ValueListener(); - - /// This method will be called with a snapshot of the data at this - /// location each time that data changes. - /// - /// @param[in] snapshot The current data at the location. - virtual void OnValueChanged(const DataSnapshot& snapshot) = 0; - - /// @brief This method will be triggered in the event that this listener - /// either failed at the server, or is removed as a result of the security and - /// Firebase rules. - /// - /// @param[in] error A code corresponding to the error that occurred. - /// @param[in] error_message A description of the error that occurred. - virtual void OnCancelled(const Error& error, const char* error_message) = 0; -}; - -/// Child listener interface. Subclasses of this listener class can be -/// used to receive events about changes in the child locations of a -/// firebase::database::Query or -/// firebase::database::DatabaseReference. Attach the listener to a -/// location with Query::AddChildListener() or -/// DatabaseReference::AddChildListener() and the appropriate method -/// will be triggered when changes occur. -class ChildListener { - public: - virtual ~ChildListener(); - - /// @brief This method is triggered when a new child is added to the location - /// to which this listener was added. - /// - /// @param[in] snapshot An immutable snapshot of the data at the new data at - /// the child location. - /// @param[in] previous_sibling_key The key name of sibling location ordered - /// before the child. This will be nullptr for the first child node of a - /// location. - virtual void OnChildAdded(const DataSnapshot& snapshot, - const char* previous_sibling_key) = 0; - /// @brief This method is triggered when the data at a child location has - /// changed. - /// - /// @param[in] snapshot An immutable snapshot of the data at the new data at - /// the child location. - /// @param[in] previous_sibling_key The key name of sibling location ordered - /// before the child. This will be nullptr for the first child node of a - /// location. - virtual void OnChildChanged(const DataSnapshot& snapshot, - const char* previous_sibling_key) = 0; - /// @brief This method is triggered when a child location's priority changes. - /// See DatabaseReference::SetPriority() for more information on priorities - /// and - /// ordering data. - /// - /// @param[in] snapshot An immutable snapshot of the data at the new data at - /// the child location. - /// @param[in] previous_sibling_key The key name of sibling location ordered - /// before the child. This will be nullptr for the first child node of a - /// location. - virtual void OnChildMoved(const DataSnapshot& snapshot, - const char* previous_sibling_key) = 0; - /// @brief This method is triggered when a child is removed from the location - /// to which this listener was added. - /// - /// @param[in] snapshot An immutable snapshot of the data at the new data at - /// the child location. - virtual void OnChildRemoved(const DataSnapshot& snapshot) = 0; - - /// @brief This method will be triggered in the event that this listener - /// either failed at the server, or is removed as a result of the security and - /// Firebase rules. - /// - /// @param[in] error A code corresponding to the error that occurred. - /// @param[in] error_message A description of the error that occurred. - virtual void OnCancelled(const Error& error, const char* error_message) = 0; -}; - -} // namespace database -} // namespace firebase - -#endif // FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_LISTENER_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/database/mutable_data.h b/packages/firebase_core/firebase_core/firebase_core/firebase/database/mutable_data.h deleted file mode 100644 index cedfa159cca6..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/database/mutable_data.h +++ /dev/null @@ -1,165 +0,0 @@ -// Copyright 2016 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_MUTABLE_DATA_H_ -#define FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_MUTABLE_DATA_H_ - -#include "firebase/internal/common.h" -#include "firebase/variant.h" - -namespace firebase { -namespace database { -namespace internal { -class DatabaseInternal; -class DatabaseReferenceInternal; -class MutableDataInternal; -class Repo; -} // namespace internal - -#ifndef SWIG -/// Instances of this class encapsulate the data and priority at a location. It -/// is used in transactions, and it is intended to be inspected and then updated -/// to the desired data at that location. -#endif // SWIG -class MutableData { - public: -#if defined(FIREBASE_USE_MOVE_OPERATORS) - /// Move constructor - /// Move is more efficient than copy and delete. - MutableData(MutableData&& rhs); - - // MutableData may be moved. - MutableData& operator=(MutableData&& rhs); -#endif // defined(FIREBASE_USE_MOVE_OPERATORS) - - /// Destructor. - ~MutableData(); - - /// @brief Used to obtain a MutableData instance that encapsulates - /// the data and priority at the given relative path. - /// - /// Note that changes made to a child MutableData instance will be visible - /// to the parent and vice versa. - /// - /// @param[in] path Path relative to this snapshot's location. - /// The pointer only needs to be valid during this call. - /// - /// @returns MutableData for the Child relative to this location. The memory - /// will be freed when the Transaction is finished. - MutableData Child(const char* path); - - /// @brief Used to obtain a MutableData instance that encapsulates - /// the data and priority at the given relative path. - /// - /// @param[in] path Path relative to this snapshot's location. - /// - /// @returns MutableData for the Child relative to this location. The memory - /// will be freed when the Transaction is finished. - MutableData Child(const std::string& path); - - /// @brief Get all the immediate children of this location. - /// - /// @returns The immediate children of this location. - std::vector children(); - - /// @brief Get the number of children of this location. - /// - /// @returns The number of immediate children of this location. - size_t children_count(); - - /// @brief Get the key name of the source location of this data. - /// - /// @note The returned pointer is only guaranteed to be valid during the - /// transaction. - /// - /// @returns Key name of the source location of this data. - const char* key() const; - - /// @brief Get the key name of the source location of this data. - /// - /// @returns Key name of the source location of this data. - std::string key_string() const; - - /// @brief Get the value of the data contained at this location. - /// - /// @returns The value of the data contained at this location. - Variant value() const; - - /// @brief Get the priority of the data contained at this snapshot. - /// - /// @returns The value of this location's Priority relative to its siblings. - Variant priority(); - - /// @brief Does this MutableData have data at a particular location? - /// - /// @param[in] path Path relative to this data's location. - /// The pointer only needs to be valid during this call. - /// - /// @returns True if there is data at the specified location, false if not. - bool HasChild(const char* path) const; - - /// @brief Does this MutableData have data at a particular location? - /// - /// @param[in] path Path relative to this data's location. - /// @returns True if there is data at the specified location, false if not. - bool HasChild(const std::string& path) const; - - /// @brief Sets the data at this location to the given value. - /// - /// @param[in] value The value to set this location to. The Variant's type - /// corresponds to the types accepted by the database JSON: - /// Null: Deletes this location from the database. - /// Int64: Inserts an integer value into this location. - /// Double: Inserts a floating point value into this location. - /// String: Inserts a string into this location. - /// (Accepts both Mutable and Static strings) - /// Vector: Inserts a JSON array into this location. The elements can be any - /// Variant type, including Vector and Map. - /// Map: Inserts a JSON associative array into this location. The keys must - /// be of type String (or Int64/Double which are converted to String). - /// The values can be any Variant type, including Vector and Map. - void set_value(const Variant& value); - - /// @brief Sets the priority of this field, which controls its sort - /// order relative to its siblings. - /// - /// @see firebase::database::DatabaseReference::SetPriority() for information - /// on how Priority affects the ordering of a node's children. - /// - /// @param[in] priority Sort priority for this child relative to its siblings. - /// The Variant types accepted are Null, Int64, Double, and String. Other - /// types will return kErrorInvalidVariantType. - void set_priority(const Variant& priority); - - private: - /// @cond FIREBASE_APP_INTERNAL - friend class internal::DatabaseReferenceInternal; - friend class internal::DatabaseInternal; - friend class internal::MutableDataInternal; - friend class internal::Repo; - friend MutableData GetInvalidMutableData(); - /// @endcond - - explicit MutableData(internal::MutableDataInternal* internal); - - MutableData(const MutableData& rhs) = delete; - MutableData& operator=(const MutableData& rhs) = delete; - - internal::MutableDataInternal* internal_; -}; - -} // namespace database -} // namespace firebase - -#endif // FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_MUTABLE_DATA_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/database/query.h b/packages/firebase_core/firebase_core/firebase_core/firebase/database/query.h deleted file mode 100644 index c60707a7ee65..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/database/query.h +++ /dev/null @@ -1,358 +0,0 @@ -// Copyright 2016 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_QUERY_H_ -#define FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_QUERY_H_ - -#include - -#include "firebase/database/listener.h" -#include "firebase/future.h" -#include "firebase/internal/common.h" - -namespace firebase { -namespace database { -namespace internal { -class QueryInternal; -} // namespace internal - -class DatabaseReference; - -#ifndef SWIG -/// The Query class is used for reading data. Listeners can be attached, which -/// will be triggered when the data changes. -#endif // SWIG -class Query { - public: - /// Default constructor. This creates an invalid Query. Attempting to perform - /// any operations on this reference will fail unless a valid Query has been - /// assigned to it. - Query() : internal_(nullptr) {} - - /// Copy constructor. Queries can be copied. Copies exist independently of - /// each other. - Query(const Query& query); - - /// Copy assignment operator. Queries can be copied. Copies exist - /// independently of each other. - Query& operator=(const Query& query); - -#if defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) - /// Move constructor. - Query(Query&& query); - /// Move assignment operator. - Query& operator=(Query&& query); -#endif // defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) - - /// @brief Required virtual destructor. - virtual ~Query(); - - /// @brief Gets the value of the query for the given location a single time. - /// - /// This is an asynchronous operation which takes time to execute, and uses - /// firebase::Future to return its result. - /// - /// @returns A Future result, which will complete when the operation either - /// succeeds or fails. On this Future's completion, if its Error is - /// kErrorNone, the operation succeeded, and the DataSnapshot contains the - /// data in this location. - Future GetValue(); - /// @brief Gets the result of the most recent call to GetValue(). - /// - /// @returns Result of the most recent call to GetValue(). - Future GetValueLastResult(); - - /// @brief Adds a listener that will be called immediately and then again any - /// time the data changes. - /// - /// @param[in] listener A ValueListener instance, which must remain in memory - /// until you remove the listener from the Query. - void AddValueListener(ValueListener* listener); - - /// @brief Removes a listener that was previously added with - /// AddValueListener(). - /// - /// @param[in] listener A ValueListener instance to remove from the - /// Query. After it is removed, you can delete it or attach it to a new - /// location. - /// - /// @note You can remove a ValueListener from a different Query than you added - /// it to, as long as the two Query instances are equivalent. - void RemoveValueListener(ValueListener* listener); - - /// @brief Removes all value listeners that were added with - /// AddValueListener(). - /// - /// @note You can remove ValueListeners from a different Query than you added - /// them to, as long as the two Query instances are equivalent. - void RemoveAllValueListeners(); - - /// @brief Adds a listener that will be called any time a child is added, - /// removed, modified, or reordered. - /// - /// @param[in] listener A ChildListener instance, which must remain in memory - /// until you remove the listener from the Query. - void AddChildListener(ChildListener* listener); - - /// @brief Removes a listener that was previously added with - /// AddChildListener(). - /// - /// @param[in] listener A ChildListener instance to remove from the - /// Query. After it is removed, you can delete it or attach it to a new - /// location. - /// - /// @note You can remove a ChildListener from a different Query than you added - /// it to, as long as the two Query instances are equivalent. - void RemoveChildListener(ChildListener* listener); - - /// @brief Removes all child listeners that were added by AddChildListener(). - /// - /// @note You can remove ChildListeners from a different Query than you added - /// them to, as long as the two Query instances are equivalent. - void RemoveAllChildListeners(); - - /// @brief Gets a DatabaseReference corresponding to the given location. - /// - /// @returns A DatabaseReference corresponding to the same location as the - /// Query, but without any of the ordering or filtering parameters. - DatabaseReference GetReference() const; - - /// @brief Sets whether this location's data should be kept in sync even if - /// there are no active Listeners. - /// - /// By calling SetKeepSynchronized(true) on a given database location, the - /// data for that location will automatically be downloaded and kept in sync, - /// even when no listeners are attached for that location. Additionally, while - /// a location is kept synced, it will not be evicted from the persistent disk - /// cache. - /// - /// @param[in] keep_sync If true, set this location to be synchronized. If - /// false, set it to not be synchronized. - void SetKeepSynchronized(bool keep_sync); - - // The OrderBy* functions are used for two purposes: - // 1. Order the data when getting the list of children. - // 2. When filtering the data using the StartAt* and EndAt* functions further - // below, use the specified ordering. - - /// @brief Gets a query in which child nodes are ordered by the values of the - /// specified path. Any previous OrderBy directive will be replaced in the - /// returned Query. - /// - /// @param[in] path Path to a child node. The value of this node will be used - /// for sorting this query. The pointer you pass in need not remain valid - /// after the call completes. - /// - /// @returns A Query in this same location, with the children are sorted by - /// the value of their own child specified here. - Query OrderByChild(const char* path); - /// @brief Gets a query in which child nodes are ordered by the values of the - /// specified path. Any previous OrderBy directive will be replaced in the - /// returned Query. - /// - /// @param[in] path Path to a child node. The value of this node will be used - /// for sorting this query. - /// - /// @returns A Query in this same location, with the children are sorted by - /// the value of their own child specified here. - Query OrderByChild(const std::string& path); - /// @brief Gets a query in which child nodes are ordered by their keys. Any - /// previous OrderBy directive will be replaced in the returned Query. - /// - /// @returns A Query in this same location, with the children are sorted by - /// their key. - Query OrderByKey(); - /// @brief Gets a query in which child nodes are ordered by their priority. - /// Any previous OrderBy directive will be replaced in the returned Query. - /// - /// @returns A Query in this same location, with the children are sorted by - /// their priority. - Query OrderByPriority(); - /// @brief Create a query in which nodes are ordered by their value. - /// - /// @returns A Query in this same location, with the children are sorted by - /// their value. - Query OrderByValue(); - - // The StartAt, EndAt, and EqualTo functions are used to limit which child - // nodes are returned when iterating through the current location. - - /// @brief Get a Query constrained to nodes with the given sort value or - /// higher. - /// - /// This method is used to generate a reference to a limited view of the data - /// at this location. The Query returned will only refer to child nodes with a - /// value greater than or equal to the given value, using the given OrderBy - /// directive (or priority as the default). - /// - /// @param[in] order_value The lowest sort value the Query should include. - /// - /// @returns A Query in this same location, filtering out child nodes that - /// have a lower sort value than the sort value specified. - Query StartAt(Variant order_value); - /// @brief Get a Query constrained to nodes with the given sort value or - /// higher, and the given key or higher. - /// - /// This method is used to generate a reference to a limited view of the data - /// at this location. The Query returned will only refer to child nodes with a - /// value greater than or equal to the given value, using the given OrderBy - /// directive (or priority as default), and additionally only child nodes with - /// a key greater than or equal to the given key. - /// - /// Known issue This currently does not work properly on all platforms. - /// Please use StartAt(Variant order_value) instead. - /// - /// @param[in] order_value The lowest sort value the Query should include. - /// @param[in] child_key The lowest key the Query should include. - /// - /// @returns A Query in this same location, filtering out child nodes that - /// have a lower sort value than the sort value specified, or a lower key than - /// the key specified. - Query StartAt(Variant order_value, const char* child_key); - - /// @brief Get a Query constrained to nodes with the given sort value or - /// lower. - /// - /// This method is used to generate a reference to a limited view of the data - /// at this location. The Query returned will only refer to child nodes with a - /// value less than or equal to the given value, using the given OrderBy - /// directive (or priority as default). - /// - /// @param[in] order_value The highest sort value the Query should refer - /// to. - /// - /// @returns A Query in this same location, filtering out child nodes that - /// have a higher sort value or key than the sort value or key specified. - Query EndAt(Variant order_value); - /// @brief Get a Query constrained to nodes with the given sort value or - /// lower, and the given key or lower. - /// - /// This method is used to generate a reference to a limited view of - /// the data at this location. The Query returned will only refer to child - /// nodes with a value less than or equal to the given value, using the given - /// OrderBy directive (or priority as default), and additionally only child - /// nodes with a key less than or equal to the given key. - /// - /// Known issue This currently does not work properly on all platforms. - /// Please use EndAt(Variant order_value) instead. - /// - /// @param[in] order_value The highest sort value the Query should include. - /// @param[in] child_key The highest key the Query should include. - /// - /// @returns A Query in this same location, filtering out child nodes that - /// have a higher sort value than the sort value specified, or a higher key - /// than the key specified. - Query EndAt(Variant order_value, const char* child_key); - - /// @brief Get a Query constrained to nodes with the exact given sort value. - /// - /// This method is used to create a query constrained to only return child - /// nodes with the given value, using the given OrderBy directive (or priority - /// as default). - /// - /// @param[in] order_value The exact sort value the Query should include. - /// - /// @returns A Query in this same location, filtering out child nodes that - /// have a different sort value than the sort value specified. - Query EqualTo(Variant order_value); - - /// @brief Get a Query constrained to nodes with the exact given sort value, - /// and the exact given key. - /// - /// This method is used to create a query constrained to only return the child - /// node with the given value, using the given OrderBy directive (or priority - /// as default), and the given key. Note that there is at most one such child - /// as child key names are unique. - /// - /// Known issue This currently does not work properly on iOS, tvOS and - /// desktop. Please use EqualTo(Variant order_value) instead. - /// - /// @param[in] order_value The exact sort value the Query should include. - /// @param[in] child_key The exact key the Query should include. - /// - /// @returns A Query in this same location, filtering out child nodes that - /// have a different sort value than the sort value specified, and containing - /// at most one child with the exact key specified. - Query EqualTo(Variant order_value, const char* child_key); - - // The LimitTo* functions are used to limit how many child nodes are returned - // when iterating through the current location. - - /// @brief Gets a Query limited to only the first results. - /// - /// Limits the query to reference only the first N child nodes, using the - /// given OrderBy directive (or priority as default). - /// - /// @param[in] limit Number of children to limit the Query to. - /// - /// @returns A Query in this same location, limited to the specified number of - /// children (taken from the beginning of the sorted list). - Query LimitToFirst(size_t limit); - /// @brief Gets a Query limited to only the last results. - /// - /// @param[in] limit Number of children to limit the Query to. - /// - /// @returns A Query in this same location, limited to the specified number of - /// children (taken from the end of the sorted list). - Query LimitToLast(size_t limit); - - /// @brief Returns true if this query is valid, false if it is not valid. An - /// invalid query could be returned by, say, attempting to OrderBy two - /// different items, or calling OrderByChild() with an empty path, or by - /// constructing a Query with the default constructor. If a Query - /// is invalid, attempting to add more constraints will also result in an - /// invalid Query. - /// - /// @returns true if this query is valid, false if this query is - /// invalid. - virtual bool is_valid() const; - - protected: - /// @cond FIREBASE_APP_INTERNAL - explicit Query(internal::QueryInternal* internal); - void SetInternal(internal::QueryInternal* internal); - void RegisterCleanup(); - void UnregisterCleanup(); - /// @endcond - - private: - /// @cond FIREBASE_APP_INTERNAL - friend bool operator==(const Query& lhs, const Query& rhs); - /// @endcond - - internal::QueryInternal* internal_; -}; - -/// @brief Compares two Query instances. -/// -/// Two Query instances on the same database, in the same location, with the -/// same parameters (OrderBy*, StartAt, EndAt, EqualTo, Limit*) are considered -/// equivalent. -/// -/// Equivalent Queries have a shared pool of ValueListeners and -/// ChildListeners. When listeners are added or removed from one Query -/// instance, it affects all equivalent Query instances. -/// -/// @param[in] lhs The Query to compare against. -/// @param[in] rhs The Query to compare against. -/// -/// @returns True if the Query instances have the same database, the same -/// path, and the same parameters, determined by StartAt(), EndAt(), -/// EqualTo(), and the OrderBy and LimitTo methods. False otherwise. -bool operator==(const Query& lhs, const Query& rhs); - -} // namespace database -} // namespace firebase - -#endif // FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_QUERY_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/database/transaction.h b/packages/firebase_core/firebase_core/firebase_core/firebase/database/transaction.h deleted file mode 100644 index cb2dd33c59e2..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/database/transaction.h +++ /dev/null @@ -1,102 +0,0 @@ -// Copyright 2016 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_TRANSACTION_H_ -#define FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_TRANSACTION_H_ - -#include "firebase/database/common.h" -#include "firebase/database/data_snapshot.h" -#include "firebase/database/mutable_data.h" -#include "firebase/internal/common.h" -#include "firebase/variant.h" - -#if defined(FIREBASE_USE_STD_FUNCTION) -#include -#endif // defined(FIREBASE_USE_STD_FUNCTION) - -namespace firebase { -namespace database { - -/// Specifies whether the transaction succeeded or not. -enum TransactionResult { - /// The transaction was successful, the MutableData was updated. - kTransactionResultSuccess, - /// The transaction did not succeed. Any changes to the MutableData - /// will be discarded. - kTransactionResultAbort, -}; - -/// Your own transaction handler, which the Firebase Realtime Database library -/// may call multiple times to apply changes to the data, and should return -/// success or failure depending on whether it succeeds. - -/// @note This version of the callback is no longer supported (unless you are -/// building for Android with stlport). You should use either one of -/// DoTransactionWithContext (a simple function pointer that accepts context -/// data) or DoTransactionFunction (based on std::function). -/// -/// @see DoTransactionWithContext for more information. -typedef TransactionResult (*DoTransaction)(MutableData* data); - -/// Your own transaction handler, which the Firebase Realtime Database library -/// may call multiple times to apply changes to the data, and should return -/// success or failure depending on whether it succeeds. The context you -/// specified to RunTransaction will be passed into this call. -/// -/// This function will be called, _possibly multiple times_, with the current -/// data at this location. The function is responsible for inspecting that data -/// and modifying it as desired, then returning a TransactionResult specifying -/// either that the MutableData was modified to a desired new state, or that the -/// transaction should be aborted. Whenever this function is called, the -/// MutableData passed in must be modified from scratch. -/// -/// Since this function may be called repeatedly for the same transaction, be -/// extremely careful of any side effects that may be triggered by this -/// function. In addition, this function is called from within the Firebase -/// Realtime Database library's run loop, so care is also required when -/// accessing data that may be in use by other threads in your application. -/// -/// Best practices for this function are to ONLY rely on the data passed in. -/// -/// @param[in] data Mutable data, which the callback can edit. -/// @param[in] context Context pointer, passed verbatim to the callback. -/// -/// @returns The callback should return kTransactionResultSuccess if the data -/// was modified, or kTransactionResultAbort if it was unable to modify the -/// data. If the callback returns kTransactionResultAbort, the RunTransaction() -/// call will return the kErrorTransactionAbortedByUser error code. -/// -/// @note If you want a callback to be triggered when the transaction is -/// finished, you can use the Future value returned by the method -/// running the transaction, and call Future::OnCompletion() to register a -/// callback to be called when the transaction either succeeds or fails. -/// -/// @see DoTransaction for more information. -typedef TransactionResult (*DoTransactionWithContext)(MutableData* data, - void* context); - -#if defined(FIREBASE_USE_STD_FUNCTION) || defined(DOXYGEN) -/// Your own transaction handler function or lambda, which the Firebase Realtime -/// Database library may call multiple times to apply changes to the data, and -/// should return success or failure depending on whether it succeeds. -/// -/// @see DoTransactionWithContext for more information. -typedef std::function - DoTransactionFunction; -#endif // defined(FIREBASE_USE_STD_FUNCTION) || defined(DOXYGEN) - -} // namespace database -} // namespace firebase - -#endif // FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_TRANSACTION_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/dynamic_links.h b/packages/firebase_core/firebase_core/firebase_core/firebase/dynamic_links.h deleted file mode 100644 index 7a96de679f62..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/dynamic_links.h +++ /dev/null @@ -1,117 +0,0 @@ -// Copyright 2017 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef FIREBASE_DYNAMIC_LINKS_SRC_INCLUDE_FIREBASE_DYNAMIC_LINKS_H_ -#define FIREBASE_DYNAMIC_LINKS_SRC_INCLUDE_FIREBASE_DYNAMIC_LINKS_H_ - -#include - -#include "firebase/app.h" -#include "firebase/internal/common.h" - -#if !defined(DOXYGEN) && !defined(SWIG) -FIREBASE_APP_REGISTER_CALLBACKS_REFERENCE(dynamic_links) -#endif // !defined(DOXYGEN) && !defined(SWIG) - -namespace firebase { - -/// @brief Firebase Dynamic Links API. -/// -/// Firebase Dynamic Links is a cross-platform solution for generating and -/// receiving links, whether or not the app is already installed. -namespace dynamic_links { - -#ifndef SWIG -/// @brief Error code used by Futures returned by this API. -enum ErrorCode { - kErrorCodeSuccess = 0, - kErrorCodeFailed, -}; -#endif // SWIG - -/// @brief Enum describing the strength of a dynamic links match. -/// -/// This version is local to dynamic links; there is a similar enum in invites -/// and another internal version in app. -enum LinkMatchStrength { - /// No match has been achieved - kLinkMatchStrengthNoMatch = 0, - - /// The match between the Dynamic Link and device is not perfect. You should - /// not reveal any personal information related to the Dynamic Link. - kLinkMatchStrengthWeakMatch, - - /// The match between the Dynamic Link and this device has a high confidence, - /// but there is a small possibility of error. - kLinkMatchStrengthStrongMatch, - - /// The match between the Dynamic Link and the device is exact. You may - /// safely reveal any personal information related to this Dynamic Link. - kLinkMatchStrengthPerfectMatch -}; - -/// @brief The received Dynamic Link. -struct DynamicLink { - /// The URL that was passed to the app. - std::string url; - /// The match strength of the dynamic link. - LinkMatchStrength match_strength; -}; - -/// @brief Base class used to receive Dynamic Links. -class Listener { - public: - virtual ~Listener(); - - /// Called on the client when a dynamic link arrives. - /// - /// @param[in] dynamic_link The data describing the Dynamic Link. - virtual void OnDynamicLinkReceived(const DynamicLink* dynamic_link) = 0; -}; - -/// @brief Initialize Firebase Dynamic Links. -/// -/// After Initialize is called, the implementation may call functions on the -/// Listener provided at any time. -/// -/// @param[in] app The Firebase App object for this application. -/// @param[in] listener A Listener object that receives Dynamic Links. -/// -/// @return kInitResultSuccess if initialization succeeded, or -/// kInitResultFailedMissingDependency on Android if Google Play services is -/// not available on the current device. -InitResult Initialize(const App& app, Listener* listener); - -/// @brief Terminate Firebase Dynamic Links. -void Terminate(); - -/// @brief Set the listener for receiving Dynamic Links. -/// -/// @param[in] listener A Listener object that receives Dynamic Links. -/// -/// @return Pointer to the previously set listener. -Listener* SetListener(Listener* listener); - -/// Fetch any pending dynamic links. Each pending link will trigger a call to -/// the registered Listener class. -/// -/// This function is implicitly called on initialization. On iOS this is called -/// automatically when the app gains focus, but on Android this needs to be -/// called manually. -void Fetch(); - -} // namespace dynamic_links -} // namespace firebase - -#endif // FIREBASE_DYNAMIC_LINKS_SRC_INCLUDE_FIREBASE_DYNAMIC_LINKS_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/dynamic_links/components.h b/packages/firebase_core/firebase_core/firebase_core/firebase/dynamic_links/components.h deleted file mode 100644 index 7a8e8fa1a44b..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/dynamic_links/components.h +++ /dev/null @@ -1,336 +0,0 @@ -// Copyright 2017 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef FIREBASE_DYNAMIC_LINKS_SRC_INCLUDE_FIREBASE_DYNAMIC_LINKS_COMPONENTS_H_ -#define FIREBASE_DYNAMIC_LINKS_SRC_INCLUDE_FIREBASE_DYNAMIC_LINKS_COMPONENTS_H_ - -#include -#include -#include - -#include "firebase/future.h" - -namespace firebase { - -namespace dynamic_links { - -/// @brief Google Analytics Parameters. -/// -/// Note that the strings used by the struct are not copied, as so must -/// either be statically allocated, or must persist in memory until the -/// DynamicLinkComponents that uses them goes out of scope. -struct GoogleAnalyticsParameters { - /// Constructs an empty set of Google Analytics parameters. - GoogleAnalyticsParameters() - : source(nullptr), - medium(nullptr), - campaign(nullptr), - term(nullptr), - content(nullptr) {} - - /// The campaign source; used to identify a search engine, newsletter, - /// or other source. - const char* source; - /// The campaign medium; used to identify a medium such as email or - /// cost-per-click (cpc). - const char* medium; - /// The campaign name; The individual campaign name, slogan, promo code, etc. - /// for a product. - const char* campaign; - /// The campaign term; used with paid search to supply the keywords for ads. - const char* term; - /// The campaign content; used for A/B testing and content-targeted ads to - /// differentiate ads or links that point to the same URL. - const char* content; -}; - -/// @brief iOS Parameters. -/// -/// Note that the strings used by the struct are not copied, as so must -/// either be statically allocated, or must persist in memory until the -/// DynamicLinkComponents that uses them goes out of scope. -struct IOSParameters { - /// Constructs a set of IOS parameters with the given bundle id. - /// - /// @param bundle_id_ The parameters ID of the iOS app to use to open the - /// link. - IOSParameters(const char* bundle_id_) - : bundle_id(bundle_id_), - fallback_url(nullptr), - custom_scheme(nullptr), - ipad_fallback_url(nullptr), - ipad_bundle_id(nullptr), - app_store_id(nullptr), - minimum_version(nullptr) {} - - /// Constructs an empty set of IOS parameters. - IOSParameters() - : bundle_id(nullptr), - fallback_url(nullptr), - custom_scheme(nullptr), - ipad_fallback_url(nullptr), - ipad_bundle_id(nullptr), - app_store_id(nullptr), - minimum_version(nullptr) {} - - /// The parameters ID of the iOS app to use to open the link. The app must be - /// connected to your project from the Overview page of the Firebase console. - /// Note this field is required. - const char* bundle_id; - /// The link to open on iOS if the app is not installed. - /// - /// Specify this to do something other than install your app from the - /// App Store when the app isn't installed, such as open the mobile - /// web version of the content, or display a promotional page for your app. - const char* fallback_url; - /// The app's custom URL scheme, if defined to be something other than your - /// app's parameters ID. - const char* custom_scheme; - /// The link to open on iPad if the app is not installed. - /// - /// Overrides fallback_url when on iPad. - const char* ipad_fallback_url; - /// The iPad parameters ID of the app. - const char* ipad_bundle_id; - /// The App Store ID, used to send users to the App Store when the app isn't - /// installed. - const char* app_store_id; - /// The minimum version of your app that can open the link. - const char* minimum_version; -}; - -/// @brief iTunes Connect App Analytics Parameters. -/// -/// Note that the strings used by the struct are not copied, as so must -/// either be statically allocated, or must persist in memory until the -/// DynamicLinkComponents that uses them goes out of scope. -struct ITunesConnectAnalyticsParameters { - /// Constructs an empty set of ITunes Connect Analytics parameters. - ITunesConnectAnalyticsParameters() - : provider_token(nullptr), - affiliate_token(nullptr), - campaign_token(nullptr) {} - - /// The provider token that enables analytics for Dynamic Links from - /// within iTunes Connect. - const char* provider_token; - /// The affiliate token used to create affiliate-coded links. - const char* affiliate_token; - /// The campaign token that developers can add to any link in order to - /// track sales from a specific marketing campaign. - const char* campaign_token; -}; - -/// @brief Android Parameters. -/// -/// Note that the strings used by the struct are not copied, as so must -/// either be statically allocated, or must persist in memory until the -/// DynamicLinkComponents that uses them goes out of scope. -struct AndroidParameters { - /// Constructs a set of Android parameters with the given package name. - /// - /// The package name of the Android app to use to open the link. - AndroidParameters(const char* package_name_) - : package_name(package_name_), - fallback_url(nullptr), - minimum_version(0) {} - - /// Constructs an empty set of Android parameters. - AndroidParameters() - : package_name(nullptr), fallback_url(nullptr), minimum_version(0) {} - - /// The package name of the Android app to use to open the link. The app - /// must be connected to your project from the Overview page of the Firebase - /// console. - /// Note this field is required. - const char* package_name; - /// The link to open when the app isn't installed. - /// - /// Specify this to do something other than install your app from the - /// Play Store when the app isn't installed, such as open the mobile web - /// version of the content, or display a promotional page for your app. - const char* fallback_url; - /// The versionCode of the minimum version of your app that can open the link. - int minimum_version; -}; - -/// @brief Social meta-tag Parameters. -/// -/// Note that the strings used by the struct are not copied, as so must -/// either be statically allocated, or must persist in memory until the -/// DynamicLinkComponents that uses them goes out of scope. -struct SocialMetaTagParameters { - /// Constructs an empty set of Social meta-tag parameters. - SocialMetaTagParameters() - : title(nullptr), description(nullptr), image_url(nullptr) {} - - /// The title to use when the Dynamic Link is shared in a social post. - const char* title; - /// The description to use when the Dynamic Link is shared in a social post. - const char* description; - /// The URL to an image related to this link. - const char* image_url; -}; - -/// @brief The desired path length for shortened Dynamic Link URLs. -enum PathLength { - /// Uses the server-default for the path length. - /// See https://goo.gl/8yDAqC for more information. - kPathLengthDefault = 0, - /// Typical short link for non-sensitive links. - kPathLengthShort, - /// Short link that uses a very long path to make it more difficult to - /// guess. Useful for sensitive links. - kPathLengthUnguessable, -}; - -/// @brief Additional options for Dynamic Link creation. -struct DynamicLinkOptions { - /// Constructs an empty set of Dynamic Link options. - DynamicLinkOptions() : path_length(kPathLengthDefault) {} - - /// The desired path length for shortened Dynamic Link URLs. - PathLength path_length; -}; - -/// @brief The returned value from creating a Dynamic Link. -struct GeneratedDynamicLink { - /// The Dynamic Link value. - std::string url; - /// Information about potential warnings on link creation. - /// - /// Usually presence of warnings means parameter format errors, parameter - /// value errors, or missing parameters. - std::vector warnings; - /// If non-empty, the cause of the Dynamic Link generation failure. - std::string error; -}; - -/// @brief The information needed to generate a Dynamic Link. -/// -/// Note that the strings used by the struct are not copied, as so must -/// either be statically allocated, or must persist in memory until this -/// struct goes out of scope. -struct DynamicLinkComponents { - /// The link your app will open. - /// You can specify any URL your app can handle, such as a link to your - /// app's content, or a URL that initiates some - /// app-specific logic such as crediting the user with a coupon, or - /// displaying a specific welcome screen. This link must be a well-formatted - /// URL, be properly URL-encoded, and use the HTTP or HTTPS scheme. - /// Note, this field is required. - const char* link; - /// The domain (of the form "https://xyz.app.goo.gl") to use for this Dynamic - /// Link. You can find this value in the Dynamic Links section of the Firebase - /// console. - /// - /// If you have set up custom domains on your project, set this to your - /// project's custom domain as listed in the Firebase console. - /// - /// Only https:// links are supported. - /// - /// Note, this field is required. - const char* domain_uri_prefix; - /// The Google Analytics parameters. - GoogleAnalyticsParameters* google_analytics_parameters; - /// The iOS parameters. - IOSParameters* ios_parameters; - /// The iTunes Connect App Analytics parameters. - ITunesConnectAnalyticsParameters* itunes_connect_analytics_parameters; - /// The Android parameters. - AndroidParameters* android_parameters; - /// The social meta-tag parameters. - SocialMetaTagParameters* social_meta_tag_parameters; - - /// Default constructor, initializes all fields to null. - DynamicLinkComponents() - : link(nullptr), - domain_uri_prefix(nullptr), - google_analytics_parameters(nullptr), - ios_parameters(nullptr), - itunes_connect_analytics_parameters(nullptr), - android_parameters(nullptr), - social_meta_tag_parameters(nullptr) {} - - /// Constructor that initializes with the given link and domain. - /// - /// @param link_ The link your app will open. - /// @param domain_uri_prefix_ The domain (of the form - /// "https://xyz.app.goo.gl") to use for this Dynamic Link. You can find this - /// value in the Dynamic Links section of the Firebase console. If you have - /// set up custom domains on your project, set this to your project's custom - /// domain as listed in the Firebase console. Note: If you do not specify - /// "https://" as the URI scheme, it will be added. - DynamicLinkComponents(const char* link_, const char* domain_uri_prefix_) - : link(link_), - domain_uri_prefix(domain_uri_prefix_), - google_analytics_parameters(nullptr), - ios_parameters(nullptr), - itunes_connect_analytics_parameters(nullptr), - android_parameters(nullptr), - social_meta_tag_parameters(nullptr) { - // For backwards compatibility with dynamic_link_domain, if - // domain_uri_prefix doesn't start with "https://", add it. - static const char kHttpsPrefix[] = "https://"; - static const size_t kHttpsPrefixLength = sizeof(kHttpsPrefix) - 1; - if (strncmp(domain_uri_prefix, kHttpsPrefix, kHttpsPrefixLength) != 0) { - domain_uri_prefix_with_scheme = - std::string(kHttpsPrefix) + domain_uri_prefix; - domain_uri_prefix = domain_uri_prefix_with_scheme.c_str(); - } - } - -#ifndef INTERNAL_EXPERIMENTAL - - private: -#endif // INTERNAL_EXPERIMENTAL - std::string domain_uri_prefix_with_scheme; -}; - -/// Creates a long Dynamic Link from the given parameters. -GeneratedDynamicLink GetLongLink(const DynamicLinkComponents& components); - -/// Creates a shortened Dynamic Link from the given parameters. -/// @param components: Settings used to configure the behavior for the link. -Future GetShortLink( - const DynamicLinkComponents& components); - -/// Creates a shortened Dynamic Link from the given parameters. -/// @param components: Settings used to configure the behavior for the link. -/// @param options: Additional options for Dynamic Link shortening, indicating -/// whether or not to produce an unguessable or shortest possible link. -/// No references to the options object will be retained after the call. -Future GetShortLink( - const DynamicLinkComponents& components, const DynamicLinkOptions& options); - -/// Creates a shortened Dynamic Link from a given long Dynamic Link. -/// @param long_dynamic_link A link previously generated from GetLongLink. -Future GetShortLink(const char* long_dynamic_link); - -/// Creates a shortened Dynamic Link from a given long Dynamic Link. -/// @param long_dynamic_link: A link previously generated from GetLongLink. -/// @param options: Additional options for Dynamic Link shortening, indicating -/// whether or not to produce an unguessable or shortest possible link. -/// No references to the options object will be retained after the call. -Future GetShortLink(const char* long_dynamic_link, - const DynamicLinkOptions& options); - -/// Get the (possibly still pending) results of the most recent GetShortUrl -/// call. -Future GetShortLinkLastResult(); - -} // namespace dynamic_links -} // namespace firebase - -#endif // FIREBASE_DYNAMIC_LINKS_SRC_INCLUDE_FIREBASE_DYNAMIC_LINKS_COMPONENTS_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore.h deleted file mode 100644 index c35de11b4d1a..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore.h +++ /dev/null @@ -1,458 +0,0 @@ -/* - * Copyright 2018 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_H_ -#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_H_ - -#include -#include - -#include "firebase/internal/common.h" - -#include "firebase/app.h" -#include "firebase/future.h" -#include "firebase/log.h" -// Include *all* the public headers to make sure including just "firestore.h" is -// sufficient for users. -#include "firebase/firestore/collection_reference.h" -#include "firebase/firestore/document_change.h" -#include "firebase/firestore/document_reference.h" -#include "firebase/firestore/document_snapshot.h" -#include "firebase/firestore/field_path.h" -#include "firebase/firestore/field_value.h" -#include "firebase/firestore/firestore_errors.h" -#include "firebase/firestore/geo_point.h" -#include "firebase/firestore/listener_registration.h" -#include "firebase/firestore/load_bundle_task_progress.h" -#include "firebase/firestore/map_field_value.h" -#include "firebase/firestore/metadata_changes.h" -#include "firebase/firestore/query.h" -#include "firebase/firestore/query_snapshot.h" -#include "firebase/firestore/set_options.h" -#include "firebase/firestore/settings.h" -#include "firebase/firestore/snapshot_metadata.h" -#include "firebase/firestore/source.h" -#include "firebase/firestore/timestamp.h" -#include "firebase/firestore/transaction.h" -#include "firebase/firestore/transaction_options.h" -#include "firebase/firestore/write_batch.h" - -namespace firebase { -/** - * @brief Cloud Firestore API. - * - * Cloud Firestore is a flexible, scalable database for mobile, web, and server - * development from Firebase and Google Cloud Platform. - */ -namespace firestore { - -class FirestoreInternal; - -namespace csharp { - -class ApiHeaders; -class TransactionManager; - -} // namespace csharp - -/** - * @brief Entry point for the Firebase Firestore C++ SDK. - * - * To use the SDK, call firebase::firestore::Firestore::GetInstance() to obtain - * an instance of Firestore, then use Collection() or Document() to obtain - * references to child paths within the database. From there, you can set data - * via CollectionReference::Add() and DocumentReference::Set(), or get data via - * CollectionReference::Get() and DocumentReference::Get(), attach listeners, - * and more. - * - * @note Firestore classes are not meant to be subclassed except for use in test - * mocks. Subclassing is not supported in production code and new SDK releases - * may break code that does so. - */ -class Firestore { - public: - /** - * @brief Returns an instance of Firestore corresponding to the given App. - * - * Firebase Firestore uses firebase::App to communicate with Firebase - * Authentication to authenticate users to the Firestore server backend. - * - * If you call GetInstance() multiple times with the same App, you will get - * the same instance of Firestore. - * - * @param[in] app Your instance of firebase::App. Firebase Firestore will use - * this to communicate with Firebase Authentication. - * @param[out] init_result_out If provided, the initialization result will be - * written here. Will be set to firebase::kInitResultSuccess if initialization - * succeeded, or firebase::kInitResultFailedMissingDependency on Android if - * Google Play services is not available on the current device. - * - * @return An instance of Firestore corresponding to the given App. - */ - static Firestore* GetInstance(::firebase::App* app, - InitResult* init_result_out = nullptr); - - /** - * @brief Returns an instance of Firestore corresponding to the default App. - * - * Firebase Firestore uses the default App to communicate with Firebase - * Authentication to authenticate users to the Firestore server backend. - * - * If you call GetInstance() multiple times, you will get the same instance. - * - * @param[out] init_result_out If provided, the initialization result will be - * written here. Will be set to firebase::kInitResultSuccess if initialization - * succeeded, or firebase::kInitResultFailedMissingDependency on Android if - * Google Play services is not available on the current device. - * - * @return An instance of Firestore corresponding to the default App. - */ - static Firestore* GetInstance(InitResult* init_result_out = nullptr); - - /** - * @brief Destructor for the Firestore object. - * - * When deleted, this instance will be removed from the cache of Firestore - * objects. If you call GetInstance() in the future with the same App, a new - * Firestore instance will be created. - */ - virtual ~Firestore(); - - /** - * Deleted copy constructor; Firestore must be created with - * Firestore::GetInstance(). - */ - Firestore(const Firestore& src) = delete; - - /** - * Deleted copy assignment operator; Firestore must be created with - * Firestore::GetInstance(). - */ - Firestore& operator=(const Firestore& src) = delete; - - /** - * @brief Returns the firebase::App that this Firestore was created with. - * - * @return The firebase::App this Firestore was created with. - */ - virtual const App* app() const; - - /** - * @brief Returns the firebase::App that this Firestore was created with. - * - * @return The firebase::App this Firestore was created with. - */ - virtual App* app(); - - /** - * @brief Returns a CollectionReference instance that refers to the - * collection at the specified path within the database. - * - * @param[in] collection_path A slash-separated path to a collection. - * - * @return The CollectionReference instance. - */ - virtual CollectionReference Collection(const char* collection_path) const; - - /** - * @brief Returns a CollectionReference instance that refers to the - * collection at the specified path within the database. - * - * @param[in] collection_path A slash-separated path to a collection. - * - * @return The CollectionReference instance. - */ - virtual CollectionReference Collection( - const std::string& collection_path) const; - - /** - * @brief Returns a DocumentReference instance that refers to the document at - * the specified path within the database. - * - * @param[in] document_path A slash-separated path to a document. - * @return The DocumentReference instance. - */ - virtual DocumentReference Document(const char* document_path) const; - - /** - * @brief Returns a DocumentReference instance that refers to the document at - * the specified path within the database. - * - * @param[in] document_path A slash-separated path to a document. - * - * @return The DocumentReference instance. - */ - virtual DocumentReference Document(const std::string& document_path) const; - - /** - * @brief Returns a Query instance that includes all documents in the - * database that are contained in a collection or subcollection with the - * given collection_id. - * - * @param[in] collection_id Identifies the collections to query over. Every - * collection or subcollection with this ID as the last segment of its path - * will be included. Cannot contain a slash. - * - * @return The Query instance. - */ - virtual Query CollectionGroup(const char* collection_id) const; - - /** - * @brief Returns a Query instance that includes all documents in the - * database that are contained in a collection or subcollection with the - * given collection_id. - * - * @param[in] collection_id Identifies the collections to query over. Every - * collection or subcollection with this ID as the last segment of its path - * will be included. Cannot contain a slash. - * - * @return The Query instance. - */ - virtual Query CollectionGroup(const std::string& collection_id) const; - - /** Returns the settings used by this Firestore object. */ - virtual Settings settings() const; - - /** Sets any custom settings used to configure this Firestore object. */ - virtual void set_settings(Settings settings); - - /** - * Creates a write batch, used for performing multiple writes as a single - * atomic operation. - * - * Unlike transactions, write batches are persisted offline and therefore are - * preferable when you don't need to condition your writes on read data. - * - * @return The created WriteBatch object. - */ - virtual WriteBatch batch() const; - - /** - * Executes the given update and then attempts to commit the changes applied - * within the transaction. If any document read within the transaction has - * changed, the update function will be retried. If it fails to commit after - * 5 attempts, the transaction will fail. - * - * @param update function or lambda to execute within the transaction context. - * The string reference parameter can be used to set the error message. - * - * @return A Future that will be resolved when the transaction finishes. - */ - virtual Future RunTransaction( - std::function update); - - /** - * Executes the given update and then attempts to commit the changes applied - * within the transaction. If any document read within the transaction has - * changed, the update function will be retried. If it fails to commit after - * the `max_attempts` specified in the given `TransactionOptions`, the - * transaction will fail. - * - * @param options The transaction options for controlling execution. - * @param update function or lambda to execute within the transaction context. - * The string reference parameter can be used to set the error message. - * - * @return A Future that will be resolved when the transaction finishes. - */ - virtual Future RunTransaction( - TransactionOptions options, - std::function update); - - /** - * Sets the log verbosity of all Firestore instances. - * - * The default verbosity level is `kLogLevelInfo`. - * - * @param[in] log_level The desired verbosity. - */ - static void set_log_level(LogLevel log_level); - - /** - * Disables network access for this instance. While the network is disabled, - * any snapshot listeners or Get() calls will return results from cache, and - * any write operations will be queued until network usage is re-enabled via a - * call to EnableNetwork(). - * - * If the network was already disabled, calling `DisableNetwork()` again is - * a no-op. - */ - virtual Future DisableNetwork(); - - /** - * Re-enables network usage for this instance after a prior call to - * DisableNetwork(). - * - * If the network is currently enabled, calling `EnableNetwork()` is a no-op. - */ - virtual Future EnableNetwork(); - - /** - * Terminates this `Firestore` instance. - * - * After calling `Terminate()`, only the `ClearPersistence()` method may be - * used. Calling any other methods will result in an error. - * - * To restart after termination, simply create a new instance of `Firestore` - * with `Firestore::GetInstance()`. - * - * `Terminate()` does not cancel any pending writes and any tasks that are - * awaiting a response from the server will not be resolved. The next time you - * start this instance, it will resume attempting to send these writes to the - * server. - * - * Note: under normal circumstances, calling `Terminate()` is not required. - * This method is useful only when you want to force this instance to release - * all of its resources or in combination with `ClearPersistence()` to ensure - * that all local state is destroyed between test runs. - * - * @return A `Future` that is resolved when the instance has been successfully - * terminated. - */ - virtual Future Terminate(); - - /** - * Waits until all currently pending writes for the active user have been - * acknowledged by the backend. - * - * The returned future is resolved immediately without error if there are no - * outstanding writes. Otherwise, the future is resolved when all previously - * issued writes (including those written in a previous app session) have been - * acknowledged by the backend. The future does not wait for writes that were - * added after the method is called. If you wish to wait for additional - * writes, you have to call `WaitForPendingWrites` again. - * - * Any outstanding `WaitForPendingWrites` futures are resolved with an - * error during user change. - */ - virtual Future WaitForPendingWrites(); - - /** - * Clears the persistent storage. This includes pending writes and cached - * documents. - * - * Must be called while the Firestore instance is not started (after the app - * is shut down or when the app is first initialized). On startup, this method - * must be called before other methods (other than `settings()` and - * `set_settings()`). If the Firestore instance is still running, the function - * will complete with an error code of `FailedPrecondition`. - * - * Note: `ClearPersistence()` is primarily intended to help write - * reliable tests that use Firestore. It uses the most efficient mechanism - * possible for dropping existing data but does not attempt to securely - * overwrite or otherwise make cached data unrecoverable. For applications - * that are sensitive to the disclosure of cache data in between user sessions - * we strongly recommend not to enable persistence in the first place. - */ - virtual Future ClearPersistence(); - - /** - * Attaches a listener for a snapshots-in-sync event. Server-generated - * updates and local changes can affect multiple snapshot listeners. - * The snapshots-in-sync event indicates that all listeners affected by - * a given change have fired. - * - * NOTE: The snapshots-in-sync event only indicates that listeners are - * in sync with each other, but does not relate to whether those - * snapshots are in sync with the server. Use `SnapshotMetadata` in the - * individual listeners to determine if a snapshot is from the cache or - * the server. - * - * @param callback A callback to be called every time all snapshot - * listeners are in sync with each other. - * @return A `ListenerRegistration` object that can be used to remove the - * listener. - */ - virtual ListenerRegistration AddSnapshotsInSyncListener( - std::function callback); - - /** - * Loads a Firestore bundle into the local cache. - * - * @param bundle A string containing the bundle to be loaded. - * @return A `Future` that is resolved when the loading is either completed - * or aborted due to an error. - */ - virtual Future LoadBundle(const std::string& bundle); - - /** - * Loads a Firestore bundle into the local cache, with the provided callback - * executed for progress updates. - * - * @param bundle A string containing the bundle to be loaded. - * @param progress_callback A callback that is called with progress - * updates, and completion or error updates. - * @return A `Future` that is resolved when the loading is either completed - * or aborted due to an error. - */ - virtual Future LoadBundle( - const std::string& bundle, - std::function progress_callback); - - /** - * Reads a Firestore `Query` from the local cache, identified by the given - * name. - * - * Named queries are packaged into bundles on the server side (along with the - * resulting documents) and loaded into local cache using `LoadBundle`. Once - * in the local cache, you can use this method to extract a query by name. - * - * If a query cannot be found, the returned future will complete with its - * `error()` set to a non-zero error code. - * - * @param query_name The name of the query to read from saved bundles. - */ - virtual Future NamedQuery(const std::string& query_name); - - protected: - /** - * Default constructor, to be used only for mocking `Firestore`. - */ - Firestore() = default; - - private: - friend class FieldValueInternal; - friend class FirestoreInternal; - friend class Wrapper; - friend struct ConverterImpl; - friend class FirestoreIntegrationTest; - friend class IncludesTest; - template - friend struct CleanupFn; - - friend class csharp::ApiHeaders; - friend class csharp::TransactionManager; - - explicit Firestore(::firebase::App* app); - explicit Firestore(FirestoreInternal* internal); - - static Firestore* CreateFirestore(::firebase::App* app, - FirestoreInternal* internal, - InitResult* init_result_out); - static Firestore* AddFirestoreToCache(Firestore* firestore, - InitResult* init_result_out); - - static void SetClientLanguage(const std::string& language_token); - - // Delete the internal_ data. - void DeleteInternal(); - - mutable FirestoreInternal* internal_ = nullptr; -}; - -} // namespace firestore -} // namespace firebase - -#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/collection_reference.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/collection_reference.h deleted file mode 100644 index 3d9d4de2ee7f..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/collection_reference.h +++ /dev/null @@ -1,183 +0,0 @@ -/* - * Copyright 2018 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_COLLECTION_REFERENCE_H_ -#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_COLLECTION_REFERENCE_H_ - -#include - -#include "firebase/firestore/map_field_value.h" -#include "firebase/firestore/query.h" - -namespace firebase { - -/// @cond FIREBASE_APP_INTERNAL -template -class Future; -/// @endcond - -namespace firestore { - -class CollectionReferenceInternal; -class DocumentReference; - -/** - * @brief A CollectionReference can be used for adding documents, getting - * document references, and querying for documents (using the methods inherited - * from `Query`). - * - * @note Firestore classes are not meant to be subclassed except for use in test - * mocks. Subclassing is not supported in production code and new SDK releases - * may break code that does so. - */ -class CollectionReference : public Query { - public: - /** - * @brief Creates an invalid CollectionReference that has to be reassigned - * before it can be used. - * - * Calling any member function on an invalid CollectionReference will be - * a no-op. If the function returns a value, it will return a zero, empty, or - * invalid value, depending on the type of the value. - */ - CollectionReference(); - - /** - * @brief Copy constructor. - * - * `CollectionReference` can be efficiently copied because it simply refers to - * a location in the database. - * - * @param[in] other `CollectionReference` to copy from. - */ - CollectionReference(const CollectionReference& other); - - /** - * @brief Move constructor. - * - * Moving is more efficient than copying for a `CollectionReference`. After - * being moved from, a `CollectionReference` is equivalent to its - * default-constructed state. - * - * @param[in] other `CollectionReference` to move data from. - */ - CollectionReference(CollectionReference&& other); - - /** - * @brief Copy assignment operator. - * - * `CollectionReference` can be efficiently copied because it simply refers to - * a location in the database. - * - * @param[in] other `CollectionReference` to copy from. - * - * @return Reference to the destination `CollectionReference`. - */ - CollectionReference& operator=(const CollectionReference& other); - - /** - * @brief Move assignment operator. - * - * Moving is more efficient than copying for a `CollectionReference`. After - * being moved from, a `CollectionReference` is equivalent to its - * default-constructed state. - * - * @param[in] other `CollectionReference` to move data from. - * - * @return Reference to the destination `CollectionReference`. - */ - CollectionReference& operator=(CollectionReference&& other); - - /** - * @brief Gets the ID of the referenced collection. - * - * @return The ID as a std::string. - */ - virtual const std::string& id() const; - - /** - * @brief Returns the path of this collection (relative to the root of the - * database) as a slash-separated string. - * - * @return The path as a std::string. - */ - virtual std::string path() const; - - /** - * @brief Gets a DocumentReference to the document that contains this - * collection. - * - * @return The DocumentReference that contains this collection if this is a - * subcollection. If this is a root collection, returns an invalid - * DocumentReference (`DocumentReference::is_valid()` will return false). - */ - virtual DocumentReference Parent() const; - - /** - * @brief Returns a DocumentReference that points to a new document with an - * auto-generated ID within this collection. - * - * @return A DocumentReference pointing to the new document. - */ - virtual DocumentReference Document() const; - - /** - * @brief Gets a DocumentReference instance that refers to the document at the - * specified path within this collection. - * - * @param[in] document_path A slash-separated relative path to a document. - * The pointer only needs to be valid during this call. - * - * @return The DocumentReference instance. - */ - virtual DocumentReference Document(const char* document_path) const; - - /** - * @brief Gets a DocumentReference instance that refers to the document at the - * specified path within this collection. - * - * @param[in] document_path A slash-separated relative path to a document. - * - * @return The DocumentReference instance. - */ - virtual DocumentReference Document(const std::string& document_path) const; - - /** - * @brief Adds a new document to this collection with the specified data, - * assigning it a document ID automatically. - * - * @param data A map containing the data for the new document. - * - * @return A Future that will be resolved with the DocumentReference of the - * newly created document. - */ - virtual Future Add(const MapFieldValue& data); - - private: - friend class DocumentReference; - friend class DocumentReferenceInternal; - friend class FirestoreInternal; - friend struct ConverterImpl; - - explicit CollectionReference(CollectionReferenceInternal* internal); - - CollectionReferenceInternal* internal() const; -}; - -} // namespace firestore -} // namespace firebase - -#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_COLLECTION_REFERENCE_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/document_change.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/document_change.h deleted file mode 100644 index fbef011d290f..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/document_change.h +++ /dev/null @@ -1,203 +0,0 @@ -/* - * Copyright 2018 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_DOCUMENT_CHANGE_H_ -#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_DOCUMENT_CHANGE_H_ - -#include - -namespace firebase { -namespace firestore { - -class DocumentChangeInternal; -class DocumentSnapshot; - -/** - * @brief A DocumentChange represents a change to the documents matching - * a query. - * - * DocumentChange contains the document affected and the type of change that - * occurred (added, modified, or removed). - * - * @note Firestore classes are not meant to be subclassed except for use in test - * mocks. Subclassing is not supported in production code and new SDK releases - * may break code that does so. - */ -class DocumentChange { - public: - /** - * An enumeration of snapshot diff types. - */ - enum class Type { - /** - * Indicates a new document was added to the set of documents matching the - * query. - */ - kAdded, - - /** - * Indicates a document within the query was modified. - */ - kModified, - - /** - * Indicates a document within the query was removed (either deleted or no - * longer matches the query). - */ - kRemoved, - }; - - /** - * The sentinel index used as a return value to indicate no matches. - */ -#if defined(ANDROID) - // Older NDK (r16b) fails to define this properly. Fix this when support for - // the older NDK is removed. - static const std::size_t npos; -#else - static constexpr std::size_t npos = static_cast(-1); -#endif // defined(ANDROID) - - /** - * @brief Creates an invalid DocumentChange that has to be reassigned before - * it can be used. - * - * Calling any member function on an invalid DocumentChange will be a no-op. - * If the function returns a value, it will return a zero, empty, or invalid - * value, depending on the type of the value. - */ - DocumentChange(); - - /** - * @brief Copy constructor. - * - * `DocumentChange` is immutable and can be efficiently copied (no deep copy - * is performed). - * - * @param[in] other `DocumentChange` to copy from. - */ - DocumentChange(const DocumentChange& other); - - /** - * @brief Move constructor. - * - * Moving is more efficient than copying for a `DocumentChange`. After being - * moved from, a `DocumentChange` is equivalent to its default-constructed - * state. - * - * @param[in] other `DocumentChange` to move data from. - */ - DocumentChange(DocumentChange&& other); - - virtual ~DocumentChange(); - - /** - * @brief Copy assignment operator. - * - * `DocumentChange` is immutable and can be efficiently copied (no deep copy - * is performed). - * - * @param[in] other `DocumentChange` to copy from. - * - * @return Reference to the destination `DocumentChange`. - */ - DocumentChange& operator=(const DocumentChange& other); - - /** - * @brief Move assignment operator. - * - * Moving is more efficient than copying for a `DocumentChange`. After being - * moved from, a `DocumentChange` is equivalent to its default-constructed - * state. - * - * @param[in] other `DocumentChange` to move data from. - * - * @return Reference to the destination `DocumentChange`. - */ - DocumentChange& operator=(DocumentChange&& other); - - /** - * Returns the type of change that occurred (added, modified, or removed). - */ - virtual Type type() const; - - /** - * @brief The document affected by this change. - * - * Returns the newly added or modified document if this DocumentChange is for - * an updated document. Returns the deleted document if this document change - * represents a removal. - */ - virtual DocumentSnapshot document() const; - - /** - * The index of the changed document in the result set immediately prior to - * this DocumentChange (that is, supposing that all prior DocumentChange - * objects have been applied). Returns DocumentChange::npos for 'added' - * events. - */ - virtual std::size_t old_index() const; - - /** - * The index of the changed document in the result set immediately after this - * DocumentChange (that is, supposing that all prior DocumentChange objects - * and the current DocumentChange object have been applied). Returns - * DocumentChange::npos for 'removed' events. - */ - virtual std::size_t new_index() const; - - /** - * @brief Returns true if this `DocumentChange` is valid, false if it is - * not valid. An invalid `DocumentChange` could be the result of: - * - Creating a `DocumentChange` using the default constructor. - * - Moving from the `DocumentChange`. - * - Deleting your Firestore instance, which will invalidate all the - * `DocumentChange` instances associated with it. - * - * @return true if this `DocumentChange` is valid, false if this - * `DocumentChange` is invalid. - */ - bool is_valid() const { return internal_ != nullptr; } - - private: - std::size_t Hash() const; - - friend bool operator==(const DocumentChange& lhs, const DocumentChange& rhs); - friend std::size_t DocumentChangeHash(const DocumentChange& change); - - friend class FirestoreInternal; - friend class Wrapper; - friend struct ConverterImpl; - template - friend struct CleanupFn; - - explicit DocumentChange(DocumentChangeInternal* internal); - - mutable DocumentChangeInternal* internal_ = nullptr; -}; - -/** Checks `lhs` and `rhs` for equality. */ -bool operator==(const DocumentChange& lhs, const DocumentChange& rhs); - -/** Checks `lhs` and `rhs` for inequality. */ -inline bool operator!=(const DocumentChange& lhs, const DocumentChange& rhs) { - return !(lhs == rhs); -} - -} // namespace firestore -} // namespace firebase - -#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_DOCUMENT_CHANGE_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/document_reference.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/document_reference.h deleted file mode 100644 index d0f82cf42d73..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/document_reference.h +++ /dev/null @@ -1,351 +0,0 @@ -/* - * Copyright 2018 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_DOCUMENT_REFERENCE_H_ -#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_DOCUMENT_REFERENCE_H_ - -#include -#include -#include - -#include "firebase/internal/common.h" - -#include "firebase/firestore/firestore_errors.h" -#include "firebase/firestore/map_field_value.h" -#include "firebase/firestore/metadata_changes.h" -#include "firebase/firestore/set_options.h" -#include "firebase/firestore/source.h" - -namespace firebase { - -/// @cond FIREBASE_APP_INTERNAL -template -class Future; -/// @endcond - -namespace firestore { - -class CollectionReference; -class DocumentReferenceInternal; -class DocumentSnapshot; -template -class EventListener; -class Firestore; -class ListenerRegistration; - -/** - * @brief A DocumentReference refers to a document location in a Firestore - * database and can be used to write, read, or listen to the location. - * - * There may or may not exist a document at the referenced location. - * A DocumentReference can also be used to create a CollectionReference to - * a subcollection. - * - * Create a DocumentReference via `Firestore::Document(const std::string& - * path)`. - * - * @note Firestore classes are not meant to be subclassed except for use in test - * mocks. Subclassing is not supported in production code and new SDK releases - * may break code that does so. - */ -class DocumentReference { - public: - /** - * @brief Creates an invalid DocumentReference that has to be reassigned - * before it can be used. - * - * Calling any member function on an invalid DocumentReference will be - * a no-op. If the function returns a value, it will return a zero, empty, or - * invalid value, depending on the type of the value. - */ - DocumentReference(); - - /** - * @brief Copy constructor. - * - * `DocumentReference` can be efficiently copied because it simply refers to - * a location in the database. - * - * @param[in] other `DocumentReference` to copy from. - */ - DocumentReference(const DocumentReference& other); - - /** - * @brief Move constructor. - * - * Moving is more efficient than copying for a `DocumentReference`. After - * being moved from, a `DocumentReference` is equivalent to its - * default-constructed state. - * - * @param[in] other `DocumentReference` to move data from. - */ - DocumentReference(DocumentReference&& other); - - virtual ~DocumentReference(); - - /** - * @brief Copy assignment operator. - * - * `DocumentReference` can be efficiently copied because it simply refers to - * a location in the database. - * - * @param[in] other `DocumentReference` to copy from. - * - * @return Reference to the destination `DocumentReference`. - */ - DocumentReference& operator=(const DocumentReference& other); - - /** - * @brief Move assignment operator. - * - * Moving is more efficient than copying for a `DocumentReference`. After - * being moved from, a `DocumentReference` is equivalent to its - * default-constructed state. - * - * @param[in] other `DocumentReference` to move data from. - * - * @return Reference to the destination `DocumentReference`. - */ - DocumentReference& operator=(DocumentReference&& other); - - /** - * @brief Returns the Firestore instance associated with this document - * reference. - * - * The pointer will remain valid indefinitely. - * - * @return Firebase Firestore instance that this DocumentReference refers to. - */ - virtual const Firestore* firestore() const; - - /** - * @brief Returns the Firestore instance associated with this document - * reference. - * - * The pointer will remain valid indefinitely. - * - * @return Firebase Firestore instance that this DocumentReference refers to. - */ - virtual Firestore* firestore(); - - /** - * @brief Returns the string ID of this document location. - * - * @return String ID of this document location. - */ - virtual const std::string& id() const; - - /** - * @brief Returns the path of this document (relative to the root of the - * database) as a slash-separated string. - * - * @return String path of this document location. - */ - virtual std::string path() const; - - /** - * @brief Returns a CollectionReference to the collection that contains this - * document. - */ - virtual CollectionReference Parent() const; - - /** - * @brief Returns a CollectionReference instance that refers to the - * subcollection at the specified path relative to this document. - * - * @param[in] collection_path A slash-separated relative path to a - * subcollection. The pointer only needs to be valid during this call. - * - * @return The CollectionReference instance. - */ - virtual CollectionReference Collection(const char* collection_path) const; - - /** - * @brief Returns a CollectionReference instance that refers to the - * subcollection at the specified path relative to this document. - * - * @param[in] collection_path A slash-separated relative path to a - * subcollection. - * - * @return The CollectionReference instance. - */ - virtual CollectionReference Collection( - const std::string& collection_path) const; - - /** - * @brief Reads the document referenced by this DocumentReference. - * - * By default, Get() attempts to provide up-to-date data when possible by - * waiting for data from the server, but it may return cached data or fail if - * you are offline and the server cannot be reached. This behavior can be - * altered via the Source parameter. - * - * @param[in] source A value to configure the get behavior (optional). - * - * @return A Future that will be resolved with the contents of the Document at - * this DocumentReference. - */ - virtual Future Get(Source source = Source::kDefault) const; - - /** - * @brief Writes to the document referred to by this DocumentReference. - * - * If the document does not yet exist, it will be created. If you pass - * SetOptions, the provided data can be merged into an existing document. - * - * @param[in] data A map of the fields and values to write to the document. - * @param[in] options An object to configure the Set() behavior (optional). - * - * @return A Future that will be resolved when the write finishes. - */ - virtual Future Set(const MapFieldValue& data, - const SetOptions& options = SetOptions()); - - /** - * @brief Updates fields in the document referred to by this - * DocumentReference. - * - * If no document exists yet, the update will fail. - * - * @param[in] data A map of field / value pairs to update. Fields can contain - * dots to reference nested fields within the document. - * - * @return A Future that will be resolved when the client is online and the - * commit has completed against the server. The future will not resolve when - * the device is offline, though local changes will be visible immediately. - */ - virtual Future Update(const MapFieldValue& data); - - /** - * @brief Updates fields in the document referred to by this - * DocumentReference. - * - * If no document exists yet, the update will fail. - * - * @param[in] data A map from FieldPath to FieldValue to update. - * - * @return A Future that will be resolved when the client is online and the - * commit has completed against the server. The future will not resolve when - * the device is offline, though local changes will be visible immediately. - */ - virtual Future Update(const MapFieldPathValue& data); - - /** - * @brief Removes the document referred to by this DocumentReference. - * - * @return A Future that will be resolved when the delete completes. - */ - virtual Future Delete(); - - /** - * @brief Starts listening to the document referenced by this - * DocumentReference. - * - * @param[in] callback The std::function to call. When this function is - * called, snapshot value is valid if and only if error is Error::kErrorOk. - * The std::string is an error message; the value may be empty if an error - * message is not available. - * - * @return A registration object that can be used to remove the listener. - */ - virtual ListenerRegistration AddSnapshotListener( - std::function - callback); - - /** - * @brief Starts listening to the document referenced by this - * DocumentReference. - * - * @param[in] metadata_changes Indicates whether metadata-only changes (that - * is, only DocumentSnapshot::metadata() changed) should trigger snapshot - * events. - * @param[in] callback The std::function to call. When this function is - * called, snapshot value is valid if and only if error is Error::kErrorOk. - * The std::string is an error message; the value may be empty if an error - * message is not available. - * - * @return A registration object that can be used to remove the listener. - */ - virtual ListenerRegistration AddSnapshotListener( - MetadataChanges metadata_changes, - std::function - callback); - - /** - * @brief Returns true if this `DocumentReference` is valid, false if it is - * not valid. An invalid `DocumentReference` could be the result of: - * - Creating a `DocumentReference` using the default constructor. - * - Moving from the `DocumentReference`. - * - Calling `CollectionReference::Parent()` on a `CollectionReference` that - * is not a subcollection. - * - Deleting your Firestore instance, which will invalidate all the - * `DocumentReference` instances associated with it. - * - * @return true if this `DocumentReference` is valid, false if this - * `DocumentReference` is invalid. - */ - bool is_valid() const { return internal_ != nullptr; } - - /** - * Returns a string representation of this `DocumentReference` for - * logging/debugging purposes. - * - * @note the exact string representation is unspecified and subject to - * change; don't rely on the format of the string. - */ - std::string ToString() const; - - /** - * Outputs the string representation of this `DocumentReference` to the given - * stream. - * - * @see `ToString()` for comments on the representation format. - */ - friend std::ostream& operator<<(std::ostream& out, - const DocumentReference& reference); - - private: - friend bool operator==(const DocumentReference& lhs, - const DocumentReference& rhs); - - friend class CollectionReferenceInternal; - friend class DocumentSnapshotInternal; - friend class FieldValueInternal; - friend class FirestoreInternal; - friend class TransactionInternal; - friend class WriteBatchInternal; - friend struct ConverterImpl; - template - friend struct CleanupFn; - - explicit DocumentReference(DocumentReferenceInternal* internal); - - mutable DocumentReferenceInternal* internal_ = nullptr; -}; - -/** Checks `lhs` and `rhs` for equality. */ -bool operator==(const DocumentReference& lhs, const DocumentReference& rhs); - -/** Checks `lhs` and `rhs` for inequality. */ -inline bool operator!=(const DocumentReference& lhs, - const DocumentReference& rhs) { - return !(lhs == rhs); -} - -} // namespace firestore -} // namespace firebase - -#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_DOCUMENT_REFERENCE_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/document_snapshot.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/document_snapshot.h deleted file mode 100644 index 7617eb5d1412..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/document_snapshot.h +++ /dev/null @@ -1,297 +0,0 @@ -/* - * Copyright 2018 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_DOCUMENT_SNAPSHOT_H_ -#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_DOCUMENT_SNAPSHOT_H_ - -#include -#include - -#include "firebase/firestore/map_field_value.h" -#include "firebase/firestore/snapshot_metadata.h" - -namespace firebase { -namespace firestore { - -class DocumentReference; -class DocumentSnapshotInternal; -class FieldPath; -class FieldValue; -class Firestore; - -/** - * @brief A DocumentSnapshot contains data read from a document in your - * Firestore database. - * - * The data can be extracted with the GetData() method, or by using - * Get() to access a specific field. For a DocumentSnapshot that points to - * a non-existing document, any data access will cause a failed assertion. You - * can use the exists() method to explicitly verify a document's existence. - * - * @note Firestore classes are not meant to be subclassed except for use in test - * mocks. Subclassing is not supported in production code and new SDK releases - * may break code that does so. - */ -class DocumentSnapshot { - public: - /** - * Controls the return value for server timestamps that have not yet been set - * to their final value. - */ - enum class ServerTimestampBehavior { - /** - * Return Null for server timestamps that have not yet been set to their - * final value. - */ - kNone = 0, - - /** - * Return local estimates for server timestamps that have not yet been set - * to their final value. This estimate will likely differ from the final - * value and may cause these pending values to change once the server result - * becomes available. - */ - kEstimate, - - /** - * Return the previous value for server timestamps that have not yet been - * set to their final value. - */ - kPrevious, - - /** The default behavior, which is equivalent to specifying kNone. */ - // - // Note, SWIG renaming mechanism doesn't properly handle initializing an - // enum constant with another enum constant (e.g., in expression `kFoo = - // kBar` only `kFoo` will be renamed, leaving `kBar` as is, leading to - // compilation errors). - // - kDefault = 0, - }; - - /** - * @brief Creates an invalid DocumentSnapshot that has to be reassigned before - * it can be used. - * - * Calling any member function on an invalid DocumentSnapshot will be a no-op. - * If the function returns a value, it will return a zero, empty, or invalid - * value, depending on the type of the value. - */ - DocumentSnapshot(); - - /** - * @brief Copy constructor. - * - * `DocumentSnapshot` is immutable and can be efficiently copied (no deep copy - * is performed). - * - * @param[in] other `DocumentSnapshot` to copy from. - */ - DocumentSnapshot(const DocumentSnapshot& other); - - /** - * @brief Move constructor. - * - * Moving is more efficient than copying for a `DocumentSnapshot`. After being - * moved from, a `DocumentSnapshot` is equivalent to its default-constructed - * state. - * - * @param[in] other `DocumentSnapshot` to move data from. - */ - DocumentSnapshot(DocumentSnapshot&& other); - - virtual ~DocumentSnapshot(); - - /** - * @brief Copy assignment operator. - * - * `DocumentSnapshot` is immutable and can be efficiently copied (no deep copy - * is performed). - * - * @param[in] other `DocumentSnapshot` to copy from. - * - * @return Reference to the destination `DocumentSnapshot`. - */ - DocumentSnapshot& operator=(const DocumentSnapshot& other); - - /** - * @brief Move assignment operator. - * - * Moving is more efficient than copying for a `DocumentSnapshot`. After being - * moved from, a `DocumentSnapshot` is equivalent to its default-constructed - * state. - * - * @param[in] other `DocumentSnapshot` to move data from. - * - * @return Reference to the destination `DocumentSnapshot`. - */ - DocumentSnapshot& operator=(DocumentSnapshot&& other); - - /** - * @brief Returns the string ID of the document for which this - * DocumentSnapshot contains data. - * - * @return String ID of this document location. - */ - virtual const std::string& id() const; - - /** - * @brief Returns the document location for which this DocumentSnapshot - * contains data. - * - * @return DocumentReference of this document location. - */ - virtual DocumentReference reference() const; - - /** - * @brief Returns the metadata about this snapshot concerning its source and - * if it has local modifications. - * - * @return SnapshotMetadata about this snapshot. - */ - virtual SnapshotMetadata metadata() const; - - /** - * @brief Explicitly verify a document's existence. - * - * @return True if the document exists in this snapshot. - */ - virtual bool exists() const; - - /** - * @brief Retrieves all fields in the document as a map of FieldValues. - * - * @param stb Configures how server timestamps that have not yet - * been set to their final value are returned from the snapshot (optional). - * - * @return A map containing all fields in the document, or an empty map if the - * document doesn't exist. - */ - virtual MapFieldValue GetData( - ServerTimestampBehavior stb = ServerTimestampBehavior::kDefault) const; - - /** - * @brief Retrieves a specific field from the document. - * - * @param field String ID of the field to retrieve. The pointer only needs to - * be valid during this call. - * @param stb Configures how server timestamps that have not yet been set to - * their final value are returned from the snapshot (optional). - * - * @return The value contained in the field. If the field does not exist in - * the document, then a `FieldValue` instance with `is_valid() == false` will - * be returned. - */ - virtual FieldValue Get( - const char* field, - ServerTimestampBehavior stb = ServerTimestampBehavior::kDefault) const; - - /** - * @brief Retrieves a specific field from the document. - * - * @param field String ID of the field to retrieve. - * @param stb Configures how server timestamps that have not yet been set to - * their final value are returned from the snapshot (optional). - * - * @return The value contained in the field. If the field does not exist in - * the document, then a `FieldValue` instance with `is_valid() == false` will - * be returned. - */ - virtual FieldValue Get( - const std::string& field, - ServerTimestampBehavior stb = ServerTimestampBehavior::kDefault) const; - - /** - * @brief Retrieves a specific field from the document. - * - * @param field Path of the field to retrieve. - * @param stb Configures how server timestamps that have not yet been set to - * their final value are returned from the snapshot (optional). - * - * @return The value contained in the field. If the field does not exist in - * the document, then a `FieldValue` instance with `is_valid() == false` will - * be returned. - */ - virtual FieldValue Get( - const FieldPath& field, - ServerTimestampBehavior stb = ServerTimestampBehavior::kDefault) const; - - /** - * @brief Returns true if this `DocumentSnapshot` is valid, false if it is - * not valid. An invalid `DocumentSnapshot` could be the result of: - * - Creating a `DocumentSnapshot` with the default constructor. - * - Moving from the `DocumentSnapshot`. - * - Deleting your Firestore instance, which will invalidate all the - * `DocumentSnapshot` instances associated with it. - * - * @return true if this `DocumentSnapshot` is valid, false if this - * `DocumentSnapshot` is invalid. - */ - bool is_valid() const { return internal_ != nullptr; } - - /** - * Returns a string representation of this `DocumentSnapshot` for - * logging/debugging purposes. - * - * @note the exact string representation is unspecified and subject to - * change; don't rely on the format of the string. - */ - std::string ToString() const; - - /** - * Outputs the string representation of this `DocumentSnapshot` to the given - * stream. - * - * @see `ToString()` for comments on the representation format. - */ - friend std::ostream& operator<<(std::ostream& out, - const DocumentSnapshot& document); - - private: - std::size_t Hash() const; - - friend bool operator==(const DocumentSnapshot& lhs, - const DocumentSnapshot& rhs); - friend std::size_t DocumentSnapshotHash(const DocumentSnapshot& snapshot); - - friend class DocumentChangeInternal; - friend class EventListenerInternal; - friend class FirestoreInternal; - friend class QueryInternal; - friend class TransactionInternal; - friend class Wrapper; - friend struct ConverterImpl; - template - friend struct CleanupFn; - - explicit DocumentSnapshot(DocumentSnapshotInternal* internal); - - mutable DocumentSnapshotInternal* internal_ = nullptr; -}; - -/** Checks `lhs` and `rhs` for equality. */ -bool operator==(const DocumentSnapshot& lhs, const DocumentSnapshot& rhs); - -/** Checks `lhs` and `rhs` for inequality. */ -inline bool operator!=(const DocumentSnapshot& lhs, - const DocumentSnapshot& rhs) { - return !(lhs == rhs); -} - -} // namespace firestore -} // namespace firebase - -#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_DOCUMENT_SNAPSHOT_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/field_path.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/field_path.h deleted file mode 100644 index d09dec641140..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/field_path.h +++ /dev/null @@ -1,205 +0,0 @@ -/* - * Copyright 2018 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_FIELD_PATH_H_ -#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_FIELD_PATH_H_ - -#include -#include -#include -#include - -namespace firebase { -namespace firestore { - -#if !defined(__ANDROID__) - -namespace model { -class FieldPath; -} // namespace model - -#else - -class FieldPathPortable; - -#endif // !defined(__ANDROID__) - -/** - * @brief A FieldPath refers to a field in a document. - * - * The path may consist of a single field name (referring to a top level field - * in the document) or a list of field names (referring to a nested field in the - * document). - */ -class FieldPath final { - public: - /** - * @brief Creates an invalid FieldPath that has to be reassigned before it can - * be used. - * - * Calling any member function on an invalid FieldPath will be a no-op. If the - * function returns a value, it will return a zero, empty, or invalid value, - * depending on the type of the value. - */ - FieldPath(); - - /** - * Creates a FieldPath from the provided field names. If more than one field - * name is provided, the path will point to a nested field in a document. - * - * @param field_names A list of field names. - */ - FieldPath(std::initializer_list field_names); - - /** - * Creates a FieldPath from the provided field names. If more than one field - * name is provided, the path will point to a nested field in a document. - * - * @param field_names A vector of field names. - */ - FieldPath(const std::vector& field_names); - - /** - * @brief Copy constructor. - * - * This performs a deep copy, creating an independent instance. - * - * @param[in] other `FieldPath` to copy from. - */ - FieldPath(const FieldPath& other); - - /** - * @brief Move constructor. - * - * Moving is more efficient than copying for `FieldPath`. After being moved - * from, `FieldPath` is in a valid but unspecified state. - * - * @param[in] other `FieldPath` to move data from. - */ - FieldPath(FieldPath&& other) noexcept; - - ~FieldPath(); - - /** - * @brief Copy assignment operator. - * - * This performs a deep copy, creating an independent instance. - * - * @param[in] other `FieldPath` to copy from. - * - * @return Reference to the destination `FieldPath`. - */ - FieldPath& operator=(const FieldPath& other); - - /** - * @brief Move assignment operator. - * - * Moving is more efficient than copying for `FieldPath`. After being moved - * from, `FieldPath` is in a valid but unspecified state. - * - * @param[in] other `FieldPath` to move data from. - * - * @return Reference to the destination `FieldPath`. - */ - FieldPath& operator=(FieldPath&& other) noexcept; - - /** - * A special sentinel FieldPath to refer to the ID of a document. It can be - * used in queries to sort or filter by the document ID. - */ - static FieldPath DocumentId(); - - /** - * @brief Returns true if this `FieldPath` is valid, false if it is not valid. - * An invalid `FieldPath` could be the result of: - * - Creating a `FieldPath` using the default constructor. - * - Moving from the `FieldPath`. - * - * @return true if this `FieldPath` is valid, false if this `FieldPath` is - * invalid. - */ - bool is_valid() const { return internal_ != nullptr; } - - /** - * Returns a string representation of this `FieldPath` for - * logging/debugging purposes. - * - * @note the exact string representation is unspecified and subject to - * change; don't rely on the format of the string. - */ - std::string ToString() const; - - /** - * Outputs the string representation of this `FieldPath` to the given - * stream. - * - * @see `ToString()` for comments on the representation format. - */ - friend std::ostream& operator<<(std::ostream& out, const FieldPath& path); - - private: - // The type of the internal object that implements the public interface. -#if !defined(SWIG) -#if !defined(__ANDROID__) - using FieldPathInternal = ::firebase::firestore::model::FieldPath; -#else - using FieldPathInternal = ::firebase::firestore::FieldPathPortable; -#endif // !defined(__ANDROID__) -#endif // !defined(SWIG) - - friend bool operator==(const FieldPath& lhs, const FieldPath& rhs); - friend bool operator!=(const FieldPath& lhs, const FieldPath& rhs); - friend struct std::hash; - - friend class DocumentSnapshot; // For access to `FromDotSeparatedString` - friend class Query; - friend class QueryInternal; - friend class SetOptions; // For access to `FromDotSeparatedString` - friend class FieldPathConverter; - friend struct ConverterImpl; - - explicit FieldPath(FieldPathInternal* internal); - - static FieldPathInternal* InternalFromSegments( - std::vector field_names); - - static FieldPath FromDotSeparatedString(const std::string& path); - - FieldPathInternal* internal_ = nullptr; -}; - -} // namespace firestore -} // namespace firebase - -#if !defined(SWIG) -namespace std { -/** - * A convenient specialization of std::hash for FieldPath. - */ -template <> -struct hash { - /** - * Calculates the hash of the argument. - * - * Note: specialization of `std::hash` is provided for convenience only. The - * implementation is subject to change. - */ - size_t operator()(const firebase::firestore::FieldPath& field_path) const; -}; -} // namespace std -#endif // !defined(SWIG) - -#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_FIELD_PATH_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/field_value.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/field_value.h deleted file mode 100644 index e66814104ed7..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/field_value.h +++ /dev/null @@ -1,436 +0,0 @@ -/* - * Copyright 2018 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_FIELD_VALUE_H_ -#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_FIELD_VALUE_H_ - -#include -#include -#include -#include -#include - -#include "firebase/firestore/map_field_value.h" -#include "firebase/internal/type_traits.h" - -namespace firebase { - -class Timestamp; - -namespace firestore { - -class DocumentReference; -class FieldValueInternal; -class GeoPoint; - -/** - * @brief A field value represents variant datatypes as stored by Firestore. - * - * FieldValue can be used when reading a particular field with - * DocumentSnapshot::Get() or fields with DocumentSnapshot::GetData(). When - * writing document fields with DocumentReference::Set() or - * DocumentReference::Update(), it can also represent sentinel values in - * addition to real data values. - * - * For a non-sentinel instance, you can check whether it is of a particular type - * with is_foo() and get the value with foo_value(), where foo can be one of - * null, boolean, integer, double, timestamp, string, blob, reference, - * geo_point, array or map. If the instance is not of type foo, the call to - * foo_value() will fail (and cause a crash). - */ -class FieldValue final { - // Helper aliases for `Increment` member functions. - // Qualifying `is_integer` is to prevent ambiguity with the - // `FieldValue::is_integer` member function. - // Note: normally, `enable_if::type` would be included in the alias, but such - // a declaration breaks SWIG (presumably, SWIG cannot handle `typename` within - // an alias template). - template - using EnableIfIntegral = enable_if<::firebase::is_integer::value, int>; - template - using EnableIfFloatingPoint = enable_if::value, int>; - - public: - /** - * The enumeration of all valid runtime types of FieldValue. - */ - enum class Type { - kNull, - kBoolean, - kInteger, - kDouble, - kTimestamp, - kString, - kBlob, - kReference, - kGeoPoint, - kArray, - kMap, - // Below are sentinel types. Sentinel types can be passed to Firestore - // methods as arguments, but are never returned from Firestore. - kDelete, - kServerTimestamp, - kArrayUnion, - kArrayRemove, - kIncrementInteger, - kIncrementDouble, - }; - - /** - * @brief Creates an invalid FieldValue that has to be reassigned before it - * can be used. - * - * Calling any member function on an invalid FieldValue will be a no-op. If - * the function returns a value, it will return a zero, empty, or invalid - * value, depending on the type of the value. - */ - FieldValue(); - - /** - * @brief Copy constructor. - * - * `FieldValue` is immutable and can be efficiently copied (no deep copy is - * performed). - * - * @param[in] other `FieldValue` to copy from. - */ - FieldValue(const FieldValue& other); - - /** - * @brief Move constructor. - * - * Moving is more efficient than copying for a `FieldValue`. After being moved - * from, a `FieldValue` is equivalent to its default-constructed state. - * - * @param[in] other `FieldValue` to move data from. - */ - FieldValue(FieldValue&& other) noexcept; - - ~FieldValue(); - - /** - * @brief Copy assignment operator. - * - * `FieldValue` is immutable and can be efficiently copied (no deep copy is - * performed). - * - * @param[in] other `FieldValue` to copy from. - * - * @return Reference to the destination `FieldValue`. - */ - FieldValue& operator=(const FieldValue& other); - - /** - * @brief Move assignment operator. - * - * Moving is more efficient than copying for a `FieldValue`. After being moved - * from, a `FieldValue` is equivalent to its default-constructed state. - * - * @param[in] other `FieldValue` to move data from. - * - * @return Reference to the destination `FieldValue`. - */ - FieldValue& operator=(FieldValue&& other) noexcept; - - /** - * @brief Constructs a FieldValue containing the given boolean value. - */ - static FieldValue Boolean(bool value); - - /** - * @brief Constructs a FieldValue containing the given 64-bit integer value. - */ - static FieldValue Integer(int64_t value); - - /** - * @brief Constructs a FieldValue containing the given double-precision - * floating point value. - */ - static FieldValue Double(double value); - - /** - * @brief Constructs a FieldValue containing the given Timestamp value. - */ - static FieldValue Timestamp(Timestamp value); - - /** - * @brief Constructs a FieldValue containing the given std::string value. - */ - static FieldValue String(std::string value); - - /** - * @brief Constructs a FieldValue containing the given blob value of given - * size. `value` is copied into the returned FieldValue. - */ - static FieldValue Blob(const uint8_t* value, size_t size); - - /** - * @brief Constructs a FieldValue containing the given reference value. - */ - static FieldValue Reference(DocumentReference value); - - /** - * @brief Constructs a FieldValue containing the given GeoPoint value. - */ - static FieldValue GeoPoint(GeoPoint value); - - /** - * @brief Constructs a FieldValue containing the given FieldValue vector - * value. - */ - static FieldValue Array(std::vector value); - - /** - * @brief Constructs a FieldValue containing the given FieldValue map value. - */ - static FieldValue Map(MapFieldValue value); - - /** @brief Gets the current type contained in this FieldValue. */ - Type type() const; - - /** @brief Gets whether this FieldValue is currently null. */ - bool is_null() const { return type() == Type::kNull; } - - /** @brief Gets whether this FieldValue contains a boolean value. */ - bool is_boolean() const { return type() == Type::kBoolean; } - - /** @brief Gets whether this FieldValue contains an integer value. */ - bool is_integer() const { return type() == Type::kInteger; } - - /** @brief Gets whether this FieldValue contains a double value. */ - bool is_double() const { return type() == Type::kDouble; } - - /** @brief Gets whether this FieldValue contains a timestamp. */ - bool is_timestamp() const { return type() == Type::kTimestamp; } - - /** @brief Gets whether this FieldValue contains a string. */ - bool is_string() const { return type() == Type::kString; } - - /** @brief Gets whether this FieldValue contains a blob. */ - bool is_blob() const { return type() == Type::kBlob; } - - /** - * @brief Gets whether this FieldValue contains a reference to a document in - * the same Firestore. - */ - bool is_reference() const { return type() == Type::kReference; } - - /** @brief Gets whether this FieldValue contains a GeoPoint. */ - bool is_geo_point() const { return type() == Type::kGeoPoint; } - - /** @brief Gets whether this FieldValue contains an array of FieldValues. */ - bool is_array() const { return type() == Type::kArray; } - - /** @brief Gets whether this FieldValue contains a map of std::string to - * FieldValue. */ - bool is_map() const { return type() == Type::kMap; } - - /** @brief Gets the boolean value contained in this FieldValue. */ - bool boolean_value() const; - - /** @brief Gets the integer value contained in this FieldValue. */ - int64_t integer_value() const; - - /** @brief Gets the double value contained in this FieldValue. */ - double double_value() const; - - /** @brief Gets the timestamp value contained in this FieldValue. */ - class Timestamp timestamp_value() const; - - /** @brief Gets the string value contained in this FieldValue. */ - std::string string_value() const; - - /** @brief Gets the blob value contained in this FieldValue. */ - const uint8_t* blob_value() const; - - /** @brief Gets the blob size contained in this FieldValue. */ - size_t blob_size() const; - - /** @brief Gets the DocumentReference contained in this FieldValue. */ - DocumentReference reference_value() const; - - /** @brief Gets the GeoPoint value contained in this FieldValue. */ - class GeoPoint geo_point_value() const; - - /** @brief Gets the vector of FieldValues contained in this FieldValue. */ - std::vector array_value() const; - - /** - * @brief Gets the map of string to FieldValue contained in this FieldValue. - */ - MapFieldValue map_value() const; - - /** - * @brief Returns `true` if this `FieldValue` is valid, `false` if it is not - * valid. An invalid `FieldValue` could be the result of: - * - Creating a `FieldValue` using the default constructor. - * - Moving from the `FieldValue`. - * - Calling `DocumentSnapshot::Get(field)` for a field that does not exist - * in the document. - * - * @return `true` if this `FieldValue` is valid, `false` if this `FieldValue` - * is invalid. - */ - bool is_valid() const { return internal_ != nullptr; } - - /** @brief Constructs a null. */ - static FieldValue Null(); - - /** - * @brief Returns a sentinel for use with Update() to mark a field for - * deletion. - */ - static FieldValue Delete(); - - /** - * Returns a sentinel that can be used with Set() or Update() to include - * a server-generated timestamp in the written data. - */ - static FieldValue ServerTimestamp(); - - /** - * Returns a special value that can be used with Set() or Update() that tells - * the server to union the given elements with any array value that already - * exists on the server. Each specified element that doesn't already exist in - * the array will be added to the end. If the field being modified is not - * already an array, it will be overwritten with an array containing exactly - * the specified elements. - * - * @param elements The elements to union into the array. - * @return The FieldValue sentinel for use in a call to Set() or Update(). - */ - static FieldValue ArrayUnion(std::vector elements); - - /** - * Returns a special value that can be used with Set() or Update() that tells - * the server to remove the given elements from any array value that already - * exists on the server. All instances of each element specified will be - * removed from the array. If the field being modified is not already an - * array, it will be overwritten with an empty array. - * - * @param elements The elements to remove from the array. - * @return The FieldValue sentinel for use in a call to Set() or Update(). - */ - static FieldValue ArrayRemove(std::vector elements); - - /** - * Returns a special value that can be used with `Set()` or `Update()` that - * tells the server to increment the field's current value by the given - * integer value. - * - * If the current field value is an integer, possible integer overflows are - * resolved to `LONG_MAX` or `LONG_MIN`. If the current field value is a - * double, both values will be interpreted as doubles and the arithmetic will - * follow IEEE 754 semantics. - * - * If field is not an integer or a double, or if the field does not yet exist, - * the transformation will set the field to the given value. - * - * @param by_value The integer value to increment by. Should be an integer - * type not larger than `int64_t`. - * @return The FieldValue sentinel for use in a call to `Set()` or `Update().` - */ - template ::type = 0> - static FieldValue Increment(T by_value) { - // Note: Doxygen will run into trouble if this function's definition is - // moved outside the class body. - static_assert( - (std::numeric_limits::max)() <= - (std::numeric_limits::max)(), - "The integer type you provided is larger than can fit in an int64_t. " - "If you are sure the value will not be truncated, please explicitly " - "cast to int64_t before passing it to FieldValue::Increment()."); - return IntegerIncrement(static_cast(by_value)); - } - - /** - * Returns a special value that can be used with `Set()` or `Update()` that - * tells the server to increment the field's current value by the given - * floating point value. - * - * If the current field value is an integer, possible integer overflows are - * resolved to `LONG_MAX` or `LONG_MIN`. If the current field value is a - * double, both values will be interpreted as doubles and the arithmetic will - * follow IEEE 754 semantics. - * - * If field is not an integer or a double, or if the field does not yet exist, - * the transformation will set the field to the given value. - * - * @param by_value The double value to increment by. Should be a floating - * point type no larger than `double`. - * @return The FieldValue sentinel for use in a call to `Set()` or `Update().` - */ - template ::type = 0> - static FieldValue Increment(T by_value) { - // Note: Doxygen will run into trouble if this function's definition is - // moved outside the class body. - static_assert( - (std::numeric_limits::max)() <= (std::numeric_limits::max)(), - "The floating point type you provided is larger than can fit in a " - "double. If you are sure the value will not be truncated, please " - "explicitly cast to double before passing it to " - "FieldValue::Increment()."); - return DoubleIncrement(static_cast(by_value)); - } - - /** - * Returns a string representation of this `FieldValue` for logging/debugging - * purposes. - * - * @note the exact string representation is unspecified and subject to - * change; don't rely on the format of the string. - */ - std::string ToString() const; - - /** - * Outputs the string representation of this `FieldValue` to the given stream. - * - * @see `ToString()` for comments on the representation format. - */ - friend std::ostream& operator<<(std::ostream& out, const FieldValue& value); - - private: - friend class DocumentReferenceInternal; - friend class DocumentSnapshotInternal; - friend class FieldValueInternal; - friend class FirestoreInternal; - friend class QueryInternal; - friend class TransactionInternal; - friend class Wrapper; - friend class WriteBatchInternal; - friend struct ConverterImpl; - friend bool operator==(const FieldValue& lhs, const FieldValue& rhs); - - explicit FieldValue(FieldValueInternal* internal); - - static FieldValue IntegerIncrement(int64_t by_value); - static FieldValue DoubleIncrement(double by_value); - - FieldValueInternal* internal_ = nullptr; -}; - -/** Checks `lhs` and `rhs` for equality. */ -bool operator==(const FieldValue& lhs, const FieldValue& rhs); - -/** Checks `lhs` and `rhs` for inequality. */ -inline bool operator!=(const FieldValue& lhs, const FieldValue& rhs) { - return !(lhs == rhs); -} - -} // namespace firestore -} // namespace firebase - -#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_FIELD_VALUE_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/firestore_errors.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/firestore_errors.h deleted file mode 100644 index 6af214a08df1..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/firestore_errors.h +++ /dev/null @@ -1,116 +0,0 @@ -/* - * Copyright 2018 Google - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIRESTORE_CORE_INCLUDE_FIREBASE_FIRESTORE_FIRESTORE_ERRORS_H_ -#define FIRESTORE_CORE_INCLUDE_FIREBASE_FIRESTORE_FIRESTORE_ERRORS_H_ - -namespace firebase { -namespace firestore { - -/** - * Error codes used by Cloud Firestore. - * - * The codes are in sync across Firestore SDKs on various platforms. - */ -enum Error { - /** The operation completed successfully. */ - // Note: NSError objects will never have a code with this value. - kErrorOk = 0, - - kErrorNone = 0, - - /** The operation was cancelled (typically by the caller). */ - kErrorCancelled = 1, - - /** Unknown error or an error from a different error domain. */ - kErrorUnknown = 2, - - /** - * Client specified an invalid argument. Note that this differs from - * FailedPrecondition. InvalidArgument indicates arguments that are - * problematic regardless of the state of the system (e.g., an invalid field - * name). - */ - kErrorInvalidArgument = 3, - - /** - * Deadline expired before operation could complete. For operations that - * change the state of the system, this error may be returned even if the - * operation has completed successfully. For example, a successful response - * from a server could have been delayed long enough for the deadline to - * expire. - */ - kErrorDeadlineExceeded = 4, - - /** Some requested document was not found. */ - kErrorNotFound = 5, - - /** Some document that we attempted to create already exists. */ - kErrorAlreadyExists = 6, - - /** The caller does not have permission to execute the specified operation. */ - kErrorPermissionDenied = 7, - - /** - * Some resource has been exhausted, perhaps a per-user quota, or perhaps the - * entire file system is out of space. - */ - kErrorResourceExhausted = 8, - - /** - * Operation was rejected because the system is not in a state required for - * the operation's execution. - */ - kErrorFailedPrecondition = 9, - - /** - * The operation was aborted, typically due to a concurrency issue like - * transaction aborts, etc. - */ - kErrorAborted = 10, - - /** Operation was attempted past the valid range. */ - kErrorOutOfRange = 11, - - /** Operation is not implemented or not supported/enabled. */ - kErrorUnimplemented = 12, - - /** - * Internal errors. Means some invariants expected by underlying system has - * been broken. If you see one of these errors, something is very broken. - */ - kErrorInternal = 13, - - /** - * The service is currently unavailable. This is a most likely a transient - * condition and may be corrected by retrying with a backoff. - */ - kErrorUnavailable = 14, - - /** Unrecoverable data loss or corruption. */ - kErrorDataLoss = 15, - - /** - * The request does not have valid authentication credentials for the - * operation. - */ - kErrorUnauthenticated = 16 -}; - -} // namespace firestore -} // namespace firebase - -#endif // FIRESTORE_CORE_INCLUDE_FIREBASE_FIRESTORE_FIRESTORE_ERRORS_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/firestore_version.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/firestore_version.h deleted file mode 100644 index 627ead9e3ae7..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/firestore_version.h +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright 2018 Google - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIRESTORE_CORE_INCLUDE_FIREBASE_FIRESTORE_FIRESTORE_VERSION_H_ -#define FIRESTORE_CORE_INCLUDE_FIREBASE_FIRESTORE_FIRESTORE_VERSION_H_ - -namespace firebase { -namespace firestore { - -/** Version string for the Firebase Firestore SDK. */ -extern const char* const kFirestoreVersionString; - -} // namespace firestore -} // namespace firebase - -#endif // FIRESTORE_CORE_INCLUDE_FIREBASE_FIRESTORE_FIRESTORE_VERSION_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/geo_point.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/geo_point.h deleted file mode 100644 index ac56e74a4515..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/geo_point.h +++ /dev/null @@ -1,120 +0,0 @@ -/* - * Copyright 2018 Google - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIRESTORE_CORE_INCLUDE_FIREBASE_FIRESTORE_GEO_POINT_H_ -#define FIRESTORE_CORE_INCLUDE_FIREBASE_FIRESTORE_GEO_POINT_H_ - -#include -#include - -namespace firebase { -namespace firestore { - -/** - * An immutable object representing a geographical point in Firestore. The point - * is represented as a latitude/longitude pair. - * - * Latitude values are in the range of [-90, 90]. - * Longitude values are in the range of [-180, 180]. - */ -class GeoPoint { - public: - /** Creates a `GeoPoint` with both latitude and longitude set to 0. */ - GeoPoint() = default; - - /** - * Creates a `GeoPoint` from the provided latitude and longitude values. - * - * @param latitude The latitude as number of degrees between -90 and 90. - * @param longitude The longitude as number of degrees between -180 and 180. - */ - GeoPoint(double latitude, double longitude); - - /** Copy constructor, `GeoPoint` is trivially copyable. */ - GeoPoint(const GeoPoint& other) = default; - - /** Move constructor, equivalent to copying. */ - GeoPoint(GeoPoint&& other) = default; - - /** Copy assignment operator, `GeoPoint` is trivially copyable. */ - GeoPoint& operator=(const GeoPoint& other) = default; - - /** Move assignment operator, equivalent to copying. */ - GeoPoint& operator=(GeoPoint&& other) = default; - - /** Returns the latitude value of this `GeoPoint`. */ - double latitude() const { - return latitude_; - } - - /** Returns the latitude value of this `GeoPoint`. */ - double longitude() const { - return longitude_; - } - - /** - * Returns a string representation of this `GeoPoint` for logging/debugging - * purposes. - * - * @note: the exact string representation is unspecified and subject to - * change; don't rely on the format of the string. - */ - std::string ToString() const; - - /** - * Outputs the string representation of this `GeoPoint` to the given stream. - * - * @see `ToString()` for comments on the representation format. - */ - friend std::ostream& operator<<(std::ostream& out, const GeoPoint& geo_point); - - private: - double latitude_ = 0.0; - double longitude_ = 0.0; -}; - -/** Checks whether `lhs` and `rhs` are in ascending order. */ -bool operator<(const GeoPoint& lhs, const GeoPoint& rhs); - -/** Checks whether `lhs` and `rhs` are in descending order. */ -inline bool operator>(const GeoPoint& lhs, const GeoPoint& rhs) { - return rhs < lhs; -} - -/** Checks whether `lhs` and `rhs` are in non-ascending order. */ -inline bool operator>=(const GeoPoint& lhs, const GeoPoint& rhs) { - return !(lhs < rhs); -} - -/** Checks whether `lhs` and `rhs` are in non-descending order. */ -inline bool operator<=(const GeoPoint& lhs, const GeoPoint& rhs) { - return !(lhs > rhs); -} - -/** Checks `lhs` and `rhs` for inequality. */ -inline bool operator!=(const GeoPoint& lhs, const GeoPoint& rhs) { - return lhs < rhs || lhs > rhs; -} - -/** Checks `lhs` and `rhs` for equality. */ -inline bool operator==(const GeoPoint& lhs, const GeoPoint& rhs) { - return !(lhs != rhs); -} - -} // namespace firestore -} // namespace firebase - -#endif // FIRESTORE_CORE_INCLUDE_FIREBASE_FIRESTORE_GEO_POINT_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/listener_registration.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/listener_registration.h deleted file mode 100644 index 20487943347f..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/listener_registration.h +++ /dev/null @@ -1,130 +0,0 @@ -/* - * Copyright 2018 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_LISTENER_REGISTRATION_H_ -#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_LISTENER_REGISTRATION_H_ - -namespace firebase { -namespace firestore { - -class FirestoreInternal; -class ListenerRegistrationInternal; - -/** Represents a listener that can be removed by calling Remove(). */ -class ListenerRegistration { - public: - /** - * @brief Creates an invalid ListenerRegistration that has to be reassigned - * before it can be used. - * - * Calling Remove() on an invalid ListenerRegistration is a no-op. - */ - ListenerRegistration(); - - /** - * @brief Copy constructor. - * - * `ListenerRegistration` can be efficiently copied because it simply refers - * to the same underlying listener. If there is more than one copy of - * a `ListenerRegistration`, after calling `Remove` on one of them, the - * listener is removed, and calling `Remove` on any other copies will be - * a no-op. - * - * @param[in] other `ListenerRegistration` to copy from. - */ - ListenerRegistration(const ListenerRegistration& other); - - /** - * @brief Move constructor. - * - * Moving is more efficient than copying for a `ListenerRegistration`. After - * being moved from, a `ListenerRegistration` is equivalent to its - * default-constructed state. - * - * @param[in] other `ListenerRegistration` to move data from. - */ - ListenerRegistration(ListenerRegistration&& other); - - virtual ~ListenerRegistration(); - - /** - * @brief Copy assignment operator. - * - * `ListenerRegistration` can be efficiently copied because it simply refers - * to the same underlying listener. If there is more than one copy of - * a `ListenerRegistration`, after calling `Remove` on one of them, the - * listener is removed, and calling `Remove` on any other copies will be - * a no-op. - * - * @param[in] other `ListenerRegistration` to copy from. - * - * @return Reference to the destination `ListenerRegistration`. - */ - ListenerRegistration& operator=(const ListenerRegistration& other); - - /** - * @brief Move assignment operator. - * - * Moving is more efficient than copying for a `ListenerRegistration`. After - * being moved from, a `ListenerRegistration` is equivalent to its - * default-constructed state. - * - * @param[in] other `ListenerRegistration` to move data from. - * - * @return Reference to the destination `ListenerRegistration`. - */ - ListenerRegistration& operator=(ListenerRegistration&& other); - - /** - * Removes the listener being tracked by this ListenerRegistration. After the - * initial call, subsequent calls have no effect. - */ - virtual void Remove(); - - /** - * @brief Returns true if this `ListenerRegistration` is valid, false if it is - * not valid. An invalid `ListenerRegistration` could be the result of: - * - Creating a `ListenerRegistration` using the default constructor. - * - Moving from the `ListenerRegistration`. - * - Deleting your Firestore instance, which will invalidate all the - * `ListenerRegistration` instances associated with it. - * - * @return true if this `ListenerRegistration` is valid, false if this - * `ListenerRegistration` is invalid. - */ - bool is_valid() const { return internal_ != nullptr; } - - private: - friend class DocumentReferenceInternal; - friend class FirestoreInternal; - friend class ListenerRegistrationInternal; - friend class QueryInternal; - friend struct ConverterImpl; - template - friend struct CleanupFn; - - explicit ListenerRegistration(ListenerRegistrationInternal* internal); - - void Cleanup(); - - FirestoreInternal* firestore_ = nullptr; - mutable ListenerRegistrationInternal* internal_ = nullptr; -}; - -} // namespace firestore -} // namespace firebase - -#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_LISTENER_REGISTRATION_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/load_bundle_task_progress.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/load_bundle_task_progress.h deleted file mode 100644 index be9b235f1205..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/load_bundle_task_progress.h +++ /dev/null @@ -1,101 +0,0 @@ -/* - * Copyright 2021 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_LOAD_BUNDLE_TASK_PROGRESS_H_ -#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_LOAD_BUNDLE_TASK_PROGRESS_H_ - -#include - -namespace firebase { -namespace firestore { - -class LoadBundleTaskProgressInternal; - -/** Represents a progress update or the final state from loading bundles. */ -class LoadBundleTaskProgress { - public: - /** - * Represents the state of bundle loading tasks. - * - * Both `kSuccess` and `kError` are final states: the task will abort - * or complete and there will be no more updates after they are reported. - */ - enum class State { kError, kInProgress, kSuccess }; - - LoadBundleTaskProgress() = default; - /** Construct a LoadBundleTaskProgress with specific state. **/ - LoadBundleTaskProgress(int32_t documents_loaded, - int32_t total_documents, - int64_t bytes_loaded, - int64_t total_bytes, - State state); - - /** Returns how many documents have been loaded. */ - int32_t documents_loaded() const { return documents_loaded_; } - - /** - * Returns the total number of documents in the bundle. Returns 0 if the - * bundle failed to parse. - */ - int32_t total_documents() const { return total_documents_; } - - /** Returns how many bytes have been loaded. */ - int64_t bytes_loaded() const { return bytes_loaded_; } - - /** - * Returns the total number of bytes in the bundle. Returns 0 if the bundle - * failed to parse. - */ - int64_t total_bytes() const { return total_bytes_; } - - /** Returns the current state of the loading progress. */ - State state() const { return state_; } - - private: - friend class EventListenerInternal; - friend class LoadBundleTaskProgressInternal; - friend struct ConverterImpl; - -#if defined(__ANDROID__) - explicit LoadBundleTaskProgress(LoadBundleTaskProgressInternal* internal); -#endif // defined(__ANDROID__) - - int32_t documents_loaded_ = 0; - int32_t total_documents_ = 0; - int64_t bytes_loaded_ = 0; - int64_t total_bytes_ = 0; - State state_ = State::kInProgress; -}; - -/** LoadBundleTaskProgress == comparison operator. **/ -inline bool operator==(const LoadBundleTaskProgress& lhs, - const LoadBundleTaskProgress& rhs) { - return lhs.state() == rhs.state() && - lhs.bytes_loaded() == rhs.bytes_loaded() && - lhs.documents_loaded() == rhs.documents_loaded() && - lhs.total_bytes() == rhs.total_bytes() && - lhs.total_documents() == rhs.total_documents(); -} - -/** LoadBundleTaskProgress != comparison operator. **/ -inline bool operator!=(const LoadBundleTaskProgress& lhs, - const LoadBundleTaskProgress& rhs) { - return !(lhs == rhs); -} - -} // namespace firestore -} // namespace firebase - -#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_LOAD_BUNDLE_TASK_PROGRESS_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/map_field_value.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/map_field_value.h deleted file mode 100644 index 8c67c05a1088..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/map_field_value.h +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright 2018 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_MAP_FIELD_VALUE_H_ -#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_MAP_FIELD_VALUE_H_ - -#include -#include - -namespace firebase { -namespace firestore { - -class FieldPath; -class FieldValue; - -/** @brief A map of `FieldValue`s indexed by stringified field paths. */ -using MapFieldValue = std::unordered_map; -/** @brief A map of `FieldValue`s indexed by field paths. */ -using MapFieldPathValue = std::unordered_map; - -} // namespace firestore -} // namespace firebase - -#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_MAP_FIELD_VALUE_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/metadata_changes.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/metadata_changes.h deleted file mode 100644 index 13f9abe48427..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/metadata_changes.h +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright 2018 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_METADATA_CHANGES_H_ -#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_METADATA_CHANGES_H_ - -namespace firebase { -namespace firestore { - -/** - * Indicates whether metadata-only changes (that is, - * DocumentSnapshot::metadata() or QuerySnapshot::metadata() changed) should - * trigger snapshot events. - */ -enum class MetadataChanges { - /** Snapshot events will not be triggered by metadata-only changes. */ - kExclude, - - /** - * Snapshot events will be triggered by any changes, including metadata-only - * changes. - */ - kInclude, -}; - -} // namespace firestore -} // namespace firebase -#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_METADATA_CHANGES_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/query.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/query.h deleted file mode 100644 index d2e73400cee6..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/query.h +++ /dev/null @@ -1,683 +0,0 @@ -/* - * Copyright 2018 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_QUERY_H_ -#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_QUERY_H_ - -#include -#include -#include -#include -#include - -#include "firebase/internal/common.h" - -#include "firebase/firestore/firestore_errors.h" -#include "firebase/firestore/metadata_changes.h" -#include "firebase/firestore/source.h" - -namespace firebase { -/// @cond FIREBASE_APP_INTERNAL -template -class Future; -/// @endcond - -namespace firestore { - -class DocumentSnapshot; -template -class EventListener; -class FieldPath; -class FieldValue; -class ListenerRegistration; -class Firestore; -class QueryInternal; -class QuerySnapshot; - -/** - * @brief A Query which you can read or listen to. - * - * You can also construct refined Query objects by adding filters and ordering. - * - * You cannot construct a valid Query directly; use CollectionReference - * methods that return a Query instead. - * - * @note Firestore classes are not meant to be subclassed except for use in test - * mocks. Subclassing is not supported in production code and new SDK releases - * may break code that does so. - */ -class Query { - public: - /** - * An enum for the direction of a sort. - */ - enum class Direction { - kAscending, - kDescending, - }; - - /** - * @brief Creates an invalid Query that has to be reassigned before it can be - * used. - * - * Calling any member function on an invalid Query will be a no-op. If the - * function returns a value, it will return a zero, empty, or invalid value, - * depending on the type of the value. - */ - Query(); - - /** - * @brief Copy constructor. - * - * `Query` is immutable and can be efficiently copied (no deep copy is - * performed). - * - * @param[in] other `Query` to copy from. - */ - Query(const Query& other); - - /** - * @brief Move constructor. - * - * Moving is more efficient than copying for a `Query`. After being moved - * from, a `Query` is equivalent to its default-constructed state. - * - * @param[in] other `Query` to move data from. - */ - Query(Query&& other); - - virtual ~Query(); - - /** - * @brief Copy assignment operator. - * - * `Query` is immutable and can be efficiently copied (no deep copy is - * performed). - * - * @param[in] other `Query` to copy from. - * - * @return Reference to the destination `Query`. - */ - Query& operator=(const Query& other); - - /** - * @brief Move assignment operator. - * - * Moving is more efficient than copying for a `Query`. After being moved - * from, a `Query` is equivalent to its default-constructed state. - * - * @param[in] other `Query` to move data from. - * - * @return Reference to the destination `Query`. - */ - Query& operator=(Query&& other); - - /** - * @brief Returns the Firestore instance associated with this query. - * - * The pointer will remain valid indefinitely. - * - * @return Firebase Firestore instance that this Query refers to. - */ - virtual const Firestore* firestore() const; - - /** - * @brief Returns the Firestore instance associated with this query. - * - * The pointer will remain valid indefinitely. - * - * @return Firebase Firestore instance that this Query refers to. - */ - virtual Firestore* firestore(); - - /** - * @brief Creates and returns a new Query with the additional filter that - * documents must contain the specified field and the value should be equal to - * the specified value. - * - * @param[in] field The name of the field to compare. - * @param[in] value The value for comparison. - * - * @return The created Query. - */ - virtual Query WhereEqualTo(const std::string& field, - const FieldValue& value) const; - - /** - * @brief Creates and returns a new Query with the additional filter that - * documents must contain the specified field and the value should be equal to - * the specified value. - * - * @param[in] field The path of the field to compare. - * @param[in] value The value for comparison. - * - * @return The created Query. - */ - virtual Query WhereEqualTo(const FieldPath& field, - const FieldValue& value) const; - - /** - * @brief Creates and returns a new Query with the additional filter that - * documents must contain the specified field and the value does not equal the - * specified value. - * - * A Query can have only one `WhereNotEqualTo()` filter, and it cannot be - * combined with `WhereNotIn()`. - * - * @param[in] field The name of the field to compare. - * @param[in] value The value for comparison. - * - * @return The created Query. - */ - virtual Query WhereNotEqualTo(const std::string& field, - const FieldValue& value) const; - - /** - * @brief Creates and returns a new Query with the additional filter that - * documents must contain the specified field and the value does not equal the - * specified value. - * - * A Query can have only one `WhereNotEqualTo()` filter, and it cannot be - * combined with `WhereNotIn()`. - * - * @param[in] field The path of the field to compare. - * @param[in] value The value for comparison. - * - * @return The created Query. - */ - virtual Query WhereNotEqualTo(const FieldPath& field, - const FieldValue& value) const; - - /** - * @brief Creates and returns a new Query with the additional filter that - * documents must contain the specified field and the value should be less - * than the specified value. - * - * @param[in] field The name of the field to compare. - * @param[in] value The value for comparison. - * - * @return The created Query. - */ - virtual Query WhereLessThan(const std::string& field, - const FieldValue& value) const; - - /** - * @brief Creates and returns a new Query with the additional filter that - * documents must contain the specified field and the value should be less - * than the specified value. - * - * @param[in] field The path of the field to compare. - * @param[in] value The value for comparison. - * - * @return The created Query. - */ - virtual Query WhereLessThan(const FieldPath& field, - const FieldValue& value) const; - - /** - * @brief Creates and returns a new Query with the additional filter that - * documents must contain the specified field and the value should be less - * than or equal to the specified value. - * - * @param[in] field The name of the field to compare. - * @param[in] value The value for comparison. - * - * @return The created Query. - */ - virtual Query WhereLessThanOrEqualTo(const std::string& field, - const FieldValue& value) const; - - /** - * @brief Creates and returns a new Query with the additional filter that - * documents must contain the specified field and the value should be less - * than or equal to the specified value. - * - * @param[in] field The path of the field to compare. - * @param[in] value The value for comparison. - * - * @return The created Query. - */ - virtual Query WhereLessThanOrEqualTo(const FieldPath& field, - const FieldValue& value) const; - - /** - * @brief Creates and returns a new Query with the additional filter that - * documents must contain the specified field and the value should be greater - * than the specified value. - * - * @param[in] field The name of the field to compare. - * @param[in] value The value for comparison. - * - * @return The created Query. - */ - virtual Query WhereGreaterThan(const std::string& field, - const FieldValue& value) const; - - /** - * @brief Creates and returns a new Query with the additional filter that - * documents must contain the specified field and the value should be greater - * than the specified value. - * - * @param[in] field The path of the field to compare. - * @param[in] value The value for comparison. - * - * @return The created Query. - */ - virtual Query WhereGreaterThan(const FieldPath& field, - const FieldValue& value) const; - - /** - * @brief Creates and returns a new Query with the additional filter that - * documents must contain the specified field and the value should be greater - * than or equal to the specified value. - * - * @param[in] field The name of the field to compare. - * @param[in] value The value for comparison. - * - * @return The created Query. - */ - virtual Query WhereGreaterThanOrEqualTo(const std::string& field, - const FieldValue& value) const; - - /** - * @brief Creates and returns a new Query with the additional filter that - * documents must contain the specified field and the value should be greater - * than or equal to the specified value. - * - * @param[in] field The path of the field to compare. - * @param[in] value The value for comparison. - * - * @return The created Query. - */ - virtual Query WhereGreaterThanOrEqualTo(const FieldPath& field, - const FieldValue& value) const; - - /** - * @brief Creates and returns a new Query with the additional filter that - * documents must contain the specified field, the value must be an array, and - * that the array must contain the provided value. - * - * A Query can have only one `WhereArrayContains()` filter and it cannot be - * combined with `WhereArrayContainsAny()` or `WhereIn()`. - * - * @param[in] field The name of the field containing an array to search. - * @param[in] value The value that must be contained in the array. - * - * @return The created Query. - */ - virtual Query WhereArrayContains(const std::string& field, - const FieldValue& value) const; - - /** - * @brief Creates and returns a new Query with the additional filter that - * documents must contain the specified field, the value must be an array, and - * that the array must contain the provided value. - * - * A Query can have only one `WhereArrayContains()` filter and it cannot be - * combined with `WhereArrayContainsAny()` or `WhereIn()`. - * - * @param[in] field The path of the field containing an array to search. - * @param[in] value The value that must be contained in the array. - * - * @return The created Query. - */ - virtual Query WhereArrayContains(const FieldPath& field, - const FieldValue& value) const; - - /** - * @brief Creates and returns a new Query with the additional filter that - * documents must contain the specified field, the value must be an array, and - * that the array must contain at least one value from the provided list. - * - * A Query can have only one `WhereArrayContainsAny()` filter and it cannot be - * combined with `WhereArrayContains()` or `WhereIn()`. - * - * @param[in] field The name of the field containing an array to search. - * @param[in] values The list that contains the values to match. - * - * @return The created Query. - */ - virtual Query WhereArrayContainsAny( - const std::string& field, const std::vector& values) const; - - /** - * @brief Creates and returns a new Query with the additional filter that - * documents must contain the specified field, the value must be an array, and - * that the array must contain at least one value from the provided list. - * - * A Query can have only one `WhereArrayContainsAny()` filter and it cannot be - * combined with` WhereArrayContains()` or `WhereIn()`. - * - * @param[in] field The path of the field containing an array to search. - * @param[in] values The list that contains the values to match. - * - * @return The created Query. - */ - virtual Query WhereArrayContainsAny( - const FieldPath& field, const std::vector& values) const; - - /** - * @brief Creates and returns a new Query with the additional filter that - * documents must contain the specified field and the value must equal one of - * the values from the provided list. - * - * A Query can have only one `WhereIn()` filter and it cannot be - * combined with `WhereArrayContainsAny()`. - * - * @param[in] field The name of the field containing an array to search. - * @param[in] values The list that contains the values to match. - * - * @return The created Query. - */ - virtual Query WhereIn(const std::string& field, - const std::vector& values) const; - - /** - * @brief Creates and returns a new Query with the additional filter that - * documents must contain the specified field and the value must equal one of - * the values from the provided list. - * - * A Query can have only one `WhereIn()` filter and it cannot be - * combined with `WhereArrayContainsAny()`. - * - * @param[in] field The path of the field containing an array to search. - * @param[in] values The list that contains the values to match. - * - * @return The created Query. - */ - virtual Query WhereIn(const FieldPath& field, - const std::vector& values) const; - - /** - * @brief Creates and returns a new Query with the additional filter that - * documents must contain the specified field and the value must not equal any - * of the values from the provided list. - * - * One special case is that `WhereNotIn` cannot match `FieldValue::Null()` - * values. To query for documents where a field exists and is - * `FieldValue::Null()`, use `WhereNotEqualTo`, which can handle this special - * case. - * - * A `Query` can have only one `WhereNotIn()` filter, and it cannot be - * combined with `WhereArrayContains()`, `WhereArrayContainsAny()`, - * `WhereIn()`, or `WhereNotEqualTo()`. - * - * @param[in] field The name of the field containing an array to search. - * @param[in] values The list that contains the values to match. - * - * @return The created Query. - */ - virtual Query WhereNotIn(const std::string& field, - const std::vector& values) const; - - /** - * @brief Creates and returns a new Query with the additional filter that - * documents must contain the specified field and the value must not equal any - * of the values from the provided list. - * - * One special case is that `WhereNotIn` cannot match `FieldValue::Null()` - * values. To query for documents where a field exists and is - * `FieldValue::Null()`, use `WhereNotEqualTo`, which can handle this special - * case. - * - * A `Query` can have only one `WhereNotIn()` filter, and it cannot be - * combined with `WhereArrayContains()`, `WhereArrayContainsAny()`, - * `WhereIn()`, or `WhereNotEqualTo()`. - * - * @param[in] field The path of the field containing an array to search. - * @param[in] values The list that contains the values to match. - * - * @return The created Query. - */ - virtual Query WhereNotIn(const FieldPath& field, - const std::vector& values) const; - - /** - * @brief Creates and returns a new Query that's additionally sorted by the - * specified field. - * - * @param[in] field The field to sort by. - * @param[in] direction The direction to sort (optional). If not specified, - * order will be ascending. - * - * @return The created Query. - */ - virtual Query OrderBy(const std::string& field, - Direction direction = Direction::kAscending) const; - - /** - * @brief Creates and returns a new Query that's additionally sorted by the - * specified field. - * - * @param[in] field The field to sort by. - * @param[in] direction The direction to sort (optional). If not specified, - * order will be ascending. - * - * @return The created Query. - */ - virtual Query OrderBy(const FieldPath& field, - Direction direction = Direction::kAscending) const; - - /** - * @brief Creates and returns a new Query that only returns the first matching - * documents up to the specified number. - * - * @param[in] limit A non-negative integer to specify the maximum number of - * items to return. - * - * @return The created Query. - */ - virtual Query Limit(int32_t limit) const; - - /** - * @brief Creates and returns a new Query that only returns the last matching - * documents up to the specified number. - * - * @param[in] limit A non-negative integer to specify the maximum number of - * items to return. - * - * @return The created Query. - */ - virtual Query LimitToLast(int32_t limit) const; - - /** - * @brief Creates and returns a new Query that starts at the provided document - * (inclusive). The starting position is relative to the order of the query. - * The document must contain all of the fields provided in the order by of - * this query. - * - * @param[in] snapshot The snapshot of the document to start at. - * - * @return The created Query. - */ - virtual Query StartAt(const DocumentSnapshot& snapshot) const; - - /** - * @brief Creates and returns a new Query that starts at the provided fields - * relative to the order of the query. The order of the field values must - * match the order of the order by clauses of the query. - * - * @param[in] values The field values to start this query at, in order of the - * query's order by. - * - * @return The created Query. - */ - virtual Query StartAt(const std::vector& values) const; - - /** - * @brief Creates and returns a new Query that starts after the provided - * document (inclusive). The starting position is relative to the order of the - * query. The document must contain all of the fields provided in the order by - * of this query. - * - * @param[in] snapshot The snapshot of the document to start after. - * - * @return The created Query. - */ - virtual Query StartAfter(const DocumentSnapshot& snapshot) const; - - /** - * @brief Creates and returns a new Query that starts after the provided - * fields relative to the order of the query. The order of the field values - * must match the order of the order by clauses of the query. - * - * @param[in] values The field values to start this query after, in order of - * the query's order by. - * - * @return The created Query. - */ - virtual Query StartAfter(const std::vector& values) const; - - /** - * @brief Creates and returns a new Query that ends before the provided - * document (inclusive). The end position is relative to the order of the - * query. The document must contain all of the fields provided in the order by - * of this query. - * - * @param[in] snapshot The snapshot of the document to end before. - * - * @return The created Query. - */ - virtual Query EndBefore(const DocumentSnapshot& snapshot) const; - - /** - * @brief Creates and returns a new Query that ends before the provided fields - * relative to the order of the query. The order of the field values must - * match the order of the order by clauses of the query. - * - * @param[in] values The field values to end this query before, in order of - * the query's order by. - * - * @return The created Query. - */ - virtual Query EndBefore(const std::vector& values) const; - - /** - * @brief Creates and returns a new Query that ends at the provided document - * (inclusive). The end position is relative to the order of the query. The - * document must contain all of the fields provided in the order by of this - * query. - * - * @param[in] snapshot The snapshot of the document to end at. - * - * @return The created Query. - */ - virtual Query EndAt(const DocumentSnapshot& snapshot) const; - - /** - * @brief Creates and returns a new Query that ends at the provided fields - * relative to the order of the query. The order of the field values must - * match the order of the order by clauses of the query. - * - * @param[in] values The field values to end this query at, in order of the - * query's order by. - * - * @return The created Query. - */ - virtual Query EndAt(const std::vector& values) const; - - /** - * @brief Executes the query and returns the results as a QuerySnapshot. - * - * By default, Get() attempts to provide up-to-date data when possible by - * waiting for data from the server, but it may return cached data or fail if - * you are offline and the server cannot be reached. This behavior can be - * altered via the Source parameter. - * - * @param[in] source A value to configure the get behavior (optional). - * - * @return A Future that will be resolved with the results of the Query. - */ - virtual Future Get(Source source = Source::kDefault) const; - - /** - * @brief Starts listening to the QuerySnapshot events referenced by this - * query. - * - * @param[in] callback The std::function to call. When this function is - * called, snapshot value is valid if and only if error is Error::kErrorOk. - * The std::string is an error message; the value may be empty if an error - * message is not available. - * - * @return A registration object that can be used to remove the listener. - */ - virtual ListenerRegistration AddSnapshotListener( - std::function - callback); - - /** - * @brief Starts listening to the QuerySnapshot events referenced by this - * query. - * - * @param[in] metadata_changes Indicates whether metadata-only changes (that - * is, only DocumentSnapshot::metadata() changed) should trigger snapshot - * events. - * @param[in] callback The std::function to call. When this function is - * called, snapshot value is valid if and only if error is Error::kErrorOk. - * The std::string is an error message; the value may be empty if an error - * message is not available. - * - * @return A registration object that can be used to remove the listener. - */ - virtual ListenerRegistration AddSnapshotListener( - MetadataChanges metadata_changes, - std::function - callback); - - /** - * @brief Returns true if this `Query` is valid, false if it is not valid. An - * invalid `Query` could be the result of: - * - Creating a `Query` using the default constructor. - * - Moving from the `Query`. - * - Deleting your Firestore instance, which will invalidate all the `Query` - * instances associated with it. - * - * @return true if this `Query` is valid, false if this `Query` is invalid. - */ - bool is_valid() const { return internal_ != nullptr; } - - private: - size_t Hash() const; - - friend bool operator==(const Query& lhs, const Query& rhs); - friend size_t QueryHash(const Query& query); - - friend class FirestoreInternal; - friend class QueryInternal; - friend class QuerySnapshotInternal; - friend struct ConverterImpl; - template - friend struct CleanupFn; - // For access to the constructor and to `internal_`. - friend class CollectionReference; - - explicit Query(QueryInternal* internal); - - mutable QueryInternal* internal_ = nullptr; -}; - -/** Checks `lhs` and `rhs` for equality. */ -bool operator==(const Query& lhs, const Query& rhs); - -/** Checks `lhs` and `rhs` for inequality. */ -inline bool operator!=(const Query& lhs, const Query& rhs) { - return !(lhs == rhs); -} - -} // namespace firestore -} // namespace firebase - -#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_QUERY_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/query_snapshot.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/query_snapshot.h deleted file mode 100644 index 2dcf7aaf5239..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/query_snapshot.h +++ /dev/null @@ -1,194 +0,0 @@ -/* - * Copyright 2018 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_QUERY_SNAPSHOT_H_ -#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_QUERY_SNAPSHOT_H_ - -#include -#include - -#include "firebase/firestore/metadata_changes.h" -#include "firebase/firestore/snapshot_metadata.h" - -namespace firebase { -namespace firestore { - -class DocumentChange; -class DocumentSnapshot; -class Query; -class QuerySnapshotInternal; - -/** - * @brief A QuerySnapshot contains zero or more DocumentSnapshot objects. - * - * QuerySnapshot can be iterated using a range-based for loop, and its size can - * be inspected with empty() and size(). - * - * @note Firestore classes are not meant to be subclassed except for use in test - * mocks. Subclassing is not supported in production code and new SDK releases - * may break code that does so. - */ -class QuerySnapshot { - public: - /** - * @brief Creates an invalid QuerySnapshot that has to be reassigned before it - * can be used. - * - * Calling any member function on an invalid QuerySnapshot will be a no-op. If - * the function returns a value, it will return a zero, empty, or invalid - * value, depending on the type of the value. - */ - QuerySnapshot(); - - /** - * @brief Copy constructor. - * - * `QuerySnapshot` is immutable and can be efficiently copied (no deep copy is - * performed). - * - * @param[in] other `QuerySnapshot` to copy from. - */ - QuerySnapshot(const QuerySnapshot& other); - - /** - * @brief Move constructor. - * - * Moving is more efficient than copying for a `QuerySnapshot`. After being - * moved from, a `QuerySnapshot` is equivalent to its default-constructed - * state. - * - * @param[in] other `QuerySnapshot` to move data from. - */ - QuerySnapshot(QuerySnapshot&& other); - - virtual ~QuerySnapshot(); - - /** - * @brief Copy assignment operator. - * - * `QuerySnapshot` is immutable and can be efficiently copied (no deep copy is - * performed). - * - * @param[in] other `QuerySnapshot` to copy from. - * - * @return Reference to the destination `QuerySnapshot`. - */ - QuerySnapshot& operator=(const QuerySnapshot& other); - - /** - * @brief Move assignment operator. - * - * Moving is more efficient than copying for a `QuerySnapshot`. After being - * moved from, a `QuerySnapshot` is equivalent to its default-constructed - * state. - * - * @param[in] other `QuerySnapshot` to move data from. - * - * @return Reference to the destination `QuerySnapshot`. - */ - QuerySnapshot& operator=(QuerySnapshot&& other); - - /** - * @brief The query from which you got this QuerySnapshot. - */ - virtual Query query() const; - - /** - * @brief Metadata about this snapshot, concerning its source and if it has - * local modifications. - * - * @return The metadata for this document snapshot. - */ - virtual SnapshotMetadata metadata() const; - - /** - * @brief The list of documents that changed since the last snapshot. - * - * If it's the first snapshot, all documents will be in the list as added - * changes. Documents with changes only to their metadata will not be - * included. - * - * @param[in] metadata_changes Indicates whether metadata-only changes (that - * is, only QuerySnapshot::metadata() changed) should be included. - * - * @return The list of document changes since the last snapshot. - */ - virtual std::vector DocumentChanges( - MetadataChanges metadata_changes = MetadataChanges::kExclude) const; - - /** - * @brief The list of documents in this QuerySnapshot in order of the query. - * - * @return The list of documents. - */ - virtual std::vector documents() const; - - /** - * @brief Checks the emptiness of the QuerySnapshot. - * - * @return True if there are no documents in the QuerySnapshot. - */ - bool empty() const { return size() == 0; } - - /** - * @brief Checks the size of the QuerySnapshot. - * - * @return The number of documents in the QuerySnapshot. - */ - virtual std::size_t size() const; - - /** - * @brief Returns true if this `QuerySnapshot` is valid, false if it is not - * valid. An invalid `QuerySnapshot` could be the result of: - * - Creating a `QuerySnapshot` using the default constructor. - * - Moving from the `QuerySnapshot`. - * - Deleting your Firestore instance, which will invalidate all the - * `QuerySnapshot` instances associated with it. - * - * @return true if this `QuerySnapshot` is valid, false if this - * `QuerySnapshot` is invalid. - */ - bool is_valid() const { return internal_ != nullptr; } - - private: - std::size_t Hash() const; - - friend bool operator==(const QuerySnapshot& lhs, const QuerySnapshot& rhs); - friend std::size_t QuerySnapshotHash(const QuerySnapshot& snapshot); - - friend class EventListenerInternal; - friend class FirestoreInternal; - friend struct ConverterImpl; - template - friend struct CleanupFn; - - explicit QuerySnapshot(QuerySnapshotInternal* internal); - - mutable QuerySnapshotInternal* internal_ = nullptr; -}; - -/** Checks `lhs` and `rhs` for equality. */ -bool operator==(const QuerySnapshot& lhs, const QuerySnapshot& rhs); - -/** Checks `lhs` and `rhs` for inequality. */ -inline bool operator!=(const QuerySnapshot& lhs, const QuerySnapshot& rhs) { - return !(lhs == rhs); -} - -} // namespace firestore -} // namespace firebase - -#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_QUERY_SNAPSHOT_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/set_options.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/set_options.h deleted file mode 100644 index bf21b07a0c45..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/set_options.h +++ /dev/null @@ -1,161 +0,0 @@ -/* - * Copyright 2018 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_SET_OPTIONS_H_ -#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_SET_OPTIONS_H_ - -#include -#include -#include - -#include "firebase/firestore/field_path.h" - -namespace firebase { -namespace firestore { - -/** - * @brief An options object that configures the behavior of Set() calls. - * - * By providing the SetOptions objects returned by Merge(), the Set() methods in - * DocumentReference, WriteBatch and Transaction can be configured to perform - * granular merges instead of overwriting the target documents in their - * entirety. - */ -class SetOptions final { - public: - /** The enumeration of all types of SetOptions. */ - enum class Type { - /** Overwrites the whole document. */ - kOverwrite, - - /** - * Replaces the values specified in the call parameter while leaves omitted - * fields untouched. - */ - kMergeAll, - - /** - * Replaces the values of the fields explicitly specified in the call - * parameter. - */ - kMergeSpecific, - }; - - /** - * Creates SetOptions with overwrite semantics. - */ - SetOptions() = default; - - /** - * @brief Copy constructor. - * - * This performs a deep copy, creating an independent instance. - * - * @param[in] other `SetOptions` to copy from. - */ - SetOptions(const SetOptions& other) = default; - - /** - * @brief Move constructor. - * - * Moving is more efficient than copying for `SetOptions`. After being moved - * from, `SetOptions` is in a valid but unspecified state. - * - * @param[in] other `SetOptions` to move data from. - */ - SetOptions(SetOptions&& other) = default; - - ~SetOptions(); - - /** - * @brief Copy assignment operator. - * - * This performs a deep copy, creating an independent instance. - * - * @param[in] other `SetOptions` to copy from. - * - * @return Reference to the destination `SetOptions`. - */ - SetOptions& operator=(const SetOptions& other) = default; - - /** - * @brief Move assignment operator. - * - * Moving is more efficient than copying for `SetOptions`. After being moved - * from, `SetOptions` is in a valid but unspecified state. - * - * @param[in] other `SetOptions` to move data from. - * - * @return Reference to the destination `SetOptions`. - */ - SetOptions& operator=(SetOptions&& other) = default; - - /** - * Returns an instance that can be used to change the behavior of Set() calls - * to only replace the values specified in its data argument. Fields omitted - * from the Set() call will remain untouched. - */ - static SetOptions Merge(); - - /** - * Returns an instance that can be used to change the behavior of Set() calls - * to only replace the given fields. Any field that is not specified in - * `fields` is ignored and remains untouched. - * - * It is an error to pass a SetOptions object to a Set() call that is missing - * a value for any of the fields specified here. - * - * @param fields The list of fields to merge. Fields can contain dots to - * reference nested fields within the document. - */ - static SetOptions MergeFields(const std::vector& fields); - - /** - * Returns an instance that can be used to change the behavior of Set() calls - * to only replace the given fields. Any field that is not specified in - * `fields` is ignored and remains untouched. - * - * It is an error to pass a SetOptions object to a Set() call that is missing - * a value for any of the fields specified here in its to data argument. - * - * @param fields The list of fields to merge. - */ - static SetOptions MergeFieldPaths(const std::vector& fields); - - private: - friend bool operator==(const SetOptions& lhs, const SetOptions& rhs); - friend class SetOptionsInternal; - - SetOptions(Type type, std::unordered_set fields); - - Type type_ = Type::kOverwrite; - std::unordered_set fields_; -}; - -/** Checks `lhs` and `rhs` for equality. */ -inline bool operator==(const SetOptions& lhs, const SetOptions& rhs) { - return lhs.type_ == rhs.type_ && lhs.fields_ == rhs.fields_; -} - -/** Checks `lhs` and `rhs` for inequality. */ -inline bool operator!=(const SetOptions& lhs, const SetOptions& rhs) { - return !(lhs == rhs); -} - -} // namespace firestore -} // namespace firebase - -#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_SET_OPTIONS_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/settings.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/settings.h deleted file mode 100644 index 8169d9f594e8..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/settings.h +++ /dev/null @@ -1,247 +0,0 @@ -/* - * Copyright 2018 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_SETTINGS_H_ -#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_SETTINGS_H_ - -#if defined(__OBJC__) -#include -#endif - -#include -#include -#include -#include - -namespace firebase { -namespace firestore { - -#if !defined(__ANDROID__) -// -// This declaration is guarded by a preprocessor macro because it causes -// problems with name lookup on Android. Android implementation of the public -// API extensively uses function calls of the form `util::Foo` which are -// expected to resolve to `::firebase::util::Foo`. As soon as namespace -// `::firebase::firestore::util` becomes visible, it shadows `::firebase::util` -// (within `::firebase::firestore`), so now all those calls fail to compile -// because they are interpreted as referring to -// `::firebase::firestore::util::Foo`, which doesn't exist. Changing existing -// code is impractical because such usages are numerous. -// -namespace util { -class Executor; -} -#endif - -class FirestoreInternal; - -/** Settings used to configure a Firestore instance. */ -class Settings final { - public: - /** - * Constant to use with `set_cache_size_bytes` to disable garbage collection. - */ - static constexpr int64_t kCacheSizeUnlimited = -1; - - /** - * @brief Creates the default settings. - */ - Settings(); - - /** - * @brief Copy constructor. - * - * This performs a deep copy, creating an independent instance. - * - * @param[in] other `Settings` to copy from. - */ - Settings(const Settings& other) = default; - - /** - * @brief Move constructor. - * - * Moving is more efficient than copying for `Settings`. After being moved - * from, `Settings` is in a valid but unspecified state. - * - * @param[in] other `Settings` to move data from. - */ - Settings(Settings&& other) = default; - - /** - * @brief Copy assignment operator. - * - * This performs a deep copy, creating an independent instance. - * - * @param[in] other `Settings` to copy from. - * - * @return Reference to the destination `Settings`. - */ - Settings& operator=(const Settings& other) = default; - - /** - * @brief Move assignment operator. - * - * Moving is more efficient than copying for `Settings`. After being moved - * from, `Settings` is in a valid but unspecified state. - * - * @param[in] other `Settings` to move data from. - * - * @return Reference to the destination `Settings`. - */ - Settings& operator=(Settings&& other) = default; - - /** - * Gets the host of the Firestore backend to connect to. - */ - const std::string& host() const { return host_; } - - /** - * Returns whether to use SSL when communicating. - */ - bool is_ssl_enabled() const { return ssl_enabled_; } - - /** - * Returns whether to enable local persistent storage. - */ - bool is_persistence_enabled() const { return persistence_enabled_; } - - /** Returns cache size for on-disk data. */ - int64_t cache_size_bytes() const { return cache_size_bytes_; } - - /** - * Sets the host of the Firestore backend. The default is - * "firestore.googleapis.com". - * - * @param host The host string. - */ - void set_host(std::string host); - - /** - * Enables or disables SSL for communication. - * - * @param enabled Set true to enable SSL for communication. - */ - void set_ssl_enabled(bool enabled); - - /** - * Enables or disables local persistent storage. - * - * @param enabled Set true to enable local persistent storage. - */ - void set_persistence_enabled(bool enabled); - - /** - * Sets an approximate cache size threshold for the on-disk data. If the cache - * grows beyond this size, Cloud Firestore will start removing data that - * hasn't been recently used. The size is not a guarantee that the cache will - * stay below that size, only that if the cache exceeds the given size, - * cleanup will be attempted. - * - * By default, collection is enabled with a cache size of 100 MB. The minimum - * value is 1 MB. - */ - void set_cache_size_bytes(int64_t value); - -#if defined(__OBJC__) || defined(DOXYGEN) - /** - * Returns a dispatch queue that Firestore will use to execute callbacks. - * - * The returned dispatch queue is used for all completion handlers and event - * handlers. - * - * If no dispatch queue is explictly set by calling `set_dispatch_queue()` - * then a dedicated "callback queue" will be used; namely, the main thread - * will not be used for callbacks unless expliclty set to do so by a call to - * `set_dispatch_queue()`. - * - * @note This method is only available when `__OBJC__` is defined, such as - * when compiling for iOS or tvOS. - * - * @see `set_dispatch_queue(dispatch_queue_t)` for information on how to - * explicitly set the dispatch queue to use. - */ - dispatch_queue_t dispatch_queue() const; - - /** - * Sets the dispatch queue that Firestore will use to execute callbacks. - * - * The specified dispatch queue will be used for all completion handlers and - * event handlers. - * - * @param queue The dispatch queue to use. - * - * @note This method is only available when `__OBJC__` is defined, such as - * when compiling for iOS or tvOS. - * - * @see `dispatch_queue()` for the "get" counterpart to this method. - */ - void set_dispatch_queue(dispatch_queue_t queue); -#endif // defined(__OBJC__) || defined(DOXYGEN) - - /** - * Returns a string representation of these `Settings` for - * logging/debugging purposes. - * - * @note the exact string representation is unspecified and subject to - * change; don't rely on the format of the string. - */ - std::string ToString() const; - - /** - * Outputs the string representation of these `Settings` to the given - * stream. - * - * @see `ToString()` for comments on the representation format. - */ - friend std::ostream& operator<<(std::ostream& out, const Settings& settings); - - private: - static constexpr int64_t kDefaultCacheSizeBytes = 100 * 1024 * 1024; - - std::string host_; - bool ssl_enabled_ = true; - bool persistence_enabled_ = true; - int64_t cache_size_bytes_ = kDefaultCacheSizeBytes; - - // - // TODO(varconst): fix Android problems and make these declarations - // unconditional. - // -#if !defined(__ANDROID__) - friend class FirestoreInternal; - std::unique_ptr CreateExecutor() const; - - std::shared_ptr executor_; -#endif -}; - -/** Checks `lhs` and `rhs` for equality. */ -inline bool operator==(const Settings& lhs, const Settings& rhs) { - return lhs.host() == rhs.host() && - lhs.is_ssl_enabled() == rhs.is_ssl_enabled() && - lhs.is_persistence_enabled() == rhs.is_persistence_enabled() && - lhs.cache_size_bytes() == rhs.cache_size_bytes(); -} - -/** Checks `lhs` and `rhs` for inequality. */ -inline bool operator!=(const Settings& lhs, const Settings& rhs) { - return !(lhs == rhs); -} - -} // namespace firestore -} // namespace firebase - -#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_SETTINGS_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/snapshot_metadata.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/snapshot_metadata.h deleted file mode 100644 index ce7f3f2b8607..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/snapshot_metadata.h +++ /dev/null @@ -1,159 +0,0 @@ -/* - * Copyright 2018 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_SNAPSHOT_METADATA_H_ -#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_SNAPSHOT_METADATA_H_ - -#include -#include - -namespace firebase { -namespace firestore { - -/** Metadata about a snapshot, describing the state of the snapshot. */ -class SnapshotMetadata final { - public: - /** - * Constructs a SnapshotMetadata that has all of its boolean members set to - * false. - */ - SnapshotMetadata() = default; - - /** - * Constructs a SnapshotMetadata by providing boolean parameters that describe - * the state of the snapshot. - * - * @param has_pending_writes Whether there is any pending write on the - * snapshot. - * @param is_from_cache Whether the snapshot is from cache instead of backend. - */ - SnapshotMetadata(bool has_pending_writes, bool is_from_cache) - : has_pending_writes_(has_pending_writes), - is_from_cache_(is_from_cache) {} - - /** - * @brief Copy constructor. - * - * This performs a deep copy, creating an independent instance. - * - * @note This class is currently trivially copyable, but it is not guaranteed - * to stay that way, and code relying on this might be broken by a future - * release. - * - * @param[in] other `SnapshotMetadata` to copy from. - */ - SnapshotMetadata(const SnapshotMetadata& other) = default; - - /** - * @brief Move constructor, equivalent to copying. - * - * After being moved from, `SnapshotMetadata` is in a valid but unspecified - * state. - * - * @param[in] other `SnapshotMetadata` to move data from. - */ - SnapshotMetadata(SnapshotMetadata&& other) = default; - - /** - * @brief Copy assignment operator. - * - * This performs a deep copy, creating an independent instance. - * - * @note This class is currently trivially copyable, but it is not guaranteed - * to stay that way, and code relying on this might be broken by a future - * release. - * - * @param[in] other `SnapshotMetadata` to copy from. - * - * @return Reference to the destination `SnapshotMetadata`. - */ - SnapshotMetadata& operator=(const SnapshotMetadata& other) = default; - - /** - * @brief Move assignment operator, equivalent to copying. - * - * After being moved from, `SnapshotMetadata` is in a valid but unspecified - * state. - * - * @param[in] other `SnapshotMetadata` to move data from. - * - * @return Reference to the destination `SnapshotMetadata`. - */ - SnapshotMetadata& operator=(SnapshotMetadata&& other) = default; - - /** - * Returns whether the snapshot contains the result of local writes. - * - * @return true if the snapshot contains the result of local writes (for - * example, Set() or Update() calls) that have not yet been committed to the - * backend. If your listener has opted into metadata updates (via - * MetadataChanges::kInclude) you will receive another snapshot with - * has_pending_writes() equal to false once the writes have been committed to - * the backend. - */ - bool has_pending_writes() const { return has_pending_writes_; } - - /** - * Returns whether the snapshot was created from cached data. - * - * @return true if the snapshot was created from cached data rather than - * guaranteed up-to-date server data. If your listener has opted into metadata - * updates (via MetadataChanges::kInclude) you will receive another snapshot - * with is_from_cache() equal to false once the client has received up-to-date - * data from the backend. - */ - bool is_from_cache() const { return is_from_cache_; } - - /** - * Returns a string representation of this `SnapshotMetadata` for - * logging/debugging purposes. - * - * @note the exact string representation is unspecified and subject to - * change; don't rely on the format of the string. - */ - std::string ToString() const; - - /** - * Outputs the string representation of this `SnapshotMetadata` to the given - * stream. - * - * @see `ToString()` for comments on the representation format. - */ - friend std::ostream& operator<<(std::ostream& out, - const SnapshotMetadata& metadata); - - private: - bool has_pending_writes_ = false; - bool is_from_cache_ = false; -}; - -/** Checks `lhs` and `rhs` for equality. */ -inline bool operator==(const SnapshotMetadata& lhs, - const SnapshotMetadata& rhs) { - return lhs.has_pending_writes() == rhs.has_pending_writes() && - lhs.is_from_cache() == rhs.is_from_cache(); -} - -/** Checks `lhs` and `rhs` for inequality. */ -inline bool operator!=(const SnapshotMetadata& lhs, - const SnapshotMetadata& rhs) { - return !(lhs == rhs); -} - -} // namespace firestore -} // namespace firebase - -#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_SNAPSHOT_METADATA_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/source.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/source.h deleted file mode 100644 index 743106d9e578..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/source.h +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright 2018 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_SOURCE_H_ -#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_SOURCE_H_ - -namespace firebase { -namespace firestore { - -/** - * @brief Configures the behavior of DocumentReference::Get() and Query::Get(). - * - * By providing a Source value, these methods can be configured to fetch results - * only from the server, only from the local cache, or attempt to fetch results - * from the server and fall back to the cache (which is the default). - */ -enum class Source { - /** - * Causes Firestore to try to retrieve an up-to-date (server-retrieved) - * snapshot, but fall back to returning cached data if the server can't be - * reached. - */ - kDefault, - - /** - * Causes Firestore to avoid the cache, generating an error if the server - * cannot be reached. Note that the cache will still be updated if the server - * request succeeds. Also note that latency-compensation still takes effect, - * so any pending write operations will be visible in the returned data - * (merged into the server-provided data). - */ - kServer, - - /** - * Causes Firestore to immediately return a value from the cache, ignoring the - * server completely (implying that the returned value may be stale with - * respect to the value on the server). If there is no data in the cache to - * satisfy the DocumentReference::Get() call will return an error and - * Query::Get() will return an empty QuerySnapshot with no documents. - */ - kCache, -}; - -} // namespace firestore -} // namespace firebase -#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_SOURCE_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/timestamp.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/timestamp.h deleted file mode 100644 index e806bb87c136..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/timestamp.h +++ /dev/null @@ -1,252 +0,0 @@ -/* - * Copyright 2018 Google - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIRESTORE_CORE_INCLUDE_FIREBASE_FIRESTORE_TIMESTAMP_H_ -#define FIRESTORE_CORE_INCLUDE_FIREBASE_FIRESTORE_TIMESTAMP_H_ - -#include -#include -#include -#include - -#if !defined(_STLPORT_VERSION) -#include // NOLINT(build/c++11) -#endif // !defined(_STLPORT_VERSION) - -namespace firebase { - -/** - * A Timestamp represents a point in time independent of any time zone or - * calendar, represented as seconds and fractions of seconds at nanosecond - * resolution in UTC Epoch time. It is encoded using the Proleptic Gregorian - * Calendar which extends the Gregorian calendar backwards to year one. It is - * encoded assuming all minutes are 60 seconds long, i.e. leap seconds are - * "smeared" so that no leap second table is needed for interpretation. Range is - * from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.999999999Z. - * - * @see - * https://github.com/google/protobuf/blob/master/src/google/protobuf/timestamp.proto - */ -class Timestamp { - public: - /** - * Creates a new timestamp representing the epoch (with seconds and - * nanoseconds set to 0). - */ - Timestamp() = default; - - /** - * Creates a new timestamp. - * - * @param seconds The number of seconds of UTC time since Unix epoch - * 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to - * 9999-12-31T23:59:59Z inclusive; otherwise, assertion failure will be - * triggered. - * @param nanoseconds The non-negative fractions of a second at nanosecond - * resolution. Negative second values with fractions must still have - * non-negative nanoseconds values that count forward in time. Must be - * from 0 to 999,999,999 inclusive; otherwise, assertion failure will be - * triggered. - */ - Timestamp(int64_t seconds, int32_t nanoseconds); - - /** Copy constructor, `Timestamp` is trivially copyable. */ - Timestamp(const Timestamp& other) = default; - - /** Move constructor, equivalent to copying. */ - Timestamp(Timestamp&& other) = default; - - /** Copy assignment operator, `Timestamp` is trivially copyable. */ - Timestamp& operator=(const Timestamp& other) = default; - - /** Move assignment operator, equivalent to copying. */ - Timestamp& operator=(Timestamp&& other) = default; - - /** - * Creates a new timestamp with the current date. - * - * The precision is up to nanoseconds, depending on the system clock. - * - * @return a new timestamp representing the current date. - */ - static Timestamp Now(); - - /** - * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z. - */ - int64_t seconds() const { - return seconds_; - } - - /** - * The non-negative fractions of a second at nanosecond resolution. Negative - * second values with fractions still have non-negative nanoseconds values - * that count forward in time. - */ - int32_t nanoseconds() const { - return nanoseconds_; - } - - /** - * Converts `time_t` to a `Timestamp`. - * - * @param seconds_since_unix_epoch - * @parblock - * The number of seconds of UTC time since Unix epoch - * 1970-01-01T00:00:00Z. Can be negative to represent dates before the - * epoch. Must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z - * inclusive; otherwise, assertion failure will be triggered. - * - * Note that while the epoch of `time_t` is unspecified, it's usually Unix - * epoch. If this assumption is broken, this function will produce - * incorrect results. - * @endparblock - * - * @return a new timestamp with the given number of seconds and zero - * nanoseconds. - */ - static Timestamp FromTimeT(time_t seconds_since_unix_epoch); - -#if !defined(_STLPORT_VERSION) - /** - * Converts `std::chrono::time_point` to a `Timestamp`. - * - * @param time_point - * @parblock - * The time point with system clock's epoch, which is - * presumed to be Unix epoch 1970-01-01T00:00:00Z. Can be negative to - * represent dates before the epoch. Must be from 0001-01-01T00:00:00Z to - * 9999-12-31T23:59:59Z inclusive; otherwise, assertion failure will be - * triggered. - * - * Note that while the epoch of `std::chrono::system_clock` is - * unspecified, it's usually Unix epoch. If this assumption is broken, - * this constructor will produce incorrect results. - * @endparblock - */ - static Timestamp FromTimePoint( - std::chrono::time_point time_point); - - /** - * Converts this `Timestamp` to a `time_point`. - * - * Important: if overflow would occur, the returned value will be the maximum - * or minimum value that `Duration` can hold. Note in particular that `long - * long` is insufficient to hold the full range of `Timestamp` values with - * nanosecond precision (which is why `Duration` defaults to `microseconds`). - */ - template - std::chrono::time_point ToTimePoint() const; -#endif // !defined(_STLPORT_VERSION) - - /** - * Returns a string representation of this `Timestamp` for logging/debugging - * purposes. - * - * @note: the exact string representation is unspecified and subject to - * change; don't rely on the format of the string. - */ - std::string ToString() const; - - /** - * Outputs the string representation of this `Timestamp` to the given stream. - * - * @see `ToString()` for comments on the representation format. - */ - friend std::ostream& operator<<(std::ostream& out, - const Timestamp& timestamp); - - private: - // Checks that the number of seconds is within the supported date range, and - // that nanoseconds satisfy 0 <= ns <= 1second. - void ValidateBounds() const; - - int64_t seconds_ = 0; - int32_t nanoseconds_ = 0; -}; - -/** Checks whether `lhs` and `rhs` are in ascending order. */ -inline bool operator<(const Timestamp& lhs, const Timestamp& rhs) { - return lhs.seconds() < rhs.seconds() || - (lhs.seconds() == rhs.seconds() && - lhs.nanoseconds() < rhs.nanoseconds()); -} - -/** Checks whether `lhs` and `rhs` are in descending order. */ -inline bool operator>(const Timestamp& lhs, const Timestamp& rhs) { - return rhs < lhs; -} - -/** Checks whether `lhs` and `rhs` are in non-ascending order. */ -inline bool operator>=(const Timestamp& lhs, const Timestamp& rhs) { - return !(lhs < rhs); -} - -/** Checks whether `lhs` and `rhs` are in non-descending order. */ -inline bool operator<=(const Timestamp& lhs, const Timestamp& rhs) { - return !(lhs > rhs); -} - -/** Checks `lhs` and `rhs` for inequality. */ -inline bool operator!=(const Timestamp& lhs, const Timestamp& rhs) { - return lhs < rhs || lhs > rhs; -} - -/** Checks `lhs` and `rhs` for equality. */ -inline bool operator==(const Timestamp& lhs, const Timestamp& rhs) { - return !(lhs != rhs); -} - -#if !defined(_STLPORT_VERSION) - -// Make sure the header compiles even when included after `` without -// `NOMINMAX` defined. `push/pop_macro` pragmas are supported by Visual Studio -// as well as Clang and GCC. -#pragma push_macro("min") -#pragma push_macro("max") -#undef min -#undef max - -template -std::chrono::time_point Timestamp::ToTimePoint() const { - namespace chr = std::chrono; - using TimePoint = chr::time_point; - - // Saturate on overflow - const auto max_seconds = chr::duration_cast(Duration::max()); - if (seconds_ > 0 && max_seconds.count() <= seconds_) { - return TimePoint{Duration::max()}; - } - const auto min_seconds = chr::duration_cast(Duration::min()); - if (seconds_ < 0 && min_seconds.count() >= seconds_) { - return TimePoint{Duration::min()}; - } - - const auto seconds = chr::duration_cast(chr::seconds(seconds_)); - const auto nanoseconds = - chr::duration_cast(chr::nanoseconds(nanoseconds_)); - return TimePoint{seconds + nanoseconds}; -} - -#pragma pop_macro("max") -#pragma pop_macro("min") - -#endif // !defined(_STLPORT_VERSION) - -} // namespace firebase - -#endif // FIRESTORE_CORE_INCLUDE_FIREBASE_FIRESTORE_TIMESTAMP_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/transaction.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/transaction.h deleted file mode 100644 index af78e0a2fb70..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/transaction.h +++ /dev/null @@ -1,143 +0,0 @@ -/* - * Copyright 2018 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_TRANSACTION_H_ -#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_TRANSACTION_H_ - -#include - -#include "firebase/firestore/firestore_errors.h" -#include "firebase/firestore/map_field_value.h" -#include "firebase/firestore/set_options.h" - -namespace firebase { -namespace firestore { - -class DocumentReference; -class DocumentSnapshot; -class TransactionInternal; - -/** - * @brief Transaction provides methods to read and write data within - * a transaction. - * - * You cannot create a `Transaction` directly; use `Firestore::RunTransaction()` - * function instead. - * - * @note Firestore classes are not meant to be subclassed except for use in test - * mocks. Subclassing is not supported in production code and new SDK releases - * may break code that does so. - */ -class Transaction { - public: - /** Destructor. */ - virtual ~Transaction(); - - /** - * @brief Deleted copy constructor. - * - * A `Transaction` object is only valid for the duration of the callback you - * pass to `Firestore::RunTransaction()` and cannot be copied. - */ - Transaction(const Transaction& other) = delete; - - /** - * @brief Deleted copy assignment operator. - * - * A `Transaction` object is only valid for the duration of the callback you - * pass to `Firestore::RunTransaction()` and cannot be copied. - */ - Transaction& operator=(const Transaction& other) = delete; - - /** - * @brief Writes to the document referred to by the provided reference. - * - * If the document does not yet exist, it will be created. If you pass - * SetOptions, the provided data can be merged into an existing document. - * - * @param[in] document The DocumentReference to overwrite. - * @param[in] data A map of the fields and values to write to the document. - * @param[in] options An object to configure the Set() behavior (optional). - */ - virtual void Set(const DocumentReference& document, - const MapFieldValue& data, - const SetOptions& options = SetOptions()); - - /** - * Updates fields in the document referred to by the provided reference. If no - * document exists yet, the update will fail. - * - * @param[in] document The DocumentReference to update. - * @param[in] data A map of field / value pairs to update. Fields can contain - * dots to reference nested fields within the document. - */ - virtual void Update(const DocumentReference& document, - const MapFieldValue& data); - - /** - * Updates fields in the document referred to by the provided reference. If no - * document exists yet, the update will fail. - * - * @param[in] document The DocumentReference to update. - * @param[in] data A map from FieldPath to FieldValue to update. - */ - virtual void Update(const DocumentReference& document, - const MapFieldPathValue& data); - - /** - * Deletes the document referred to by the provided reference. - * - * @param[in] document The DocumentReference to delete. - */ - virtual void Delete(const DocumentReference& document); - - /** - * Reads the document referred by the provided reference. - * - * @param[in] document The DocumentReference to read. - * @param[out] error_code An out parameter to capture an error, if one - * occurred. - * @param[out] error_message An out parameter to capture error message, if - * any. - * @return The contents of the document at this DocumentReference or invalid - * DocumentSnapshot if there is any error. - */ - virtual DocumentSnapshot Get(const DocumentReference& document, - Error* error_code, - std::string* error_message); - - protected: - /** - * Default constructor, to be used only for mocking a `Transaction`. - */ - Transaction() = default; - - private: - friend class FirestoreInternal; - friend class TransactionInternal; - friend struct ConverterImpl; - template - friend struct CleanupFn; - - explicit Transaction(TransactionInternal* internal); - - mutable TransactionInternal* internal_ = nullptr; -}; - -} // namespace firestore -} // namespace firebase - -#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_TRANSACTION_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/transaction_options.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/transaction_options.h deleted file mode 100644 index 9433578879b3..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/transaction_options.h +++ /dev/null @@ -1,137 +0,0 @@ -/* - * Copyright 2022 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_TRANSACTION_OPTIONS_H_ -#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_TRANSACTION_OPTIONS_H_ - -#include -#include -#include - -namespace firebase { -namespace firestore { - -/** - * Options to customize transaction behavior for `Firestore.runTransaction()`. - */ -class TransactionOptions final { - public: - /** - * @brief Creates the default `TransactionOptions`. - */ - TransactionOptions() = default; - - /** - * @brief Copy constructor. - * - * This performs a deep copy, creating an independent instance. - * - * @param[in] other `TransactionOptions` to copy from. - */ - TransactionOptions(const TransactionOptions& other) = default; - - /** - * @brief Move constructor. - * - * Moving is not any more efficient than copying for `TransactionOptions` - * because this class is trivially copyable; however, future additions to this - * class may make it not trivially copyable, at which point moving would be - * more efficient than copying. After being moved from, `TransactionOptions` - * is in a valid but unspecified state. - * - * @param[in] other `TransactionOptions` to move data from. - */ - TransactionOptions(TransactionOptions&& other) = default; - - /** - * @brief Copy assignment operator. - * - * This performs a deep copy, creating an independent instance. - * - * @param[in] other `TransactionOptions` to copy from. - * - * @return Reference to the destination `TransactionOptions`. - */ - TransactionOptions& operator=(const TransactionOptions& other) = default; - - /** - * @brief Move assignment operator. - * - * Moving is not any more efficient than copying for `TransactionOptions` - * because this class is trivially copyable; however, future additions to this - * class may make it not trivially copyable, at which point moving would be - * more efficient than copying. After being moved from, `TransactionOptions` - * is in a valid but unspecified state. - * - * @param[in] other `TransactionOptions` to move data from. - * - * @return Reference to the destination `TransactionOptions`. - */ - TransactionOptions& operator=(TransactionOptions&& other) = default; - - /** - * @brief Gets the maximum number of attempts to commit, after which the - * transaction fails. - * - * The default value is 5. - */ - int32_t max_attempts() const { return max_attempts_; } - - /** - * @brief Sets the maximum number of attempts to commit, after which the - * transaction fails. - * - * The default value is 5. - * - * @param[in] max_attempts The maximum number of attempts; must be greater - * than zero. - */ - void set_max_attempts(int32_t max_attempts); - - /** - * Returns a string representation of this `TransactionOptions` object for - * logging/debugging purposes. - * - * @note the exact string representation is unspecified and subject to - * change; don't rely on the format of the string. - */ - std::string ToString() const; - - /** - * Outputs the string representation of this `TransactionOptions` object to - * the given stream. - * - * @see `ToString()` for comments on the representation format. - */ - friend std::ostream& operator<<(std::ostream&, const TransactionOptions&); - - private: - int32_t max_attempts_ = 5; -}; - -/** Compares two `TransactionOptions` objects for equality. */ -bool operator==(const TransactionOptions&, const TransactionOptions&); - -/** Compares two `TransactionOptions` objects for inequality. */ -inline bool operator!=(const TransactionOptions& lhs, - const TransactionOptions& rhs) { - return !(lhs == rhs); -} - -} // namespace firestore -} // namespace firebase - -#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_TRANSACTION_OPTIONS_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/write_batch.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/write_batch.h deleted file mode 100644 index 1e92cd693516..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/write_batch.h +++ /dev/null @@ -1,188 +0,0 @@ -/* - * Copyright 2018 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_WRITE_BATCH_H_ -#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_WRITE_BATCH_H_ - -#include "firebase/firestore/map_field_value.h" -#include "firebase/firestore/set_options.h" - -namespace firebase { - -/// @cond FIREBASE_APP_INTERNAL -template -class Future; -/// @endcond - -namespace firestore { - -class DocumentReference; -class WriteBatchInternal; - -/** - * @brief A write batch is used to perform multiple writes as a single atomic - * unit. - * - * A WriteBatch object provides methods for adding writes to the write batch. - * None of the writes will be committed (or visible locally) until Commit() is - * called. - * - * Unlike transactions, write batches are persisted offline and therefore are - * preferable when you don't need to condition your writes on read data. - * - * @note Firestore classes are not meant to be subclassed except for use in test - * mocks. Subclassing is not supported in production code and new SDK releases - * may break code that does so. - */ -class WriteBatch { - public: - /** - * @brief Creates an invalid WriteBatch that has to be reassigned before it - * can be used. - * - * Calling any member function on an invalid WriteBatch will be a no-op. If - * the function returns a value, it will return a zero, empty, or invalid - * value, depending on the type of the value. - */ - WriteBatch(); - - /** - * @brief Copy constructor. - * - * This performs a deep copy, creating an independent instance. - * - * @param[in] other `WriteBatch` to copy from. - */ - WriteBatch(const WriteBatch& other); - - /** - * @brief Move constructor. - * - * Moving is more efficient than copying for a `WriteBatch`. After being moved - * from, a `WriteBatch` is equivalent to its default-constructed state. - * - * @param[in] other `WriteBatch` to move data from. - */ - WriteBatch(WriteBatch&& other); - - virtual ~WriteBatch(); - - /** - * @brief Copy assignment operator. - * - * This performs a deep copy, creating an independent instance. - * - * @param[in] other `WriteBatch` to copy from. - * - * @return Reference to the destination `WriteBatch`. - */ - WriteBatch& operator=(const WriteBatch& other); - - /** - * @brief Move assignment operator. - * - * Moving is more efficient than copying for a `WriteBatch`. After being moved - * from, a `WriteBatch` is equivalent to its default-constructed state. - * - * @param[in] other `WriteBatch` to move data from. - * - * @return Reference to the destination `WriteBatch`. - */ - WriteBatch& operator=(WriteBatch&& other); - - /** - * @brief Writes to the document referred to by the provided reference. - * - * If the document does not yet exist, it will be created. If you pass - * SetOptions, the provided data can be merged into an existing document. - * - * @param document The DocumentReference to write to. - * @param data A map of the fields and values to write to the document. - * @param[in] options An object to configure the Set() behavior (optional). - * - * @return This WriteBatch instance. Used for chaining method calls. - */ - virtual WriteBatch& Set(const DocumentReference& document, - const MapFieldValue& data, - const SetOptions& options = SetOptions()); - - /** - * Updates fields in the document referred to by the provided reference. If no - * document exists yet, the update will fail. - * - * @param document The DocumentReference to update. - * @param data A map of field / value pairs to update. Fields can contain dots - * to reference nested fields within the document. - * @return This WriteBatch instance. Used for chaining method calls. - */ - virtual WriteBatch& Update(const DocumentReference& document, - const MapFieldValue& data); - - /** - * Updates fields in the document referred to by the provided reference. If no - * document exists yet, the update will fail. - * - * @param document The DocumentReference to update. - * @param data A map from FieldPath to FieldValue to update. - * @return This WriteBatch instance. Used for chaining method calls. - */ - virtual WriteBatch& Update(const DocumentReference& document, - const MapFieldPathValue& data); - - /** - * Deletes the document referred to by the provided reference. - * - * @param document The DocumentReference to delete. - * @return This WriteBatch instance. Used for chaining method calls. - */ - virtual WriteBatch& Delete(const DocumentReference& document); - - /** - * Commits all of the writes in this write batch as a single atomic unit. - * - * @return A Future that will be resolved when the write finishes. - */ - virtual Future Commit(); - - /** - * @brief Returns true if this `WriteBatch` is valid, false if it is not - * valid. An invalid `WriteBatch` could be the result of: - * - Creating a `WriteBatch` using the default constructor. - * - Moving from the `WriteBatch`. - * - Deleting your Firestore instance, which will invalidate all the - * `WriteBatch` instances associated with it. - * - * @return true if this `WriteBatch` is valid, false if this `WriteBatch` is - * invalid. - */ - bool is_valid() const { return internal_ != nullptr; } - - private: - friend class FirestoreInternal; - friend class WriteBatchInternal; - friend struct ConverterImpl; - template - friend struct CleanupFn; - - explicit WriteBatch(WriteBatchInternal* internal); - - mutable WriteBatchInternal* internal_ = nullptr; -}; - -} // namespace firestore -} // namespace firebase - -#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_WRITE_BATCH_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/functions.h b/packages/firebase_core/firebase_core/firebase_core/firebase/functions.h deleted file mode 100644 index 500a05cc7ae9..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/functions.h +++ /dev/null @@ -1,115 +0,0 @@ -// Copyright 2017 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef FIREBASE_FUNCTIONS_SRC_INCLUDE_FIREBASE_FUNCTIONS_H_ -#define FIREBASE_FUNCTIONS_SRC_INCLUDE_FIREBASE_FUNCTIONS_H_ - -#include - -#include "firebase/app.h" -#include "firebase/functions/callable_reference.h" -#include "firebase/functions/callable_result.h" -#include "firebase/functions/common.h" - -namespace firebase { - -/// Namespace for the Firebase C++ SDK for Cloud Functions. -namespace functions { - -/// @cond FIREBASE_APP_INTERNAL -namespace internal { -class FunctionsInternal; -} // namespace internal -/// @endcond - -class FunctionsReference; - -#ifndef SWIG -/// @brief Entry point for the Firebase C++ SDK for Cloud Functions. -/// -/// To use the SDK, call firebase::functions::Functions::GetInstance() to -/// obtain an instance of Functions, then use GetHttpsCallable() to obtain -/// references to callable functions. From there you can call them with -/// CallableReference::Call(). -#endif // SWIG -class Functions { - public: - /// @brief Destructor. You may delete an instance of Functions when - /// you are finished using it, to shut down the Functions library. - ~Functions(); - - /// @brief Get an instance of Functions corresponding to the given App. - /// - /// Cloud Functions uses firebase::App to communicate with Firebase - /// Authentication to authenticate users to the server backend. - /// - /// @param[in] app An instance of firebase::App. Cloud Functions will use - /// this to communicate with Firebase Authentication. - /// @param[out] init_result_out Optional: If provided, write the init result - /// here. Will be set to kInitResultSuccess if initialization succeeded, or - /// kInitResultFailedMissingDependency on Android if Google Play services is - /// not available on the current device. - /// - /// @returns An instance of Functions corresponding to the given App. - static Functions* GetInstance(::firebase::App* app, - InitResult* init_result_out = nullptr); - - /// @brief Get an instance of Functions corresponding to the given App. - /// - /// Cloud Functions uses firebase::App to communicate with Firebase - /// Authentication to authenticate users to the server backend. - /// - /// @param[in] app An instance of firebase::App. Cloud Functions will use - /// this to communicate with Firebase Authentication. - /// @param[in] region The region to call functions in. - /// @param[out] init_result_out Optional: If provided, write the init result - /// here. Will be set to kInitResultSuccess if initialization succeeded, or - /// kInitResultFailedMissingDependency on Android if Google Play services is - /// not available on the current device. - /// - /// @returns An instance of Functions corresponding to the given App. - static Functions* GetInstance(::firebase::App* app, const char* region, - InitResult* init_result_out = nullptr); - - /// @brief Get the firebase::App that this Functions was created with. - /// - /// @returns The firebase::App this Functions was created with. - ::firebase::App* app(); - - /// @brief Get a FunctionsReference for the specified path. - HttpsCallableReference GetHttpsCallable(const char* name) const; - - /// @brief Get a FunctionsReference for the specified URL. - HttpsCallableReference GetHttpsCallableFromURL(const char* url) const; - - /// @brief Sets an origin for a Cloud Functions emulator to use. - void UseFunctionsEmulator(const char* origin); - - private: - /// @cond FIREBASE_APP_INTERNAL - Functions(::firebase::App* app, const char* region); - Functions(const Functions& src); - Functions& operator=(const Functions& src); - - // Delete the internal_ data. - void DeleteInternal(); - - internal::FunctionsInternal* internal_; - /// @endcond -}; - -} // namespace functions -} // namespace firebase - -#endif // FIREBASE_FUNCTIONS_SRC_INCLUDE_FIREBASE_FUNCTIONS_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/functions/callable_reference.h b/packages/firebase_core/firebase_core/firebase_core/firebase/functions/callable_reference.h deleted file mode 100644 index 9641c23564df..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/functions/callable_reference.h +++ /dev/null @@ -1,124 +0,0 @@ -// Copyright 2017 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef FIREBASE_FUNCTIONS_SRC_INCLUDE_FIREBASE_FUNCTIONS_CALLABLE_REFERENCE_H_ -#define FIREBASE_FUNCTIONS_SRC_INCLUDE_FIREBASE_FUNCTIONS_CALLABLE_REFERENCE_H_ - -#include -#include - -#include "firebase/future.h" -#include "firebase/internal/common.h" - -namespace firebase { -class Variant; - -namespace functions { -class Functions; -class HttpsCallableResult; - -/// @cond FIREBASE_APP_INTERNAL -namespace internal { -class HttpsCallableReferenceInternal; -} // namespace internal -/// @endcond - -#ifndef SWIG -/// Represents a reference to a Cloud Functions object. -/// Developers can call HTTPS Callable Functions. -#endif // SWIG -class HttpsCallableReference { - public: - /// @brief Default constructor. This creates an invalid - /// HttpsCallableReference. Attempting to perform any operations on this - /// reference will fail unless a valid HttpsCallableReference has been - /// assigned to it. - HttpsCallableReference() : internal_(nullptr) {} - - ~HttpsCallableReference(); - - /// @brief Copy constructor. It's totally okay (and efficient) to copy - /// HttpsCallableReference instances, as they simply point to the same - /// location. - /// - /// @param[in] reference HttpsCallableReference to copy from. - HttpsCallableReference(const HttpsCallableReference& reference); - - /// @brief Copy assignment operator. It's totally okay (and efficient) to copy - /// HttpsCallableReference instances, as they simply point to the same - /// location. - /// - /// @param[in] reference HttpsCallableReference to copy from. - /// - /// @returns Reference to the destination HttpsCallableReference. - HttpsCallableReference& operator=(const HttpsCallableReference& reference); - -#if defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) - /// @brief Move constructor. Moving is an efficient operation for - /// HttpsCallableReference instances. - /// - /// @param[in] other HttpsCallableReference to move data from. - HttpsCallableReference(HttpsCallableReference&& other); - - /// @brief Move assignment operator. Moving is an efficient operation for - /// HttpsCallableReference instances. - /// - /// @param[in] other HttpsCallableReference to move data from. - /// - /// @returns Reference to the destination HttpsCallableReference. - HttpsCallableReference& operator=(HttpsCallableReference&& other); -#endif // defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) - - /// @brief Gets the firebase::functions::Functions instance to which we refer. - /// - /// The pointer will remain valid indefinitely. - /// - /// @returns The firebase::functions::Functions instance that this - /// HttpsCallableReference refers to. - Functions* functions(); - - /// @brief Calls the function. - /// - /// @returns The result of the call; - Future Call(); - - /// @brief Calls the function. - /// - /// @param[in] data The params to pass to the function. - /// @returns The result of the call; - Future Call(const Variant& data); - - /// @brief Returns true if this HttpsCallableReference is valid, false if it - /// is not valid. An invalid HttpsCallableReference indicates that the - /// reference is uninitialized (created with the default constructor) or that - /// there was an error retrieving the reference. - /// - /// @returns true if this HttpsCallableReference is valid, false if this - /// HttpsCallableReference is invalid. - bool is_valid() const; - - private: - /// @cond FIREBASE_APP_INTERNAL - friend class Functions; - - HttpsCallableReference(internal::HttpsCallableReferenceInternal* internal); - - internal::HttpsCallableReferenceInternal* internal_; - /// @endcond -}; - -} // namespace functions -} // namespace firebase - -#endif // FIREBASE_FUNCTIONS_SRC_INCLUDE_FIREBASE_FUNCTIONS_CALLABLE_REFERENCE_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/functions/callable_result.h b/packages/firebase_core/firebase_core/firebase_core/firebase/functions/callable_result.h deleted file mode 100644 index 5186377ae828..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/functions/callable_result.h +++ /dev/null @@ -1,96 +0,0 @@ -// Copyright 2018 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef FIREBASE_FUNCTIONS_SRC_INCLUDE_FIREBASE_FUNCTIONS_CALLABLE_RESULT_H_ -#define FIREBASE_FUNCTIONS_SRC_INCLUDE_FIREBASE_FUNCTIONS_CALLABLE_RESULT_H_ - -#include "firebase/functions/common.h" -#include "firebase/variant.h" - -namespace firebase { -namespace functions { - -/// @cond FIREBASE_APP_INTERNAL -namespace internal { -class HttpsCallableReferenceInternal; -} -/// @endcond - -/// An HttpsCallableResult contains the result of calling an HttpsCallable. -class HttpsCallableResult { - public: - /// @brief Creates an HttpsCallableResult with null data. - HttpsCallableResult() {} - - ~HttpsCallableResult() {} - - /// @brief Copy constructor. Copying is as efficient as copying a Variant. - /// - /// @param[in] other HttpsCallableResult to copy data from. - HttpsCallableResult(const HttpsCallableResult& other) : data_(other.data_) {} - - /// @brief Assignment operator. Copying is as efficient as copying a Variant. - /// - /// @param[in] other HttpsCallableResult to copy data from. - /// - /// @returns Reference to the destination HttpsCallableResult. - HttpsCallableResult& operator=(const HttpsCallableResult& other) { - data_ = other.data_; - return *this; - } - -#if defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) - /// @brief Move constructor. Moving is an efficient operation for - /// HttpsCallableResult instances. - /// - /// @param[in] other HttpsCallableResult to move data from. - HttpsCallableResult(HttpsCallableResult&& other) { - data_ = std::move(other.data_); - } - - /// @brief Move assignment operator. Moving is an efficient operation for - /// HttpsCallableResult instances. - /// - /// @param[in] other HttpsCallableResult to move data from. - /// - /// @returns Reference to the destination HttpsCallableResult. - HttpsCallableResult& operator=(HttpsCallableResult&& other) { - data_ = std::move(other.data_); - return *this; - } - -#endif // defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) - - /// @brief Returns the data that is the result of a Call. - /// - /// @returns The variant containing the data. - const Variant& data() const { return data_; } - - private: - /// @cond FIREBASE_APP_INTERNAL - // Only functions are allowed to construct results. - friend class ::firebase::functions::internal::HttpsCallableReferenceInternal; - HttpsCallableResult(const Variant& data) : data_(data) {} -#if defined(FIREBASE_USE_MOVE_OPERATORS) - HttpsCallableResult(Variant&& data) : data_(std::move(data)) {} -#endif // defined(FIREBASE_USE_MOVE_OPERATORS) - - Variant data_; - /// @endcond -}; - -} // namespace functions -} // namespace firebase - -#endif // FIREBASE_FUNCTIONS_SRC_INCLUDE_FIREBASE_FUNCTIONS_CALLABLE_RESULT_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/functions/common.h b/packages/firebase_core/firebase_core/firebase_core/firebase/functions/common.h deleted file mode 100644 index 143dc8257618..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/functions/common.h +++ /dev/null @@ -1,202 +0,0 @@ -// Copyright 2017 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef FIREBASE_FUNCTIONS_SRC_INCLUDE_FIREBASE_FUNCTIONS_COMMON_H_ -#define FIREBASE_FUNCTIONS_SRC_INCLUDE_FIREBASE_FUNCTIONS_COMMON_H_ - -#include "firebase/variant.h" - -namespace firebase { -namespace functions { - -/// Error code returned by Cloud Functions C++ functions. -/// Standard gRPC error codes, as defined in: -/// https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto -enum Error { -#ifdef INTERNAL_EXPERIMENTAL -// LINT.IfChange -#endif // INTERNAL_EXPERIMENTAL - - // Not an error; returned on success - // - // HTTP Mapping: 200 OK - kErrorNone = 0, - - // The operation was cancelled, typically by the caller. - // - // HTTP Mapping: 499 Client Closed Request - kErrorCancelled = 1, - - // Unknown error. For example, this error may be returned when - // a `Status` value received from another address space belongs to - // an error space that is not known in this address space. Also - // errors raised by APIs that do not return enough error information - // may be converted to this error. - // - // HTTP Mapping: 500 Internal Server Error - kErrorUnknown = 2, - - // The client specified an invalid argument. Note that this differs - // from `FAILED_PRECONDITION`. `INVALID_ARGUMENT` indicates arguments - // that are problematic regardless of the state of the system - // (e.g., a malformed file name). - // - // HTTP Mapping: 400 Bad Request - kErrorInvalidArgument = 3, - - // The deadline expired before the operation could complete. For operations - // that change the state of the system, this error may be returned - // even if the operation has completed successfully. For example, a - // successful response from a server could have been delayed long - // enough for the deadline to expire. - // - // HTTP Mapping: 504 Gateway Timeout - kErrorDeadlineExceeded = 4, - - // Some requested entity (e.g., file or directory) was not found. - // - // Note to server developers: if a request is denied for an entire class - // of users, such as gradual feature rollout or undocumented whitelist, - // `NOT_FOUND` may be used. If a request is denied for some users within - // a class of users, such as user-based access control, `PERMISSION_DENIED` - // must be used. - // - // HTTP Mapping: 404 Not Found - kErrorNotFound = 5, - - // The entity that a client attempted to create (e.g., file or directory) - // already exists. - // - // HTTP Mapping: 409 Conflict - kErrorAlreadyExists = 6, - - // The caller does not have permission to execute the specified - // operation. `PERMISSION_DENIED` must not be used for rejections - // caused by exhausting some resource (use `RESOURCE_EXHAUSTED` - // instead for those errors). `PERMISSION_DENIED` must not be - // used if the caller can not be identified (use `UNAUTHENTICATED` - // instead for those errors). This error code does not imply the - // request is valid or the requested entity exists or satisfies - // other pre-conditions. - // - // HTTP Mapping: 403 Forbidden - kErrorPermissionDenied = 7, - - // The request does not have valid authentication credentials for the - // operation. - // - // HTTP Mapping: 401 Unauthorized - kErrorUnauthenticated = 16, - - // Some resource has been exhausted, perhaps a per-user quota, or - // perhaps the entire file system is out of space. - // - // HTTP Mapping: 429 Too Many Requests - kErrorResourceExhausted = 8, - - // The operation was rejected because the system is not in a state - // required for the operation's execution. For example, the directory - // to be deleted is non-empty, an rmdir operation is applied to - // a non-directory, etc. - // - // Service implementors can use the following guidelines to decide - // between `FAILED_PRECONDITION`, `ABORTED`, and `UNAVAILABLE`: - // (a) Use `UNAVAILABLE` if the client can retry just the failing call. - // (b) Use `ABORTED` if the client should retry at a higher level - // (e.g., when a client-specified test-and-set fails, indicating the - // client should restart a read-modify-write sequence). - // (c) Use `FAILED_PRECONDITION` if the client should not retry until - // the system state has been explicitly fixed. E.g., if an "rmdir" - // fails because the directory is non-empty, `FAILED_PRECONDITION` - // should be returned since the client should not retry unless - // the files are deleted from the directory. - // - // HTTP Mapping: 400 Bad Request - kErrorFailedPrecondition = 9, - - // The operation was aborted, typically due to a concurrency issue such as - // a sequencer check failure or transaction abort. - // - // See the guidelines above for deciding between `FAILED_PRECONDITION`, - // `ABORTED`, and `UNAVAILABLE`. - // - // HTTP Mapping: 409 Conflict - kErrorAborted = 10, - - // The operation was attempted past the valid range. E.g., seeking or - // reading past end-of-file. - // - // Unlike `INVALID_ARGUMENT`, this error indicates a problem that may - // be fixed if the system state changes. For example, a 32-bit file - // system will generate `INVALID_ARGUMENT` if asked to read at an - // offset that is not in the range [0,2^32-1], but it will generate - // `OUT_OF_RANGE` if asked to read from an offset past the current - // file size. - // - // There is a fair bit of overlap between `FAILED_PRECONDITION` and - // `OUT_OF_RANGE`. We recommend using `OUT_OF_RANGE` (the more specific - // error) when it applies so that callers who are iterating through - // a space can easily look for an `OUT_OF_RANGE` error to detect when - // they are done. - // - // HTTP Mapping: 400 Bad Request - kErrorOutOfRange = 11, - - // The operation is not implemented or is not supported/enabled in this - // service. - // - // HTTP Mapping: 501 Not Implemented - kErrorUnimplemented = 12, - - // Internal errors. This means that some invariants expected by the - // underlying system have been broken. This error code is reserved - // for serious errors. - // - // HTTP Mapping: 500 Internal Server Error - kErrorInternal = 13, - - // The service is currently unavailable. This is most likely a - // transient condition, which can be corrected by retrying with - // a backoff. - // - // See the guidelines above for deciding between `FAILED_PRECONDITION`, - // `ABORTED`, and `UNAVAILABLE`. - // - // HTTP Mapping: 503 Service Unavailable - kErrorUnavailable = 14, - - // Unrecoverable data loss or corruption. - // - // HTTP Mapping: 500 Internal Server Error - kErrorDataLoss = 15, - -}; - -#ifdef INTERNAL_EXPERIMENTAL -/// @cond FIREBASE_APP_INTERNAL -namespace internal { - -// Get the human-readable error message corresponding to an error code. -// -// Returns a statically-allocated string describing the error code you pass in. -const char* GetErrorMessage(Error error); - -} // namespace internal -/// @endcond -#endif // INTERNAL_EXPERIMENTAL - -} // namespace functions -} // namespace firebase - -#endif // FIREBASE_FUNCTIONS_SRC_INCLUDE_FIREBASE_FUNCTIONS_COMMON_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/future.h b/packages/firebase_core/firebase_core/firebase_core/firebase/future.h deleted file mode 100644 index 0d09fc079a32..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/future.h +++ /dev/null @@ -1,533 +0,0 @@ -/* - * Copyright 2016 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_APP_SRC_INCLUDE_FIREBASE_FUTURE_H_ -#define FIREBASE_APP_SRC_INCLUDE_FIREBASE_FUTURE_H_ - -#include -#include - -#include - -#include "firebase/internal/common.h" -#include "firebase/internal/mutex.h" - -#ifdef FIREBASE_USE_STD_FUNCTION -#include -#endif - -namespace firebase { - -// Predeclarations. -/// @cond FIREBASE_APP_INTERNAL -namespace detail { -class FutureApiInterface; -class CompletionCallbackHandle; -} // namespace detail -/// @endcond - -/// Asynchronous call status. -enum FutureStatus { - /// Results are ready. - kFutureStatusComplete, - - /// Result is still being processed. - kFutureStatusPending, - - /// No result is pending. - /// FutureBase::Release() or move operator was called. - kFutureStatusInvalid -}; - -/// Handle that the API uses to identify an asynchronous call. -/// The exact interpretation of the handle is up to the API. -typedef uintptr_t FutureHandleId; - -/// Class that provides more context to FutureHandleId, which allows the -/// underlying API to track handles, perform reference counting, etc. -class FutureHandle { - public: - /// @cond FIREBASE_APP_INTERNAL - FutureHandle(); - explicit FutureHandle(FutureHandleId id) : FutureHandle(id, nullptr) {} - FutureHandle(FutureHandleId id, detail::FutureApiInterface* api); - ~FutureHandle(); - - // Copy constructor and assignment operator. - FutureHandle(const FutureHandle& rhs); - FutureHandle& operator=(const FutureHandle& rhs); - -#if defined(FIREBASE_USE_MOVE_OPERATORS) - // Move constructor and assignment operator. - FutureHandle(FutureHandle&& rhs) noexcept; - FutureHandle& operator=(FutureHandle&& rhs) noexcept; -#endif // defined(FIREBASE_USE_MOVE_OPERATORS) - - // Comparison operators. - bool operator!=(const FutureHandle& rhs) const { return !(*this == rhs); } - bool operator==(const FutureHandle& rhs) const { - // Only compare IDs, since the API is irrelevant (comparison will only occur - // within the context of a single API anyway). - return id() == rhs.id(); - } - - FutureHandleId id() const { return id_; } - detail::FutureApiInterface* api() const { return api_; } - - // Detach from the FutureApi. This handle will no longer increment the - // Future's reference count. This is mainly used for testing, so that you can - // still look up the Future based on its handle's ID without affecting the - // reference count yourself. - void Detach(); - - // Called by CleanupNotifier when the API is being deleted. At this point we - // can ignore all of the reference counts since all Future data is about to be - // deleted anyway. - void Cleanup() { api_ = nullptr; } - - private: - FutureHandleId id_; - detail::FutureApiInterface* api_; - /// @endcond -}; - -/// @brief Type-independent return type of asynchronous calls. -/// -/// @see Future for code samples. -/// -/// @cond FIREBASE_APP_INTERNAL -/// Notes: -/// - Futures have pointers back to the API, but the API does not maintain -/// pointers to its Futures. Therefore, all Futures must be destroyed -/// *before* the API is destroyed. -/// - Futures can be moved or copied. Call results are reference counted, -/// and are destroyed when they are no longer referenced by any Futures. -/// - The actual `Status`, `Error`, and `Result` values are kept inside the -/// API. This makes synchronization and data management easier. -/// -/// WARNING: This class should remain POD (plain old data). It should not have -/// virtual methods. Nor should the derived Future class add any -/// data. Internally, we static_cast FutureBase to Future, -/// so the underlying data should remain the same. -/// @endcond -class FutureBase { - public: - /// Function pointer for a completion callback. When we call this, we will - /// send the completed future, along with the user data that you specified - /// when you set up the callback. - typedef void (*CompletionCallback)(const FutureBase& result_data, - void* user_data); - -#if defined(INTERNAL_EXPERIMENTAL) - /// Handle, representing a completion callback, that can be passed to - /// RemoveOnCompletion. - using CompletionCallbackHandle = detail::CompletionCallbackHandle; -#endif - - /// Construct an untyped future. - FutureBase(); - - /// @cond FIREBASE_APP_INTERNAL - - /// Construct an untyped future using the specified API and handle. - /// - /// @param api API class used to provide the future implementation. - /// @param handle Handle to the future. - FutureBase(detail::FutureApiInterface* api, const FutureHandle& handle); - - /// @endcond - - ~FutureBase(); - - /// Copy constructor and operator. - /// Increment the reference count when creating a copy of the future. - FutureBase(const FutureBase& rhs); - - /// Copy an untyped future. - FutureBase& operator=(const FutureBase& rhs); - -#if defined(FIREBASE_USE_MOVE_OPERATORS) - /// Move constructor and operator. - /// Move is more efficient than copy and delete because we don't touch the - /// reference counting in the API. - FutureBase(FutureBase&& rhs) noexcept; - - /// Copy an untyped future. - FutureBase& operator=(FutureBase&& rhs) noexcept; -#endif // defined(FIREBASE_USE_MOVE_OPERATORS) - - /// Explicitly release the internal resources for a future. - /// Future will become invalid. - void Release(); - - /// Completion status of the asynchronous call. - FutureStatus status() const; - - /// When status() is firebase::kFutureStatusComplete, returns the API-defined - /// error code. Otherwise, return value is undefined. - int error() const; - - /// When status() is firebase::kFutureStatusComplete, returns the API-defined - /// error message, as human-readable text, or an empty string if the API does - /// not provide a human readable description of the error. - /// - /// @note The returned pointer is only valid for the lifetime of the Future - /// or its copies. - const char* error_message() const; - - /// Result of the asynchronous call, or nullptr if the result is still - /// pending. Cast is required since GetFutureResult() returns void*. - const void* result_void() const; - -#if defined(INTERNAL_EXPERIMENTAL) - /// Special timeout value indicating an infinite timeout. - /// - /// Passing this value to FutureBase::Wait() or Future::Await() will cause - /// those methods to wait until the future is complete. - /// - /// @Warning It is inadvisable to use this from code that could be called - /// from an event loop. - static const int kWaitTimeoutInfinite; - - /// Block (i.e. suspend the current thread) until either the future is - /// completed or the specified timeout period (in milliseconds) has elapsed. - /// If `timeout_milliseconds` is `kWaitTimeoutInfinite`, then the timeout - /// period is treated as being infinite, i.e. this will block until the - /// future is completed. - /// - /// @return True if the future completed, or - /// false if the timeout period elapsed before the future completed. - bool Wait(int timeout_milliseconds) const; -#endif // defined(INTERNAL_EXPERIMENTAL) - - /// Register a single callback that will be called at most once, when the - /// future is completed. - /// - /// If you call any OnCompletion() method more than once on the same future, - /// only the most recent callback you registered with OnCompletion() will be - /// called. -#if defined(INTERNAL_EXPERIMENTAL) - /// However completions registered with AddCompletion() will still be - /// called even if there is a subsequent call to OnCompletion(). - /// - /// When the future completes, first the most recent callback registered with - /// OnCompletion(), if any, will be called; then all callbacks registered with - /// AddCompletion() will be called, in the order that they were registered. -#endif - /// - /// When your callback is called, the user_data that you supplied here will be - /// passed back as the second parameter. - /// - /// @param[in] callback Function pointer to your callback. - /// @param[in] user_data Optional user data. We will pass this back to your - /// callback. - void OnCompletion(CompletionCallback callback, void* user_data) const; - -#if defined(FIREBASE_USE_STD_FUNCTION) || defined(DOXYGEN) - /// Register a single callback that will be called at most once, when the - /// future is completed. - /// - /// If you call any OnCompletion() method more than once on the same future, - /// only the most recent callback you registered with OnCompletion() will be - /// called. -#if defined(INTERNAL_EXPERIMENTAL) - /// However completions registered with AddCompletion() will still be - /// called even if there is a subsequent call to OnCompletion(). - /// - /// When the future completes, first the most recent callback registered with - /// OnCompletion(), if any, will be called; then all callbacks registered with - /// AddCompletion() will be called, in the order that they were registered. -#endif - /// - /// @param[in] callback Function or lambda to call. - /// - /// @note This method is not available when using STLPort on Android, as - /// `std::function` is not supported on STLPort. - void OnCompletion(std::function callback) const; -#endif // defined(FIREBASE_USE_STD_FUNCTION) || defined(DOXYGEN) - -#if defined(INTERNAL_EXPERIMENTAL) - /// Like OnCompletion, but allows adding multiple callbacks. - /// - /// If you call AddCompletion() more than once, all of the completions that - /// you register will be called, when the future is completed. However, any - /// callbacks which were subsequently removed by calling RemoveOnCompletion - /// will not be called. - /// - /// When the future completes, first the most recent callback registered with - /// OnCompletion(), if any, will be called; then all callbacks registered with - /// AddCompletion() will be called, in the order that they were registered. - /// - /// @param[in] callback Function pointer to your callback. - /// @param[in] user_data Optional user data. We will pass this back to your - /// callback. - /// @return A handle that can be passed to RemoveOnCompletion. - CompletionCallbackHandle AddOnCompletion(CompletionCallback callback, - void* user_data) const; - -#if defined(FIREBASE_USE_STD_FUNCTION) || defined(DOXYGEN) - /// Like OnCompletion, but allows adding multiple callbacks. - /// - /// If you call AddCompletion() more than once, all of the completions that - /// you register will be called, when the future is completed. However, any - /// callbacks which were subsequently removed by calling RemoveOnCompletion - /// will not be called. - /// - /// When the future completes, first the most recent callback registered with - /// OnCompletion(), if any, will be called; then all callbacks registered with - /// AddCompletion() will be called, in the order that they were registered. - /// - /// @param[in] callback Function or lambda to call. - /// @return A handle that can be passed to RemoveOnCompletion. - /// - /// @note This method is not available when using STLPort on Android, as - /// `std::function` is not supported on STLPort. - CompletionCallbackHandle AddOnCompletion( - std::function callback) const; - -#endif // defined(FIREBASE_USE_STD_FUNCTION) || defined(DOXYGEN) - - /// Unregisters a callback that was previously registered with - /// AddOnCompletion. - /// - /// @param[in] completion_handle The return value of a previous call to - /// AddOnCompletion. - void RemoveOnCompletion(CompletionCallbackHandle completion_handle) const; -#endif // defined(INTERNAL_EXPERIMENTAL) - - /// Returns true if the two Futures reference the same result. - bool operator==(const FutureBase& rhs) const { - MutexLock lock(mutex_); - return api_ == rhs.api_ && handle_ == rhs.handle_; - } - - /// Returns true if the two Futures reference different results. - bool operator!=(const FutureBase& rhs) const { return !operator==(rhs); } - -#if defined(INTERNAL_EXPERIMENTAL) - /// Returns the API-specific handle. Should only be called by the API. - FutureHandle GetHandle() const { - MutexLock lock(mutex_); - return handle_; - } -#endif // defined(INTERNAL_EXPERIMENTAL) - - protected: - /// @cond FIREBASE_APP_INTERNAL - - mutable Mutex mutex_; - - /// Backpointer to the issuing API class. - /// Set to nullptr when Future is invalidated. - detail::FutureApiInterface* api_; - - /// API-specified handle type. - FutureHandle handle_; - - /// @endcond -}; - -/// @brief Type-specific version of FutureBase. -/// -/// The Firebase C++ SDK uses this class to return results from asynchronous -/// operations. All Firebase C++ functions and method calls that operate -/// asynchronously return a Future, and provide a "LastResult" function to -/// retrieve the most recent Future result. -/// -/// @code -/// // You can retrieve the Future from the function call directly, like this: -/// Future< SampleResultType > future = firebase::SampleAsyncOperation(); -/// -/// // Or you can retrieve it later, like this: -/// firebase::SampleAsyncOperation(); -/// // [...] -/// Future< SampleResultType > future = -/// firebase::SampleAsyncOperationLastResult(); -/// @endcode -/// -/// When you have a Future from an asynchronous operation, it will eventually -/// complete. Once it is complete, you can check for errors (a nonzero error() -/// means an error occurred) and get the result data if no error occurred by -/// calling result(). -/// -/// There are two ways to find out that a Future has completed. You can poll -/// its status(), or set an OnCompletion() callback: -/// -/// @code -/// // Check whether the status is kFutureStatusComplete. -/// if (future.status() == firebase::kFutureStatusComplete) { -/// if (future.error() == 0) { -/// DoSomethingWithResultData(future.result()); -/// } -/// else { -/// LogMessage("Error %d: %s", future.error(), future.error_message()); -/// } -/// } -/// -/// // Or, set an OnCompletion callback, which accepts a C++11 lambda or -/// // function pointer. You can pass your own user data to the callback. In -/// // most cases, the callback will be running in a different thread, so take -/// // care to make sure your code is thread-safe. -/// future.OnCompletion([](const Future< SampleResultType >& completed_future, -/// void* user_data) { -/// // We are probably in a different thread right now. -/// if (completed_future.error() == 0) { -/// DoSomethingWithResultData(completed_future.result()); -/// } -/// else { -/// LogMessage("Error %d: %s", -/// completed_future.error(), -/// completed_future.error_message()); -/// } -/// }, user_data); -/// @endcode -/// -/// @tparam ResultType The type of this Future's result. -// -// WARNING: This class should not have virtual methods or data members. -// See the warning in FutureBase for further details. -template -class Future : public FutureBase { - public: - /// Function pointer for a completion callback. When we call this, we will - /// send the completed future, along with the user data that you specified - /// when you set up the callback. - typedef void (*TypedCompletionCallback)(const Future& result_data, - void* user_data); - - /// Construct a future. - Future() {} - - /// @cond FIREBASE_APP_INTERNAL - - /// Construct a future using the specified API and handle. - /// - /// @param api API class used to provide the future implementation. - /// @param handle Handle to the future. - Future(detail::FutureApiInterface* api, const FutureHandle& handle) - : FutureBase(api, handle) {} - - /// @endcond - - /// Result of the asynchronous call, or nullptr if the result is still - /// pending. Allows the API to provide a type-specific interface. - /// - const ResultType* result() const { - return static_cast(result_void()); - } - -#if defined(INTERNAL_EXPERIMENTAL) - /// Waits (blocks) until either the future is completed, or the specified - /// timeout period (in milliseconds) has elapsed, then returns the result of - /// the asynchronous call. - /// - /// This is a convenience method that calls Wait() and then returns result(). - /// - /// If `timeout_milliseconds` is `kWaitTimeoutInfinite`, then the timeout - /// period is treated as being infinite, i.e. this will block until the - /// future is completed. - const ResultType* Await(int timeout_milliseconds) const { - Wait(timeout_milliseconds); - return result(); - } -#endif // defined(INTERNAL_EXPERIMENTAL) - - /// Register a single callback that will be called at most once, when the - /// future is completed. - /// - /// If you call any OnCompletion() method more than once on the same future, - /// only the most recent callback you registered will be called. - /// - /// When your callback is called, the user_data that you supplied here will be - /// passed back as the second parameter. - /// - /// @param[in] callback Function pointer to your callback. - /// @param[in] user_data Optional user data. We will pass this back to your - /// callback. - /// - /// @note This is the same callback as FutureBase::OnCompletion(), so you - /// can't expect to set both and have both run; again, only the most recently - /// registered one will run. - inline void OnCompletion(TypedCompletionCallback callback, - void* user_data) const; - -#if defined(FIREBASE_USE_STD_FUNCTION) || defined(DOXYGEN) - /// Register a single callback that will be called at most once, when the - /// future is completed. - /// - /// If you call any OnCompletion() method more than once on the same future, - /// only the most recent callback you registered will be called. - /// - /// @param[in] callback Function or lambda to call. - /// - /// @note This method is not available when using STLPort on Android, as - /// `std::function` is not supported on STLPort. - /// - /// @note This is the same callback as FutureBase::OnCompletion(), so you - /// can't expect to set both and have both run; again, only the most recently - /// registered one will run. - inline void OnCompletion( - std::function&)> callback) const; -#endif // defined(FIREBASE_USE_STD_FUNCTION) || defined(DOXYGEN) - -#if defined(INTERNAL_EXPERIMENTAL) - /// Like OnCompletion, but allows adding multiple callbacks. - /// - /// If you call AddCompletion() more than once, all of the completions that - /// you register will be called, when the future is completed. However, any - /// callbacks which were subsequently removed by calling RemoveOnCompletion - /// will not be called. - /// - /// When the future completes, first the most recent callback registered with - /// OnCompletion(), if any, will be called; then all callbacks registered with - /// AddCompletion() will be called, in the order that they were registered. - /// - /// @param[in] callback Function pointer to your callback. - /// @param[in] user_data Optional user data. We will pass this back to your - /// callback. - /// @return A handle that can be passed to RemoveOnCompletion. - inline CompletionCallbackHandle AddOnCompletion( - TypedCompletionCallback callback, void* user_data) const; - -#if defined(FIREBASE_USE_STD_FUNCTION) || defined(DOXYGEN) - /// Like OnCompletion, but allows adding multiple callbacks. - /// - /// If you call AddCompletion() more than once, all of the completions that - /// you register will be called, when the future is completed. However, any - /// callbacks which were subsequently removed by calling RemoveOnCompletion - /// will not be called. - /// - /// When the future completes, first the most recent callback registered with - /// OnCompletion(), if any, will be called; then all callbacks registered with - /// AddCompletion() will be called, in the order that they were registered. - /// - /// @param[in] callback Function or lambda to call. - /// @return A handle that can be passed to RemoveOnCompletion. - /// - /// @note This method is not available when using STLPort on Android, as - /// `std::function` is not supported on STLPort. - inline CompletionCallbackHandle AddOnCompletion( - std::function&)> callback) const; -#endif // defined(FIREBASE_USE_STD_FUNCTION) || defined(DOXYGEN) -#endif // defined(INTERNAL_EXPERIMENTAL) -}; - -} // namespace firebase - -// Include the inline implementation. -#include "firebase/internal/future_impl.h" - -#endif // FIREBASE_APP_SRC_INCLUDE_FIREBASE_FUTURE_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/gma.h b/packages/firebase_core/firebase_core/firebase_core/firebase/gma.h deleted file mode 100644 index b7da2cf569b9..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/gma.h +++ /dev/null @@ -1,207 +0,0 @@ -/* - * Copyright 2021 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_GMA_SRC_INCLUDE_FIREBASE_GMA_H_ -#define FIREBASE_GMA_SRC_INCLUDE_FIREBASE_GMA_H_ - -#include "firebase/internal/platform.h" - -#if FIREBASE_PLATFORM_ANDROID -#include -#endif // FIREBASE_PLATFORM_ANDROID - -#include - -#include "firebase/app.h" -#include "firebase/gma/ad_view.h" -#include "firebase/gma/interstitial_ad.h" -#include "firebase/gma/rewarded_ad.h" -#include "firebase/gma/types.h" -#include "firebase/internal/common.h" - -#if !defined(DOXYGEN) && !defined(SWIG) -FIREBASE_APP_REGISTER_CALLBACKS_REFERENCE(gma) -#endif // !defined(DOXYGEN) && !defined(SWIG) - -namespace firebase { -// In the GMA docs, link to firebase::Future in the Firebase C++ docs. -#if defined(DOXYGEN_ADMOB) -/// @brief The Google Mobile Ads C++ SDK uses this class to return results from -/// asynchronous operations. All C++ functions and method calls that operate -/// asynchronously return a %Future, and provide a "LastResult" -/// function to retrieve the most recent %Future result. -/// -/// The Google Mobile Ads C++ SDK uses this class from the Firebase C++ SDK to -/// return results from asynchronous operations. For more information, see the -/// Firebase -/// C++ SDK documentation. -template -class Future { - // Empty class (used for documentation only). -}; -#endif // defined(DOXYGEN_ADMOB) - -/// @brief API for Google Mobile Ads with Firebase. -/// -/// The GMA API allows you to load and display mobile ads using the Google -/// Mobile Ads SDK. Each ad format has its own header file. -namespace gma { - -/// Initializes Google Mobile Ads (GMA) via Firebase. -/// -/// @param[in] app The Firebase app for which to initialize mobile ads. -/// -/// @param[out] init_result_out Optional: If provided, write the basic init -/// result here. kInitResultSuccess if initialization succeeded, or -/// kInitResultFailedMissingDependency on Android if Google Play services is not -/// available on the current device and the Google Mobile Ads SDK requires -/// Google Play services (for example, when using 'play-services-ads-lite'). -/// Note that this does not include the adapter initialization status, which is -/// returned in the Future. -/// -/// @return If init_result_out is kInitResultSuccess, this Future will contain -/// the initialization status of each adapter once initialization is complete. -/// Otherwise, the returned Future will have kFutureStatusInvalid. -Future Initialize( - const ::firebase::App& app, InitResult* init_result_out = nullptr); - -#if FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) -/// Initializes Google Mobile Ads (GMA) without Firebase for Android. -/// -/// The arguments to @ref Initialize are platform-specific so the caller must do -/// something like this: -/// @code -/// #if defined(__ANDROID__) -/// firebase::gma::Initialize(jni_env, activity); -/// #else -/// firebase::gma::Initialize(); -/// #endif -/// @endcode -/// -/// @param[in] jni_env JNIEnv pointer. -/// @param[in] activity Activity used to start the application. -/// @param[out] init_result_out Optional: If provided, write the basic init -/// result here. kInitResultSuccess if initialization succeeded, or -/// kInitResultFailedMissingDependency on Android if Google Play services is not -/// available on the current device and the Google Mobile Ads SDK requires -/// Google Play services (for example, when using 'play-services-ads-lite'). -/// Note that this does not include the adapter initialization status, which is -/// returned in the Future. -/// -/// @return If init_result_out is kInitResultSuccess, this Future will contain -/// the initialization status of each adapter once initialization is complete. -/// Otherwise, the returned Future will have kFutureStatusInvalid. -Future Initialize( - JNIEnv* jni_env, jobject activity, InitResult* init_result_out = nullptr); - -#endif // defined(__ANDROID__) || defined(DOXYGEN) -#if !FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) -/// Initializes Google Mobile Ads (GMA) without Firebase for iOS. -/// -/// @param[out] init_result_out Optional: If provided, write the basic init -/// result here. kInitResultSuccess if initialization succeeded, or -/// kInitResultFailedMissingDependency on Android if Google Play services is not -/// available on the current device and the Google Mobile Ads SDK requires -/// Google Play services (for example, when using 'play-services-ads-lite'). -/// Note that this does not include the adapter initialization status, which is -/// returned in the Future. -/// -/// @return If init_result_out is kInitResultSuccess, this Future -/// will contain the initialization status of each adapter once initialization -/// is complete. Otherwise, the returned Future will have -/// kFutureStatusInvalid. -Future Initialize( - InitResult* init_result_out = nullptr); -#endif // !defined(__ANDROID__) || defined(DOXYGEN) - -/// Get the Future returned by a previous call to -/// @ref firebase::gma::Initialize(). -Future InitializeLastResult(); - -/// Get the current adapter initialization status. You can poll this method to -/// check which adapters have been initialized. -AdapterInitializationStatus GetInitializationStatus(); - -/// Disables automated SDK crash reporting on iOS. If not called, the SDK -/// records the original exception handler if available and registers a new -/// exception handler. The new exception handler only reports SDK related -/// exceptions and calls the recorded original exception handler. -/// -/// This method has no effect on Android. -void DisableSDKCrashReporting(); - -/// Disables mediation adapter initialization on iOS during initialization of -/// the GMA SDK. Calling this method may negatively impact your ad -/// performance and should only be called if you will not use GMA SDK -/// controlled mediation during this app session. This method must be called -/// before initializing the GMA SDK or loading ads and has no effect once the -/// SDK has been initialized. -/// -/// This method has no effect on Android. -void DisableMediationInitialization(); - -/// Sets the global @ref RequestConfiguration that will be used for -/// every @ref AdRequest during the app's session. -/// -/// @param[in] request_configuration The request configuration that should be -/// applied to all ad requests. -void SetRequestConfiguration(const RequestConfiguration& request_configuration); - -/// Gets the global RequestConfiguration. -/// -/// @return the currently active @ref RequestConfiguration that's being -/// used for every ad request. -/// @note: on iOS, the -/// @ref RequestConfiguration::tag_for_child_directed_treatment and -/// @ref RequestConfiguration::tag_for_under_age_of_consent fields will be set -/// to RequestConfiguration.kChildDirectedTreatmentUnspecified, and -/// RequestConfiguration.kUnderAgeOfConsentUnspecified, respectfully. -RequestConfiguration GetRequestConfiguration(); - -/// Opens the ad inspector UI. -/// -/// @param[in] parent The platform-specific UI element that will host the -/// ad inspector. For iOS this should be the window's -/// UIViewController. For Android this is the -/// Activity Context which the GMA SDK is running in. -/// @param[in] listener The listener will be invoked when the user closes -/// the ad inspector UI. @ref firebase::gma::Initialize(). must be called -/// prior to this function. -void OpenAdInspector(AdParent parent, AdInspectorClosedListener* listener); - -/// Controls whether the Google Mobile Ads SDK Same App Key is enabled. -/// -/// This function must be invoked after GMA has been initialized. The value set -/// persists across app sessions. The key is enabled by default. -/// -/// This operation is supported on iOS only. This is a no-op on Android -/// systems. -/// -/// @param[in] is_enabled whether the Google Mobile Ads SDK Same App Key is -/// enabled. -void SetIsSameAppKeyEnabled(bool is_enabled); - -/// @brief Terminate GMA. -/// -/// Frees resources associated with GMA that were allocated during -/// @ref firebase::gma::Initialize(). -void Terminate(); - -} // namespace gma -} // namespace firebase - -#endif // FIREBASE_GMA_SRC_INCLUDE_FIREBASE_GMA_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/gma/ad_view.h b/packages/firebase_core/firebase_core/firebase_core/firebase/gma/ad_view.h deleted file mode 100644 index 16916a21665f..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/gma/ad_view.h +++ /dev/null @@ -1,267 +0,0 @@ -/* - * Copyright 2021 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_GMA_SRC_INCLUDE_FIREBASE_GMA_AD_VIEW_H_ -#define FIREBASE_GMA_SRC_INCLUDE_FIREBASE_GMA_AD_VIEW_H_ - -#include "firebase/future.h" -#include "firebase/gma/types.h" -#include "firebase/internal/common.h" - -namespace firebase { -namespace gma { - -namespace internal { -// Forward declaration for platform-specific data, implemented in each library. -class AdViewInternal; -} // namespace internal - -class AdViewBoundingBoxListener; -struct BoundingBox; - -/// @brief Loads and displays Google Mobile Ads AdView ads. -/// -/// Each AdView object corresponds to a single GMA ad placement of a specified -/// size. There are methods to load an ad, move it, show it and hide it, and -/// retrieve the bounds of the ad onscreen. -/// -/// AdView objects provide information about their current state through -/// Futures. Methods like @ref Initialize, @ref LoadAd, and @ref Hide each have -/// a corresponding @ref Future from which the result of the last call can be -/// determined. The two variants of @ref SetPosition share a single result -/// @ref Future, since they're essentially the same action. -/// -/// For example, you could initialize, load, and show an AdView while -/// checking the result of the previous action at each step as follows: -/// -/// @code -/// namespace gma = ::firebase::gma; -/// gma::AdView* ad_view = new gma::AdView(); -/// ad_view->Initialize(ad_parent, "YOUR_AD_UNIT_ID", desired_ad_size) -/// @endcode -/// -/// Then, later: -/// -/// @code -/// if (ad_view->InitializeLastResult().status() == -/// ::firebase::kFutureStatusComplete && -/// ad_view->InitializeLastResult().error() == -/// firebase::gma::kAdErrorCodeNone) { -/// ad_view->LoadAd(your_ad_request); -/// } -/// @endcode -class AdView { - public: - /// The possible screen positions for a @ref AdView, configured via - /// @ref SetPosition. - enum Position { - /// The position isn't one of the predefined screen locations. - kPositionUndefined = -1, - /// Top of the screen, horizontally centered. - kPositionTop = 0, - /// Bottom of the screen, horizontally centered. - kPositionBottom, - /// Top-left corner of the screen. - kPositionTopLeft, - /// Top-right corner of the screen. - kPositionTopRight, - /// Bottom-left corner of the screen. - kPositionBottomLeft, - /// Bottom-right corner of the screen. - kPositionBottomRight, - }; - - /// Creates an uninitialized @ref AdView object. - /// @ref Initialize must be called before the object is used. - AdView(); - - ~AdView(); - - /// Initializes the @ref AdView object. - /// @param[in] parent The platform-specific UI element that will host the ad. - /// @param[in] ad_unit_id The ad unit ID to use when requesting ads. - /// @param[in] size The desired ad size for the ad. - Future Initialize(AdParent parent, const char* ad_unit_id, - const AdSize& size); - - /// Returns a @ref Future that has the status of the last call to - /// @ref Initialize. - Future InitializeLastResult() const; - - /// Begins an asynchronous request for an ad. If successful, the ad will - /// automatically be displayed in the AdView. - /// @param[in] request An AdRequest struct with information about the request - /// to be made (such as targeting info). - Future LoadAd(const AdRequest& request); - - /// Returns a @ref Future containing the status of the last call to - /// @ref LoadAd. - Future LoadAdLastResult() const; - - /// Retrieves the @ref AdView's current onscreen size and location. - /// - /// @return The current size and location. Values are in pixels, and location - /// coordinates originate from the top-left corner of the screen. - BoundingBox bounding_box() const; - - /// Sets an AdListener for this ad view. - /// - /// @param[in] listener An AdListener object which will be invoked - /// when lifecycle events occur on this AdView. - void SetAdListener(AdListener* listener); - - /// Sets a listener to be invoked when the Ad's bounding box - /// changes size or location. - /// - /// @param[in] listener A AdViewBoundingBoxListener object which will be - /// invoked when the ad changes size, shape, or position. - void SetBoundingBoxListener(AdViewBoundingBoxListener* listener); - - /// Sets a listener to be invoked when this ad is estimated to have earned - /// money. - /// - /// @param[in] listener A PaidEventListener object to be invoked when a - /// paid event occurs on the ad. - void SetPaidEventListener(PaidEventListener* listener); - - /// Moves the @ref AdView so that its top-left corner is located at - /// (x, y). Coordinates are in pixels from the top-left corner of the screen. - /// - /// When built for Android, the library will not display an ad on top of or - /// beneath an Activity's status bar. If a call to SetPostion - /// would result in an overlap, the @ref AdView is placed just below the - /// status bar, so no overlap occurs. - /// @param[in] x The desired horizontal coordinate. - /// @param[in] y The desired vertical coordinate. - /// - /// @return a @ref Future which will be completed when this move operation - /// completes. - Future SetPosition(int x, int y); - - /// Moves the @ref AdView so that it's located at the given predefined - /// position. - /// - /// @param[in] position The predefined position to which to move the - /// @ref AdView. - /// - /// @return a @ref Future which will be completed when this move operation - /// completes. - Future SetPosition(Position position); - - /// Returns a @ref Future containing the status of the last call to either - /// version of @ref SetPosition. - Future SetPositionLastResult() const; - - /// Hides the AdView. - Future Hide(); - - /// Returns a @ref Future containing the status of the last call to - /// @ref Hide. - Future HideLastResult() const; - - /// Shows the @ref AdView. - Future Show(); - - /// Returns a @ref Future containing the status of the last call to - /// @ref Show. - Future ShowLastResult() const; - - /// Pauses the @ref AdView. Should be called whenever the C++ engine - /// pauses or the application loses focus. - Future Pause(); - - /// Returns a @ref Future containing the status of the last call to - /// @ref Pause. - Future PauseLastResult() const; - - /// Resumes the @ref AdView after pausing. - Future Resume(); - - /// Returns a @ref Future containing the status of the last call to - /// @ref Resume. - Future ResumeLastResult() const; - - /// Cleans up and deallocates any resources used by the @ref AdView. - /// You must call this asynchronous operation before this object's destructor - /// is invoked or risk leaking device resources. - Future Destroy(); - - /// Returns a @ref Future containing the status of the last call to - /// @ref Destroy. - Future DestroyLastResult() const; - - /// Returns the AdSize of the AdView. - /// - /// @return An @ref AdSize object representing the size of the ad. If this - /// view has not been initialized then the AdSize will be 0,0. - AdSize ad_size() const; - - protected: - /// Pointer to a listener for AdListener events. - AdListener* ad_listener_; - - /// Pointer to a listener for BoundingBox events. - AdViewBoundingBoxListener* ad_view_bounding_box_listener_; - - /// Pointer to a listener for paid events. - PaidEventListener* paid_event_listener_; - - private: - // An internal, platform-specific implementation object that this class uses - // to interact with the Google Mobile Ads SDKs for iOS and Android. - internal::AdViewInternal* internal_; -}; - -/// A listener class that developers can extend and pass to an @ref AdView -/// object's @ref AdView::SetBoundingBoxListener method to be notified of -/// changes to the size of the Ad's bounding box. -class AdViewBoundingBoxListener { - public: - virtual ~AdViewBoundingBoxListener(); - - /// This method is called when the @ref AdView object's bounding box - /// changes. - /// - /// @param[in] ad_view The view whose bounding box changed. - /// @param[in] box The new bounding box. - virtual void OnBoundingBoxChanged(AdView* ad_view, BoundingBox box) = 0; -}; - -/// @brief The screen location and dimensions of an AdView once it has been -/// initialized. -struct BoundingBox { - /// Default constructor which initializes all member variables to 0. - BoundingBox() - : height(0), width(0), x(0), y(0), position(AdView::kPositionUndefined) {} - - /// Height of the ad in pixels. - int height; - /// Width of the ad in pixels. - int width; - /// Horizontal position of the ad in pixels from the left. - int x; - /// Vertical position of the ad in pixels from the top. - int y; - - /// The position of the AdView if one has been set as the target position, or - /// kPositionUndefined otherwise. - AdView::Position position; -}; - -} // namespace gma -} // namespace firebase - -#endif // FIREBASE_GMA_SRC_INCLUDE_FIREBASE_GMA_AD_VIEW_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/gma/interstitial_ad.h b/packages/firebase_core/firebase_core/firebase_core/firebase/gma/interstitial_ad.h deleted file mode 100644 index 4680537178c8..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/gma/interstitial_ad.h +++ /dev/null @@ -1,128 +0,0 @@ -/* - * Copyright 2021 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_GMA_SRC_INCLUDE_FIREBASE_GMA_INTERSTITIAL_AD_H_ -#define FIREBASE_GMA_SRC_INCLUDE_FIREBASE_GMA_INTERSTITIAL_AD_H_ - -#include "firebase/future.h" -#include "firebase/gma/types.h" -#include "firebase/internal/common.h" - -namespace firebase { -namespace gma { - -namespace internal { -// Forward declaration for platform-specific data, implemented in each library. -class InterstitialAdInternal; -} // namespace internal - -/// @brief Loads and displays Google Mobile Ads interstitial ads. -/// -/// @ref InterstitialAd is a single-use object that can load and show a -/// single GMA interstitial ad. -/// -/// InterstitialAd objects provide information about their current state -/// through Futures. @ref Initialize, @ref LoadAd, and @ref Show each have a -/// corresponding @ref Future from which you can determine result of the -/// previous call. -/// -/// Here's how one might initialize, load, and show an interstitial ad while -/// checking against the result of the previous action at each step: -/// -/// @code -/// namespace gma = ::firebase::gma; -/// gma::InterstitialAd* interstitial = new gma::InterstitialAd(); -/// interstitial->Initialize(ad_parent); -/// @endcode -/// -/// Then, later: -/// -/// @code -/// if (interstitial->InitializeLastResult().status() == -/// ::firebase::kFutureStatusComplete && -/// interstitial->InitializeLastResult().error() == -/// firebase::gma::kAdErrorCodeNone) { -/// interstitial->LoadAd( "YOUR_AD_UNIT_ID", my_ad_request); -/// } -/// @endcode -/// -/// And after that: -/// -/// @code -/// if (interstitial->LoadAdLastResult().status() == -/// ::firebase::kFutureStatusComplete && -/// interstitial->LoadAdLastResult().error() == -/// firebase::gma::kAdErrorCodeNone)) { -/// interstitial->Show(); -/// } -/// @endcode -class InterstitialAd { - public: - /// Creates an uninitialized @ref InterstitialAd object. - /// @ref Initialize must be called before the object is used. - InterstitialAd(); - - ~InterstitialAd(); - - /// Initialize the @ref InterstitialAd object. - /// @param[in] parent The platform-specific UI element that will host the ad. - Future Initialize(AdParent parent); - - /// Returns a @ref Future containing the status of the last call to - /// @ref Initialize. - Future InitializeLastResult() const; - - /// Begins an asynchronous request for an ad. - /// - /// @param[in] ad_unit_id The ad unit ID to use in loading the ad. - /// @param[in] request An AdRequest struct with information about the request - /// to be made (such as targeting info). - Future LoadAd(const char* ad_unit_id, const AdRequest& request); - - /// Returns a @ref Future containing the status of the last call to - /// @ref LoadAd. - Future LoadAdLastResult() const; - - /// Shows the @ref InterstitialAd. This should not be called unless an ad has - /// already been loaded. - Future Show(); - - /// Returns a @ref Future containing the status of the last call to - /// @ref Show. - Future ShowLastResult() const; - - /// Sets the @ref FullScreenContentListener for this @ref InterstitialAd. - /// - /// @param[in] listener A valid @ref FullScreenContentListener to receive - /// callbacks. - void SetFullScreenContentListener(FullScreenContentListener* listener); - - /// Registers a callback to be invoked when this ad is estimated to have - /// earned money - /// - /// @param[in] listener A valid @ref PaidEventListener to receive callbacks. - void SetPaidEventListener(PaidEventListener* listener); - - private: - // An internal, platform-specific implementation object that this class uses - // to interact with the Google Mobile Ads SDKs for iOS and Android. - internal::InterstitialAdInternal* internal_; -}; - -} // namespace gma -} // namespace firebase - -#endif // FIREBASE_GMA_SRC_INCLUDE_FIREBASE_GMA_INTERSTITIAL_AD_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/gma/rewarded_ad.h b/packages/firebase_core/firebase_core/firebase_core/firebase/gma/rewarded_ad.h deleted file mode 100644 index a3c5431486d4..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/gma/rewarded_ad.h +++ /dev/null @@ -1,152 +0,0 @@ -/* - * Copyright 2021 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_GMA_SRC_INCLUDE_FIREBASE_GMA_REWARDED_AD_H_ -#define FIREBASE_GMA_SRC_INCLUDE_FIREBASE_GMA_REWARDED_AD_H_ - -#include - -#include "firebase/future.h" -#include "firebase/gma/types.h" -#include "firebase/internal/common.h" - -namespace firebase { -namespace gma { - -namespace internal { -// Forward declaration for platform-specific data, implemented in each library. -class RewardedAdInternal; -} // namespace internal - -/// @brief Loads and displays Google Mobile Ads rewarded ads. -/// -/// @ref RewardedAd is a single-use object that can load and show a -/// single GMA rewarded ad. -/// -/// RewardedAd objects provide information about their current state -/// through Futures. @ref Initialize, @ref LoadAd, and @ref Show each have a -/// corresponding @ref Future from which you can determine result of the -/// previous call. -/// -/// Here's how one might initialize, load, and show an rewarded ad while -/// checking against the result of the previous action at each step: -/// -/// @code -/// namespace gma = ::firebase::gma; -/// gma::RewardedAd* rewarded = new gma::RewardedAd(); -/// rewarded->Initialize(ad_parent); -/// @endcode -/// -/// Then, later: -/// -/// @code -/// if (rewarded->InitializeLastResult().status() == -/// ::firebase::kFutureStatusComplete && -/// rewarded->InitializeLastResult().error() == -/// firebase::gma::kAdErrorCodeNone) { -/// rewarded->LoadAd( "YOUR_AD_UNIT_ID", my_ad_request); -/// } -/// @endcode -/// -/// And after that: -/// -/// @code -/// if (rewarded->LoadAdLastResult().status() == -/// ::firebase::kFutureStatusComplete && -/// rewarded->LoadAdLastResult().error() == -/// firebase::gma::kAdErrorCodeNone)) { -/// rewarded->Show(&my_user_earned_reward_listener); -/// } -/// @endcode -class RewardedAd { - public: - /// Options for RewardedAd server-side verification callbacks. Set options on - /// a RewardedAd object using the @ref SetServerSideVerificationOptions - /// method. - struct ServerSideVerificationOptions { - /// Custom data to be included in server-side verification callbacks. - std::string custom_data; - - /// User id to be used in server-to-server reward callbacks. - std::string user_id; - }; - - /// Creates an uninitialized @ref RewardedAd object. - /// @ref Initialize must be called before the object is used. - RewardedAd(); - - ~RewardedAd(); - - /// Initialize the @ref RewardedAd object. - /// @param[in] parent The platform-specific UI element that will host the ad. - Future Initialize(AdParent parent); - - /// Returns a @ref Future containing the status of the last call to - /// @ref Initialize. - Future InitializeLastResult() const; - - /// Begins an asynchronous request for an ad. - /// - /// @param[in] ad_unit_id The ad unit ID to use in loading the ad. - /// @param[in] request An AdRequest struct with information about the request - /// to be made (such as targeting info). - Future LoadAd(const char* ad_unit_id, const AdRequest& request); - - /// Returns a @ref Future containing the status of the last call to - /// @ref LoadAd. - Future LoadAdLastResult() const; - - /// Shows the @ref RewardedAd. This should not be called unless an ad has - /// already been loaded. - /// - /// @param[in] listener The @ref UserEarnedRewardListener to be notified when - /// user earns a reward. - Future Show(UserEarnedRewardListener* listener); - - /// Returns a @ref Future containing the status of the last call to - /// @ref Show. - Future ShowLastResult() const; - - /// Sets the @ref FullScreenContentListener for this @ref RewardedAd. - /// - /// @param[in] listener A valid @ref FullScreenContentListener to receive - /// callbacks. - void SetFullScreenContentListener(FullScreenContentListener* listener); - - /// Registers a callback to be invoked when this ad is estimated to have - /// earned money - /// - /// @param[in] listener A valid @ref PaidEventListener to receive callbacks. - void SetPaidEventListener(PaidEventListener* listener); - - /// Sets the server side verification options. - /// - /// @param[in] serverSideVerificationOptions A @ref - /// ServerSideVerificationOptions object containing custom data and a user - /// Id. - void SetServerSideVerificationOptions( - const ServerSideVerificationOptions& serverSideVerificationOptions); - - private: - // An internal, platform-specific implementation object that this class uses - // to interact with the Google Mobile Ads SDKs for iOS and Android. - internal::RewardedAdInternal* internal_; -}; - -} // namespace gma -} // namespace firebase - -#endif // FIREBASE_GMA_SRC_INCLUDE_FIREBASE_GMA_REWARDED_AD_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/gma/types.h b/packages/firebase_core/firebase_core/firebase_core/firebase/gma/types.h deleted file mode 100644 index 292ee4138a68..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/gma/types.h +++ /dev/null @@ -1,939 +0,0 @@ -/* - * Copyright 2021 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_GMA_SRC_INCLUDE_FIREBASE_GMA_TYPES_H_ -#define FIREBASE_GMA_SRC_INCLUDE_FIREBASE_GMA_TYPES_H_ - -#include -#include -#include -#include -#include - -#include "firebase/future.h" -#include "firebase/internal/platform.h" - -#if FIREBASE_PLATFORM_ANDROID -#include -#elif FIREBASE_PLATFORM_IOS || FIREBASE_PLATFORM_TVOS -extern "C" { -#include -} // extern "C" -#endif // FIREBASE_PLATFORM_ANDROID, FIREBASE_PLATFORM_IOS, - // FIREBASE_PLATFORM_TVOS - -namespace firebase { -namespace gma { - -struct AdErrorInternal; -struct AdapterResponseInfoInternal; -struct BoundingBox; -struct ResponseInfoInternal; - -class AdapterResponseInfo; -class AdViewBoundingBoxListener; -class GmaInternal; -class AdView; -class InterstitialAd; -class PaidEventListener; -class ResponseInfo; - -namespace internal { -class AdViewInternal; -} - -/// This is a platform specific datatype that is required to create -/// a Google Mobile Ads ad. -/// -/// The following defines the datatype on each platform: -///
    -///
  • Android: A `jobject` which references an Android Activity.
  • -///
  • iOS: An `id` which references an iOS UIView.
  • -///
-#if FIREBASE_PLATFORM_ANDROID -/// An Android Activity from Java. -typedef jobject AdParent; -#elif FIREBASE_PLATFORM_IOS || FIREBASE_PLATFORM_TVOS -/// A pointer to an iOS UIView. -typedef id AdParent; -#else -/// A void pointer for stub classes. -typedef void* AdParent; -#endif // FIREBASE_PLATFORM_ANDROID, FIREBASE_PLATFORM_IOS, - // FIREBASE_PLATFORM_TVOS - -/// Error codes returned by Future::error(). -enum AdErrorCode { - /// Call completed successfully. - kAdErrorCodeNone, - /// The ad has not been fully initialized. - kAdErrorCodeUninitialized, - /// The ad is already initialized (repeat call). - kAdErrorCodeAlreadyInitialized, - /// A call has failed because an ad is currently loading. - kAdErrorCodeLoadInProgress, - /// A call to load an ad has failed due to an internal SDK error. - kAdErrorCodeInternalError, - /// A call to load an ad has failed due to an invalid request. - kAdErrorCodeInvalidRequest, - /// A call to load an ad has failed due to a network error. - kAdErrorCodeNetworkError, - /// A call to load an ad has failed because no ad was available to serve. - kAdErrorCodeNoFill, - /// An attempt has been made to show an ad on an Android Activity that has - /// no window token (such as one that's not done initializing). - kAdErrorCodeNoWindowToken, - /// An attempt to load an Ad Network extras class for an ad request has - /// failed. - kAdErrorCodeAdNetworkClassLoadError, - /// The ad server experienced a failure processing the request. - kAdErrorCodeServerError, - /// The current device’s OS is below the minimum required version. - kAdErrorCodeOSVersionTooLow, - /// The request was unable to be loaded before being timed out. - kAdErrorCodeTimeout, - /// Will not send request because the interstitial object has already been - /// used. - kAdErrorCodeInterstitialAlreadyUsed, - /// The mediation response was invalid. - kAdErrorCodeMediationDataError, - /// Error finding or creating a mediation ad network adapter. - kAdErrorCodeMediationAdapterError, - /// Attempting to pass an invalid ad size to an adapter. - kAdErrorCodeMediationInvalidAdSize, - /// Invalid argument error. - kAdErrorCodeInvalidArgument, - /// Received invalid response. - kAdErrorCodeReceivedInvalidResponse, - /// Will not send a request because the rewarded ad object has already been - /// used. - kAdErrorCodeRewardedAdAlreadyUsed, - /// A mediation ad network adapter received an ad request, but did not fill. - /// The adapter’s error is included as an underlyingError. - kAdErrorCodeMediationNoFill, - /// Will not send request because the ad object has already been used. - kAdErrorCodeAdAlreadyUsed, - /// Will not send request because the application identifier is missing. - kAdErrorCodeApplicationIdentifierMissing, - /// Android Ad String is invalid. - kAdErrorCodeInvalidAdString, - /// The ad can not be shown when app is not in the foreground. - kAdErrorCodeAppNotInForeground, - /// A mediation adapter failed to show the ad. - kAdErrorCodeMediationShowError, - /// The ad is not ready to be shown. - kAdErrorCodeAdNotReady, - /// Ad is too large for the scene. - kAdErrorCodeAdTooLarge, - /// Attempted to present ad from a non-main thread. This is an internal - /// error which should be reported to support if encountered. - kAdErrorCodeNotMainThread, - /// A debug operation failed because the device is not in test mode. - kAdErrorCodeNotInTestMode, - /// An attempt to load the Ad Inspector failed. - kAdErrorCodeInspectorFailedToLoad, - /// The request to show the Ad Inspector failed because it's already open. - kAdErrorCodeInsepctorAlreadyOpen, - /// Fallback error for any unidentified cases. - kAdErrorCodeUnknown, -}; - -/// A listener for receiving notifications during the lifecycle of a BannerAd. -class AdListener { - public: - virtual ~AdListener(); - - /// Called when a click is recorded for an ad. - virtual void OnAdClicked() {} - - /// Called when the user is about to return to the application after clicking - /// on an ad. - virtual void OnAdClosed() {} - - /// Called when an impression is recorded for an ad. - virtual void OnAdImpression() {} - - /// Called when an ad opens an overlay that covers the screen. - virtual void OnAdOpened() {} -}; - -/// Information about why an ad operation failed. -class AdError { - public: - /// Default Constructor. - AdError(); - - /// Copy Constructor. - AdError(const AdError& ad_error); - - /// Destructor. - virtual ~AdError(); - - /// Assignment operator. - AdError& operator=(const AdError& obj); - - /// Retrieves an AdError which represents the cause of this error. - /// - /// @return a pointer to an adError which represents the cause of this - /// AdError. If there was no cause then nullptr is returned. - std::unique_ptr GetCause() const; - - /// Gets the error's code. - AdErrorCode code() const; - - /// Gets the domain of the error. - const std::string& domain() const; - - /// Gets the message describing the error. - const std::string& message() const; - - /// Gets the ResponseInfo if an error occurred during a loadAd operation. - /// The ResponseInfo will have empty fields if this AdError does not - /// represent an error stemming from a load ad operation. - const ResponseInfo& response_info() const; - - /// Returns a log friendly string version of this object. - virtual const std::string& ToString() const; - - /// A domain string which represents an undefined error domain. - /// - /// The GMA SDK returns this domain for domain() method invocations when - /// converting error information from legacy mediation adapter callbacks. - static const char* const kUndefinedDomain; - - private: - friend class AdapterResponseInfo; - friend class GmaInternal; - friend class AdView; - friend class InterstitialAd; - - /// Constructor used when building results in Ad event callbacks. - explicit AdError(const AdErrorInternal& ad_error_internal); - - // Collection of response from adapters if this Result is due to a loadAd - // operation. - ResponseInfo* response_info_; - - // An internal, platform-specific implementation object that this class uses - // to interact with the Google Mobile Ads SDKs for iOS and Android. - AdErrorInternal* internal_; -}; - -/// Information about an ad response. -class ResponseInfo { - public: - /// Constructor creates an uninitialized ResponseInfo. - ResponseInfo(); - - /// Gets the AdapterResponseInfo objects for the ad response. - /// - /// @return a vector of AdapterResponseInfo objects containing metadata for - /// each adapter included in the ad response. - const std::vector& adapter_responses() const { - return adapter_responses_; - } - - /// A class name that identifies the ad network that returned the ad. - /// Returns an empty string if the ad failed to load. - const std::string& mediation_adapter_class_name() const { - return mediation_adapter_class_name_; - } - - /// Gets the response ID string for the loaded ad. Returns an empty - /// string if the ad fails to load. - const std::string& response_id() const { return response_id_; } - - /// Gets a log friendly string version of this object. - const std::string& ToString() const { return to_string_; } - - private: - friend class AdError; - friend class GmaInternal; - - explicit ResponseInfo(const ResponseInfoInternal& internal); - - std::vector adapter_responses_; - std::string mediation_adapter_class_name_; - std::string response_id_; - std::string to_string_; -}; - -/// Information about the result of an ad operation. -class AdResult { - public: - /// Default Constructor. - AdResult(); - - /// Constructor. - explicit AdResult(const AdError& ad_error); - - /// Destructor. - virtual ~AdResult(); - - /// Returns true if the operation was successful. - bool is_successful() const; - - /// An object representing an error which occurred during an ad operation. - /// If the @ref AdResult::is_successful() returned true, then the - /// @ref AdError object returned via this method will contain no contextual - /// information. - const AdError& ad_error() const; - - /// For debugging and logging purposes, successfully loaded ads provide a - /// ResponseInfo object which contains information about the adapter which - /// loaded the ad. If the ad failed to load then the object returned from - /// this method will have default values. Information about the error - /// should be retrieved via @ref AdResult::ad_error() instead. - const ResponseInfo& response_info() const; - - private: - friend class GmaInternal; - - /// Constructor invoked upon successful ad load. This contains response - /// information from the adapter which loaded the ad. - explicit AdResult(const ResponseInfo& response_info); - - /// Denotes if the @ref AdResult represents a success or an error. - bool is_successful_; - - /// Information about the error. Will be a default-constructed @ref AdError - /// if this result represents a success. - AdError ad_error_; - - /// Information from the adapter which loaded the ad. - ResponseInfo response_info_; -}; - -/// A snapshot of a mediation adapter's initialization status. -class AdapterStatus { - public: - AdapterStatus() : is_initialized_(false), latency_(0) {} - - /// Detailed description of the status. - /// - /// This method should only be used for informational purposes, such as - /// logging. Use @ref is_initialized to make logical decisions regarding an - /// adapter's status. - const std::string& description() const { return description_; } - - /// Returns the adapter's initialization state. - bool is_initialized() const { return is_initialized_; } - - /// The adapter's initialization latency in milliseconds. - /// 0 if initialization has not yet ended. - int latency() const { return latency_; } - -#if !defined(DOXYGEN) - // Equality operator for testing. - bool operator==(const AdapterStatus& rhs) const { - return (description() == rhs.description() && - is_initialized() == rhs.is_initialized() && - latency() == rhs.latency()); - } -#endif // !defined(DOXYGEN) - - private: - friend class GmaInternal; - std::string description_; - bool is_initialized_; - int latency_; -}; - -/// An immutable snapshot of the GMA SDK’s initialization status, categorized -/// by mediation adapter. -class AdapterInitializationStatus { - public: - /// Initialization status of each known ad network, keyed by its adapter's - /// class name. - std::map GetAdapterStatusMap() const { - return adapter_status_map_; - } -#if !defined(DOXYGEN) - // Equality operator for testing. - bool operator==(const AdapterInitializationStatus& rhs) const { - return (GetAdapterStatusMap() == rhs.GetAdapterStatusMap()); - } -#endif // !defined(DOXYGEN) - - private: - friend class GmaInternal; - std::map adapter_status_map_; -}; - -/// Listener to be invoked when the Ad Inspector has been closed. -class AdInspectorClosedListener { - public: - virtual ~AdInspectorClosedListener(); - - /// Called when the user clicked the ad. The AdResult contains the status of - /// the operation, including details of the error if one occurred. - virtual void OnAdInspectorClosed(const AdResult& ad_result) = 0; -}; - -/// @brief Response information for an individual ad network contained within -/// a @ref ResponseInfo object. -class AdapterResponseInfo { - public: - /// Destructor - ~AdapterResponseInfo(); - - /// @brief Information about the result including whether an error - /// occurred, and any contextual information about that error. - /// - /// @return the error that occurred while rendering the ad. If no error - /// occurred then the AdResult's successful method will return true. - AdResult ad_result() const { return ad_result_; } - - /// Returns a string representation of a class name that identifies the ad - /// network adapter. - const std::string& adapter_class_name() const { return adapter_class_name_; } - - /// Amount of time the ad network spent loading an ad. - /// - /// @return number of milliseconds the network spent loading an ad. This value - /// is 0 if the network did not make a load attempt. - int64_t latency_in_millis() const { return latency_; } - - /// A log friendly string version of this object. - const std::string& ToString() const { return to_string_; } - - private: - friend class ResponseInfo; - - /// Constructs an Adapter Response Info Object. - explicit AdapterResponseInfo(const AdapterResponseInfoInternal& internal); - - AdResult ad_result_; - std::string adapter_class_name_; - int64_t latency_; - std::string to_string_; -}; - -/// The size of a banner ad. -class AdSize { - public: - /// Denotes the orientation of the AdSize. - enum Orientation { - /// AdSize should reflect the current orientation of the device. - kOrientationCurrent = 0, - - /// AdSize will be adaptively formatted in Landscape mode. - kOrientationLandscape, - - /// AdSize will be adaptively formatted in Portrait mode. - kOrientationPortrait - }; - - /// Denotes the type size object that the @ref AdSize represents. - enum Type { - /// The standard AdSize type of a set height and width. - kTypeStandard = 0, - - /// An adaptive size anchored to a portion of the screen. - kTypeAnchoredAdaptive, - - /// An adaptive size intended to be embedded in scrollable content. - kTypeInlineAdaptive, - }; - - /// Mobile Marketing Association (MMA) banner ad size (320x50 - /// density-independent pixels). - static const AdSize kBanner; - - /// Interactive Advertising Bureau (IAB) full banner ad size - /// (468x60 density-independent pixels). - static const AdSize kFullBanner; - - /// Taller version of kBanner. Typically 320x100. - static const AdSize kLargeBanner; - - /// Interactive Advertising Bureau (IAB) leaderboard ad size - /// (728x90 density-independent pixels). - static const AdSize kLeaderboard; - - /// Interactive Advertising Bureau (IAB) medium rectangle ad size - /// (300x250 density-independent pixels). - static const AdSize kMediumRectangle; - - /// Creates a new AdSize. - /// - /// @param[in] width The width of the ad in density-independent pixels. - /// @param[in] height The height of the ad in density-independent pixels. - AdSize(uint32_t width, uint32_t height); - - /// @brief Creates an AdSize with the given width and a Google-optimized - /// height to create a banner ad in landscape mode. - /// - /// @param[in] width The width of the ad in density-independent pixels. - /// - /// @return an AdSize with the given width and a Google-optimized height - /// to create a banner ad. The size returned will have an aspect ratio - /// similar to BANNER, suitable for anchoring near the top or bottom of - /// your app. The exact size of the ad returned can be retrieved by calling - /// @ref AdView::ad_size once the ad has been loaded. - static AdSize GetLandscapeAnchoredAdaptiveBannerAdSize(uint32_t width); - - /// @brief Creates an AdSize with the given width and a Google-optimized - /// height to create a banner ad in portrait mode. - /// - /// @param[in] width The width of the ad in density-independent pixels. - /// - /// @return an AdSize with the given width and a Google-optimized height - /// to create a banner ad. The size returned will have an aspect ratio - /// similar to BANNER, suitable for anchoring near the top or bottom - /// of your app. The exact size of the ad returned can be retrieved by - /// calling @ref AdView::ad_size once the ad has been loaded. - static AdSize GetPortraitAnchoredAdaptiveBannerAdSize(uint32_t width); - - /// @brief Creates an AdSize with the given width and a Google-optimized - /// height to create a banner ad given the current orientation. - /// - /// @param[in] width The width of the ad in density-independent pixels. - /// - /// @return an AdSize with the given width and a Google-optimized height - /// to create a banner ad. The size returned will have an aspect ratio - /// similar to AdSize, suitable for anchoring near the top or bottom of - /// your app. The exact size of the ad returned can be retrieved by calling - /// @ref AdView::ad_size once the ad has been loaded. - static AdSize GetCurrentOrientationAnchoredAdaptiveBannerAdSize( - uint32_t width); - - /// @brief This ad size is most suitable for banner ads given a maximum - /// height. - /// - /// This AdSize allows Google servers to choose an optimal ad size with - /// a height less than or equal to the max height given in - /// - /// @param[in] width The width of the ad in density-independent pixels. - /// @param[in] max_height The maximum height that a loaded ad will have. Must - /// be - /// at least 32 dp, but a maxHeight of 50 dp or higher is recommended. - /// - /// @return an AdSize with the given width and a height that is always 0. - /// The exact size of the ad returned can be retrieved by calling - /// @ref AdView::ad_size once the ad has been loaded. - static AdSize GetInlineAdaptiveBannerAdSize(int width, int max_height); - - /// @brief Creates an AdSize with the given width and the device’s - /// landscape height. - /// - /// This ad size allows Google servers to choose an optimal ad size with - /// a height less than or equal to the height of the screen in landscape - /// orientation. - /// - /// @param[in] width The width of the ad in density-independent pixels. - /// - /// @return an AdSize with the given width and a height that is always 0. - /// The exact size of the ad returned can be retrieved by calling - /// @ref AdView::ad_size once the ad has been loaded. - static AdSize GetLandscapeInlineAdaptiveBannerAdSize(int width); - - /// @brief Creates an AdSize with the given width and the device’s - /// portrait height. - /// - /// This ad size allows Google servers to choose an optimal ad size with - /// a height less than or equal to the height of the screen in portrait - /// orientation. - /// - /// @param[in] width The width of the ad in density-independent pixels. - /// - /// @return an AdSize with the given width and a height that is always 0. - /// The exact size of the ad returned can be retrieved by calling - /// @ref AdView::ad_size once the ad has been loaded. - static AdSize GetPortraitInlineAdaptiveBannerAdSize(int width); - - /// @brief A convenience method to return an inline adaptive banner ad size - /// given the current interface orientation. - /// - /// This AdSize allows Google servers to choose an optimal ad size with a - /// height less than or equal to the height of the screen in the requested - /// orientation. - /// - /// @param[in] width The width of the ad in density-independent pixels. - /// - /// @return an AdSize with the given width and a height that is always 0. - /// The exact size of the ad returned can be retrieved by calling - /// @ref AdView::ad_size once the ad has been loaded. - static AdSize GetCurrentOrientationInlineAdaptiveBannerAdSize(int width); - - /// Comparison operator. - /// - /// @return true if `rhs` refers to the same AdSize as `this`. - bool operator==(const AdSize& rhs) const; - - /// Comparison operator. - /// - /// @returns true if `rhs` refers to a different AdSize as `this`. - bool operator!=(const AdSize& rhs) const; - - /// The width of the region represented by this AdSize. Value is in - /// density-independent pixels. - uint32_t width() const { return width_; } - - /// The height of the region represented by this AdSize. Value is in - /// density-independent pixels. - uint32_t height() const { return height_; } - - /// The AdSize orientation. - Orientation orientation() const { return orientation_; } - - /// The AdSize type, either standard size or adaptive. - Type type() const { return type_; } - - private: - friend class firebase::gma::internal::AdViewInternal; - - /// Returns an Anchor Adpative AdSize Object given a width and orientation. - static AdSize GetAnchoredAdaptiveBannerAdSize(uint32_t width, - Orientation orientation); - - /// Returns true if the AdSize parameter is equivalient to this AdSize object. - bool is_equal(const AdSize& ad_size) const; - - /// Denotes the orientation for anchored adaptive AdSize objects. - Orientation orientation_; - - /// Advertisement width in platform-indepenent pixels. - uint32_t width_; - - /// Advertisement width in platform-indepenent pixels. - uint32_t height_; - - /// The type of AdSize (standard or adaptive) - Type type_; -}; - -/// Contains targeting information used to fetch an ad. -class AdRequest { - public: - /// Creates an @ref AdRequest with no custom configuration. - AdRequest(); - - /// Creates an @ref AdRequest with the optional content URL. - /// - /// When requesting an ad, apps may pass the URL of the content they are - /// serving. This enables keyword targeting to match the ad with the content. - /// - /// The URL is ignored if null or the number of characters exceeds 512. - /// - /// @param[in] content_url the url of the content being viewed. - explicit AdRequest(const char* content_url); - - ~AdRequest(); - - /// The content URL targeting information. - /// - /// @return the content URL for the @ref AdRequest. The string will be empty - /// if no content URL has been configured. - const std::string& content_url() const { return content_url_; } - - /// A Map of adapter class names to their collection of extra parameters, as - /// configured via @ref add_extra. - const std::map >& extras() - const { - return extras_; - } - - /// Keywords which will help GMA to provide targeted ads, as added by - /// @ref add_keyword. - const std::unordered_set& keywords() const { return keywords_; } - - /// Returns the set of neighboring content URLs or an empty set if no URLs - /// were set via @ref add_neighboring_content_urls(). - const std::unordered_set& neighboring_content_urls() const { - return neighboring_content_urls_; - } - - /// Add a network extra for the associated ad mediation adapter. - /// - /// Appends an extra to the corresponding list of extras for the ad mediation - /// adapter. Each ad mediation adapter can have multiple extra strings. - /// - /// @param[in] adapter_class_name the class name of the ad mediation adapter - /// for which to add the extra. - /// @param[in] extra_key a key which will be passed to the corresponding ad - /// mediation adapter. - /// @param[in] extra_value the value associated with extra_key. - void add_extra(const char* adapter_class_name, const char* extra_key, - const char* extra_value); - - /// Adds a keyword for targeting purposes. - /// - /// Multiple keywords may be added via repeated invocations of this method. - /// - /// @param[in] keyword a string that GMA will use to aid in targeting ads. - void add_keyword(const char* keyword); - - /// When requesting an ad, apps may pass the URL of the content they are - /// serving. This enables keyword targeting to match the ad with the content. - /// - /// The URL is ignored if null or the number of characters exceeds 512. - /// - /// @param[in] content_url the url of the content being viewed. - void set_content_url(const char* content_url); - - /// Adds to the list of URLs which represent web content near an ad. - /// - /// Promotes brand safety and allows displayed ads to have an app level - /// rating (MA, T, PG, etc) that is more appropriate to neighboring content. - /// - /// Subsequent invocations append to the existing list. - /// - /// @param[in] neighboring_content_urls neighboring content URLs to be - /// attached to the existing neighboring content URLs. - void add_neighboring_content_urls( - const std::vector& neighboring_content_urls); - - private: - std::string content_url_; - std::map > extras_; - std::unordered_set keywords_; - std::unordered_set neighboring_content_urls_; -}; - -/// Describes a reward credited to a user for interacting with a RewardedAd. -class AdReward { - public: - /// Creates an @ref AdReward. - AdReward(const std::string& type, int64_t amount) - : type_(type), amount_(amount) {} - - /// Returns the reward amount. - int64_t amount() const { return amount_; } - - /// Returns the type of the reward. - const std::string& type() const { return type_; } - - private: - const int64_t amount_; - const std::string type_; -}; - -/// The monetary value earned from an ad. -class AdValue { - public: - /// Allowed constants for @ref precision_type(). - enum PrecisionType { - /// An ad value with unknown precision. - kdValuePrecisionUnknown = 0, - /// An ad value estimated from aggregated data. - kAdValuePrecisionEstimated, - /// A publisher-provided ad value, such as manual CPMs in a mediation group. - kAdValuePrecisionPublisherProvided = 2, - /// The precise value paid for this ad. - kAdValuePrecisionPrecise = 3 - }; - - /// Constructor - AdValue(const char* currency_code, PrecisionType precision_type, - int64_t value_micros) - : currency_code_(currency_code), - precision_type_(precision_type), - value_micros_(value_micros) {} - - /// The value's ISO 4217 currency code. - const std::string& currency_code() const { return currency_code_; } - - /// The precision of the reported ad value. - PrecisionType precision_type() const { return precision_type_; } - - /// The ad's value in micro-units, where 1,000,000 micro-units equal one - /// unit of the currency. - int64_t value_micros() const { return value_micros_; } - - private: - const std::string currency_code_; - const PrecisionType precision_type_; - const int64_t value_micros_; -}; - -/// @brief Listener to be invoked when ads show and dismiss full screen content, -/// such as a fullscreen ad experience or an in-app browser. -class FullScreenContentListener { - public: - virtual ~FullScreenContentListener(); - - /// Called when the user clicked the ad. - virtual void OnAdClicked() {} - - /// Called when the ad dismissed full screen content. - virtual void OnAdDismissedFullScreenContent() {} - - /// Called when the ad failed to show full screen content. - /// - /// @param[in] ad_error An object containing detailed information - /// about the error. - virtual void OnAdFailedToShowFullScreenContent(const AdError& ad_error) {} - - /// Called when an impression is recorded for an ad. - virtual void OnAdImpression() {} - - /// Called when the ad showed the full screen content. - virtual void OnAdShowedFullScreenContent() {} -}; - -/// Listener to be invoked when ads have been estimated to earn money. -class PaidEventListener { - public: - virtual ~PaidEventListener(); - - /// Called when an ad is estimated to have earned money. - virtual void OnPaidEvent(const AdValue& value) {} -}; - -/// @brief Global configuration that will be used for every @ref AdRequest. -/// Set the configuration via @ref SetRequestConfiguration. -struct RequestConfiguration { - /// A maximum ad content rating, which may be configured via - /// @ref max_ad_content_rating. - enum MaxAdContentRating { - /// No content rating has been specified. - kMaxAdContentRatingUnspecified = -1, - - /// Content suitable for general audiences, including families. - kMaxAdContentRatingG, - - /// Content suitable only for mature audiences. - kMaxAdContentRatingMA, - - /// Content suitable for most audiences with parental guidance. - kMaxAdContentRatingPG, - - /// Content suitable for teen and older audiences. - kMaxAdContentRatingT - }; - - /// Specify whether you would like your app to be treated as child-directed - /// for purposes of the Children’s Online Privacy Protection Act (COPPA). - /// Values defined here may be configured via - /// @ref tag_for_child_directed_treatment. - enum TagForChildDirectedTreatment { - /// Indicates that ad requests will include no indication of how you would - /// like your app treated with respect to COPPA. - kChildDirectedTreatmentUnspecified = -1, - - /// Indicates that your app should not be treated as child-directed for - /// purposes of the Children’s Online Privacy Protection Act (COPPA). - kChildDirectedTreatmentFalse, - - /// Indicates that your app should be treated as child-directed for purposes - /// of the Children’s Online Privacy Protection Act (COPPA). - kChildDirectedTreatmentTrue - }; - - /// Configuration values to mark your app to receive treatment for users in - /// the European Economic Area (EEA) under the age of consent. Values defined - /// here should be configured via @ref tag_for_under_age_of_consent. - enum TagForUnderAgeOfConsent { - /// Indicates that the publisher has not specified whether the ad request - /// should receive treatment for users in the European Economic Area (EEA) - /// under the age of consent. - kUnderAgeOfConsentUnspecified = -1, - - /// Indicates the publisher specified that the ad request should not receive - /// treatment for users in the European Economic Area (EEA) under the age of - /// consent. - kUnderAgeOfConsentFalse, - - /// Indicates the publisher specified that the ad request should receive - /// treatment for users in the European Economic Area (EEA) under the age of - /// consent. - kUnderAgeOfConsentTrue - }; - - /// Sets a maximum ad content rating. GMA ads returned for your app will - /// have a content rating at or below that level. - MaxAdContentRating max_ad_content_rating; - - /// @brief Allows you to specify whether you would like your app - /// to be treated as child-directed for purposes of the Children’s Online - /// Privacy Protection Act (COPPA) - - /// http://business.ftc.gov/privacy-and-security/childrens-privacy. - /// - /// If you set this value to - /// RequestConfiguration.kChildDirectedTreatmentTrue, you will indicate - /// that your app should be treated as child-directed for purposes of the - /// Children’s Online Privacy Protection Act (COPPA). - /// - /// If you set this value to - /// RequestConfiguration.kChildDirectedTreatmentFalse, you will indicate - /// that your app should not be treated as child-directed for purposes of the - /// Children’s Online Privacy Protection Act (COPPA). - /// - /// If you do not set this value, or set this value to - /// RequestConfiguration.kChildDirectedTreatmentUnspecified, ad requests will - /// include no indication of how you would like your app treated with respect - /// to COPPA. - /// - /// By setting this value, you certify that this notification is accurate and - /// you are authorized to act on behalf of the owner of the app. You - /// understand that abuse of this setting may result in termination of your - /// Google account. - /// - /// @note: it may take some time for this designation to be fully implemented - /// in applicable Google services. - /// - TagForChildDirectedTreatment tag_for_child_directed_treatment; - - /// This value allows you to mark your app to receive treatment for users in - /// the European Economic Area (EEA) under the age of consent. This feature is - /// designed to help facilitate compliance with the General Data Protection - /// Regulation (GDPR). Note that you may have other legal obligations under - /// GDPR. Please review the European Union's guidance and consult with your - /// own legal counsel. Please remember that Google's tools are designed to - /// facilitate compliance and do not relieve any particular publisher of its - /// obligations under the law. - /// - /// When using this feature, a Tag For Users under the Age of Consent in - /// Europe (TFUA) parameter will be included in all ad requests. This - /// parameter disables personalized advertising, including remarketing, for - /// that specific ad request. It also disables requests to third-party ad - /// vendors, such as ad measurement pixels and third-party ad servers. - /// - /// If you set this value to RequestConfiguration.kUnderAgeOfConsentTrue, you - /// will indicate that you want your app to be handled in a manner suitable - /// for users under the age of consent. - /// - /// If you set this value to RequestConfiguration.kUnderAgeOfConsentFalse, - /// you will indicate that you don't want your app to be handled in a manner - /// suitable for users under the age of consent. - /// - /// If you do not set this value, or set this value to - /// kUnderAgeOfConsentUnspecified, your app will include no indication of how - /// you would like your app to be handled in a manner suitable for users under - /// the age of consent. - TagForUnderAgeOfConsent tag_for_under_age_of_consent; - - /// Sets a list of test device IDs corresponding to test devices which will - /// always request test ads. - std::vector test_device_ids; -}; - -/// Listener to be invoked when the user earned a reward. -class UserEarnedRewardListener { - public: - virtual ~UserEarnedRewardListener(); - /// Called when the user earned a reward. The app is responsible for - /// crediting the user with the reward. - /// - /// @param[in] reward the @ref AdReward that should be granted to the user. - virtual void OnUserEarnedReward(const AdReward& reward) {} -}; - -} // namespace gma -} // namespace firebase - -#endif // FIREBASE_GMA_SRC_INCLUDE_FIREBASE_GMA_TYPES_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/installations.h b/packages/firebase_core/firebase_core/firebase_core/firebase/installations.h deleted file mode 100644 index c9774bc37e73..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/installations.h +++ /dev/null @@ -1,123 +0,0 @@ -// Copyright 2020 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef FIREBASE_INSTALLATIONS_SRC_INCLUDE_FIREBASE_INSTALLATIONS_H_ -#define FIREBASE_INSTALLATIONS_SRC_INCLUDE_FIREBASE_INSTALLATIONS_H_ - -#include -#include - -#include "firebase/app.h" -#include "firebase/future.h" -#include "firebase/internal/common.h" - -/// @brief Namespace that encompasses all Firebase APIs. -namespace firebase { - -namespace installations { - -/// Installations error codes. -enum Error { - kErrorNone = 0, - /// An unknown error occurred. - kErrorUnknown, - /// Installations service cannot be accessed. - kErrorNoAccess, - /// Some of the parameters of the request were invalid. - kErrorInvalidConfiguration, -}; - -namespace internal { -// Implementation specific data for an Installation. -class InstallationsInternal; -} // namespace internal - -/// @brief Installations provides a unique identifier for each app instance and -/// a mechanism to authenticate and authorize actions (for example, sending an -/// FCM message). -/// -/// Provides a unique identifier for a Firebase installation. -/// Provides an auth token for a Firebase installation. -/// Provides a API to perform data deletion for a Firebase -/// installation. -class Installations { - public: - ~Installations(); - - /// @brief Get the App this object is connected to. - /// - /// @return App this object is connected to. - App* app() const { return app_; } - - /// @brief Returns the Installations object for an App creating the - /// Installations if required. - /// - /// @param[in] app The App to create an Installations object from. - /// - /// @return Installations object if successful, nullptr otherwise. - static Installations* GetInstance(App* app); - - /// @brief Returns a stable identifier that uniquely identifies the app - /// installation. - /// - /// @return Unique identifier for the app installation. - Future GetId(); - - /// @brief Get the results of the most recent call to @ref GetId. - Future GetIdLastResult(); - - /// @brief Call to delete this Firebase app installation from the Firebase - /// backend. - Future Delete(); - - /// @brief Get the results of the most recent call to @ref Delete. - Future DeleteLastResult(); - - /// @brief Returns a token that authorizes an Entity to perform an action on - /// behalf of the application identified by installations. - /// - /// This is similar to an OAuth2 token except it applies to the - /// application instance instead of a user. - /// - /// For example, to get a token that can be used to send messages to an - /// application via Firebase Cloud Messaging, set entity to the - /// sender ID, and set scope to "FCM". - /// - /// @param forceRefresh If set true, will always return a new token. - /// - /// @return Returns a valid authentication token for the Firebase - /// installation. - Future GetToken(bool forceRefresh); - - /// @brief Get the results of the most recent call to @ref GetToken. - Future GetTokenLastResult(); - - private: - explicit Installations(App* app); - - static Installations* FindInstallations(App* app); - // Installations internal initialize. - bool InitInternal(); - // Clean up Installations instance. - void DeleteInternal(); - - App* app_; - internal::InstallationsInternal* installations_internal_; -}; - -} // namespace installations - -} // namespace firebase - -#endif // FIREBASE_INSTALLATIONS_SRC_INCLUDE_FIREBASE_INSTALLATIONS_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/internal/common.h b/packages/firebase_core/firebase_core/firebase_core/firebase/internal/common.h deleted file mode 100644 index 2e2878a0bd97..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/internal/common.h +++ /dev/null @@ -1,128 +0,0 @@ -/* - * Copyright 2016 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_APP_SRC_INCLUDE_FIREBASE_INTERNAL_COMMON_H_ -#define FIREBASE_APP_SRC_INCLUDE_FIREBASE_INTERNAL_COMMON_H_ - -// This file contains definitions that configure the SDK. - -// Include a STL header file, othewise _STLPORT_VERSION won't be set. -#include - -// Move operators use rvalue references, which are a C++11 extension. -// Also, Visual Studio 2010 and later actually support move operators despite -// reporting __cplusplus to be 199711L, so explicitly check for that. -// Also, stlport doesn't implement std::move(). -#if (__cplusplus >= 201103L || _MSC_VER >= 1600) && !defined(_STLPORT_VERSION) -#define FIREBASE_USE_MOVE_OPERATORS -#endif - -// stlport doesn't implement std::function. -#if !defined(_STLPORT_VERSION) -#define FIREBASE_USE_STD_FUNCTION -#endif // !defined(_STLPORT_VERSION) - -// stlport doesn't implement std::aligned_storage. -#if defined(_STLPORT_VERSION) -#include - -namespace firebase { -template -struct AlignedStorage { - struct type { - alignas(Alignment) unsigned char data[Length]; - }; -}; -} // namespace firebase -#define FIREBASE_ALIGNED_STORAGE ::firebase::AlignedStorage -#else -#include -#define FIREBASE_ALIGNED_STORAGE std::aligned_storage -#endif // defined(_STLPORT_VERSION) - -// Visual Studio 2013 does not support snprintf, so use streams instead. -#if !(defined(_MSC_VER) && _MSC_VER <= 1800) -#define FIREBASE_USE_SNPRINTF -#endif // !(defined(_MSC_VER) && _MSC_VER <= 1800) - -#if !(defined(_MSC_VER) && _MSC_VER <= 1800) -#define FIREBASE_USE_EXPLICIT_DEFAULT_METHODS -#endif // !(defined(_MSC_VER) && _MSC_VER <= 1800) - -#if !defined(DOXYGEN) && !defined(SWIG) -#if !defined(_WIN32) && !defined(__CYGWIN__) -// Prevent GCC & Clang from stripping a symbol. -#define FIREBASE_APP_KEEP_SYMBOL __attribute__((used)) -#else -// MSVC needs to reference a symbol directly in the application for it to be -// kept in the final executable. In this case, the end user's application -// must include the appropriate Firebase header (e.g firebase/analytics.h) to -// initialize the module. -#define FIREBASE_APP_KEEP_SYMBOL -#endif // !defined(_WIN32) && !defined(__CYGWIN__) - -// Module initializer's name. -// -// This can be used to explicitly include a module initializer in an application -// to prevent the object from being stripped by the linker. The symbol is -// located in the "firebase" namespace so can be referenced using: -// -// ::firebase::FIREBASE_APP_REGISTER_CALLBACKS_REFERENCE_NAME(name) -// -// Where "name" is the module name, for example "analytics". -#define FIREBASE_APP_REGISTER_CALLBACKS_INITIALIZER_NAME(module_name) \ - g_##module_name##_initializer - -// Declare a module initializer variable as a global. -#define FIREBASE_APP_REGISTER_CALLBACKS_INITIALIZER_VARIABLE(module_name) \ - namespace firebase { \ - extern void* FIREBASE_APP_REGISTER_CALLBACKS_INITIALIZER_NAME(module_name); \ - } /* namespace firebase */ - -// Generates code which references a module initializer. -// For example, FIREBASE_APP_REGISTER_REFERENCE(analytics) will register the -// module initializer for the analytics module. -#define FIREBASE_APP_REGISTER_CALLBACKS_REFERENCE(module_name) \ - FIREBASE_APP_REGISTER_CALLBACKS_INITIALIZER_VARIABLE(module_name) \ - namespace firebase { \ - static void* module_name##_ref FIREBASE_APP_KEEP_SYMBOL = \ - &FIREBASE_APP_REGISTER_CALLBACKS_INITIALIZER_NAME(module_name); \ - } /* namespace firebase */ -#endif // !defined(DOXYGEN) && !defined(SWIG) - -#if defined(SWIG) || defined(DOXYGEN) -// SWIG needs to ignore the FIREBASE_DEPRECATED tag. -#define FIREBASE_DEPRECATED -#endif // defined(SWIG) || defined(DOXYGEN) - -#ifndef FIREBASE_DEPRECATED -#ifdef __GNUC__ -#define FIREBASE_DEPRECATED __attribute__((deprecated)) -#elif defined(_MSC_VER) -#define FIREBASE_DEPRECATED __declspec(deprecated) -#else -// We don't know how to mark functions as "deprecated" with this compiler. -#define FIREBASE_DEPRECATED -#endif -#endif // FIREBASE_DEPRECATED - -// Calculates the number of elements in an array. -#define FIREBASE_ARRAYSIZE(x) (sizeof(x) / sizeof((x)[0])) - -// Guaranteed compile time strlen. -#define FIREBASE_STRLEN(s) (FIREBASE_ARRAYSIZE(s) - sizeof((s)[0])) - -#endif // FIREBASE_APP_SRC_INCLUDE_FIREBASE_INTERNAL_COMMON_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/internal/future_impl.h b/packages/firebase_core/firebase_core/firebase_core/firebase/internal/future_impl.h deleted file mode 100644 index 59e7771d010b..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/internal/future_impl.h +++ /dev/null @@ -1,359 +0,0 @@ -/* - * Copyright 2016 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_APP_SRC_INCLUDE_FIREBASE_INTERNAL_FUTURE_IMPL_H_ -#define FIREBASE_APP_SRC_INCLUDE_FIREBASE_INTERNAL_FUTURE_IMPL_H_ - -/// @cond FIREBASE_APP_INTERNAL - -// You shouldn't include future_impl.h directly, since its just the inline -// implementation of the functions in future.h. Include future.h instead. -#include "firebase/future.h" - -#if defined(FIREBASE_USE_MOVE_OPERATORS) -#include -#endif // defined(FIREBASE_USE_MOVE_OPERATORS) - -namespace firebase { - -class ReferenceCountedFutureImpl; - -namespace detail { - -class CompletionCallbackHandle; - -/// Pure-virtual interface that APIs must implement to use Futures. -class FutureApiInterface { - public: - // typedef void FutureCallbackFn(const FutureBase* future); - virtual ~FutureApiInterface(); - - /// Increment the reference count on handle's asynchronous call. - /// Called when the Future is copied. - virtual void ReferenceFuture(const FutureHandle& handle) = 0; - - /// Decrement the reference count on handle's asynchronous call. - /// Called when the Future is destroyed or moved. - /// If the reference count drops to zero, the asynchronous call can be - /// forgotten. - virtual void ReleaseFuture(const FutureHandle& handle) = 0; - - /// Return the status of the asynchronous call. - virtual FutureStatus GetFutureStatus(const FutureHandle& handle) const = 0; - - /// Return the API-specific error. - /// Valid when GetFutureStatus() is kFutureStatusComplete, and undefined - /// otherwise. - virtual int GetFutureError(const FutureHandle& handle) const = 0; - - /// Return the API-specific error, in human-readable form, or "" if no message - /// has been provided. - /// Valid when GetFutureStatus() is kFutureStatusComplete, and undefined - /// otherwise. - virtual const char* GetFutureErrorMessage( - const FutureHandle& handle) const = 0; - - /// Return a pointer to the completed asynchronous result, or NULL if - /// result is still pending. - /// After an asynchronous call is marked complete, the API should not - /// modify the result (especially on a callback thread), since the threads - /// owning the Future can reference the result memory via this function. - virtual const void* GetFutureResult(const FutureHandle& handle) const = 0; - - /// Register a callback that will be called when this future's status is set - /// to Complete. If clear_existing_callbacks is true, then the new callback - /// will replace any existing callbacks, otherwise it will be added to the - /// list of callbacks. - /// - /// The future's result data will be passed back when the callback is - /// called, along with the user_data supplied here. - /// - /// After the callback has been called, if `user_data_delete_fn_ptr` is - /// non-null, then `(*user_data_delete_fn_ptr)(user_data)` will be called. - virtual CompletionCallbackHandle AddCompletionCallback( - const FutureHandle& handle, FutureBase::CompletionCallback callback, - void* user_data, void (*user_data_delete_fn)(void*), - bool clear_existing_callbacks) = 0; - - /// Unregister a callback that was previously registered with - /// `AddCompletionCallback`. - virtual void RemoveCompletionCallback( - const FutureHandle& handle, CompletionCallbackHandle callback_handle) = 0; - -#if defined(FIREBASE_USE_STD_FUNCTION) - /// Register a callback that will be called when this future's status is set - /// to Complete. - /// - /// If `clear_existing_callbacks` is true, then the new callback - /// will replace any existing callbacks, otherwise it will be added to the - /// list of callbacks. - /// - /// The future's result data will be passed back when the callback is - /// called. - /// - /// @return A handle that can be passed to `FutureBase::RemoveCompletion`. - virtual CompletionCallbackHandle AddCompletionCallbackLambda( - const FutureHandle& handle, - std::function callback, - bool clear_existing_callbacks) = 0; -#endif // defined(FIREBASE_USE_STD_FUNCTION) - - /// Register this Future instance to be cleaned up. - virtual void RegisterFutureForCleanup(FutureBase* future) = 0; - - /// Unregister this Future instance from the cleanup list. - virtual void UnregisterFutureForCleanup(FutureBase* future) = 0; -}; - -inline void RegisterForCleanup(FutureApiInterface* api, FutureBase* future) { - if (api != NULL) { // NOLINT - api->RegisterFutureForCleanup(future); - } -} - -inline void UnregisterForCleanup(FutureApiInterface* api, FutureBase* future) { - if (api != NULL) { // NOLINT - api->UnregisterFutureForCleanup(future); - } -} - -class CompletionCallbackHandle { - public: - // Construct a null CompletionCallbackHandle. - CompletionCallbackHandle() - : callback_(nullptr), - user_data_(nullptr), - user_data_delete_fn_(nullptr) {} - - private: - friend class ::firebase::FutureBase; - friend class ::firebase::ReferenceCountedFutureImpl; - CompletionCallbackHandle(FutureBase::CompletionCallback callback, - void* user_data, void (*user_data_delete_fn)(void*)) - : callback_(callback), - user_data_(user_data), - user_data_delete_fn_(user_data_delete_fn) {} - - FutureBase::CompletionCallback callback_; - void* user_data_; - void (*user_data_delete_fn_)(void*); -}; - -} // namespace detail - -template -void Future::OnCompletion(TypedCompletionCallback callback, - void* user_data) const { - FutureBase::OnCompletion(reinterpret_cast(callback), - user_data); -} - -#if defined(FIREBASE_USE_STD_FUNCTION) -template -inline void Future::OnCompletion( - std::function&)> callback) const { - FutureBase::OnCompletion( - *reinterpret_cast*>(&callback)); -} -#endif // defined(FIREBASE_USE_STD_FUNCTION) - -#if defined(INTERNAL_EXPERIMENTAL) -template -FutureBase::CompletionCallbackHandle Future::AddOnCompletion( - TypedCompletionCallback callback, void* user_data) const { - return FutureBase::AddOnCompletion( - reinterpret_cast(callback), user_data); -} - -#if defined(FIREBASE_USE_STD_FUNCTION) -template -inline FutureBase::CompletionCallbackHandle Future::AddOnCompletion( - std::function&)> callback) const { - return FutureBase::AddOnCompletion( - *reinterpret_cast*>(&callback)); -} -#endif // defined(FIREBASE_USE_STD_FUNCTION) - -#endif // defined(INTERNAL_EXPERIMENTAL) - -inline FutureBase::FutureBase() - : mutex_(Mutex::Mode::kModeNonRecursive), - api_(NULL), - handle_(0) {} // NOLINT - -inline FutureBase::FutureBase(detail::FutureApiInterface* api, - const FutureHandle& handle) - : mutex_(Mutex::Mode::kModeNonRecursive), api_(api), handle_(handle) { - api_->ReferenceFuture(handle_); - // Once the FutureBase has reference, we don't need extra handle reference. - handle_.Detach(); - detail::RegisterForCleanup(api_, this); -} - -inline FutureBase::~FutureBase() { Release(); } - -inline FutureBase::FutureBase(const FutureBase& rhs) - : mutex_(Mutex::Mode::kModeNonRecursive), - api_(NULL) // NOLINT -{ // NOLINT - *this = rhs; -} - -inline FutureBase& FutureBase::operator=(const FutureBase& rhs) { - Release(); - - detail::FutureApiInterface* new_api; - FutureHandle new_handle; - { - MutexLock lock(rhs.mutex_); - new_api = rhs.api_; - new_handle = rhs.handle_; - } - - { - MutexLock lock(mutex_); - api_ = new_api; - handle_ = new_handle; - - if (api_ != NULL) { // NOLINT - api_->ReferenceFuture(handle_); - } - detail::RegisterForCleanup(api_, this); - } - - return *this; -} - -#if defined(FIREBASE_USE_MOVE_OPERATORS) -inline FutureBase::FutureBase(FutureBase&& rhs) noexcept - : mutex_(Mutex::Mode::kModeNonRecursive), - api_(NULL) // NOLINT -{ - *this = std::move(rhs); -} - -inline FutureBase& FutureBase::operator=(FutureBase&& rhs) noexcept { - Release(); - - detail::FutureApiInterface* new_api; - FutureHandle new_handle; - { - MutexLock lock(rhs.mutex_); - detail::UnregisterForCleanup(rhs.api_, &rhs); - new_api = rhs.api_; - new_handle = rhs.handle_; - rhs.api_ = NULL; // NOLINT - } - - MutexLock lock(mutex_); - api_ = new_api; - handle_ = new_handle; - detail::RegisterForCleanup(api_, this); - return *this; -} -#endif // defined(FIREBASE_USE_MOVE_OPERATORS) - -inline void FutureBase::Release() { - MutexLock lock(mutex_); - if (api_ != NULL) { // NOLINT - detail::UnregisterForCleanup(api_, this); - api_->ReleaseFuture(handle_); - api_ = NULL; // NOLINT - } -} - -inline FutureStatus FutureBase::status() const { - MutexLock lock(mutex_); - return api_ == NULL ? // NOLINT - kFutureStatusInvalid - : api_->GetFutureStatus(handle_); -} - -inline int FutureBase::error() const { - MutexLock lock(mutex_); - return api_ == NULL ? -1 : api_->GetFutureError(handle_); // NOLINT -} - -inline const char* FutureBase::error_message() const { - MutexLock lock(mutex_); - return api_ == NULL ? NULL : api_->GetFutureErrorMessage(handle_); // NOLINT -} - -inline const void* FutureBase::result_void() const { - MutexLock lock(mutex_); - return api_ == NULL ? NULL : api_->GetFutureResult(handle_); // NOLINT -} - -inline void FutureBase::OnCompletion(CompletionCallback callback, - void* user_data) const { - MutexLock lock(mutex_); - if (api_ != NULL) { // NOLINT - api_->AddCompletionCallback(handle_, callback, user_data, nullptr, - /*clear_existing_callbacks=*/true); - } -} - -#if defined(INTERNAL_EXPERIMENTAL) -inline FutureBase::CompletionCallbackHandle FutureBase::AddOnCompletion( - CompletionCallback callback, void* user_data) const { - MutexLock lock(mutex_); - if (api_ != NULL) { // NOLINT - return api_->AddCompletionCallback(handle_, callback, user_data, nullptr, - /*clear_existing_callbacks=*/false); - } - return CompletionCallbackHandle(); -} - -inline void FutureBase::RemoveOnCompletion( - CompletionCallbackHandle completion_handle) const { - MutexLock lock(mutex_); - if (api_ != NULL) { // NOLINT - api_->RemoveCompletionCallback(handle_, completion_handle); - } -} -#endif // defined(INTERNAL_EXPERIMENTAL) - -#if defined(FIREBASE_USE_STD_FUNCTION) -inline void FutureBase::OnCompletion( - std::function callback) const { - MutexLock lock(mutex_); - if (api_ != NULL) { // NOLINT - api_->AddCompletionCallbackLambda(handle_, callback, - /*clear_existing_callbacks=*/true); - } -} - -#if defined(INTERNAL_EXPERIMENTAL) -inline FutureBase::CompletionCallbackHandle FutureBase::AddOnCompletion( - std::function callback) const { - MutexLock lock(mutex_); - if (api_ != NULL) { // NOLINT - return api_->AddCompletionCallbackLambda( - handle_, callback, - /*clear_existing_callbacks=*/false); - } - return CompletionCallbackHandle(); -} -#endif // defined(INTERNAL__EXPERIMENTAL) - -#endif // defined(FIREBASE_USE_STD_FUNCTION) - -// NOLINTNEXTLINE - allow namespace overridden -} // namespace firebase - -/// @endcond - -#endif // FIREBASE_APP_SRC_INCLUDE_FIREBASE_INTERNAL_FUTURE_IMPL_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/internal/mutex.h b/packages/firebase_core/firebase_core/firebase_core/firebase/internal/mutex.h deleted file mode 100644 index 86f6a45d1b38..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/internal/mutex.h +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Copyright 2016 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_APP_SRC_INCLUDE_FIREBASE_INTERNAL_MUTEX_H_ -#define FIREBASE_APP_SRC_INCLUDE_FIREBASE_INTERNAL_MUTEX_H_ - -#include "firebase/internal/platform.h" - -#if FIREBASE_PLATFORM_WINDOWS -#include -#else -#include -#endif // FIREBASE_PLATFORM_WINDOWS - -namespace firebase { - -#if !defined(DOXYGEN) - -/// @brief A simple synchronization lock. Only one thread at a time can Acquire. -class Mutex { - public: - // Bitfield that describes the mutex configuration. - enum Mode { - kModeNonRecursive = (0 << 0), - kModeRecursive = (1 << 0), - }; - - Mutex() : Mutex(kModeRecursive) {} - - explicit Mutex(Mode mode); - - ~Mutex(); - - // Acquires the lock for this mutex, blocking until it is available. - void Acquire(); - - // Releases the lock for this mutex acquired by a previous `Acquire()` call. - void Release(); - -// Returns the implementation-defined native mutex handle. -// Used by firebase::Thread implementation. -#if FIREBASE_PLATFORM_WINDOWS - HANDLE* native_handle() { return &synchronization_object_; } -#else - pthread_mutex_t* native_handle() { return &mutex_; } -#endif // FIREBASE_PLATFORM_WINDOWS - - private: - Mutex(const Mutex&) = delete; - Mutex& operator=(const Mutex&) = delete; - -#if FIREBASE_PLATFORM_WINDOWS - HANDLE synchronization_object_; - Mode mode_; -#else - pthread_mutex_t mutex_; -#endif // FIREBASE_PLATFORM_WINDOWS -}; - -/// @brief Acquire and hold a /ref Mutex, while in scope. -/// -/// Example usage: -/// \code{.cpp} -/// Mutex syncronization_mutex; -/// void MyFunctionThatRequiresSynchronization() { -/// MutexLock lock(syncronization_mutex); -/// // ... logic ... -/// } -/// \endcode -class MutexLock { - public: - explicit MutexLock(Mutex& mutex) : mutex_(&mutex) { mutex_->Acquire(); } - ~MutexLock() { mutex_->Release(); } - - private: - // Copy is disallowed. - MutexLock(const MutexLock& rhs); // NOLINT - MutexLock& operator=(const MutexLock& rhs); - - Mutex* mutex_; -}; - -#endif // !defined(DOXYGEN) - -} // namespace firebase - -#endif // FIREBASE_APP_SRC_INCLUDE_FIREBASE_INTERNAL_MUTEX_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/internal/platform.h b/packages/firebase_core/firebase_core/firebase_core/firebase/internal/platform.h deleted file mode 100644 index 17d64e32d022..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/internal/platform.h +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Copyright 2019 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_APP_SRC_INCLUDE_FIREBASE_INTERNAL_PLATFORM_H_ -#define FIREBASE_APP_SRC_INCLUDE_FIREBASE_INTERNAL_PLATFORM_H_ - -// This header serts exactly one of these FIREBASE_PLATFORM macros to 1, and the -// rest to 0: -// -// FIREBASE_PLATFORM_ANDROID -// FIREBASE_PLATFORM_IOS -// FIREBASE_PLATFORM_TVOS -// FIREBASE_PLATFORM_OSX -// FIREBASE_PLATFORM_WINDOWS -// FIREBASE_PLATFORM_LINUX -// FIREBASE_PLATFORM_UNKNOWN -// -// You can use e.g. #if FIREBASE_PLATFORM_OSX to conditionally compile code -// after including this header. -// -// It also defines some convenience macros: -// FIREBASE_PLATFORM_DESKTOP (1 on OSX, WINDOWS, and LINUX, 0 otherwise) -// FIREBASE_PLATFORM_MOBILE (1 on IOS and ANDROID, 0 otherwise) - -#define FIREBASE_PLATFORM_ANDROID 0 -#define FIREBASE_PLATFORM_IOS 0 -#define FIREBASE_PLATFORM_TVOS 0 -#define FIREBASE_PLATFORM_OSX 0 -#define FIREBASE_PLATFORM_WINDOWS 0 -#define FIREBASE_PLATFORM_LINUX 0 -#define FIREBASE_PLATFORM_UNKNOWN 0 - -#ifdef __APPLE__ -#include "TargetConditionals.h" -#endif // __APPLE__ - -#if defined(__ANDROID__) -#undef FIREBASE_PLATFORM_ANDROID -#define FIREBASE_PLATFORM_ANDROID 1 -#elif defined(TARGET_OS_IOS) && TARGET_OS_IOS -#undef FIREBASE_PLATFORM_IOS -#define FIREBASE_PLATFORM_IOS 1 -#elif defined(TARGET_OS_TV) && TARGET_OS_TV -#undef FIREBASE_PLATFORM_TVOS -#define FIREBASE_PLATFORM_TVOS 1 -#elif defined(TARGET_OS_OSX) && TARGET_OS_OSX -#undef FIREBASE_PLATFORM_OSX -#define FIREBASE_PLATFORM_OSX 1 -#elif defined(_WIN32) -#undef FIREBASE_PLATFORM_WINDOWS -#define FIREBASE_PLATFORM_WINDOWS 1 -#elif defined(__linux__) -#undef FIREBASE_PLATFORM_LINUX -#define FIREBASE_PLATFORM_LINUX 1 -#else -#undef FIREBASE_PLATFORM_UNKNOWN -#define FIREBASE_PLATFORM_UNKNOWN 1 -#endif - -#if FIREBASE_PLATFORM_LINUX - -// Include std library header to get version defines -#include - -#if defined(__clang__) -#define FIREBASE_COMPILER_CLANG 1 -#elif defined(__GNUC__) -#define FIREBASE_COMPILER_GCC 1 -#endif - -#if defined(_LIBCPP_VERSION) -#define FIREBASE_STANDARD_LIBCPP 1 -#elif defined(__GLIBCXX__) -#define FIREBASE_STANDARD_LIBSTDCPP 1 -#endif - -#if (FIREBASE_COMPILER_CLANG && FIREBASE_STANDARD_LIBCPP) -#define FIREBASE_LINUX_BUILD_CONFIG_STRING "clang_libstdcpp" -#elif (FIREBASE_COMPILER_CLANG && FIREBASE_STANDARD_LIBSTDCPP) -#define FIREBASE_LINUX_BUILD_CONFIG_STRING "clang_libcpp" -#elif (FIREBASE_COMPILER_GCC && FIREBASE_STANDARD_LIBCPP) -#define FIREBASE_LINUX_BUILD_CONFIG_STRING "gcc_libstdcpp" -#elif (FIREBASE_COMPILER_GCC && FIREBASE_STANDARD_LIBSTDCPP) -#define FIREBASE_LINUX_BUILD_CONFIG_STRING "gcc_libcpp" -#else -#error "Unsupported compiler or standard library" -#endif - -#endif // FIREBASE_PLATFORM_LINUX - -#define FIREBASE_PLATFORM_MOBILE \ - (FIREBASE_PLATFORM_IOS || FIREBASE_PLATFORM_ANDROID) -#define FIREBASE_PLATFORM_DESKTOP \ - (FIREBASE_PLATFORM_LINUX || FIREBASE_PLATFORM_WINDOWS || \ - FIREBASE_PLATFORM_OSX) - -#endif // FIREBASE_APP_SRC_INCLUDE_FIREBASE_INTERNAL_PLATFORM_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/internal/type_traits.h b/packages/firebase_core/firebase_core/firebase_core/firebase/internal/type_traits.h deleted file mode 100644 index 7c465ea27c1e..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/internal/type_traits.h +++ /dev/null @@ -1,134 +0,0 @@ -/* - * Copyright 2017 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_APP_SRC_INCLUDE_FIREBASE_INTERNAL_TYPE_TRAITS_H_ -#define FIREBASE_APP_SRC_INCLUDE_FIREBASE_INTERNAL_TYPE_TRAITS_H_ - -#include -#include - -// Doxygen breaks trying to parse this file, and since it is internal logic, -// it doesn't need to be included in the generated documentation. -#ifndef DOXYGEN - -namespace firebase { - -template -struct remove_reference { - typedef T type; -}; - -template -struct remove_reference { - typedef T type; -}; - -template -struct remove_reference { - typedef T type; -}; - -template -struct is_array { - static constexpr bool value = false; -}; - -template -struct is_array { - static constexpr bool value = true; -}; - -template -struct is_array { - static constexpr bool value = true; -}; - -template -struct is_lvalue_reference { - static constexpr bool value = false; -}; - -template -struct is_lvalue_reference { - static constexpr bool value = true; -}; - -// STLPort does include header, but its contents are in `std::tr1` -// namespace. To work around this, use aliases. -// TODO(varconst): all of the reimplementations of traits above can be replaced -// with appropriate aliases. -// TODO(varconst): the traits in this file would be more conformant if they -// inherited from `std::integral_constant`. -#ifdef STLPORT -#define FIREBASE_TYPE_TRAITS_NS std::tr1 -#else -#define FIREBASE_TYPE_TRAITS_NS std -#endif - -template -using decay = FIREBASE_TYPE_TRAITS_NS::decay; - -template -using decay_t = typename decay::type; - -template -using enable_if = FIREBASE_TYPE_TRAITS_NS::enable_if; - -template -using is_floating_point = FIREBASE_TYPE_TRAITS_NS::is_floating_point; - -template -using is_integral = FIREBASE_TYPE_TRAITS_NS::is_integral; - -template -using is_same = FIREBASE_TYPE_TRAITS_NS::is_same; - -template -using integral_constant = FIREBASE_TYPE_TRAITS_NS::integral_constant; - -using true_type = FIREBASE_TYPE_TRAITS_NS::true_type; -using false_type = FIREBASE_TYPE_TRAITS_NS::false_type; - -#undef FIREBASE_TYPE_TRAITS_NS - -// `is_char::value` is true iff `T` is a character type (including `wchar_t` -// and C++11 fixed-width character types). -template -struct is_char { - static constexpr bool value = -#if __cplusplus >= 202002L - is_same::value || -#endif -#if __cplusplus >= 201103L - is_same::value || is_same::value || -#endif - is_same::value || is_same::value || - is_same::value || is_same::value; -}; - -// A subset of `std::is_integral`: excludes `bool` and character types. -template -struct is_integer { - static constexpr bool value = - is_integral::value && !is_same::value && !is_char::value; -}; - -// NOLINTNEXTLINE - allow namespace overridden -} // namespace firebase - -#endif // DOXYGEN - -#endif // FIREBASE_APP_SRC_INCLUDE_FIREBASE_INTERNAL_TYPE_TRAITS_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/log.h b/packages/firebase_core/firebase_core/firebase_core/firebase/log.h deleted file mode 100644 index 3d36ce37dcb3..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/log.h +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright 2016 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_APP_SRC_INCLUDE_FIREBASE_LOG_H_ -#define FIREBASE_APP_SRC_INCLUDE_FIREBASE_LOG_H_ - -/// @brief Namespace that encompasses all Firebase APIs. -namespace firebase { - -/// @brief Levels used when logging messages. -enum LogLevel { - /// Verbose Log Level - kLogLevelVerbose = 0, - /// Debug Log Level - kLogLevelDebug, - /// Info Log Level - kLogLevelInfo, - /// Warning Log Level - kLogLevelWarning, - /// Error Log Level - kLogLevelError, - /// Assert Log Level - kLogLevelAssert, -}; - -/// @brief Sets the logging verbosity. -/// All log messages at or above the specific log level. -/// -/// @param[in] level Log level to display, by default this is set to -/// kLogLevelInfo. -void SetLogLevel(LogLevel level); - -/// @brief Gets the logging verbosity. -/// -/// @return Get the currently configured logging verbosity. -LogLevel GetLogLevel(); - -// NOLINTNEXTLINE - allow namespace overridden -} // namespace firebase - -#endif // FIREBASE_APP_SRC_INCLUDE_FIREBASE_LOG_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/messaging.h b/packages/firebase_core/firebase_core/firebase_core/firebase/messaging.h deleted file mode 100644 index e7c7f5776868..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/messaging.h +++ /dev/null @@ -1,728 +0,0 @@ -// Copyright 2016 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef FIREBASE_MESSAGING_SRC_INCLUDE_FIREBASE_MESSAGING_H_ -#define FIREBASE_MESSAGING_SRC_INCLUDE_FIREBASE_MESSAGING_H_ - -#include - -#include -#include -#include - -#include "firebase/app.h" -#include "firebase/future.h" -#include "firebase/internal/common.h" - -#if !defined(DOXYGEN) && !defined(SWIG) -FIREBASE_APP_REGISTER_CALLBACKS_REFERENCE(messaging) -#endif // !defined(DOXYGEN) && !defined(SWIG) - -namespace firebase { - -/// @brief Firebase Cloud Messaging API. -/// -/// Firebase Cloud Messaging allows you to send data from your server to your -/// users' devices, and receive messages from devices on the same connection -/// if you're using a XMPP server. -/// -/// The FCM service handles all aspects of queueing of messages and delivery -/// to client applications running on target devices. -namespace messaging { - -/// @brief A class to configure the behavior of Firebase Cloud Messaging. -/// -/// This class contains various configuration options that control some of -/// Firebase Cloud Messaging's behavior. -struct MessagingOptions { - /// Default constructor. - MessagingOptions() : suppress_notification_permission_prompt(false) {} - - /// If true, do not display the prompt to the user requesting permission to - /// allow notifications to this app. If the prompt is suppressed in this way, - /// the developer must manually prompt the user for permission at some point - /// in the future using `RequestPermission()`. - /// - /// If this prompt has already been accepted once in the past the prompt will - /// not be displayed again. - /// - /// This option currently only applies to iOS and tvOS. - bool suppress_notification_permission_prompt; -}; - -/// @brief Data structure for parameters that are unique to the Android -/// implementation. -struct AndroidNotificationParams { - /// The channel id that was provided when the message was sent. - std::string channel_id; -}; - -/// Used for messages that display a notification. -/// -/// On android, this requires that the app is using the Play Services client -/// library. -struct Notification { - Notification() : android(nullptr) {} - -#ifndef SWIG - /// Copy constructor. Makes a deep copy of this Message. - Notification(const Notification& other) : android(nullptr) { *this = other; } -#endif // !SWIG - -#ifndef SWIG - /// Copy assignment operator. Makes a deep copy of this Message. - Notification& operator=(const Notification& other) { - this->title = other.title; - this->body = other.body; - this->icon = other.icon; - this->sound = other.sound; - this->tag = other.tag; - this->color = other.color; - this->click_action = other.click_action; - this->body_loc_key = other.body_loc_key; - this->body_loc_args = other.body_loc_args; - this->title_loc_key = other.title_loc_key; - this->title_loc_args = other.title_loc_args; - delete this->android; - if (other.android) { - this->android = new AndroidNotificationParams(*other.android); - } else { - this->android = nullptr; - } - return *this; - } -#endif // !SWIG - - /// Destructor. - ~Notification() { delete android; } - - /// Indicates notification title. This field is not visible on tvOS, iOS - /// phones and tablets. - std::string title; - - /// Indicates notification body text. - std::string body; - - /// Indicates notification icon. Sets value to myicon for drawable resource - /// myicon. - std::string icon; - - /// Indicates a sound to play when the device receives the notification. - /// Supports default, or the filename of a sound resource bundled in the - /// app. - /// - /// Android sound files must reside in /res/raw/, while iOS and tvOS sound - /// files can be in the main bundle of the client app or in the - /// Library/Sounds folder of the app’s data container. - std::string sound; - - /// Indicates the badge on the client app home icon. iOS and tvOS only. - std::string badge; - - /// Indicates whether each notification results in a new entry in the - /// notification drawer on Android. If not set, each request creates a new - /// notification. If set, and a notification with the same tag is already - /// being shown, the new notification replaces the existing one in the - /// notification drawer. - std::string tag; - - /// Indicates color of the icon, expressed in \#rrggbb format. Android only. - std::string color; - - /// The action associated with a user click on the notification. - /// - /// On Android, if this is set, an activity with a matching intent filter is - /// launched when user clicks the notification. - /// - /// If set on iOS or tvOS, corresponds to category in APNS payload. - std::string click_action; - - /// Indicates the key to the body string for localization. - /// - /// On iOS and tvOS, this corresponds to "loc-key" in APNS payload. - /// - /// On Android, use the key in the app's string resources when populating this - /// value. - std::string body_loc_key; - - /// Indicates the string value to replace format specifiers in body string - /// for localization. - /// - /// On iOS and tvOS, this corresponds to "loc-args" in APNS payload. - /// - /// On Android, these are the format arguments for the string resource. For - /// more information, see [Formatting strings][1]. - /// - /// [1]: - /// https://developer.android.com/guide/topics/resources/string-resource.html#FormattingAndStyling - std::vector body_loc_args; - - /// Indicates the key to the title string for localization. - /// - /// On iOS and tvOS, this corresponds to "title-loc-key" in APNS payload. - /// - /// On Android, use the key in the app's string resources when populating this - /// value. - std::string title_loc_key; - - /// Indicates the string value to replace format specifiers in title string - /// for localization. - /// - /// On iOS and tvOS, this corresponds to "title-loc-args" in APNS payload. - /// - /// On Android, these are the format arguments for the string resource. For - /// more information, see [Formatting strings][1]. - /// - /// [1]: - /// https://developer.android.com/guide/topics/resources/string-resource.html#FormattingAndStyling - std::vector title_loc_args; - - /// Parameters that are unique to the Android implementation. - AndroidNotificationParams* android; -}; - -/// @brief Data structure used to send messages to, and receive messages from, -/// cloud messaging. -struct Message { - /// Initialize the message. - Message() - : time_to_live(0), - notification(nullptr), - notification_opened(false), - sent_time(0) {} - - /// Destructor. - ~Message() { delete notification; } - -#ifndef SWIG - /// Copy constructor. Makes a deep copy of this Message. - Message(const Message& other) : notification(nullptr) { *this = other; } -#endif // !SWIG - -#ifndef SWIG - /// Copy assignment operator. Makes a deep copy of this Message. - Message& operator=(const Message& other) { - this->from = other.from; - this->to = other.to; - this->collapse_key = other.collapse_key; - this->data = other.data; - this->raw_data = other.raw_data; - this->message_id = other.message_id; - this->message_type = other.message_type; - this->priority = other.priority; - this->original_priority = other.original_priority; - this->sent_time = other.sent_time; - this->time_to_live = other.time_to_live; - this->error = other.error; - this->error_description = other.error_description; - delete this->notification; - if (other.notification) { - this->notification = new Notification(*other.notification); - } else { - this->notification = nullptr; - } - this->notification_opened = other.notification_opened; - this->link = other.link; - return *this; - } -#endif // !SWIG - - /// Authenticated ID of the sender. This is a project number in most cases. - /// - /// Any value starting with google.com, goog. or gcm. are reserved. - /// - /// This field is only used for downstream messages received through - /// Listener::OnMessage(). - std::string from; - - /// This parameter specifies the recipient of a message. - /// - /// For example it can be a registration token, a topic name, an Instance ID - /// or project ID. - /// - /// PROJECT_ID@gcm.googleapis.com or Instance ID are accepted. - std::string to; - - /// This parameter identifies a group of messages (e.g., with collapse_key: - /// "Updates Available") that can be collapsed, so that only the last message - /// gets sent when delivery can be resumed. This is intended to avoid sending - /// too many of the same messages when the device comes back online or becomes - /// active. - /// - /// Note that there is no guarantee of the order in which messages get sent. - /// - /// Note: A maximum of 4 different collapse keys is allowed at any given time. - /// This means a FCM connection server can simultaneously store 4 different - /// send-to-sync messages per client app. If you exceed this number, there is - /// no guarantee which 4 collapse keys the FCM connection server will keep. - /// - /// This field is only used for downstream messages received through - /// Listener::OnMessage(). - std::string collapse_key; - - /// The metadata, including all original key/value pairs. Includes some of the - /// HTTP headers used when sending the message. `gcm`, `google` and `goog` - /// prefixes are reserved for internal use. - std::map data; - - /// Binary payload. - std::vector raw_data; - - /// Message ID. This can be specified by sender. Internally a hash of the - /// message ID and other elements will be used for storage. The ID must be - /// unique for each topic subscription - using the same ID may result in - /// overriding the original message or duplicate delivery. - std::string message_id; - - /// Equivalent with a content-type. - /// - /// Defined values: - /// - "deleted_messages" - indicates the server had too many messages and - /// dropped some, and the client should sync with his own server. - /// Current limit is 100 messages stored. - /// - "send_event" - indicates an upstream message has been pushed to the - /// FCM server. It does not guarantee the upstream destination received - /// it. - /// Parameters: "message_id" - /// - "send_error" - indicates an upstream message expired, without being - /// sent to the FCM server. - /// Parameters: "message_id" and "error" - /// - /// If this field is missing, the message is a regular message. - /// - /// This field is only used for downstream messages received through - /// Listener::OnMessage(). - std::string message_type; - - /// Sets the priority of the message. Valid values are "normal" and "high." On - /// iOS and tvOS, these correspond to APNs priority 5 and 10. - /// - /// By default, messages are sent with normal priority. Normal priority - /// optimizes the client app's battery consumption, and should be used unless - /// immediate delivery is required. For messages with normal priority, the app - /// may receive the message with unspecified delay. - /// - /// When a message is sent with high priority, it is sent immediately, and the - /// app can wake a sleeping device and open a network connection to your - /// server. - /// - /// For more information, see [Setting the priority of a message][1]. - /// - /// This field is only used for downstream messages received through - /// Listener::OnMessage(). - /// - /// [1]: - /// https://firebase.google.com/docs/cloud-messaging/concept-options#setting-the-priority-of-a-message - std::string priority; - - /// This parameter specifies 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. For more - /// information, see [Setting the lifespan of a message][1]. - /// - /// This field is only used for downstream messages received through - /// Listener::OnMessage(). - /// - /// [1]: https://firebase.google.com/docs/cloud-messaging/concept-options#ttl - int32_t time_to_live; - - /// Error code. Used in "nack" messages for CCS, and in responses from the - /// server. - /// See the CCS specification for the externally-supported list. - /// - /// This field is only used for downstream messages received through - /// Listener::OnMessage(). - std::string error; - - /// Human readable details about the error. - /// - /// This field is only used for downstream messages received through - /// Listener::OnMessage(). - std::string error_description; - - /// Optional notification to show. This only set if a notification was - /// received with this message, otherwise it is null. - /// - /// The notification is only guaranteed to be valid during the call to - /// Listener::OnMessage(). If you need to keep it around longer you will need - /// to make a copy of either the Message or Notification. Copying the Message - /// object implicitly makes a deep copy of the notification (allocated with - /// new) which is owned by the Message. - /// - /// This field is only used for downstream messages received through - /// Listener::OnMessage(). - Notification* notification; - - /// A flag indicating whether this message was opened by tapping a - /// notification in the OS system tray. If the message was received this way - /// this flag is set to true. - bool notification_opened; - - /// The link into the app from the message. - /// - /// This field is only used for downstream messages received through - /// Listener::OnMessage(). - std::string link; - - /// @cond FIREBASE_APP_INTERNAL - /// Original priority of the message. - std::string original_priority; - - /// UTC timestamp in milliseconds when the message was sent. - /// See https://en.wikipedia.org/wiki/Unix_time for details of UTC. - int64_t sent_time; - /// @endcond -}; - -/// @brief Base class used to receive messages from Firebase Cloud Messaging. -/// -/// You need to override base class methods to handle any events required by the -/// application. Methods are invoked asynchronously and may be invoked on other -/// threads. -class Listener { - public: - virtual ~Listener(); - - /// Called on the client when a message arrives. - /// - /// @param[in] message The data describing this message. - virtual void OnMessage(const Message& message) = 0; - - /// Called on the client when a registration token arrives. This function - /// will eventually be called in response to a call to - /// firebase::messaging::Initialize(...). - /// - /// @param[in] token The registration token. - virtual void OnTokenReceived(const char* token) = 0; -}; - -/// @brief Initialize Firebase Cloud Messaging. -/// -/// After Initialize is called, the implementation may call functions on the -/// Listener provided at any time. -/// -/// @param[in] app The Firebase App object for this application. -/// @param[in] listener A Listener object that listens for events from the -/// Firebase Cloud Messaging servers. -/// -/// @return kInitResultSuccess if initialization succeeded, or -/// kInitResultFailedMissingDependency on Android if Google Play services is -/// not available on the current device. -InitResult Initialize(const App& app, Listener* listener); - -/// @brief Initialize Firebase Cloud Messaging. -/// -/// After Initialize is called, the implementation may call functions on the -/// Listener provided at any time. -/// -/// @param[in] app The Firebase App object for this application. -/// @param[in] listener A Listener object that listens for events from the -/// Firebase Cloud Messaging servers. -/// @param[in] options A set of options that configure the -/// initialzation behavior of Firebase Cloud Messaging. -/// -/// @return kInitResultSuccess if initialization succeeded, or -/// kInitResultFailedMissingDependency on Android if Google Play services is -/// not available on the current device. -InitResult Initialize(const App& app, Listener* listener, - const MessagingOptions& options); - -/// @brief Terminate Firebase Cloud Messaging. -/// -/// Frees resources associated with Firebase Cloud Messaging. -/// -/// @note On Android, the services will not be shut down by this method. -void Terminate(); - -/// Determines if automatic token registration during initalization is enabled. -/// -/// @return true if auto token registration is enabled and false if disabled. -bool IsTokenRegistrationOnInitEnabled(); - -/// Enable or disable token registration during initialization of Firebase Cloud -/// Messaging. -/// -/// This token is what identifies the user to Firebase, so disabling this avoids -/// creating any new identity and automatically sending it to Firebase, unless -/// consent has been granted. -/// -/// If this setting is enabled, it triggers the token registration refresh -/// immediately. This setting is persisted across app restarts and overrides the -/// setting "firebase_messaging_auto_init_enabled" specified in your Android -/// manifest (on Android) or Info.plist (on iOS and tvOS). -/// -///

By default, token registration during initialization is enabled. -/// -/// The registration happens before you can programmatically disable it, so -/// if you need to change the default, (for example, because you want to prompt -/// the user before FCM generates/refreshes a registration token on app -/// startup), add to your application’s manifest: -/// -/// -/// @if NOT_DOXYGEN -/// -/// @else -/// @code -/// <meta-data android:name="firebase_messaging_auto_init_enabled" -/// android:value="false" /> -/// @endcode -/// @endif -/// -/// or on iOS or tvOS to your Info.plist: -/// -/// @if NOT_DOXYGEN -/// FirebaseMessagingAutoInitEnabled -/// -/// @else -/// @code -/// <key>FirebaseMessagingAutoInitEnabled</key> -/// <false/> -/// @endcode -/// @endif -/// -/// @param enable sets if a registration token should be requested on -/// initialization. -void SetTokenRegistrationOnInitEnabled(bool enable); - -#ifndef SWIG -/// @brief Set the listener for events from the Firebase Cloud Messaging -/// servers. -/// -/// A listener must be set for the application to receive messages from -/// the Firebase Cloud Messaging servers. The implementation may call functions -/// on the Listener provided at any time. -/// -/// @param[in] listener A Listener object that listens for events from the -/// Firebase Cloud Messaging servers. -/// -/// @return Pointer to the previously set listener. -Listener* SetListener(Listener* listener); -#endif // !SWIG - -/// Error code returned by Firebase Cloud Messaging C++ functions. -enum Error { - /// The operation was a success, no error occurred. - kErrorNone = 0, - /// Permission to receive notifications was not granted. - kErrorFailedToRegisterForRemoteNotifications, - /// Topic name is invalid for subscription/unsubscription. - kErrorInvalidTopicName, - /// Could not subscribe/unsubscribe because there is no registration token. - kErrorNoRegistrationToken, - /// Unknown error. - kErrorUnknown, -}; - -/// @brief Displays a prompt to the user requesting permission to display -/// notifications. -/// -/// The permission prompt only appears on iOS and tvOS. If the user has -/// already agreed to allow notifications, no prompt is displayed and the -/// returned future is completed immediately. -/// -/// @return A future that completes when the notification prompt has been -/// dismissed. -Future RequestPermission(); - -/// @brief Gets the result of the most recent call to RequestPermission(); -/// -/// @return Result of the most recent call to RequestPermission(). -Future RequestPermissionLastResult(); - -/// @brief Subscribe to receive all messages to the specified topic. -/// -/// Subscribes an app instance to a topic, enabling it to receive messages -/// sent to that topic. -/// -/// Call this function from the main thread. FCM is not thread safe. -/// -/// @param[in] topic The name of the topic to subscribe. Must match the -/// following regular expression: `[a-zA-Z0-9-_.~%]{1,900}`. -Future Subscribe(const char* topic); - -/// @brief Gets the result of the most recent call to Unsubscribe(); -/// -/// @return Result of the most recent call to Unsubscribe(). -Future SubscribeLastResult(); - -/// @brief Unsubscribe from a topic. -/// -/// Unsubscribes an app instance from a topic, stopping it from receiving -/// any further messages sent to that topic. -/// -/// Call this function from the main thread. FCM is not thread safe. -/// -/// @param[in] topic The name of the topic to unsubscribe from. Must match the -/// following regular expression: `[a-zA-Z0-9-_.~%]{1,900}`. -Future Unsubscribe(const char* topic); - -/// @brief Gets the result of the most recent call to Unsubscribe(); -/// -/// @return Result of the most recent call to Unsubscribe(). -Future UnsubscribeLastResult(); - -/// Determines whether Firebase Cloud Messaging exports message delivery metrics -/// to BigQuery. -/// -/// This function is currently only implemented on Android, and returns false -/// with no other behavior on other platforms. -/// -/// @return true if Firebase Cloud Messaging exports message delivery metrics to -/// BigQuery. -bool DeliveryMetricsExportToBigQueryEnabled(); - -/// Enables or disables Firebase Cloud Messaging message delivery metrics export -/// to BigQuery. -/// -/// By default, message delivery metrics are not exported to BigQuery. Use this -/// method to enable or disable the export at runtime. In addition, you can -/// enable the export by adding to your manifest. Note that the run-time method -/// call will override the manifest value. -/// -/// -/// -/// This function is currently only implemented on Android, and has no behavior -/// on other platforms. -/// -/// @param[in] enable Whether Firebase Cloud Messaging should export message -/// delivery metrics to BigQuery. -void SetDeliveryMetricsExportToBigQuery(bool enable); - -/// @brief This creates a Firebase Installations ID, if one does not exist, and -/// sends information about the application and the device where it's running to -/// the Firebase backend. -/// -/// @return A future with the token. -Future GetToken(); - -/// @brief Gets the result of the most recent call to GetToken(); -/// -/// @return Result of the most recent call to GetToken(). -Future GetTokenLastResult(); - -/// @brief Deletes the default token for this Firebase project. -/// -/// Note that this does not delete the Firebase Installations ID that may have -/// been created when generating the token. See Installations.Delete() for -/// deleting that. -/// -/// @return A future that completes when the token is deleted. -Future DeleteToken(); - -/// @brief Gets the result of the most recent call to DeleteToken(); -/// -/// @return Result of the most recent call to DeleteToken(). -Future DeleteTokenLastResult(); - -class PollableListenerImpl; - -/// @brief A listener that can be polled to consume pending `Message`s. -/// -/// This class is intended to be used with applications that have a main loop -/// that frequently updates, such as in the case of a game that has a main -/// loop that updates 30 to 60 times a second. Rather than respond to incoming -/// messages and tokens via the `OnMessage` virtual function, this class will -/// queue up the message internally in a thread-safe manner so that it can be -/// consumed with `PollMessage`. For example: -/// -/// ::firebase::messaging::PollableListener listener; -/// ::firebase::messaging::Initialize(app, &listener); -/// -/// while (true) { -/// std::string token; -/// if (listener.PollRegistrationToken(&token)) { -/// LogMessage("Received a registration token"); -/// } -/// -/// ::firebase::messaging::Message message; -/// while (listener.PollMessage(&message)) { -/// LogMessage("Received a new message"); -/// } -/// -/// // Remainder of application logic... -/// } -class PollableListener : public Listener { - public: - /// @brief The default constructor. - PollableListener(); - - /// @brief The required virtual destructor. - virtual ~PollableListener(); - - /// @brief An implementation of `OnMessage` which adds the incoming messages - /// to a queue, which can be consumed by calling `PollMessage`. - virtual void OnMessage(const Message& message); - - /// @brief An implementation of `OnTokenReceived` which stores the incoming - /// token so that it can be consumed by calling `PollRegistrationToken`. - virtual void OnTokenReceived(const char* token); - - /// @brief Returns the first message queued up, if any. - /// - /// If one or more messages has been received, the first message in the - /// queue will be popped and used to populate the `message` argument and the - /// function will return `true`. If there are no pending messages, `false` is - /// returned. This function should be called in a loop until all messages have - /// been consumed, like so: - /// - /// ::firebase::messaging::Message message; - /// while (listener.PollMessage(&message)) { - /// LogMessage("Received a new message"); - /// } - /// - /// @param[out] message The `Message` struct to be populated. If there were no - /// pending messages, `message` is not modified. - /// - /// @return Returns `true` if there was a pending message, `false` otherwise. - bool PollMessage(Message* message); - - /// @brief Returns the registration key, if a new one has been received. - /// - /// When a new registration token is received, it is cached internally and can - /// be retrieved by calling `PollRegistrationToken`. The cached registration - /// token will be used to populate the `token` argument, then the cache will - /// be cleared and the function will return `true`. If there is no cached - /// registration token this function retuns `false`. - /// - /// std::string token; - /// if (listener.PollRegistrationToken(&token)) { - /// LogMessage("Received a registration token"); - /// } - /// - /// @param[out] token A string to be populated with the new token if one has - /// been received. If there were no new token, the string is left unmodified. - /// - /// @return Returns `true` if there was a new token, `false` otherwise. - bool PollRegistrationToken(std::string* token) { - bool got_token; - std::string token_received = PollRegistrationToken(&got_token); - if (got_token) { - *token = token_received; - } - return got_token; - } - - private: - std::string PollRegistrationToken(bool* got_token); - - // The implementation of the `PollableListener`. - PollableListenerImpl* impl_; -}; - -} // namespace messaging -} // namespace firebase - -#endif // FIREBASE_MESSAGING_SRC_INCLUDE_FIREBASE_MESSAGING_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/remote_config.h b/packages/firebase_core/firebase_core/firebase_core/firebase/remote_config.h deleted file mode 100644 index a2bd41775775..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/remote_config.h +++ /dev/null @@ -1,526 +0,0 @@ -// Copyright 2016 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef FIREBASE_REMOTE_CONFIG_SRC_INCLUDE_FIREBASE_REMOTE_CONFIG_H_ -#define FIREBASE_REMOTE_CONFIG_SRC_INCLUDE_FIREBASE_REMOTE_CONFIG_H_ - -#include -#include -#include - -#include "firebase/app.h" -#include "firebase/future.h" -#include "firebase/internal/common.h" -#include "firebase/internal/platform.h" -#ifndef SWIG -#include "firebase/variant.h" -#endif // SWIG - -#if !defined(DOXYGEN) && !defined(SWIG) -FIREBASE_APP_REGISTER_CALLBACKS_REFERENCE(remote_config) -#endif // !defined(DOXYGEN) && !defined(SWIG) - -/// @brief Namespace that encompasses all Firebase APIs. -namespace firebase { - -#ifndef SWIG -/// @brief Firebase Remote Config API. -/// -/// Firebase Remote Config is a cloud service that lets you change the -/// appearance and behavior of your app without requiring users to download an -/// app update. -#endif // SWIG -namespace remote_config { - -/// @brief Describes the most recent fetch request status. -enum LastFetchStatus { - /// The most recent fetch was a success, and its data is ready to be - /// applied, if you have not already done so. - kLastFetchStatusSuccess, - /// The most recent fetch request failed. - kLastFetchStatusFailure, - /// The most recent fetch is still in progress. - kLastFetchStatusPending, -}; - -/// @brief Describes the most recent fetch failure. -enum FetchFailureReason { - /// The fetch has not yet failed. - kFetchFailureReasonInvalid, - /// The most recent fetch failed because it was throttled by the server. - /// (You are sending too many fetch requests in too short a time.) - kFetchFailureReasonThrottled, - /// The most recent fetch failed for an unknown reason. - kFetchFailureReasonError, -}; - -/// @brief Describes the state of the most recent Fetch() call. -/// Normally returned as a result of the GetInfo() function. -struct ConfigInfo { - /// @brief The time (in milliseconds since the epoch) that the last fetch - /// operation completed. - uint64_t fetch_time; - - /// @brief The status of the last fetch request. - LastFetchStatus last_fetch_status; - - /// @brief The reason the most recent fetch failed. - FetchFailureReason last_fetch_failure_reason; - - /// @brief The time (in milliseconds since the epoch) when the refreshing of - /// Remote Config data is throttled. - uint64_t throttled_end_time; -}; - -/// @brief Describes the source a config value was retrieved from. -enum ValueSource { - /// The value was not specified and no default was specified, so a static - /// value (0 for numeric values, an empty string for strings) was returned. - kValueSourceStaticValue, - /// The value was found in the remote data store, and returned. - kValueSourceRemoteValue, - /// The value was not specified, so the specified default value was - /// returned instead. - kValueSourceDefaultValue, -}; - -/// @brief Describes a retrieved value. -struct ValueInfo { - /// Where the config value was retrieved from (Default Config or Active - /// Config). - ValueSource source; - /// If true this indicates conversion to the requested type - /// succeeded, otherwise conversion failed so the static value for the - /// requested type was retrieved instead. - bool conversion_successful; -}; - -/// @brief Keys of API settings. -/// -/// @see SetConfigSetting -/// @see GetConfigSetting -enum ConfigSetting { - /// Set the value associated with this key to "1" to enable developer mode - /// (i.e disable throttling) and "0" to disable. - kConfigSettingDeveloperMode, -}; - -/// @brief The default cache expiration used by Fetch(), equal to 12 hours, -/// in milliseconds. -static const uint64_t kDefaultCacheExpiration = 60 * 60 * 12 * 1000; - -/// @brief The default timeout used by Fetch(), equal to 30 seconds, -/// in milliseconds. -static const uint64_t kDefaultTimeoutInMilliseconds = 30 * 1000; - -/// @brief Describes a mapping of a key to a string value. Used to set default -/// values. -struct ConfigKeyValue { - /// The lookup key string. -#ifndef SWIG - /// - /// @note Ensure this string stays valid for the duration of the - /// call to SetDefaults. -#endif // SWIG - const char* key; - /// The value string to be stored. -#ifndef SWIG - /// - /// @note Ensure this string stays valid for the duration of the - /// call to SetDefaults. -#endif // SWIG - const char* value; -}; - -#ifndef SWIG -/// @brief Describes a mapping of a key to a value of any type. Used to set -/// default values. -struct ConfigKeyValueVariant { - /// The lookup key string. - /// - /// @note Ensure this string stays valid for the duration of the - /// call to SetDefaults. - const char* key; - /// The value to be stored. The type of the Variant determines the type of - /// default data for the given key. - /// - /// @note If you use a Variant of type StaticString, ensure it stays - /// valid for the duration of the call to SetDefaults. - Variant value; -}; -#endif // SWIG - -/// @brief Configurations for Remote Config behavior. -struct ConfigSettings { - /// The timeout specifies how long the client should wait for a connection to - /// the Firebase Remote Config servers. - /// - /// @note A fetch call will fail if it takes longer than the specified timeout - /// to connect to the Remote Config servers. Default is 60 seconds. - uint64_t fetch_timeout_in_milliseconds = kDefaultTimeoutInMilliseconds; - - /// The minimum interval between successive fetch calls. - /// - /// @note Fetches less than duration seconds after the last fetch from the - /// Firebase Remote Config server would use values returned during the last - /// fetch. Default is 12 hours. - uint64_t minimum_fetch_interval_in_milliseconds = kDefaultCacheExpiration; -}; - -namespace internal { -class RemoteConfigInternal; -} // namespace internal - -#ifndef SWIG -/// @brief Entry point for the Firebase C++ SDK for Remote Config. -/// -/// To use the SDK, call firebase::remote_config::RemoteConfig::GetInstance() to -/// obtain an instance of RemoteConfig, then call operations on that instance. -/// The instance contains the complete set of FRC parameter values available to -/// your app. The instance also stores values fetched from the FRC Server until -/// they are made available for use with a call to @ref Activate(). -#endif // SWIG -class RemoteConfig { - public: - ~RemoteConfig(); - - /// @brief Returns a Future that contains ConfigInfo representing the - /// initialization status of this Firebase Remote Config instance. - /// Use this method to ensure Set/Get call not being blocked. - Future EnsureInitialized(); - - /// @brief Get the (possibly still pending) results of the most recent - /// EnsureInitialized() call. - /// - /// @return The future result from the last call to EnsureInitialized(). - Future EnsureInitializedLastResult(); - - /// Asynchronously activates the most recently fetched configs, so that the - /// fetched key value pairs take effect. - /// - /// @return A Future that contains true if fetched configs were - /// activated. The future will contain false if the configs were already - /// activated. - Future Activate(); - - /// @brief Get the (possibly still pending) results of the most recent - /// Activate() call. - /// - /// @return The future result from the last call to Activate(). - Future ActivateLastResult(); - - /// Asynchronously fetches and then activates the fetched configs. - /// - /// If the time elapsed since the last fetch from the Firebase Remote Config - /// backend is more than the default minimum fetch interval, configs are - /// fetched from the backend. - /// - /// After the fetch is complete, the configs are activated so that the fetched - /// key value pairs take effect. - /// - /// @return A Future that contains true if the current call - /// activated the fetched configs; if no configs were fetched from the backend - /// and the local fetched configs have already been activated, the future will - /// contain false. - Future FetchAndActivate(); - - /// @brief Get the (possibly still pending) results of the most recent - /// FetchAndActivate() call. - /// - /// @return The future result from the last call to FetchAndActivate(). - Future FetchAndActivateLastResult(); - - /// @brief Fetches config data from the server. - /// - /// @note This does not actually apply the data or make it accessible, - /// it merely retrieves it and caches it. To accept and access the newly - /// retrieved values, you must call @ref Activate(). - /// - /// Note that this function is asynchronous, and will normally take an - /// unspecified amount of time before completion. - /// - /// @return A Future which can be used to determine when the fetch is - /// complete. - Future Fetch(); - - /// @brief Fetches config data from the server. - /// - /// @note This does not actually apply the data or make it accessible, - /// it merely retrieves it and caches it. To accept and access the newly - /// retrieved values, you must call @ref Activate(). - /// Note that this function is asynchronous, and will normally take an - /// unspecified amount of time before completion. - /// - /// @param[in] cache_expiration_in_seconds The number of seconds to keep - /// previously fetch data available. If cached data is available that is - /// newer than cache_expiration_in_seconds, then the function returns - /// immediately and does not fetch any data. A cache_expiration_in_seconds of - /// zero will always cause a fetch. - /// - /// @return A Future which can be used to determine when the fetch is - /// complete. - Future Fetch(uint64_t cache_expiration_in_seconds); - - /// @brief Get the (possibly still pending) results of the most recent Fetch() - /// call. - /// - /// @return The future result from the last call to Fetch(). - Future FetchLastResult(); - -#if defined(__ANDROID__) - /// @brief Sets the default values, using an XML resource. - /// - /// @note This method is specific to the Android implementation. - /// - /// This completely overwrites all previous default values. - /// - /// @param[in] defaults_resource_id Id for the XML resource, which should be - /// in your applications res/xml folder. - /// - /// @return a Future which can be used to determine when the operation is - /// complete. - Future SetDefaults(int defaults_resource_id); -#endif // __ANDROID__ - -#ifndef SWIG - /// @brief Sets the default values based on a mapping of string to Variant. - /// This allows you to specify defaults of type other than string. - /// - /// The type of each Variant in the map determines the type of data for which - /// you are providing a default. For example, boolean values can be retrieved - /// with GetBool(), integer values can be retrieved with GetLong(), double - /// values can be retrieved with GetDouble(), string values can be retrieved - /// with GetString(), and binary data can be retrieved with GetData(). - /// Aggregate Variant types are not allowed. - /// - /// @see firebase::Variant for more information on how to create a Variant of - /// each type. - /// - /// @note This completely overrides all previous values. - /// - /// @param defaults Array of ConfigKeyValueVariant, representing the new set - /// of defaults to apply. If the same key is specified multiple times, the - /// value associated with the last duplicate key is applied. - /// @param number_of_defaults Number of elements in the defaults array. - /// - /// @return a Future which can be used to determine when the operation is - /// complete. - Future SetDefaults(const ConfigKeyValueVariant* defaults, - size_t number_of_defaults); -#endif // SWIG - - /// @brief Sets the default values based on a string map. - /// - /// @note This completely overrides all previous values. - /// - /// @param defaults Array of ConfigKeyValue, representing the new set of - /// defaults to apply. If the same key is specified multiple times, the - /// value associated with the last duplicate key is applied. - /// @param number_of_defaults Number of elements in the defaults array. - /// - /// @return a Future which can be used to determine when the operation is - /// complete. - Future SetDefaults(const ConfigKeyValue* defaults, - size_t number_of_defaults); - - /// @brief Get the (possibly still pending) results of the most recent - /// SetDefaults() call. - /// - /// @return The future result from the last call to SetDefaults(). - Future SetDefaultsLastResult(); - - /// @brief Asynchronously changes the settings for this Remote Config - /// instance. - /// - /// @param settings The new settings to be applied. - /// - /// @return a Future which can be used to determine when the operation is - /// complete. - Future SetConfigSettings(ConfigSettings settings); - - /// @brief Gets the current settings of the RemoteConfig object. - /// - /// @return A ConfigSettings struct. - ConfigSettings GetConfigSettings(); - - /// @brief Get the (possibly still pending) results of the most recent - /// SetConfigSettings() call. - /// - /// @return The future result from the last call to SetConfigSettings(). - Future SetConfigSettingsLastResult(); - - /// @brief Returns the value associated with a key, converted to a bool. - /// - /// Values of "1", "true", "t", "yes", "y" and "on" are interpreted (case - /// insensitive) as true and "0", "false", "f", "no", "n", "off", - /// and empty strings are interpreted (case insensitive) as - /// false. - /// - /// @param[in] key Key of the value to be retrieved. - /// - /// @return Value associated with the specified key converted to a boolean - /// value. - bool GetBoolean(const char* key); - - /// @brief Returns the value associated with a key, converted to a bool. - /// - /// Values of "1", "true", "t", "yes", "y" and "on" are interpreted (case - /// insensitive) as true and "0", "false", "f", "no", "n", "off", - /// and empty strings are interpreted (case insensitive) as - /// false. - /// - /// @param[in] key Key of the value to be retrieved. - /// @param[out] info A return value, specifying the source of the returned - /// value. - /// - /// @return Value associated with the specified key converted to a boolean - /// value. - bool GetBoolean(const char* key, ValueInfo* info); - - /// @brief Returns the value associated with a key, converted to a 64-bit - /// integer. - /// - /// @param[in] key Key of the value to be retrieved. - /// - /// @return Value associated with the specified key converted to a 64-bit - /// integer. - int64_t GetLong(const char* key); - - /// @brief Returns the value associated with a key, converted to a 64-bit - /// integer. - /// - /// @param[in] key Key of the value to be retrieved. - /// @param[out] info A return value, specifying the source of the returned - /// value. - /// - /// @return Value associated with the specified key converted to a 64-bit - /// integer. - int64_t GetLong(const char* key, ValueInfo* info); - - /// @brief Returns the value associated with a key, converted to a double. - /// - /// @param[in] key Key of the value to be retrieved. - /// - /// @return Value associated with the specified key converted to a double. - double GetDouble(const char* key); - - /// @brief Returns the value associated with a key, converted to a double. - /// - /// @param[in] key Key of the value to be retrieved. - /// @param[out] info A return value, specifying the source of the returned - /// value. - /// - /// @return Value associated with the specified key converted to a double. - double GetDouble(const char* key, ValueInfo* info); - - /// @brief Returns the value associated with a key, converted to a string. - /// - /// @param[in] key Key of the value to be retrieved. - /// - /// @return Value as a string associated with the specified key. - std::string GetString(const char* key); - - /// @brief Returns the value associated with a key, converted to a string. - /// - /// @param[in] key Key of the value to be retrieved. - /// @param[out] info A return value, specifying the source of the returned - /// value. - /// - /// @return Value as a string associated with the specified key. - std::string GetString(const char* key, ValueInfo* info); - - /// @brief Returns the value associated with a key, as a vector of raw - /// byte-data. - /// - /// @param[in] key Key of the value to be retrieved. - /// - /// @return Vector of bytes. - std::vector GetData(const char* key); - - /// @brief Returns the value associated with a key, as a vector of raw - /// byte-data. - /// - /// @param[in] key Key of the value to be retrieved. - /// @param[out] info A return value, specifying the source of the returned - /// value. - /// - /// @return Vector of bytes. - std::vector GetData(const char* key, ValueInfo* info); - - /// @brief Gets the set of keys that start with the given prefix. - /// - /// @param[in] prefix The key prefix to look for. If empty or null, this - /// method will return all keys. - /// - /// @return Set of Remote Config parameter keys that start with the specified - /// prefix. Will return an empty set if there are no keys with the given - /// prefix. - std::vector GetKeysByPrefix(const char* prefix); - - /// @brief Gets the set of all keys. - /// - /// @return Set of all Remote Config parameter keys. - std::vector GetKeys(); - - /// @brief Returns a Map of Firebase Remote Config key value pairs. - /// - /// Evaluates the values of the parameters in the following order: - /// The activated value, if the last successful @ref Activate() contained the - /// key. The default value, if the key was set with @ref SetDefaults(). - std::map GetAll(); - - /// @brief Returns information about the last fetch request, in the form - /// of a ConfigInfo struct. - /// - /// @return A ConfigInfo struct, containing fields reflecting the state - /// of the most recent fetch request. - const ConfigInfo GetInfo(); - - /// Gets the App this remote config object is connected to. - App* app() { return app_; } - - /// Returns the RemoteConfig object for an App. Creates the RemoteConfig if - /// required. - /// - /// To get the RemoteConfig object for the default app, use, - /// GetInstance(GetDefaultFirebaseApp()); - /// - /// If the library RemoteConfig fails to initialize, init_result_out will be - /// written with the result status (if a pointer is given). - /// - /// @param[in] app The App to use for the RemoteConfig object. - static RemoteConfig* GetInstance(App* app); - - private: - explicit RemoteConfig(App* app); - - // Find RemoteConfig instance using App. Return null if the instance does not - // exist. - static RemoteConfig* FindRemoteConfig(App* app); - - // Clean up RemoteConfig instance. - void DeleteInternal(); - - /// The Firebase App this remote config is connected to. - App* app_; - - bool InitInternal(); - - internal::RemoteConfigInternal* internal_; -}; - -} // namespace remote_config -} // namespace firebase - -#endif // FIREBASE_REMOTE_CONFIG_SRC_INCLUDE_FIREBASE_REMOTE_CONFIG_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/storage.h b/packages/firebase_core/firebase_core/firebase_core/firebase/storage.h deleted file mode 100644 index 8d081e4c0ead..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/storage.h +++ /dev/null @@ -1,161 +0,0 @@ -// Copyright 2016 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_H_ -#define FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_H_ - -#include - -#include "firebase/app.h" -#include "firebase/internal/common.h" -#include "firebase/storage/common.h" -#include "firebase/storage/controller.h" -#include "firebase/storage/listener.h" -#include "firebase/storage/metadata.h" -#include "firebase/storage/storage_reference.h" - -#if !defined(DOXYGEN) -#ifndef SWIG -FIREBASE_APP_REGISTER_CALLBACKS_REFERENCE(storage) -#endif // SWIG -#endif // !defined(DOXYGEN) - -namespace firebase { - -/// Namespace for the Firebase C++ SDK for Cloud Storage. -namespace storage { - -namespace internal { -class StorageInternal; -class MetadataInternal; -} // namespace internal - -class StorageReference; - -#ifndef SWIG -/// @brief Entry point for the Firebase C++ SDK for Cloud Storage. -/// -/// To use the SDK, call firebase::storage::Storage::GetInstance() to -/// obtain an instance of Storage, then use GetReference() to obtain references -/// to child blobs. From there you can upload data with -/// StorageReference::PutStream(), get data via StorageReference::GetStream(). -#endif // SWIG -class Storage { - public: - /// @brief Destructor. You may delete an instance of Storage when - /// you are finished using it, to shut down the Storage library. - ~Storage(); - - /// @brief Get an instance of Storage corresponding to the given App. - /// - /// Cloud Storage uses firebase::App to communicate with Firebase - /// Authentication to authenticate users to the server backend. - /// - /// @param[in] app An instance of firebase::App. Cloud Storage will use - /// this to communicate with Firebase Authentication. - /// @param[out] init_result_out Optional: If provided, write the init result - /// here. Will be set to kInitResultSuccess if initialization succeeded, or - /// kInitResultFailedMissingDependency on Android if Google Play services is - /// not available on the current device. - /// - /// @returns An instance of Storage corresponding to the given App. - static Storage* GetInstance(::firebase::App* app, - InitResult* init_result_out = nullptr); - - /// @brief Get an instance of Storage corresponding to the given App, - /// with the given Cloud Storage URL. - /// - /// Cloud Storage uses firebase::App to communicate with Firebase - /// Authentication to authenticate users to the server backend. - /// - /// @param[in] app An instance of firebase::App. Cloud Storage will use - /// this to communicate with Firebase Authentication. - /// @param[in] url Cloud Storage URL. - /// @param[out] init_result_out Optional: If provided, write the init result - /// here. Will be set to kInitResultSuccess if initialization succeeded, or - /// kInitResultFailedMissingDependency on Android if Google Play services is - /// not available on the current device. - /// - /// @returns An instance of Storage corresponding to the given App. - static Storage* GetInstance(::firebase::App* app, const char* url, - InitResult* init_result_out = nullptr); - - /// @brief Get the firease::App that this Storage was created with. - /// - /// @returns The firebase::App this Storage was created with. - ::firebase::App* app(); - - /// @brief Get the URL that this Storage was created with. - /// - /// @returns The URL this Storage was created with, or an empty - /// string if this Storage was created with default parameters. - std::string url(); - - /// @brief Get a StorageReference to the root of the database. - StorageReference GetReference() const; - - /// @brief Get a StorageReference for the specified path. - StorageReference GetReference(const char* path) const; - /// @brief Get a StorageReference for the specified path. - StorageReference GetReference(const std::string& path) const { - return GetReference(path.c_str()); - } - - /// @brief Get a StorageReference for the provided URL. - StorageReference GetReferenceFromUrl(const char* url) const; - /// @brief Get a StorageReference for the provided URL. - StorageReference GetReferenceFromUrl(const std::string& url) const { - return GetReferenceFromUrl(url.c_str()); - } - - /// @brief Returns the maximum time in seconds to retry a download if a - /// failure occurs. - double max_download_retry_time(); - /// @brief Sets the maximum time to retry a download if a failure occurs. - /// Defaults to 600 seconds (10 minutes). - void set_max_download_retry_time(double max_transfer_retry_seconds); - - /// @brief Returns the maximum time to retry an upload if a failure occurs. - double max_upload_retry_time(); - /// @brief Sets the maximum time to retry an upload if a failure occurs. - /// Defaults to 600 seconds (10 minutes). - void set_max_upload_retry_time(double max_transfer_retry_seconds); - - /// @brief Returns the maximum time to retry operations other than upload - /// and download if a failure occurs. - double max_operation_retry_time(); - /// @brief Sets the maximum time to retry operations other than upload and - /// download if a failure occurs. Defaults to 120 seconds (2 minutes). - void set_max_operation_retry_time(double max_transfer_retry_seconds); - - private: - /// @cond FIREBASE_APP_INTERNAL - friend class Metadata; - friend class internal::MetadataInternal; - - Storage(::firebase::App* app, const char* url); - Storage(const Storage& src); - Storage& operator=(const Storage& src); - - // Destroy the internal_ object. - void DeleteInternal(); - - internal::StorageInternal* internal_; - /// @endcond -}; - -} // namespace storage -} // namespace firebase - -#endif // FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/storage/common.h b/packages/firebase_core/firebase_core/firebase_core/firebase/storage/common.h deleted file mode 100644 index 567ed714920c..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/storage/common.h +++ /dev/null @@ -1,62 +0,0 @@ -// Copyright 2016 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_COMMON_H_ -#define FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_COMMON_H_ - -namespace firebase { -namespace storage { - -/// Error code returned by Cloud Storage C++ functions. -enum Error { - /// The operation was a success, no error occurred. - kErrorNone = 0, - /// An unknown error occurred. - kErrorUnknown, - /// No object exists at the desired reference. - kErrorObjectNotFound, - /// No bucket is configured for Cloud Storage. - kErrorBucketNotFound, - /// No project is configured for Cloud Storage. - kErrorProjectNotFound, - /// Quota on your Cloud Storage bucket has been exceeded. - kErrorQuotaExceeded, - /// User is unauthenticated. - kErrorUnauthenticated, - /// User is not authorized to perform the desired action. - kErrorUnauthorized, - /// The maximum time limit on an operation (upload, download, delete, etc.) - /// has been exceeded. - kErrorRetryLimitExceeded, - /// File on the client does not match the checksum of the file received by the - /// server. - kErrorNonMatchingChecksum, - /// Size of the downloaded file exceeds the amount of memory allocated for the - /// download. - kErrorDownloadSizeExceeded, - /// User cancelled the operation. - kErrorCancelled, -}; - -/// @brief Get the human-readable error message corresponding to an error code. -/// -/// @param[in] error Error code to get the error message for. -/// -/// @returns Statically-allocated string describing the error. -const char* GetErrorMessage(Error error); - -} // namespace storage -} // namespace firebase - -#endif // FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_COMMON_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/storage/controller.h b/packages/firebase_core/firebase_core/firebase_core/firebase/storage/controller.h deleted file mode 100644 index 42f29aa0c73b..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/storage/controller.h +++ /dev/null @@ -1,146 +0,0 @@ -// Copyright 2016 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_CONTROLLER_H_ -#define FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_CONTROLLER_H_ - -#include "firebase/storage/storage_reference.h" - -namespace firebase { -namespace storage { - -/// @cond FIREBASE_APP_INTERNAL -namespace internal { -class ControllerInternal; -class ListenerInternal; -class RestOperation; -} // namespace internal -/// @endcond - -/// @brief Controls an ongoing operation, allowing the caller to Pause, Resume -/// or Cancel an ongoing download or upload. -/// -/// An instance of Controller can be constructed and passed to -/// StorageReference::GetBytes(), StorageReference::GetFile(), -/// StorageReference::PutBytes(), or StorageReference::PutFile() to become -/// associated with it. Each Controller can only be associated with one -/// operation at a time. -/// -/// A Controller is also passed as an argument to Listener's callbacks. The -/// Controller passed to a StorageReference operation is not the same object -/// passed to Listener callbacks (though it refers to the same operation), so -/// there are no restrictions on the lifetime of the Controller the user creates -/// (but the Controller passed into a Listener callbacks should only be used -/// from within that callback). -/// -/// This class is currently not thread safe and can only be called on the main -/// thread. -class Controller { - public: - /// @brief Default constructor. - /// - /// You may construct your own Controller to pass into various - /// StorageReference operations. - Controller(); - - /// @brief Destructor. - ~Controller(); - - /// @brief Copy constructor. - /// - /// @param[in] other Controller to copy from. - Controller(const Controller& other); - - /// @brief Copy assignment operator. - /// - /// @param[in] other Controller to copy from. - /// - /// @returns Reference to the destination Controller. - Controller& operator=(const Controller& other); - -#if defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) - /// @brief Move constructor. Moving is an efficient operation for - /// Controller instances. - /// - /// @param[in] other Controller to move from. - Controller(Controller&& other); - - /// @brief Move assignment operator. Moving is an efficient operation for - /// Controller instances. - /// - /// @param[in] other Controller to move from. - /// - /// @returns Reference to the destination Controller. - Controller& operator=(Controller&& other); -#endif // defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) - - /// @brief Pauses the operation currently in progress. - /// - /// @returns True if the operation was successfully paused, false otherwise. - bool Pause(); - - /// @brief Resumes the operation that is paused. - /// - /// @returns True if the operation was successfully resumed, false otherwise. - bool Resume(); - - /// @brief Cancels the operation currently in progress. - /// - /// @returns True if the operation was successfully canceled, false otherwise. - bool Cancel(); - - /// @brief Returns true if the operation is paused. - bool is_paused() const; - - /// @brief Returns the number of bytes transferred so far. - /// - /// @returns The number of bytes transferred so far. - int64_t bytes_transferred() const; - - /// @brief Returns the total bytes to be transferred. - /// - /// @returns The total bytes to be transferred. This will return -1 if - /// the size of the transfer is unknown. - int64_t total_byte_count() const; - - /// @brief Returns the StorageReference associated with this Controller. - /// - /// @returns The StorageReference associated with this Controller. - StorageReference GetReference() const; - - /// @brief Returns true if this Controller is valid, false if it is not - /// valid. An invalid Controller is one that is not associated with an - /// operation. - /// - /// @returns true if this Controller is valid, false if this Controller is - /// invalid. - bool is_valid() const; - - private: - /// @cond FIREBASE_APP_INTERNAL - friend class internal::StorageReferenceInternal; - friend class internal::ControllerInternal; - friend class internal::ListenerInternal; - friend class internal::RestOperation; - - Controller(internal::ControllerInternal* internal); - - internal::ControllerInternal* internal_; - /// @endcond -}; - -} // namespace storage -} // namespace firebase - -#endif // FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_CONTROLLER_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/storage/listener.h b/packages/firebase_core/firebase_core/firebase_core/firebase/storage/listener.h deleted file mode 100644 index 8bd624f61537..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/storage/listener.h +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright 2016 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_LISTENER_H_ -#define FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_LISTENER_H_ - -#include "firebase/storage/controller.h" - -namespace firebase { -namespace storage { - -/// @cond FIREBASE_APP_INTERNAL -namespace internal { -class ListenerInternal; -class StorageInternal; -class StorageReferenceInternal; -class RestOperation; -} // namespace internal -/// @endcond - -/// @brief Base class used to receive pause and progress events on a running -/// read or write operation. -/// -/// Subclasses of this listener class can be used to receive events about data -/// transfer progress a location. Attach the listener to a location using -/// StorageReference::GetBytes(), StorageReference::GetFile(), -/// StorageReference::PutBytes(), and StorageReference::PutFile(); then -/// OnPaused() will be called whenever the Read or Write operation is paused, -/// and OnProgress() will be called periodically as the transfer makes progress. -class Listener { - public: - /// @brief Constructor. - Listener(); - - /// @brief Virtual destructor. - virtual ~Listener(); - - /// @brief The operation was paused. - /// - /// @param[in] controller A controller that can be used to check the status - /// and make changes to the ongoing operation. - virtual void OnPaused(Controller* controller) = 0; - - /// @brief There has been progress event. - /// - /// @param[in] controller A controller that can be used to check the status - /// and make changes to the ongoing operation. - virtual void OnProgress(Controller* controller) = 0; - - private: - /// @cond FIREBASE_APP_INTERNAL - friend class internal::StorageReferenceInternal; - friend class internal::RestOperation; - - // Platform specific data. - internal::ListenerInternal* impl_; - /// @endcond -}; - -} // namespace storage -} // namespace firebase - -#endif // FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_LISTENER_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/storage/metadata.h b/packages/firebase_core/firebase_core/firebase_core/firebase/storage/metadata.h deleted file mode 100644 index 8d697c1072e7..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/storage/metadata.h +++ /dev/null @@ -1,276 +0,0 @@ -// Copyright 2016 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_METADATA_H_ -#define FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_METADATA_H_ - -#include -#include -#include -#include - -#include "firebase/internal/common.h" - -namespace firebase { -namespace storage { - -namespace internal { -class MetadataInternal; -class MetadataInternalCommon; -class StorageInternal; -class StorageReferenceInternal; -} // namespace internal - -class Storage; -class StorageReference; - -/// @brief Metadata stores default attributes such as size and content type. -/// -/// Metadata for a StorageReference. You may also store custom metadata key -/// value pairs. Metadata values may be used to authorize operations using -/// declarative validation rules. -class Metadata { - public: - /// @brief Create a default Metadata that you can modify and use. - Metadata(); - -#ifdef INTERNAL_EXPERIMENTAL - Metadata(internal::MetadataInternal* internal); -#endif - - /// @brief Copy constructor. - /// - /// @param[in] other Metadata to copy from. - Metadata(const Metadata& other); - - /// @brief Copy assignment operator. - /// - /// @param[in] other Metadata to copy from. - /// - /// @returns Reference to the destination Metadata. - Metadata& operator=(const Metadata& other); - -#if defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) - /// @brief Move constructor. Moving is an efficient operation for Metadata. - /// - /// @param[in] other Metadata to move from. - Metadata(Metadata&& other); - - /// @brief Move assignment operator. Moving is an efficient operation for - /// Metadata. - /// - /// @param[in] other Metadata to move from. - /// - /// @returns Reference to the destination Metadata. - Metadata& operator=(Metadata&& other); -#endif // defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) - - ~Metadata(); - - /// @brief Return the owning Google Cloud Storage bucket for the - /// StorageReference. - /// - /// @returns The owning Google Cloud Storage bucket for the StorageReference. - const char* bucket() const; - - /// @brief Set the Cache Control setting of the StorageReference. - /// - /// @see https://tools.ietf.org/html/rfc7234#section-5.2 - void set_cache_control(const char* cache_control); - - /// @brief Set the Cache Control setting of the StorageReference. - /// - /// @see https://tools.ietf.org/html/rfc7234#section-5.2 - void set_cache_control(const std::string& cache_control) { - set_cache_control(cache_control.c_str()); - } - - /// @brief Return the Cache Control setting of the StorageReference. - /// - /// @returns The Cache Control setting of the StorageReference. - /// - /// @see https://tools.ietf.org/html/rfc7234#section-5.2 - const char* cache_control() const; - - /// @brief Set the content disposition of the StorageReference. - /// - /// @see https://tools.ietf.org/html/rfc6266 - void set_content_disposition(const char* disposition); - - /// @brief Set the content disposition of the StorageReference. - /// - /// @see https://tools.ietf.org/html/rfc6266 - void set_content_disposition(const std::string& disposition) { - set_content_disposition(disposition.c_str()); - } - - /// @brief Return the content disposition of the StorageReference. - /// - /// @returns The content disposition of the StorageReference. - /// - /// @see https://tools.ietf.org/html/rfc6266 - const char* content_disposition() const; - - /// @brief Set the content encoding for the StorageReference. - /// - /// @see https://tools.ietf.org/html/rfc2616#section-14.11 - void set_content_encoding(const char* encoding); - - /// @brief Set the content encoding for the StorageReference. - /// - /// @see https://tools.ietf.org/html/rfc2616#section-14.11 - void set_content_encoding(const std::string& encoding) { - set_content_encoding(encoding.c_str()); - } - - /// @brief Return the content encoding for the StorageReference. - /// - /// @returns The content encoding for the StorageReference. - /// - /// @see https://tools.ietf.org/html/rfc2616#section-14.11 - const char* content_encoding() const; - - /// @brief Set the content language for the StorageReference. - /// - /// @see https://tools.ietf.org/html/rfc2616#section-14.12 - void set_content_language(const char* language); - - /// @brief Set the content language for the StorageReference. - /// - /// This must be an ISO 639-1 two-letter language code. - /// E.g. "zh", "es", "en". - /// - /// @see https://www.loc.gov/standards/iso639-2/php/code_list.php - void set_content_language(const std::string& language) { - set_content_language(language.c_str()); - } - - /// @brief Return the content language for the StorageReference. - /// - /// @returns The content language for the StorageReference. - /// - /// @see https://tools.ietf.org/html/rfc2616#section-14.12 - const char* content_language() const; - - /// @brief Set the content type of the StorageReference. - /// - /// @see https://tools.ietf.org/html/rfc2616#section-14.17 - void set_content_type(const char* type); - - /// @brief Set the content type of the StorageReference. - /// - /// @see https://tools.ietf.org/html/rfc2616#section-14.17 - void set_content_type(const std::string& type) { - set_content_type(type.c_str()); - } - - /// @brief Return the content type of the StorageReference. - /// - /// @returns The content type of the StorageReference. - /// - /// @see https://tools.ietf.org/html/rfc2616#section-14.17 - const char* content_type() const; - - /// @brief Return the time the StorageReference was created in milliseconds - /// since the epoch. - /// - /// @returns The time the StorageReference was created in milliseconds since - /// the epoch. - int64_t creation_time() const; - - /// @brief Return a map of custom metadata key value pairs. - /// - /// The pointer returned is only valid during the lifetime of the Metadata - /// object that owns it. - /// - /// @returns The keys for custom metadata. - std::map* custom_metadata() const; - - // download_url() and download_urls() are deprecated and removed. - // Please use StorageReference::GetDownloadUrl() instead. - - /// @brief Return a version String indicating what version of the - /// StorageReference. - /// - /// @returns A value indicating the version of the StorageReference. - int64_t generation() const; - - /// @brief Return a version String indicating the version of this - /// StorageMetadata. - /// - /// @returns A value indicating the version of this StorageMetadata. - int64_t metadata_generation() const; - - /// @brief Return a simple name of the StorageReference object. - /// - /// @returns A simple name of the StorageReference object. - const char* name() const; - - /// @brief Return the path of the StorageReference object. - /// - /// @returns The path of the StorageReference object. - const char* path() const; - - /// @brief Return the associated StorageReference to which this Metadata - /// belongs. - /// - /// @returns The associated StorageReference to which this Metadata belongs. - /// If this Metadata is invalid or is not associated with any file, an invalid - /// StorageReference is returned. - StorageReference GetReference() const; - - /// @brief Return the stored Size in bytes of the StorageReference object. - /// - /// @returns The stored Size in bytes of the StorageReference object. - int64_t size_bytes() const; - - /// @brief Return the time the StorageReference was last updated in - /// milliseconds since the epoch. - /// - /// @return The time the StorageReference was last updated in milliseconds - /// since the epoch. - int64_t updated_time() const; - - /// @brief Returns true if this Metadata is valid, false if it is not - /// valid. An invalid Metadata is returned when a method such as - /// StorageReference::GetMetadata() completes with an error. - /// - /// @returns true if this Metadata is valid, false if this Metadata is - /// invalid. - bool is_valid() const; - - /// @brief MD5 hash of the data; encoded using base64. - /// - /// @returns MD5 hash of the data; encoded using base64. - const char* md5_hash() const; - - private: - /// @cond FIREBASE_APP_INTERNAL - friend class StorageReference; - friend class internal::MetadataInternal; - friend class internal::MetadataInternalCommon; - friend class internal::StorageReferenceInternal; - -#ifndef INTERNAL_EXPERIMENTAL - Metadata(internal::MetadataInternal* internal); -#endif - - internal::MetadataInternal* internal_; - /// @endcond -}; - -} // namespace storage -} // namespace firebase - -#endif // FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_METADATA_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/storage/storage_reference.h b/packages/firebase_core/firebase_core/firebase_core/firebase/storage/storage_reference.h deleted file mode 100644 index e5c7c2f85ae6..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/storage/storage_reference.h +++ /dev/null @@ -1,361 +0,0 @@ -// Copyright 2016 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_STORAGE_REFERENCE_H_ -#define FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_STORAGE_REFERENCE_H_ - -#include -#include - -#include "firebase/future.h" -#include "firebase/internal/common.h" -#include "firebase/storage/metadata.h" - -namespace firebase { -namespace storage { - -class Controller; -class Listener; -class Storage; - -/// @cond FIREBASE_APP_INTERNAL -namespace internal { -class ControllerInternal; -class MetadataInternal; -class StorageInternal; -class StorageReferenceInternalCommon; -class StorageReferenceInternal; -} // namespace internal -/// @endcond FIREBASE_APP_INTERNAL - -#ifndef SWIG -/// Represents a reference to a Cloud Storage object. -/// Developers can upload and download objects, get/set object metadata, and -/// delete an object at a specified path. -#endif // SWIG -class StorageReference { - public: - /// @brief Default constructor. This creates an invalid StorageReference. - /// Attempting to perform any operations on this reference will fail unless a - /// valid StorageReference has been assigned to it. - StorageReference() : internal_(nullptr) {} - - ~StorageReference(); - - /// @brief Copy constructor. It's totally okay (and efficient) to copy - /// StorageReference instances, as they simply point to the same location. - /// - /// @param[in] reference StorageReference to copy from. - StorageReference(const StorageReference& reference); - - /// @brief Copy assignment operator. It's totally okay (and efficient) to copy - /// StorageReference instances, as they simply point to the same location. - /// - /// @param[in] reference StorageReference to copy from. - /// - /// @returns Reference to the destination StorageReference. - StorageReference& operator=(const StorageReference& reference); - -#if defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) - /// @brief Move constructor. Moving is an efficient operation for - /// StorageReference instances. - /// - /// @param[in] other StorageReference to move data from. - StorageReference(StorageReference&& other); - - /// @brief Move assignment operator. Moving is an efficient operation for - /// StorageReference instances. - /// - /// @param[in] other StorageReference to move data from. - /// - /// @returns Reference to the destination StorageReference. - StorageReference& operator=(StorageReference&& other); -#endif // defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) - - /// @brief Gets the firebase::storage::Storage instance to which we refer. - /// - /// The pointer will remain valid indefinitely. - /// - /// @returns The firebase::storage::Storage instance that this - /// StorageReference refers to. - Storage* storage(); - - /// @brief Gets a reference to a location relative to this one. - /// - /// @param[in] path Path relative to this reference's location. - /// The pointer only needs to be valid during this call. - /// - /// @returns Child relative to this location. - StorageReference Child(const char* path) const; - - /// @brief Gets a reference to a location relative to this one. - /// - /// @param[in] path Path relative to this reference's location. - /// - /// @returns Child relative to this location. - StorageReference Child(const std::string& path) const { - return Child(path.c_str()); - } - - /// @brief Deletes the object at the current path. - /// - /// @returns A Future result, which will complete when the operation either - /// succeeds or fails. When the Future is completed, if its Error is - /// kErrorNone, the operation succeeded. - Future Delete(); - - /// @brief Returns the result of the most recent call to RemoveValue(); - /// - /// @returns The result of the most recent call to RemoveValue(); - Future DeleteLastResult(); - - /// @brief Return the Google Cloud Storage bucket that holds this object. - /// - /// @returns The bucket. - std::string bucket(); - - /// @brief Return the full path of the storage reference, not including - /// the Google Cloud Storage bucket. - /// - /// @returns Full path to the storage reference, not including GCS bucket. - /// For example, for the reference "gs://bucket/path/to/object.txt", the full - /// path would be "path/to/object.txt". - std::string full_path(); - - /// @brief Asynchronously downloads the object from this StorageReference. - /// - /// A byte array will be allocated large enough to hold the entire file in - /// memory. Therefore, using this method will impact memory usage of your - /// process. - /// - /// @param[in] path Path to local file on device to download into. - /// @param[in] listener A listener that will respond to events on this read - /// operation. If not nullptr, a listener that will respond to events on this - /// read operation. The caller is responsible for allocating and deallocating - /// the listener. The same listener can be used for multiple operations. - /// @param[out] controller_out Controls the write operation, providing the - /// ability to pause, resume or cancel an ongoing write operation. If not - /// nullptr, this method will output a Controller here that you can use to - /// control the write operation. - /// - /// @returns A future that returns the number of bytes read. - Future GetFile(const char* path, Listener* listener = nullptr, - Controller* controller_out = nullptr); - - /// @brief Returns the result of the most recent call to GetFile(); - /// - /// @returns The result of the most recent call to GetFile(); - Future GetFileLastResult(); - - /// @brief Asynchronously downloads the object from this StorageReference. - /// - /// A byte array will be allocated large enough to hold the entire file in - /// memory. Therefore, using this method will impact memory usage of your - /// process. - /// - /// @param[in] buffer A byte buffer to read the data into. This buffer must - /// be valid for the duration of the transfer. - /// @param[in] buffer_size The size of the byte buffer. - /// @param[in] listener A listener that will respond to events on this read - /// operation. If not nullptr, a listener that will respond to events on this - /// read operation. The caller is responsible for allocating and deallocating - /// the listener. The same listener can be used for multiple operations. - /// @param[out] controller_out Controls the write operation, providing the - /// ability to pause, resume or cancel an ongoing write operation. If not - /// nullptr, this method will output a Controller here that you can use to - /// control the write operation. - /// - /// @returns A future that returns the number of bytes read. - Future GetBytes(void* buffer, size_t buffer_size, - Listener* listener = nullptr, - Controller* controller_out = nullptr); - - /// @brief Returns the result of the most recent call to GetBytes(); - /// - /// @returns The result of the most recent call to GetBytes(); - Future GetBytesLastResult(); - - /// @brief Asynchronously retrieves a long lived download URL with a revokable - /// token. - /// - /// This can be used to share the file with others, but can be revoked by a - /// developer in the Firebase Console if desired. - /// - /// @returns A Future result, which will complete when the operation either - /// succeeds or fails. When the Future is completed, if its Error is - /// kErrorNone, the operation succeeded and the URL is returned. - Future GetDownloadUrl(); - - /// @brief Returns the result of the most recent call to GetDownloadUrl(); - /// - /// @returns The result of the most recent call to GetDownloadUrl(); - Future GetDownloadUrlLastResult(); - - /// @brief Retrieves metadata associated with an object at this - /// StorageReference. - /// - /// @returns A Future result, which will complete when the operation either - /// succeeds or fails. When the Future is completed, if its Error is - /// kErrorNone, the operation succeeded and the Metadata is returned. - Future GetMetadata(); - - /// @brief Returns the result of the most recent call to GetMetadata(); - /// - /// @returns The result of the most recent call to GetMetadata(); - Future GetMetadataLastResult(); - - /// @brief Updates the metadata associated with this StorageReference. - /// - /// @returns A Future result, which will complete when the operation either - /// succeeds or fails. When the Future is completed, if its Error is - /// kErrorNone, the operation succeeded and the Metadata is returned. - Future UpdateMetadata(const Metadata& metadata); - - /// @brief Returns the result of the most recent call to UpdateMetadata(); - /// - /// @returns The result of the most recent call to UpdateMetadata(); - Future UpdateMetadataLastResult(); - - /// @brief Returns the short name of this object. - /// - /// @returns the short name of this object. - std::string name(); - - /// @brief Returns a new instance of StorageReference pointing to the parent - /// location or null if this instance references the root location. - /// - /// @returns The parent StorageReference. - StorageReference GetParent(); - - /// @brief Asynchronously uploads data to the currently specified - /// StorageReference, without additional metadata. - /// - /// @param[in] buffer A byte buffer to write data from. This buffer must be - /// valid for the duration of the transfer. - /// @param[in] buffer_size The size of the byte buffer. - /// @param[in] listener A listener that will respond to events on this read - /// operation. If not nullptr, a listener that will respond to events on this - /// write operation. The caller is responsible for allocating and deallocating - /// the listener. The same listener can be used for multiple operations. - /// @param[out] controller_out Controls the write operation, providing the - /// ability to pause, resume or cancel an ongoing write operation. If not - /// nullptr, this method will output a Controller here that you can use to - /// control the write operation. - /// - /// @returns A future that returns the Metadata. - Future PutBytes(const void* buffer, size_t buffer_size, - Listener* listener = nullptr, - Controller* controller_out = nullptr); - - /// @brief Asynchronously uploads data to the currently specified - /// StorageReference, without additional metadata. - /// - /// @param[in] buffer A byte buffer to write data from. This buffer must be - /// valid for the duration of the transfer. - /// @param[in] buffer_size The number of bytes to write. - /// @param[in] metadata Metadata containing additional information (MIME type, - /// etc.) about the object being uploaded. - /// @param[in] listener A listener that will respond to events on this read - /// operation. If not nullptr, a listener that will respond to events on this - /// write operation. The caller is responsible for allocating and deallocating - /// the listener. The same listener can be used for multiple operations. - /// @param[out] controller_out Controls the write operation, providing the - /// ability to pause, resume or cancel an ongoing write operation. If not - /// nullptr, this method will output a Controller here that you can use to - /// control the write operation. - /// - /// @returns A future that returns the Metadata. - Future PutBytes(const void* buffer, size_t buffer_size, - const Metadata& metadata, - Listener* listener = nullptr, - Controller* controller_out = nullptr); - - /// @brief Returns the result of the most recent call to PutBytes(); - /// - /// @returns The result of the most recent call to PutBytes(); - Future PutBytesLastResult(); - - /// @brief Asynchronously uploads data to the currently specified - /// StorageReference, without additional metadata. - /// - /// @param[in] path Path to local file on device to upload to Firebase - /// Storage. - /// @param[in] listener A listener that will respond to events on this read - /// operation. If not nullptr, a listener that will respond to events on this - /// write operation. The caller is responsible for allocating and deallocating - /// the listener. The same listener can be used for multiple operations. - /// @param[out] controller_out Controls the write operation, providing the - /// ability to pause, resume or cancel an ongoing write operation. If not - /// nullptr, this method will output a Controller here that you can use to - /// control the write operation. - /// - /// @returns A future that returns the Metadata. - Future PutFile(const char* path, Listener* listener = nullptr, - Controller* controller_out = nullptr); - - /// @brief Asynchronously uploads data to the currently specified - /// StorageReference, without additional metadata. - /// - /// @param[in] path Path to local file on device to upload to Firebase - /// Storage. - /// @param[in] metadata Metadata containing additional information (MIME type, - /// etc.) about the object being uploaded. - /// @param[in] listener A listener that will respond to events on this read - /// operation. If not nullptr, a listener that will respond to events on this - /// write operation. The caller is responsible for allocating and deallocating - /// the listener. The same listener can be used for multiple operations. - /// @param[out] controller_out Controls the write operation, providing the - /// ability to pause, resume or cancel an ongoing write operation. If not - /// nullptr, this method will output a Controller here that you can use to - /// control the write operation. - /// - /// @returns A future that returns the Metadata. - Future PutFile(const char* path, const Metadata& metadata, - Listener* listener = nullptr, - Controller* controller_out = nullptr); - - /// @brief Returns the result of the most recent call to PutFile(); - /// - /// @returns The result of the most recent call to PutFile(); - Future PutFileLastResult(); - - /// @brief Returns true if this StorageReference is valid, false if it is not - /// valid. An invalid StorageReference indicates that the reference is - /// uninitialized (created with the default constructor) or that there was an - /// error retrieving the reference. - /// - /// @returns true if this StorageReference is valid, false if this - /// StorageReference is invalid. - bool is_valid() const; - - private: - /// @cond FIREBASE_APP_INTERNAL - friend class Controller; - friend class internal::ControllerInternal; - friend class Metadata; - friend class internal::MetadataInternal; - friend class Storage; - friend class internal::StorageReferenceInternal; - friend class internal::StorageReferenceInternalCommon; - - StorageReference(internal::StorageReferenceInternal* internal); - - internal::StorageReferenceInternal* internal_; - /// @endcond -}; - -} // namespace storage -} // namespace firebase - -#endif // FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_STORAGE_REFERENCE_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/util.h b/packages/firebase_core/firebase_core/firebase_core/firebase/util.h deleted file mode 100644 index 4c78d45f3ac8..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/util.h +++ /dev/null @@ -1,101 +0,0 @@ -/* - * Copyright 2016 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_APP_SRC_INCLUDE_FIREBASE_UTIL_H_ -#define FIREBASE_APP_SRC_INCLUDE_FIREBASE_UTIL_H_ - -#include "firebase/app.h" -#include "firebase/future.h" - -namespace firebase { - -struct ModuleInitializerData; - -/// @brief Utility class to help with initializing Firebase modules. -/// -/// This optional class handles a basic Firebase C++ SDK code pattern: attempt -/// to initialize a Firebase module, and if the initialization fails on Android -/// due to Google Play services being unavailable, prompt the user to -/// update/enable Google Play services on their device. -/// -/// If the developer wants more advanced behavior (for example, wait to prompt -/// the user to update or enable Google Play services until later, or opt not to -/// use Firebase modules), they can still initialize each Firebase module -/// individually, and use google_play_services::MakeAvailable() directly if any -/// initializations fail. -class ModuleInitializer { - public: - /// @brief Initialization function, which should initialize a single Firebase - /// module and return the InitResult. - typedef InitResult (*InitializerFn)(App* app, void* context); - - ModuleInitializer(); - virtual ~ModuleInitializer(); - - /// @brief Initialize Firebase modules by calling one or more user-supplied - /// functions, each of which must initialize at most one library, and should - /// return the InitResult of the initialization. - /// - /// This function will run the initializers in order, checking the return - /// value of each. On Android, if the InitResult returned is - /// kInitResultFailedMissingDependency, this indicates that Google Play - /// services is not available and a Firebase module requires it. This function - /// will attempt to fix Google Play services, and will retry initializations - /// where it left off, beginning with the one that failed. - /// - /// @returns A future result. When all of the initializers are completed, the - /// Future will be completed with Error() = 0. If an initializer fails and the - /// situation cannot be fixed, the Future will be completed with Error() equal - /// to the number of initializers that did not succeed (since they are run in - /// order, this tells you which ones failed). - /// - /// @param[in] app The firebase::App that will be passed to the initializers, - /// as well as used to fix Google Play services on Android if needed. - /// - /// @param[in] context User-defined context, which will be passed to the - /// initializer functions. If you don't need this, you can use nullptr. - /// - /// @param[in] init_fns Your initialization functions to call, in an array. At - /// their simplest, these will each simply call a single Firebase module's - /// Initialize(app) and return the result, but you can perform more complex - /// logic if you prefer. - /// - /// @param[in] init_fns_count Number of initialization functions in the - /// supplied array. - /// - /// @note If a pending Initialize() is already running, this function will - /// return the existing Future rather than adding any new functions to the - /// initializer list. - Future Initialize(App* app, void* context, - const InitializerFn* init_fns, size_t init_fns_count); - - /// @brief Initialize one Firebase module by calling a single user-supplied - /// function that should initialize a Firebase module and return the - /// InitResult. @see Initialize(::firebase::App*, void*, const InitializerFn*) - /// for more information. - Future Initialize(App* app, void* context, InitializerFn init_fn); - - /// @brief Get the result of the most recent call to @see Initialize(). - Future InitializeLastResult(); - - private: - ModuleInitializerData* data_; -}; - -// NOLINTNEXTLINE - allow namespace overridden -} // namespace firebase - -#endif // FIREBASE_APP_SRC_INCLUDE_FIREBASE_UTIL_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/variant.h b/packages/firebase_core/firebase_core/firebase_core/firebase/variant.h deleted file mode 100644 index ef1d552dffa4..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/variant.h +++ /dev/null @@ -1,1197 +0,0 @@ -/* - * Copyright 2016 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_APP_SRC_INCLUDE_FIREBASE_VARIANT_H_ -#define FIREBASE_APP_SRC_INCLUDE_FIREBASE_VARIANT_H_ - -#include - -#include -#include -#include -#include -#include - -#include "firebase/internal/common.h" - -/// @brief Namespace that encompasses all Firebase APIs. - -namespace firebase { -namespace internal { -class VariantInternal; -} -} // namespace firebase - -namespace firebase { - -// -// SWIG uses the Variant class as a readonly object, and so ignores most of the -// functions. In order to keep things clean, functions that should be exposed -// are explicitly listed in app.SWIG, and everything else is ignored. -// - -/// Variant data type used by Firebase libraries. -class Variant { - public: - /// Type of data that this variant object contains. - enum Type { - /// Null, or no data. - kTypeNull, - /// A 64-bit integer. - kTypeInt64, - /// A double-precision floating point number. - kTypeDouble, - /// A boolean value. - kTypeBool, - /// A statically-allocated string we point to. - kTypeStaticString, - /// A std::string. - kTypeMutableString, - /// A std::vector of Variant. - kTypeVector, - /// A std::map, mapping Variant to Variant. - kTypeMap, - /// An statically-allocated blob of data that we point to. Never constructed - /// by default. Use Variant::FromStaticBlob() to create a Variant of this - /// type. - kTypeStaticBlob, - /// A blob of data that the Variant holds. Never constructed by default. Use - /// Variant::FromMutableBlob() to create a Variant of this type, and copy - /// binary data from an existing source. - kTypeMutableBlob, - - // Note: If you add new types update enum InternalType; - }; - -// -// Because of the VariantVariantMap C# class, we need to hide the constructors -// explicitly, as the SWIG ignore does not seem to work with that macro. -// -#ifndef SWIG - /// @brief Construct a null Variant. - /// - /// The Variant constructed will be of type Null. - Variant() : type_(kInternalTypeNull), value_({}) {} - - /// @brief Construct a Variant with the given templated type. - /// - /// @param[in] value The value to construct the variant. - /// - /// Valid types for this constructor are `int`, `int64_t`, `float`, `double`, - /// `bool`, `const char*`, and `char*` (but see below for additional Variant - /// types). - /// - /// - /// Type `int` or `int64_t`: - /// * The Variant constructed will be of type Int64. - /// - /// Type `double` or `float`: - /// * The Variant constructed will be of type Double. - /// - /// Type `bool`: - /// * The Variant constructed will be of type Bool. - /// - /// Type `const char*`: - /// * The Variant constructed will be of type StaticString, and is_string() - /// will return true. **Note:** If you use this constructor, you must - /// ensure that the memory pointed to stays valid for the life of the - /// Variant, otherwise call mutable_string() or set_mutable_string(), - /// which will copy the string to an internal buffer. - /// - /// Type `char*`: - /// * The Variant constructed will be of type MutableString, and is_string() - /// will return true. - /// - /// Other types will result in compiler error unless using the following - /// constructor overloads: - /// * `std::string` - /// * `std::vector` - /// * `std::vector` where T is convertible to variant type - /// * `T*`, `size_t` where T is convertible to variant type - /// * `std::map` - /// * `std::map` where K and V is convertible to variant type - template - Variant(T value) // NOLINT - : type_(kInternalTypeNull) { - set_value_t(value); - } - - /// @brief Construct a Variant containing the given string value (makes a - /// copy). - /// - /// The Variant constructed will be of type MutableString, and is_string() - /// will return true. - /// - /// @param[in] value The string to use for the Variant. - Variant(const std::string& value) // NOLINT - : type_(kInternalTypeNull) { - set_mutable_string(value); - } - - /// @brief Construct a Variant containing the given std::vector of Variant. - /// - /// The Variant constructed will be of type Vector. - /// - /// @param[in] value The STL vector to copy into the Variant. - Variant(const std::vector& value) // NOLINT - : type_(kInternalTypeNull) { - set_vector(value); - } - - /// @brief Construct a Variant containing the given std::vector of something - /// that can be constructed into a Variant. - /// - /// The Variant constructed will be of type Vector. - /// - /// @param[in] value An STL vector containing elements that can be converted - /// to Variant (such as ints, strings, vectors). A Variant will be created for - /// each element, and copied into the Vector Variant constructed here. - template - Variant(const std::vector& value) // NOLINT - : type_(kInternalTypeNull) { - Clear(kTypeVector); - vector().reserve(value.size()); - for (size_t i = 0; i < value.size(); i++) { - vector().push_back(Variant(static_cast(value[i]))); - } - } - - /// @brief Construct a Variant from an array of supported types into a Vector. - /// - /// The Variant constructed will be of type Vector. - /// - /// @param[in] array_of_values A C array containing elements that can be - /// converted to Variant (such as ints, strings, vectors). A Variant will be - /// created for each element, and copied into the Vector Variant constructed - /// here. - /// @param[in] array_size Number of elements of the array. - template - Variant(const T array_of_values[], size_t array_size) - : type_(kInternalTypeNull) { - Clear(kTypeVector); - vector().reserve(array_size); - for (size_t i = 0; i < array_size; i++) { - vector()[i] = Variant(array_of_values[i]); - } - } - - /// @brief Construct a Variatn containing the given std::map of Variant to - /// Variant. - /// - /// The Variant constructed will be of type Map. - /// - /// @param[in] value The STL map to copy into the Variant. - Variant(const std::map& value) // NOLINT - : type_(kInternalTypeNull) { - set_map(value); - } - - /// @brief Construct a Variant containing the given std::map of something that - /// can be constructed into a Variant, to something that can be constructed - /// into a Variant. - /// - /// The Variant constructed will be of type Map. - /// - /// @param[in] value An STL map containing keys and values that can be - /// converted to Variant (such as ints, strings, vectors). A Variant will be - /// created for each key and for each value, and copied by pairs into the Map - /// Variant constructed here. - template - Variant(const std::map& value) // NOLINT - : type_(kInternalTypeNull) { - Clear(kTypeMap); - for (typename std::map::const_iterator i = value.begin(); - i != value.end(); ++i) { - map().insert(std::make_pair(Variant(i->first), Variant(i->second))); - } - } - - /// @brief Copy constructor. Performs a deep copy. - /// - /// @param[in] other Source Variant to copy from. - Variant(const Variant& other) : type_(kInternalTypeNull) { *this = other; } - - /// @brief Copy assignment operator. Performs a deep copy. - /// - /// @param[in] other Source Variant to copy from. - Variant& operator=(const Variant& other); - -#if defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) - - /// @brief Move constructor. Efficiently moves the more complex data types by - /// simply reassigning pointer ownership. - /// - /// @param[in] other Source Variant to move from. - Variant(Variant&& other) noexcept : type_(kInternalTypeNull) { - *this = std::move(other); - } - - /// @brief Move assignment operator. Efficiently moves the more complex data - /// types by simply reassigning pointer ownership. - /// - /// @param[in] other Source Variant to move from. - Variant& operator=(Variant&& other) noexcept; - -#endif // defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) -#endif // SWIG - - /// Destructor. Frees the memory that this Variant owns. - ~Variant() { Clear(); } - - /// @brief Equality operator. Both the type and the value must be equal - /// (except that static strings CAN be == to mutable strings). For container - /// types, element-by-element comparison is performed. For strings, string - /// comparison is performed. - /// - /// @param[in] other Variant to compare to. - /// - /// @return True if the Variants are of identical types and values, false - /// otherwise. - bool operator==(const Variant& other) const; - - /// @brief Inequality operator, only meant for internal use. - /// - /// Explanation: In order to use Variant as a key for std::map, we must - /// provide a comparison function. This comparison function is ONLY for - /// std::map to be able to use a Variant as a map key. - /// - /// We define v1 < v2 IFF: - /// * If different types, compare type as int: v1.type() < v2.type() - /// (note: this means that Variant(1) < Variant(0.0) - be careful!) - /// * If both are int64: v1.int64_value() < v2.int64_value(); - /// * If both are double: v1.double_value() < v2.double_value() - /// * If both are bool: v1.bool_value() < v2.bool_value(); - /// * If both are either static or mutable strings: strcmp(v1, v2) < 0 - /// * If both are vectors: - /// * If v1[0] < v2[0], that means v1 < v2 == true. Otherwise: - /// * If v1[0] > v2[0], that means v1 < v2 == false. Otherwise: - /// * Continue to the next element of both vectors and compare again. - /// * If you reach the end of one vector first, that vector is considered - /// to be lesser. - /// * If both are maps, iterate similar to vectors (since maps are ordered), - /// but for each element, first compare the key, then the value. - /// * If both are blobs, the smaller-sized blob is considered lesser. If both - /// blobs are the same size, use memcmp to compare the bytes. - /// - /// We have defined this operation such that if !(v1 < v2) && !(v2 < v1), it - /// must follow that v1 == v2. - /// - /// @param[in] other Variant to compare to. - /// - /// @return Results of the comparison, as described in this documentation. - /// - /// @note This will not give you the results you expect if you compare - /// Variants of different types! For example, Variant(0.0) < Variant(1). - bool operator<(const Variant& other) const; - - /// @brief Inequality operator: x != y is evaluated as !(x == y). - /// - /// @param[in] other Variant to compare to. - /// - /// @return Results of the comparison. - bool operator!=(const Variant& other) const { return !(*this == other); } - - /// @brief Inequality operator: x > y is evaluated as y < x - /// - /// @param[in] other Variant to compare to. - /// - /// @return Results of the comparison. - bool operator>(const Variant& other) const { return other < *this; } - - /// @brief Inequality operator: x >= y is evaluated as !(x < y) - /// - /// @param[in] other Variant to compare to. - /// - /// @return Results of the comparison. - bool operator>=(const Variant& other) const { return !(*this < other); } - - /// @brief Inequality operator: x <= y is evaluated as !(x > y) - /// - /// @param[in] other Variant to compare to. - /// - /// @return Results of the comparison. - bool operator<=(const Variant& other) const { return !(*this > other); } - - /// @brief Clear the given Variant data, optionally into a new type. Frees up - /// any memory that might have been allocated. After calling this, you can - /// access the Variant as the new type. - /// - /// @param[in] new_type Optional new type to clear the Variant to. You may - /// immediately begin using the Variant as that new type. - void Clear(Type new_type = kTypeNull); - - // Convenience functions (used similarly to constants). - - /// @brief Get a Variant of type Null. - /// - /// @return A Variant of type Null. - static Variant Null() { return Variant(); } - - /// @brief Get a Variant of integer value 0. - /// - /// @return A Variant of type Int64, with value 0. - static Variant Zero() { return Variant::FromInt64(0L); } - - /// @brief Get a Variant of integer value 1. - /// - /// @return A Variant of type Int64, with value 1. - static Variant One() { return Variant::FromInt64(1L); } - - /// @brief Get a Variant of double value 0.0. - /// - /// @return A Variant of type Double, with value 0.0. - static Variant ZeroPointZero() { return Variant::FromDouble(0.0); } - - /// @brief Get a Variant of double value 1.0. - /// - /// @return A Variant of type Double, with value 1.0. - static Variant OnePointZero() { return Variant::FromDouble(1.0); } - - /// @brief Get a Variant of bool value false. - /// - /// @return A Variant of type Bool, with value false. - static Variant False() { return Variant::FromBool(false); } - - /// @brief Get a Variant of bool value true. - /// - /// @return A Variant of type Bool, with value true. - static Variant True() { return Variant::FromBool(true); } - - /// @brief Get an empty string variant. - /// - /// @return A Variant of type StaticString, referring to an empty string. - static Variant EmptyString() { return Variant::FromStaticString(""); } - - /// @brief Get a Variant containing an empty mutable string. - /// - /// @return A Variant of type MutableString, containing an empty string. - static Variant EmptyMutableString() { - Variant v; - v.Clear(kTypeMutableString); - return v; - } - - /// @brief Get a Variant containing an empty vector. You can immediately call - /// vector() on it to work with the vector it contains. - /// - /// @return A Variant of type Vector, containing no elements. - static Variant EmptyVector() { - Variant v; - v.Clear(kTypeVector); - return v; - } - - /// @brief Get a Variant containing an empty map. You can immediately call - /// map() on - /// it to work with the map it contains. - /// - /// @return A Variant of type Map, containing no elements. - static Variant EmptyMap() { - Variant v; - v.Clear(kTypeMap); - return v; - } - - /// @brief Return a Variant containing an empty mutable blob of the requested - /// size, filled with 0-bytes. - /// - /// @param[in] size_bytes Size of the buffer you want, in bytes. - /// - /// @returns A Variant containing a mutable blob of the requested size, filled - /// with 0-bytes. - static Variant EmptyMutableBlob(size_t size_bytes) { - Variant v; - uint8_t* blank_data = new uint8_t[size_bytes]; - memset(blank_data, 0, size_bytes); - v.Clear(kTypeMutableBlob); - v.set_blob_pointer(blank_data, size_bytes); - return v; - } - - /// @brief Get the current type contained in this Variant. - /// - /// @return The Variant's type. - Type type() const { - // To avoid breaking user code, alias the small string type to mutable - // string. - if (type_ == kInternalTypeSmallString) { - return kTypeMutableString; - } - - return static_cast(type_); - } - - /// @brief Get whether this Variant is currently null. - /// - /// @return True if the Variant is Null, false otherwise. - bool is_null() const { return type() == kTypeNull; } - - /// @brief Get whether this Variant contains an integer. - /// - /// @return True if the Variant's type is Int64, false otherwise. - bool is_int64() const { return type() == kTypeInt64; } - - /// @brief Get whether this Variant contains a double. - /// - /// @return True if the Variant's type is Double, false otherwise. - bool is_double() const { return type() == kTypeDouble; } - - /// @brief Get whether this Variant contains a bool. - /// - /// @return True if the Variant's type is Bool, false otherwise. - bool is_bool() const { return type() == kTypeBool; } - - /// @brief Get whether this Variant contains a vector. - /// - /// @return True if the Variant's type is Vector, false otherwise. - bool is_vector() const { return type() == kTypeVector; } - - /// @brief Get whether this Variant contains a map. - /// - /// @return True if the Variant's type is Map, false otherwise. - bool is_map() const { return type() == kTypeMap; } - - /// @brief Get whether this Variant contains a static string. - /// - /// @return True if the Variant's type is StaticString, false otherwise. - bool is_static_string() const { return type() == kTypeStaticString; } - - /// @brief Get whether this Variant contains a mutable string. - /// - /// @return True if the Variant's type is MutableString, false otherwise. - bool is_mutable_string() const { return type() == kTypeMutableString; } - - /// @brief Get whether this Variant contains a string. - /// - /// @return True if the Variant's type is either StaticString or - /// MutableString or SmallString; false otherwise. - /// - /// @note No matter which type of string the Variant contains, you can read - /// its value via string_value(). - bool is_string() const { - return is_static_string() || is_mutable_string() || is_small_string(); - } - - /// @brief Get whether this Variant contains a static blob. - /// - /// @return True if the Variant's type is StaticBlob, false otherwise. - bool is_static_blob() const { return type() == kTypeStaticBlob; } - - /// @brief Get whether this Variant contains a mutable blob. - /// - /// @return True if the Variant's type is MutableBlob, false otherwise. - bool is_mutable_blob() const { return type() == kTypeMutableBlob; } - - /// @brief Get whether this Variant contains a blob. - /// - /// @return True if the Variant's type is either StaticBlob or - /// MutableBlob; false otherwise. - /// - /// @note No matter which type of blob the Variant contains, you can read - /// its data via blob_data() and get its size via blob_size(). - bool is_blob() const { return is_static_blob() || is_mutable_blob(); } - - /// @brief Get whether this Variant contains a numeric type, Int64 or Double. - /// - /// @return True if the Variant's type is either Int64 or Double; false - /// otherwise. - bool is_numeric() const { return is_int64() || is_double(); } - - /// @brief Get whether this Variant contains a fundamental type: Null, Int64, - /// Double, Bool, or one of the two String types. Essentially - /// !is_containerType(). - /// - /// @return True if the Variant's type is Int64, Double, Bool, or Null; false - /// otherwise. - bool is_fundamental_type() const { - return is_int64() || is_double() || is_string() || is_bool() || is_null(); - } - - /// @brief Get whether this Variant contains a container type: Vector or Map. - /// - /// @return True if the Variant's type is Vector or Map; false otherwise. - bool is_container_type() const { return is_vector() || is_map(); } - - /// @brief Get the current Variant converted into a string. Only valid for - /// fundamental types. - /// - /// Special cases: Booleans will be returned as "true" or "false". Null will - /// be returned as an empty string. The returned string may be either mutable - /// or static, depending on the source type. All other cases will return an - /// empty string. - /// - /// @return A Variant containing a String that represents the value of this - /// original Variant. - Variant AsString() const; - - /// @brief Get the current Variant converted into an integer. Only valid for - /// fundamental types. - /// - /// Special cases: If a String can be parsed as a number - /// via strtol(), it will be. If a Bool is true, this will return 1. All other - /// cases (including non-fundamental types) will return 0. - /// - /// @return A Variant containing an Int64 that represents the value of this - /// original Variant. - Variant AsInt64() const; - - /// @brief Get the current Variant converted into a floating-point - /// number. Only valid for fundamental types. - /// - /// Special cases: If a Bool is true, this will return 1. All other cases will - /// return 0. - /// - /// @return A Variant containing a Double that represents the value of this - /// original Variant. - Variant AsDouble() const; - - /// @brief Get the current Variant converted into a boolean. Null, 0, 0.0, - /// empty strings, empty vectors, empty maps, blobs of size 0, and "false" - /// (case-sensitive) are all considered false. All other values are true. - /// - /// @return A Variant of type Bool containing the original Variant interpreted - /// as a Bool. - Variant AsBool() const; - - /// @brief Mutable accessor for a Variant containing a string. - /// - /// If the Variant contains a static string, it will be converted into a - /// mutable string, which copies the const char*'s data into a std::string. - /// - /// @return Reference to the string contained in this Variant. - /// - /// @note If the Variant is not one of the two String types, this will assert. - std::string& mutable_string() { - if (type_ == kInternalTypeStaticString || - type_ == kInternalTypeSmallString) { - // Automatically promote a static or small string to a mutable string. - set_mutable_string(string_value(), false); - } - assert_is_type(kTypeMutableString); - return *value_.mutable_string_value; - } - - /// @brief Get the size of a blob. This method works with both static - /// and mutable blobs. - /// - /// @return Number of bytes of binary data contained in the blob. - size_t blob_size() const { - assert_is_blob(); - return value_.blob_value.size; - } - - /// @brief Get the pointer to the binary data contained in a blob. - /// This method works with both static and mutable blob. - /// - /// @return Pointer to the binary data. Use blob_size() to get the - /// number of bytes. - const uint8_t* blob_data() const { - assert_is_blob(); - return value_.blob_value.ptr; - } - - /// @brief Get a mutable pointer to the binary data contained in - /// a blob. - /// - /// If the Variant contains a static blob, it will be converted into a mutable - /// blob, which copies the binary data into the Variant's buffer. - /// - /// @returns Pointer to a mutable buffer of binary data. The size of the - /// buffer cannot be changed, but the contents are mutable. - uint8_t* mutable_blob_data() { - if (type_ == kInternalTypeStaticBlob) { - // Automatically promote a static blob to a mutable blob. - set_mutable_blob(blob_data(), blob_size()); - } - assert_is_type(kTypeMutableBlob); - return const_cast(value_.blob_value.ptr); - } - - /// @brief Const accessor for a Variant contianing mutable blob data. - /// - /// @note Unlike the non-const accessor, this accessor cannot "promote" a - /// static blob to mutable, and thus will assert if the Variant you pass in - /// is not of MutableBlob type. - /// - /// @returns Pointer to a mutable buffer of binary data. The size of the - /// buffer cannot be changed, but the contents are mutable. - uint8_t* mutable_blob_data() const { - assert_is_type(kTypeMutableBlob); - return const_cast(value_.blob_value.ptr); - } - - /// @brief Mutable accessor for a Variant containing a vector of Variant - /// data. - /// - /// @return Reference to the vector contained in this Variant. - /// - /// @note If the Variant is not of Vector type, this will assert. - std::vector& vector() { - assert_is_type(kTypeVector); - return *value_.vector_value; - } - /// @brief Mutable accessor for a Variant containing a map of Variant data. - /// - /// @return Reference to the map contained in this Variant. - /// - /// @note If the Variant is not of Map type, this will assert. - std::map& map() { - assert_is_type(kTypeMap); - return *value_.map_value; - } - - /// @brief Const accessor for a Variant containing an integer. - /// - /// @return The integer contained in this Variant. - /// - /// @note If the Variant is not of Int64 type, this will assert. - int64_t int64_value() const { - assert_is_type(kTypeInt64); - return value_.int64_value; - } - - /// @brief Const accessor for a Variant containing a double. - /// - /// @return The double contained in this Variant. - /// - /// @note If the Variant is not of Double type, this will assert. - double double_value() const { - assert_is_type(kTypeDouble); - return value_.double_value; - } - - /// @brief Const accessor for a Variant containing a bool. - /// - /// @return The bool contained in this Variant. - /// - /// @note If the Variant is not of Bool type, this will assert. - const bool& bool_value() const { - assert_is_type(kTypeBool); - return value_.bool_value; - } - - /// @brief Const accessor for a Variant containing a string. - /// - /// This can return both static and mutable strings. The pointer is only - /// guaranteed to persist if this Variant's type is StaticString. - /// - /// @return The string contained in this Variant. - /// - /// @note If the Variant is not of StaticString or MutableString type, this - /// will assert. - const char* string_value() const { - assert_is_string(); - if (type_ == kInternalTypeMutableString) - return value_.mutable_string_value->c_str(); - else if (type_ == kInternalTypeStaticString) - return value_.static_string_value; - else // if (type_ == kInternalTypeSmallString) - return value_.small_string; - } - - /// @brief Const accessor for a Variant containing a string. - /// - /// @note Unlike the non-const accessor, this accessor cannot "promote" a - /// static string to mutable, and thus returns a std::string copy instead of a - /// const reference to a std::string - /// - /// @return std::string with the string contents contained in this Variant. - std::string mutable_string() const { - assert_is_string(); - return string_value(); - } - - /// @brief Const accessor for a Variant containing a vector of Variant data. - /// - /// @return Reference to the vector contained in this Variant. - /// - /// @note If the Variant is not of Vector type, this will assert. - const std::vector& vector() const { - assert_is_type(kTypeVector); - return *value_.vector_value; - } - - /// @brief Const accessor for a Variant containing a map of strings to - /// Variant - /// data. - /// - /// @return Reference to the map contained in this Variant. - /// - /// @note If the Variant is not of Map type, this will assert. - const std::map& map() const { - assert_is_type(kTypeMap); - return *value_.map_value; - } - - /// @brief Sets the Variant value to null. - /// - /// The Variant's type will be Null. - void set_null() { Clear(kTypeNull); } - - /// @brief Sets the Variant to an 64-bit integer value. - /// - /// The Variant's type will be set to Int64. - /// - /// @param[in] value The 64-bit integer value for the Variant. - void set_int64_value(int64_t value) { - Clear(kTypeInt64); - value_.int64_value = value; - } - - /// @brief Sets the Variant to an double-precision floating point value. - /// - /// The Variant's type will be set to Double. - /// - /// @param[in] value The double-precision floating point value for the - /// Variant. - void set_double_value(double value) { - Clear(kTypeDouble); - value_.double_value = value; - } - - /// @brief Sets the Variant to the given boolean value. - /// - /// The Variant's type will be set to Bool. - /// - /// @param[in] value The boolean value for the Variant. - void set_bool_value(bool value) { - Clear(kTypeBool); - value_.bool_value = value; - } - - /// @brief Sets the Variant to point to a static string buffer. - /// - /// The Variant's type will be set to StaticString. - /// - /// @note If you use this method, you must ensure that the memory pointed to - /// stays valid for the life of the Variant, or otherwise call - /// mutable_string() or set_mutable_string(), which will copy the string to an - /// internal buffer. - /// - /// @param[in] value A pointer to the static null-terminated string for the - /// Variant. - void set_string_value(const char* value) { - Clear(kTypeStaticString); - value_.static_string_value = value; - } - - /// @brief Sets the Variant to a mutable string. - /// - /// The Variant's type will be set to MutableString. - /// - /// @param[in] value A pointer to a null-terminated string, which will be - /// copied into to the Variant. - void set_string_value(char* value) { - size_t len = strlen(value); - if (len < kMaxSmallStringSize) { - Clear(static_cast(kInternalTypeSmallString)); - strncpy(value_.small_string, value, len + 1); - } else { - set_mutable_string(std::string(value, len)); - } - } - - /// @brief Sets the Variant to a mutable string. - /// - /// The Variant's type will be set to MutableString. - /// - /// @param[in] value The string to use for the Variant. - void set_string_value(const std::string& value) { set_mutable_string(value); } - - /// @brief Sets the Variant to a copy of the given string. - /// - /// The Variant's type will be set to SmallString if the size of the string is - /// less than kMaxSmallStringSize (8 bytes on x86, 16 bytes on x64) or - /// otherwise set to MutableString. - /// - /// @param[in] value The string to use for the Variant. - /// @param[in] use_small_string Check to see if the input string should be - /// treated as a small string or left as a mutable string - void set_mutable_string(const std::string& value, - bool use_small_string = true) { - if (value.size() < kMaxSmallStringSize && use_small_string) { - Clear(static_cast(kInternalTypeSmallString)); - strncpy(value_.small_string, value.data(), value.size() + 1); - } else { - Clear(kTypeMutableString); - *value_.mutable_string_value = value; - } - } - - /// @brief Sets the Variant to a copy of the given binary data. - /// - /// The Variant's type will be set to MutableBlob. - /// - /// @param[in] src_data The data to use for the Variant. If you - /// pass in nullptr, no data will be copied, but a buffer of the - /// requested size will be allocated. - /// @param[in] size_bytes The size of the data, in bytes. - void set_mutable_blob(const void* src_data, size_t size_bytes) { - uint8_t* dest_data = new uint8_t[size_bytes]; // Will be deleted when - // `this` is deleted. - if (src_data != nullptr) { - memcpy(dest_data, src_data, size_bytes); - } - Clear(kTypeMutableBlob); - set_blob_pointer(dest_data, size_bytes); - } - - /// @brief Sets the Variant to point to static binary data. - /// - /// The Variant's type will be set to kTypeStaticBlob. - /// - /// @param[in] static_data Pointer to statically-allocated binary data. The - /// Variant will point to the data, not copy it. - /// @param[in] size_bytes Size of the data, in bytes. - /// - /// @note If you use this method, you must ensure that the memory pointer to - /// stays valid for the life of the Variant, or otherwise call - /// mutable_blob_data() or set_mutable_blob(), which will copy the data into - /// an internal buffer. - void set_static_blob(const void* static_data, size_t size_bytes) { - Clear(kTypeStaticBlob); - set_blob_pointer(static_data, size_bytes); - } - - /// @brief Sets the Variant to a copy of the given vector. - /// - /// The Variant's type will be set to Vector. - /// - /// @param[in] value The STL vector to copy into the Variant. - - void set_vector(const std::vector& value) { - Clear(kTypeVector); - *value_.vector_value = value; - } - - /// @brief Sets the Variant to a copy of the given map. - /// - /// The Variant's type will be set to Map. - /// - /// @param[in] value The STL map to copy into the Variant. - void set_map(const std::map& value) { - Clear(kTypeMap); - *value_.map_value = value; - } - - /// @brief Assigns an existing string which was allocated on the heap into the - /// Variant without performing a copy. This object will take over ownership of - /// the pointer, and will set the std::string* you pass in to NULL. - /// - /// The Variant's type will be set to MutableString. - /// - /// @param[in, out] str Pointer to a pointer to an STL string. The Variant - /// will take over ownership of the pointer to the string, and set the - /// pointer - /// you passed in to NULL. - void AssignMutableString(std::string** str) { - Clear(kTypeNull); - type_ = kInternalTypeMutableString; - value_.mutable_string_value = *str; - *str = NULL; // NOLINT - } - - /// @brief Assigns an existing vector which was allocated on the heap into the - /// Variant without performing a copy. This object will take over ownership of - /// the pointer, and will set the std::vector* you pass in to NULL. - /// - /// The Variant's type will be set to Vector. - /// - /// @param[in, out] vect Pointer to a pointer to an STL vector. The Variant - /// will take over ownership of the pointer to the vector, and set the - /// pointer - /// you passed in to NULL. - void AssignVector(std::vector** vect) { - Clear(kTypeNull); - type_ = kInternalTypeVector; - value_.vector_value = *vect; - *vect = NULL; // NOLINT - } - - /// @brief Assigns an existing map which was allocated on the heap into the - /// Variant without performing a copy. This object will take over ownership - /// of - /// the map, and will set the std::map** you pass in to NULL. - /// - /// The Variant's type will be set to Map. - /// - /// @param[in, out] map Pointer to a pointer to an STL map. The Variant will - /// take over ownership of the pointer to the map, and set the pointer you - /// passed in to NULL. - void AssignMap(std::map** map) { - Clear(kTypeNull); - type_ = kInternalTypeMap; - value_.map_value = *map; - *map = NULL; // NOLINT - } - - // Convenience methods for the times when constructors are too ambiguious. - - /// @brief Return a Variant from a 64-bit integer. - /// - /// @param[in] value 64-bit integer value to put into the Variant. - /// - /// @returns A Variant containing the 64-bit integer. - static Variant FromInt64(int64_t value) { return Variant(value); } - - /// @brief Return a Variant from a double-precision floating point number. - /// - /// @param[in] value Double-precision floating point value to put into the - /// Variant; - /// - /// @returns A Variant containing the double-precision floating point number. - static Variant FromDouble(double value) { return Variant(value); } - - /// @brief Return a Variant from a boolean. - /// - /// @param[in] value Boolean value to put into the Variant. - /// - /// @returns A Variant containing the Boolean. - static Variant FromBool(bool value) { return Variant(value); } - - /// @brief Return a Variant from a static string. - /// - /// @param[in] value Pointer to statically-allocated null-terminated string. - /// - /// @returns A Variant referring to the string pointer you passed in. - /// - /// @note If you use this function, you must ensure that the memory pointed - /// to stays valid for the life of the Variant, otherwise call - /// mutable_string() or set_mutable_string(), which will copy the string to an - /// internal buffer. - static Variant FromStaticString(const char* value) { return Variant(value); } - - /// @brief Return a Variant from a string. - /// - /// This method makes a copy of the string. - /// - /// @param[in] value String value to copy into the Variant. - /// - /// @returns A Variant containing a copy of the string. - static Variant FromMutableString(const std::string& value) { - return Variant(value); - } - - /// @brief Return a Variant that points to static binary data. - /// - /// @param[in] static_data Pointer to statically-allocated binary data. The - /// Variant will point to the data, not copy it. - /// @param[in] size_bytes Size of the data, in bytes. - /// - /// @returns A Variant pointing to the binary data. - /// - /// @note If you use this function, you must ensure that the memory pointed - /// to stays valid for the life of the Variant, otherwise call - /// mutable_blob() or set_mutable_blob(), which will copy the data to an - /// internal buffer. - static Variant FromStaticBlob(const void* static_data, size_t size_bytes) { - Variant v; - v.set_static_blob(static_data, size_bytes); - return v; - } - - /// @brief Return a Variant containing a copy of binary data. - /// - /// @param[in] src_data Pointer to binary data to be copied into the Variant. - /// @param[in] size_bytes Size of the data, in bytes. - /// - /// @returns A Variant containing a copy of the binary data. - static Variant FromMutableBlob(const void* src_data, size_t size_bytes) { - Variant v; - v.set_mutable_blob(src_data, size_bytes); - return v; - } - - /// @brief Return a Variant from a string, but make it mutable. - /// - /// Only copies the string once, unlike Variant(std::string(value)), which - /// copies the string twice. - /// - /// @param[in] value String value to copy into the Variant and make mutable. - /// - /// @returns A Variant containing a mutable copy of the string. - static Variant MutableStringFromStaticString(const char* value) { - std::string* str = new std::string(value); - Variant v; - v.AssignMutableString(&str); - return v; - } - - /// @brief Get the human-readable type name of a Variant type. - /// - /// @param[in] type Variant type to describe. - /// - /// @returns A string describing the type, suitable for error messages or - /// debugging. For example "Int64" or "MutableString". - static const char* TypeName(Type type); - - private: - // Internal Type of data that this variant object contains to avoid breaking - // API - enum InternalType { - /// Null, or no data. - kInternalTypeNull = kTypeNull, - /// A 64-bit integer. - kInternalTypeInt64 = kTypeInt64, - /// A double-precision floating point number. - kInternalTypeDouble = kTypeDouble, - /// A boolean value. - kInternalTypeBool = kTypeBool, - /// A statically-allocated string we point to. - kInternalTypeStaticString = kTypeStaticString, - /// A std::string. - kInternalTypeMutableString = kTypeMutableString, - /// A std::vector of Variant. - kInternalTypeVector = kTypeVector, - /// A std::map, mapping Variant to Variant. - kInternalTypeMap = kTypeMap, - /// An statically-allocated blob of data that we point to. Never constructed - /// by default. Use Variant::FromStaticBlob() to create a Variant of this - /// type. - kInternalTypeStaticBlob = kTypeStaticBlob, - /// A blob of data that the Variant holds. Never constructed by default. Use - /// Variant::FromMutableBlob() to create a Variant of this type, and copy - /// binary data from an existing source. - kInternalTypeMutableBlob = kTypeMutableBlob, - // A c string stored in the Variant internal data blob as opposed to be - // newed as a std::string. Max size is 16 bytes on x64 and 8 bytes on x86. - kInternalTypeSmallString = kTypeMutableBlob + 1, - // Not a valid type. Used to get the total number of Variant types. - kMaxTypeValue, - }; - - /// Human-readable type names, for error logging. - static const char* const kTypeNames[]; - - /// Assert that this Variant is of the given type, failing if it is not. - void assert_is_type(Type type) const; - - /// Assert that this Variant is NOT of the given type, failing if it is. - void assert_is_not_type(Type type) const; - - /// Assert that this Variant is a static string or mutable string, failing if - /// it is not. - void assert_is_string() const; - - /// Assert that this Variant is a static blob or mutable blob, failing if - /// it is not. - void assert_is_blob() const; - - /// Sets the blob's data pointer, for kTypeStaticBlob and kTypeMutableBlob. - /// Asserts if the Variant isn't a blob. Caller is responsible for managing - /// the pointer's memory and deleting any existing data at the location. - void set_blob_pointer(const void* blob_ptr, size_t size) { - assert_is_blob(); - value_.blob_value.ptr = static_cast(blob_ptr); - value_.blob_value.size = size; - } - - // If you hit a compiler error here it means you are trying to construct a - // variant with unsupported type. Ether cast to correct type or add support - // below. - template - void set_value_t(T value) = delete; - - // Get whether this Variant contains a small string. - bool is_small_string() const { return type_ == kInternalTypeSmallString; } - - // Current type contained in this Variant. - InternalType type_; - - // Older versions of visual studio cant have this inline in the union and do - // sizeof for small string - typedef struct { - const uint8_t* ptr; - size_t size; - } BlobValue; - - // Union of plain old data (scalars or pointers). - union Value { - int64_t int64_value; - double double_value; - bool bool_value; - const char* static_string_value; - std::string* mutable_string_value; - std::vector* vector_value; - std::map* map_value; - BlobValue blob_value; - char small_string[sizeof(BlobValue)]; - } value_; - - static constexpr size_t kMaxSmallStringSize = sizeof(Value::small_string); - - friend class firebase::internal::VariantInternal; -}; - -template <> -inline void Variant::set_value_t(int64_t value) { - set_int64_value(value); -} - -template <> -inline void Variant::set_value_t(int value) { - set_int64_value(static_cast(value)); -} - -template <> -inline void Variant::set_value_t(int16_t value) { - set_int64_value(static_cast(value)); -} - -template <> -inline void Variant::set_value_t(uint8_t value) { - set_int64_value(static_cast(value)); -} - -template <> -inline void Variant::set_value_t(int8_t value) { - set_int64_value(static_cast(value)); -} - -template <> -inline void Variant::set_value_t(char value) { - set_int64_value(static_cast(value)); -} - -template <> -inline void Variant::set_value_t(double value) { - set_double_value(value); -} - -template <> -inline void Variant::set_value_t(float value) { - set_double_value(static_cast(value)); -} - -template <> -inline void Variant::set_value_t(bool value) { - set_bool_value(value); -} - -template <> -inline void Variant::set_value_t(const char* value) { - set_string_value(value); -} - -template <> -inline void Variant::set_value_t(char* value) { - set_mutable_string(value); -} - -// NOLINTNEXTLINE - allow namespace overridden -} // namespace firebase - -#endif // FIREBASE_APP_SRC_INCLUDE_FIREBASE_VARIANT_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/version.h b/packages/firebase_core/firebase_core/firebase_core/firebase/version.h deleted file mode 100644 index 79d77fc8af4a..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/version.h +++ /dev/null @@ -1,68 +0,0 @@ -// Copyright 2016 Google Inc. All Rights Reserved. - -#ifndef FIREBASE_APP_CLIENT_CPP_SRC_VERSION_H_ -#define FIREBASE_APP_CLIENT_CPP_SRC_VERSION_H_ - -/// @def FIREBASE_VERSION_MAJOR -/// @brief Major version number of the Firebase C++ SDK. -/// @see kFirebaseVersionString -#define FIREBASE_VERSION_MAJOR 10 -/// @def FIREBASE_VERSION_MINOR -/// @brief Minor version number of the Firebase C++ SDK. -/// @see kFirebaseVersionString -#define FIREBASE_VERSION_MINOR 5 -/// @def FIREBASE_VERSION_REVISION -/// @brief Revision number of the Firebase C++ SDK. -/// @see kFirebaseVersionString -#define FIREBASE_VERSION_REVISION 0 - -/// @cond FIREBASE_APP_INTERNAL -#define FIREBASE_STRING_EXPAND(X) #X -#define FIREBASE_STRING(X) FIREBASE_STRING_EXPAND(X) -/// @endcond - -// Version number. -// clang-format off -#define FIREBASE_VERSION_NUMBER_STRING \ - FIREBASE_STRING(FIREBASE_VERSION_MAJOR) "." \ - FIREBASE_STRING(FIREBASE_VERSION_MINOR) "." \ - FIREBASE_STRING(FIREBASE_VERSION_REVISION) -// clang-format on - -// Identifier for version string, e.g. kFirebaseVersionString. -#define FIREBASE_VERSION_IDENTIFIER(library) k##library##VersionString - -// Concatenated version string, e.g. "Firebase C++ x.y.z". -#define FIREBASE_VERSION_STRING(library) \ - #library " C++ " FIREBASE_VERSION_NUMBER_STRING - -#if !defined(DOXYGEN) -#if !defined(_WIN32) && !defined(__CYGWIN__) -#define DEFINE_FIREBASE_VERSION_STRING(library) \ - extern volatile __attribute__((weak)) \ - const char* FIREBASE_VERSION_IDENTIFIER(library); \ - volatile __attribute__((weak)) \ - const char* FIREBASE_VERSION_IDENTIFIER(library) = \ - FIREBASE_VERSION_STRING(library) -#else -#define DEFINE_FIREBASE_VERSION_STRING(library) \ - static const char* FIREBASE_VERSION_IDENTIFIER(library) = \ - FIREBASE_VERSION_STRING(library) -#endif // !defined(_WIN32) && !defined(__CYGWIN__) -#else // if defined(DOXYGEN) - -/// @brief Namespace that encompasses all Firebase APIs. -namespace firebase { - -/// @brief String which identifies the current version of the Firebase C++ -/// SDK. -/// -/// @see FIREBASE_VERSION_MAJOR -/// @see FIREBASE_VERSION_MINOR -/// @see FIREBASE_VERSION_REVISION -static const char* kFirebaseVersionString = FIREBASE_VERSION_STRING; - -} // namespace firebase -#endif // !defined(DOXYGEN) - -#endif // FIREBASE_APP_CLIENT_CPP_SRC_VERSION_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/generate_xml_from_google_services_json.py b/packages/firebase_core/firebase_core/firebase_core/generate_xml_from_google_services_json.py deleted file mode 100644 index 8996cd8490f3..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/generate_xml_from_google_services_json.py +++ /dev/null @@ -1,496 +0,0 @@ -#!/usr/bin/python - -# Copyright 2016 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Stand-alone implementation of the Gradle Firebase plugin. - -Converts the services json file to xml: -https://googleplex-android.googlesource.com/platform/tools/base/+/studio-master-dev/build-system/google-services/src/main/groovy/com/google/gms/googleservices -""" - -__author__ = 'Wouter van Oortmerssen' - -import argparse -import ctypes -import json -import os -import platform -import sys -from xml.etree import ElementTree - -if platform.system().lower() == 'windows': - import ctypes.wintypes # pylint: disable=g-import-not-at-top - -# Map Python 2's unicode method to encode a string as bytes in python 3. -try: - unicode('') # See whether unicode class is available (Python < 3) -except NameError: - unicode = str # pylint: disable=redefined-builtin,invalid-name - -# Input filename if it isn't set. -DEFAULT_INPUT_FILENAME = 'app/google-services.json' -# Output filename if it isn't set. -DEFAULT_OUTPUT_FILENAME = 'res/values/googleservices.xml' -# Input filename for .plist files, if it isn't set. -DEFAULT_PLIST_INPUT_FILENAME = 'GoogleService-Info.plist' -# Output filename for .json files, if it isn't set. -DEFAULT_JSON_OUTPUT_FILENAME = 'google-services-desktop.json' - -OAUTH_CLIENT_TYPE_ANDROID_APP = 1 -OAUTH_CLIENT_TYPE_WEB = 3 - - -def read_xml_value(xml_node): - """Utility method for reading values from the plist XML. - - Args: - xml_node: An ElementTree node, that contains a value. - - Returns: - The value of the node, or None, if it could not be read. - """ - if xml_node.tag == 'string': - return xml_node.text - elif xml_node.tag == 'integer': - return int(xml_node.text) - elif xml_node.tag == 'real': - return float(xml_node.text) - elif xml_node.tag == 'false': - return 0 - elif xml_node.tag == 'true': - return 1 - else: - # other types of input are ignored. (data, dates, arrays, etc.) - return None - - -def construct_plist_dictionary(xml_root): - """Constructs a dictionary of values based on the contents of a plist file. - - Args: - xml_root: An ElementTree node, that represents the root of the xml file - that is to be parsed. (Which should be a dictionary containing - key-value pairs of the properties that need to be extracted.) - - Returns: - A dictionary, containing key-value pairs for all (supported) entries in the - node. - """ - xml_dict = xml_root.find('dict') - - if xml_dict is None: - return None - - plist_dict = {} - i = 0 - while i < len(xml_dict): - if xml_dict[i].tag == 'key': - key = xml_dict[i].text - i += 1 - if i < len(xml_dict): - value = read_xml_value(xml_dict[i]) - if value is not None: - plist_dict[key] = value - i += 1 - - return plist_dict - - -def update_dict_keys(key_map, input_dict): - """Creates a dict from input_dict with the same values but new keys. - - Two dictionaries are passed to this function: the key_map that represents a - mapping of source keys to destination keys, and the input_dict that is the - dictionary that is to be duplicated, replacing any key that matches a source - key with a destination key. Source keys that are not present in the - input_dict will not have their destination key represented in the result. - - In other words, if key_map is `{'old': 'new', 'foo': 'bar'}`, and input_dict - is `{'old': 10}`, the result will be `{'new': 10}`. - - Args: - key_map (dict): A dictionary of strings to strings that maps source keys to - destination keys. - input_dict (dict): The dictionary of string keys to any value type, which - is to be duplicated, replacing source keys with the corresponding - destination keys from key_map. - - Returns: - dict: A new dictionary with updated keys. - """ - return { - new_key: input_dict[old_key] - for (old_key, new_key) in key_map.items() - if old_key in input_dict - } - - -def construct_google_services_json(xml_dict): - """Constructs a google services json file from a dictionary. - - Args: - xml_dict: A dictionary of all the key/value pairs that are needed for the - output json file. - Returns: - A string representing the output json file. - """ - - try: - json_struct = { - 'project_info': - update_dict_keys( - { - 'GCM_SENDER_ID': 'project_number', - 'DATABASE_URL': 'firebase_url', - 'PROJECT_ID': 'project_id', - 'STORAGE_BUCKET': 'storage_bucket' - }, xml_dict), - 'client': [{ - 'client_info': { - 'mobilesdk_app_id': xml_dict['GOOGLE_APP_ID'], - 'android_client_info': { - 'package_name': xml_dict['BUNDLE_ID'] - } - }, - 'oauth_client': [{ - 'client_id': xml_dict['CLIENT_ID'], - }], - 'api_key': [{ - 'current_key': xml_dict['API_KEY'] - }], - 'services': { - 'analytics_service': { - 'status': xml_dict['IS_ANALYTICS_ENABLED'] - }, - 'appinvite_service': { - 'status': xml_dict['IS_APPINVITE_ENABLED'] - } - } - },], - 'configuration_version': - '1' - } - return json.dumps(json_struct, indent=2) - except KeyError as e: - sys.stderr.write('Could not find key in plist file: [%s]\n' % (e.args[0])) - return None - - -def convert_plist_to_json(plist_string, input_filename): - """Converts an input plist string into a .json file and saves it. - - Args: - plist_string: The contents of the loaded plist file. - - input_filename: The file name that the plist data was read from. - Returns: - the converted string, or None if there were errors. - """ - - try: - root = ElementTree.fromstring(plist_string) - except ElementTree.ParseError: - sys.stderr.write('Error parsing file %s.\n' - 'It does not appear to be valid XML.\n' % (input_filename)) - return None - - plist_dict = construct_plist_dictionary(root) - if plist_dict is None: - sys.stderr.write('In file %s, could not locate a top-level \'dict\' ' - 'element.\n' - 'File format should be plist XML, with a top-level ' - 'dictionary containing project settings as key-value ' - 'pairs.\n' % (input_filename)) - return None - - json_string = construct_google_services_json(plist_dict) - return json_string - - -def gen_string(parent, name, text): - """Generate one element and put into the list of keeps. - - Args: - parent: The object that will hold the string. - name: The name to store the string under. - text: The text of the string. - """ - if text: - prev = parent.get('tools:keep', '') - if prev: - prev += ',' - parent.set('tools:keep', prev + '@string/' + name) - child = ElementTree.SubElement(parent, 'string', { - 'name': name, - 'translatable': 'false' - }) - child.text = text - - -def indent(elem, level=0): - """Recurse through XML tree and add indentation. - - Args: - elem: The element to recurse over - level: The current indentation level. - """ - i = '\n' + level*' ' - if elem is not None: - if not elem.text or not elem.text.strip(): - elem.text = i + ' ' - if not elem.tail or not elem.tail.strip(): - elem.tail = i - for elem in elem: - indent(elem, level+1) - if not elem.tail or not elem.tail.strip(): - elem.tail = i - else: - if level and (not elem.tail or not elem.tail.strip()): - elem.tail = i - - -def argv_as_unicode_win32(): - """Returns unicode command line arguments on windows. - """ - - get_command_line_w = ctypes.cdll.kernel32.GetCommandLineW - get_command_line_w.restype = ctypes.wintypes.LPCWSTR - - # CommandLineToArgvW parses the Unicode command line - command_line_to_argv_w = ctypes.windll.shell32.CommandLineToArgvW - command_line_to_argv_w.argtypes = [ - ctypes.wintypes.LPCWSTR, - ctypes.POINTER(ctypes.c_int) - ] - command_line_to_argv_w.restype = ctypes.POINTER( - ctypes.wintypes.LPWSTR) - - argc = ctypes.c_int(0) - argv = command_line_to_argv_w(get_command_line_w(), argc) - - # Strip the python executable from the arguments if it exists - # (It would be listed as the first argument on the windows command line, but - # not in the arguments to the python script) - sys_argv_len = len(sys.argv) - return [unicode(argv[i]) for i in - range(argc.value - sys_argv_len, argc.value)] - - -def main(): - parser = argparse.ArgumentParser( - description=(( - 'Converts a Firebase %s into %s similar to the Gradle plugin, or ' - 'converts a Firebase %s into a %s suitible for use on desktop apps.' % - (DEFAULT_INPUT_FILENAME, DEFAULT_OUTPUT_FILENAME, - DEFAULT_PLIST_INPUT_FILENAME, DEFAULT_JSON_OUTPUT_FILENAME)))) - parser.add_argument('-i', help='Override input file name', - metavar='FILE', required=False) - parser.add_argument('-o', help='Override destination file name', - metavar='FILE', required=False) - parser.add_argument('-p', help=('Package ID to select within the set of ' - 'packages in the input file. If this is ' - 'not specified, the first package in the ' - 'input file is selected.')) - parser.add_argument('-l', help=('List all package IDs referenced by the ' - 'input file. If this is specified, ' - 'the output file is not created.'), - action='store_true', default=False, required=False) - parser.add_argument('-f', help=('Print project fields from the input file ' - 'in the form \'name=value\\n\' for each ' - 'field. If this is specified, the output ' - 'is not created.'), - action='store_true', default=False, required=False) - parser.add_argument( - '--plist', - help=( - 'Specifies a plist file to convert to a JSON configuration file. ' - 'If this is enabled, the script will expect a .plist file as input, ' - 'which it will convert into %s file. The output file is ' - '*not* suitable for use with Firebase on Android.' % - (DEFAULT_JSON_OUTPUT_FILENAME)), - action='store_true', - default=False, - required=False) - - # python 2 on Windows doesn't handle unicode arguments well, so we need to - # pre-process the command line arguments before trying to parse them. - if platform.system() == 'Windows': - sys.argv = argv_as_unicode_win32() - - args = parser.parse_args() - - if args.plist: - input_filename = DEFAULT_PLIST_INPUT_FILENAME - output_filename = DEFAULT_JSON_OUTPUT_FILENAME - else: - input_filename = DEFAULT_INPUT_FILENAME - output_filename = DEFAULT_OUTPUT_FILENAME - - if args.i: - # Encode the input string (type unicode) as a normal string (type str) - # using the 'utf-8' encoding so that it can be worked with the same as - # input names from other sources (like the defaults). - input_filename_raw = args.i.encode('utf-8') - # Decode the filename to a unicode string using the 'utf-8' encoding to - # properly handle filepaths with unicode characters in them. - input_filename = input_filename_raw.decode('utf-8') - - if args.o: - output_filename = args.o - - with open(input_filename, 'r') as ifile: - file_string = ifile.read() - - json_string = None - if args.plist: - json_string = convert_plist_to_json(file_string, input_filename) - if json_string is None: - return 1 - jsobj = json.loads(json_string) - else: - jsobj = json.loads(file_string) - - root = ElementTree.Element('resources') - root.set('xmlns:tools', 'http://schemas.android.com/tools') - - project_info = jsobj.get('project_info') - if project_info: - gen_string(root, 'firebase_database_url', project_info.get('firebase_url')) - gen_string(root, 'gcm_defaultSenderId', project_info.get('project_number')) - gen_string(root, 'google_storage_bucket', - project_info.get('storage_bucket')) - gen_string(root, 'project_id', project_info.get('project_id')) - - if args.f: - if not project_info: - sys.stderr.write('No project info found in %s.' % input_filename) - return 1 - for field, value in sorted(project_info.items()): - sys.stdout.write('%s=%s\n' % (field, value)) - return 0 - - packages = set() - client_list = jsobj.get('client') - if client_list: - # Search for the user specified package in the file. - selected_package_name = '' - selected_client = client_list[0] - find_package_name = args.p - for client in client_list: - package_name = client.get('client_info', {}).get( - 'android_client_info', {}).get('package_name', '') - if not package_name: - package_name = client.get('oauth_client', {}).get( - 'android_info', {}).get('package_name', '') - if package_name: - if not selected_package_name: - selected_package_name = package_name - selected_client = client - if package_name == find_package_name: - selected_package_name = package_name - selected_client = client - packages.add(package_name) - - if args.p and selected_package_name != find_package_name: - sys.stderr.write('No packages found in %s which match the package ' - 'name %s\n' - '\n' - 'Found the following:\n' - '%s\n' % (input_filename, find_package_name, - '\n'.join(packages))) - return 1 - - client_api_key = selected_client.get('api_key') - if client_api_key: - client_api_key0 = client_api_key[0] - gen_string(root, 'google_api_key', client_api_key0.get('current_key')) - gen_string(root, 'google_crash_reporting_api_key', - client_api_key0.get('current_key')) - - client_info = selected_client.get('client_info') - if client_info: - gen_string(root, 'google_app_id', client_info.get('mobilesdk_app_id')) - - # Only include the first matching OAuth client ID per type. - client_id_web_parsed = False - client_id_android_parsed = False - - oauth_client_list = selected_client.get('oauth_client') - if oauth_client_list: - for oauth_client in oauth_client_list: - client_type = oauth_client.get('client_type') - client_id = oauth_client.get('client_id') - if not (client_type and client_id): continue - if (client_type == OAUTH_CLIENT_TYPE_WEB and - not client_id_web_parsed): - gen_string(root, 'default_web_client_id', client_id) - client_id_web_parsed = True - if (client_type == OAUTH_CLIENT_TYPE_ANDROID_APP and - not client_id_android_parsed): - gen_string(root, 'default_android_client_id', client_id) - client_id_android_parsed = True - - services = selected_client.get('services') - if services: - ads_service = services.get('ads_service') - if ads_service: - gen_string(root, 'test_banner_ad_unit_id', - ads_service.get('test_banner_ad_unit_id')) - gen_string(root, 'test_interstitial_ad_unit_id', - ads_service.get('test_interstitial_ad_unit_id')) - analytics_service = services.get('analytics_service') - if analytics_service: - analytics_property = analytics_service.get('analytics_property') - if analytics_property: - gen_string(root, 'ga_trackingId', - analytics_property.get('tracking_id')) - # enable this once we have an example if this service being present - # in the json data: - maps_service_enabled = False - if maps_service_enabled: - maps_service = services.get('maps_service') - if maps_service: - maps_api_key = maps_service.get('api_key') - if maps_api_key: - for k in range(0, len(maps_api_key)): - # generates potentially multiple of these keys, which is - # the same behavior as the java plugin. - gen_string(root, 'google_maps_key', - maps_api_key[k].get('maps_api_key')) - - tree = ElementTree.ElementTree(root) - - indent(root) - - if args.l: - for package in sorted(packages): - if package: - sys.stdout.write(package + '\n') - else: - path = os.path.dirname(output_filename) - - if path and not os.path.exists(path): - os.makedirs(path) - - if not args.plist: - tree.write(output_filename, 'utf-8', True) - else: - with open(output_filename, 'w') as ofile: - ofile.write(json_string) - - return 0 - -if __name__ == '__main__': - sys.exit(main()) \ No newline at end of file diff --git a/packages/firebase_core/firebase_core/firebase_core/generated_bindings.dart b/packages/firebase_core/firebase_core/firebase_core/generated_bindings.dart deleted file mode 100644 index f58d1524bee8..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/generated_bindings.dart +++ /dev/null @@ -1,26 +0,0 @@ -// AUTO GENERATED FILE, DO NOT EDIT. -// -// Generated by `package:ffigen`. -import 'dart:ffi' as ffi; - -class NativeLibrary { - /// Holds the symbol lookup function. - final ffi.Pointer Function(String symbolName) - _lookup; - - /// The symbols are looked up in [dynamicLibrary]. - NativeLibrary(ffi.DynamicLibrary dynamicLibrary) - : _lookup = dynamicLibrary.lookup; - - /// The symbols are looked up with [lookup]. - NativeLibrary.fromLookup( - ffi.Pointer Function(String symbolName) - lookup) - : _lookup = lookup; - - late final ffi.Pointer _firebase = _lookup('firebase'); - - int get firebase => _firebase.value; - - set firebase(int value) => _firebase.value = value; -} diff --git a/packages/firebase_core/firebase_core/firebase_core/google-services-desktop.json b/packages/firebase_core/firebase_core/firebase_core/google-services-desktop.json deleted file mode 100644 index a3bf216f4de0..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/google-services-desktop.json +++ /dev/null @@ -1,37 +0,0 @@ -{ - "project_info": { - "project_number": "406099696497", - "firebase_url": "https://flutterfire-e2e-tests-default-rtdb.europe-west1.firebasedatabase.app", - "project_id": "flutterfire-e2e-tests", - "storage_bucket": "flutterfire-e2e-tests.appspot.com" - }, - "client": [ - { - "client_info": { - "mobilesdk_app_id": "1:406099696497:ios:58cbc26aca8e5cf83574d0", - "android_client_info": { - "package_name": "io.flutter.plugins.firebase.auth.example" - } - }, - "oauth_client": [ - { - "client_id": "406099696497-134k3722m01rtrsklhf3b7k8sqa5r7in.apps.googleusercontent.com" - } - ], - "api_key": [ - { - "current_key": "AIzaSyDooSUGSf63Ghq02_iIhtnmwMDs4HlWS6c" - } - ], - "services": { - "analytics_service": { - "status": 0 - }, - "appinvite_service": { - "status": 1 - } - } - } - ], - "configuration_version": "1" -} \ No newline at end of file diff --git a/packages/firebase_core/firebase_core/firebase_core/lib/firebase_core.dart b/packages/firebase_core/firebase_core/firebase_core/lib/firebase_core.dart deleted file mode 100644 index d1295e26ad15..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/lib/firebase_core.dart +++ /dev/null @@ -1,8 +0,0 @@ - -import 'firebase_core_platform_interface.dart'; - -class FirebaseCore { - Future getPlatformVersion() { - return FirebaseCorePlatform.instance.getPlatformVersion(); - } -} diff --git a/packages/firebase_core/firebase_core/firebase_core/lib/firebase_core_method_channel.dart b/packages/firebase_core/firebase_core/firebase_core/lib/firebase_core_method_channel.dart deleted file mode 100644 index 5da300fa9013..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/lib/firebase_core_method_channel.dart +++ /dev/null @@ -1,17 +0,0 @@ -import 'package:flutter/foundation.dart'; -import 'package:flutter/services.dart'; - -import 'firebase_core_platform_interface.dart'; - -/// An implementation of [FirebaseCorePlatform] that uses method channels. -class MethodChannelFirebaseCore extends FirebaseCorePlatform { - /// The method channel used to interact with the native platform. - @visibleForTesting - final methodChannel = const MethodChannel('firebase_core'); - - @override - Future getPlatformVersion() async { - final version = await methodChannel.invokeMethod('getPlatformVersion'); - return version; - } -} diff --git a/packages/firebase_core/firebase_core/firebase_core/lib/firebase_core_platform_interface.dart b/packages/firebase_core/firebase_core/firebase_core/lib/firebase_core_platform_interface.dart deleted file mode 100644 index 6f6e165b7957..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/lib/firebase_core_platform_interface.dart +++ /dev/null @@ -1,29 +0,0 @@ -import 'package:plugin_platform_interface/plugin_platform_interface.dart'; - -import 'firebase_core_method_channel.dart'; - -abstract class FirebaseCorePlatform extends PlatformInterface { - /// Constructs a FirebaseCorePlatform. - FirebaseCorePlatform() : super(token: _token); - - static final Object _token = Object(); - - static FirebaseCorePlatform _instance = MethodChannelFirebaseCore(); - - /// The default instance of [FirebaseCorePlatform] to use. - /// - /// Defaults to [MethodChannelFirebaseCore]. - static FirebaseCorePlatform get instance => _instance; - - /// Platform-specific implementations should set this with their own - /// platform-specific class that extends [FirebaseCorePlatform] when - /// they register themselves. - static set instance(FirebaseCorePlatform instance) { - PlatformInterface.verifyToken(instance, _token); - _instance = instance; - } - - Future getPlatformVersion() { - throw UnimplementedError('platformVersion() has not been implemented.'); - } -} diff --git a/packages/firebase_core/firebase_core/firebase_core/linux/CMakeLists.txt b/packages/firebase_core/firebase_core/firebase_core/linux/CMakeLists.txt deleted file mode 100644 index 5cec31c86b71..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/linux/CMakeLists.txt +++ /dev/null @@ -1,47 +0,0 @@ -# The Flutter tooling requires that developers have CMake 3.10 or later -# installed. You should not increase this version, as doing so will cause -# the plugin to fail to compile for some customers of the plugin. -cmake_minimum_required(VERSION 3.10) - -# Project-level configuration. -set(PROJECT_NAME "firebase_core") -project(${PROJECT_NAME} LANGUAGES CXX) - -# This value is used when generating builds using this plugin, so it must -# not be changed. -set(PLUGIN_NAME "firebase_core_plugin") - -# Define the plugin library target. Its name must not be changed (see comment -# on PLUGIN_NAME above). -# -# Any new source files that you add to the plugin should be added here. -add_library(${PLUGIN_NAME} SHARED - "firebase_core_plugin.cc" -) - -# Apply a standard set of build settings that are configured in the -# application-level CMakeLists.txt. This can be removed for plugins that want -# full control over build settings. -apply_standard_settings(${PLUGIN_NAME}) - -# Symbols are hidden by default to reduce the chance of accidental conflicts -# between plugins. This should not be removed; any symbols that should be -# exported should be explicitly exported with the FLUTTER_PLUGIN_EXPORT macro. -set_target_properties(${PLUGIN_NAME} PROPERTIES - CXX_VISIBILITY_PRESET hidden) -target_compile_definitions(${PLUGIN_NAME} PRIVATE FLUTTER_PLUGIN_IMPL) - -# Source include directories and library dependencies. Add any plugin-specific -# dependencies here. -target_include_directories(${PLUGIN_NAME} INTERFACE - "${CMAKE_CURRENT_SOURCE_DIR}/include") -target_link_libraries(${PLUGIN_NAME} PRIVATE flutter) -target_link_libraries(${PLUGIN_NAME} PRIVATE PkgConfig::GTK) - -# List of absolute paths to libraries that should be bundled with the plugin. -# This list could contain prebuilt libraries, or libraries created by an -# external build triggered from this build file. -set(firebase_core_bundled_libraries - "" - PARENT_SCOPE -) diff --git a/packages/firebase_core/firebase_core/firebase_core/linux/firebase_core_plugin.cc b/packages/firebase_core/firebase_core/firebase_core/linux/firebase_core_plugin.cc deleted file mode 100644 index 4fd897624ca4..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/linux/firebase_core_plugin.cc +++ /dev/null @@ -1,70 +0,0 @@ -#include "include/firebase_core/firebase_core_plugin.h" - -#include -#include -#include - -#include - -#define FIREBASE_CORE_PLUGIN(obj) \ - (G_TYPE_CHECK_INSTANCE_CAST((obj), firebase_core_plugin_get_type(), \ - FirebaseCorePlugin)) - -struct _FirebaseCorePlugin { - GObject parent_instance; -}; - -G_DEFINE_TYPE(FirebaseCorePlugin, firebase_core_plugin, g_object_get_type()) - -// Called when a method call is received from Flutter. -static void firebase_core_plugin_handle_method_call( - FirebaseCorePlugin* self, - FlMethodCall* method_call) { - g_autoptr(FlMethodResponse) response = nullptr; - - const gchar* method = fl_method_call_get_name(method_call); - - if (strcmp(method, "getPlatformVersion") == 0) { - struct utsname uname_data = {}; - uname(&uname_data); - g_autofree gchar *version = g_strdup_printf("Linux %s", uname_data.version); - g_autoptr(FlValue) result = fl_value_new_string(version); - response = FL_METHOD_RESPONSE(fl_method_success_response_new(result)); - } else { - response = FL_METHOD_RESPONSE(fl_method_not_implemented_response_new()); - } - - fl_method_call_respond(method_call, response, nullptr); -} - -static void firebase_core_plugin_dispose(GObject* object) { - G_OBJECT_CLASS(firebase_core_plugin_parent_class)->dispose(object); -} - -static void firebase_core_plugin_class_init(FirebaseCorePluginClass* klass) { - G_OBJECT_CLASS(klass)->dispose = firebase_core_plugin_dispose; -} - -static void firebase_core_plugin_init(FirebaseCorePlugin* self) {} - -static void method_call_cb(FlMethodChannel* channel, FlMethodCall* method_call, - gpointer user_data) { - FirebaseCorePlugin* plugin = FIREBASE_CORE_PLUGIN(user_data); - firebase_core_plugin_handle_method_call(plugin, method_call); -} - -void firebase_core_plugin_register_with_registrar(FlPluginRegistrar* registrar) { - FirebaseCorePlugin* plugin = FIREBASE_CORE_PLUGIN( - g_object_new(firebase_core_plugin_get_type(), nullptr)); - - g_autoptr(FlStandardMethodCodec) codec = fl_standard_method_codec_new(); - g_autoptr(FlMethodChannel) channel = - fl_method_channel_new(fl_plugin_registrar_get_messenger(registrar), - "firebase_core", - FL_METHOD_CODEC(codec)); - fl_method_channel_set_method_call_handler(channel, method_call_cb, - g_object_ref(plugin), - g_object_unref); - - g_object_unref(plugin); -} diff --git a/packages/firebase_core/firebase_core/firebase_core/linux/include/firebase_core/firebase_core_plugin.h b/packages/firebase_core/firebase_core/firebase_core/linux/include/firebase_core/firebase_core_plugin.h deleted file mode 100644 index 3f15a61a3e72..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/linux/include/firebase_core/firebase_core_plugin.h +++ /dev/null @@ -1,26 +0,0 @@ -#ifndef FLUTTER_PLUGIN_FIREBASE_CORE_PLUGIN_H_ -#define FLUTTER_PLUGIN_FIREBASE_CORE_PLUGIN_H_ - -#include - -G_BEGIN_DECLS - -#ifdef FLUTTER_PLUGIN_IMPL -#define FLUTTER_PLUGIN_EXPORT __attribute__((visibility("default"))) -#else -#define FLUTTER_PLUGIN_EXPORT -#endif - -typedef struct _FirebaseCorePlugin FirebaseCorePlugin; -typedef struct { - GObjectClass parent_class; -} FirebaseCorePluginClass; - -FLUTTER_PLUGIN_EXPORT GType firebase_core_plugin_get_type(); - -FLUTTER_PLUGIN_EXPORT void firebase_core_plugin_register_with_registrar( - FlPluginRegistrar* registrar); - -G_END_DECLS - -#endif // FLUTTER_PLUGIN_FIREBASE_CORE_PLUGIN_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/pubspec.yaml b/packages/firebase_core/firebase_core/firebase_core/pubspec.yaml deleted file mode 100644 index c942173c517b..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/pubspec.yaml +++ /dev/null @@ -1,36 +0,0 @@ -name: firebase_core -description: A new Flutter plugin project. -version: 0.0.1 -homepage: - -environment: - sdk: '>=2.19.2 <3.0.0' - flutter: '>=2.5.0' - -dependencies: - ffi: ^2.0.1 - flutter: - sdk: flutter - plugin_platform_interface: ^2.0.2 - -dev_dependencies: - flutter_test: - sdk: flutter - flutter_lints: ^2.0.0 - ffigen: ^7.2.6 - -flutter: - plugin: - platforms: - linux: - pluginClass: FirebaseCorePlugin - windows: - pluginClass: FirebaseCorePluginCApi - -ffigen: - output: 'generated_bindings.dart' - headers: - entry-points: - - 'firebase/app.h' - include-directives: - - 'firebase/**.h' diff --git a/packages/firebase_core/firebase_core/firebase_core/test/firebase_core_method_channel_test.dart b/packages/firebase_core/firebase_core/firebase_core/test/firebase_core_method_channel_test.dart deleted file mode 100644 index 70c7fc5e7362..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/test/firebase_core_method_channel_test.dart +++ /dev/null @@ -1,24 +0,0 @@ -import 'package:flutter/services.dart'; -import 'package:flutter_test/flutter_test.dart'; -import 'package:firebase_core/firebase_core_method_channel.dart'; - -void main() { - MethodChannelFirebaseCore platform = MethodChannelFirebaseCore(); - const MethodChannel channel = MethodChannel('firebase_core'); - - TestWidgetsFlutterBinding.ensureInitialized(); - - setUp(() { - channel.setMockMethodCallHandler((MethodCall methodCall) async { - return '42'; - }); - }); - - tearDown(() { - channel.setMockMethodCallHandler(null); - }); - - test('getPlatformVersion', () async { - expect(await platform.getPlatformVersion(), '42'); - }); -} diff --git a/packages/firebase_core/firebase_core/firebase_core/test/firebase_core_test.dart b/packages/firebase_core/firebase_core/firebase_core/test/firebase_core_test.dart deleted file mode 100644 index bb8e54416b4e..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/test/firebase_core_test.dart +++ /dev/null @@ -1,29 +0,0 @@ -import 'package:flutter_test/flutter_test.dart'; -import 'package:firebase_core/firebase_core.dart'; -import 'package:firebase_core/firebase_core_platform_interface.dart'; -import 'package:firebase_core/firebase_core_method_channel.dart'; -import 'package:plugin_platform_interface/plugin_platform_interface.dart'; - -class MockFirebaseCorePlatform - with MockPlatformInterfaceMixin - implements FirebaseCorePlatform { - - @override - Future getPlatformVersion() => Future.value('42'); -} - -void main() { - final FirebaseCorePlatform initialPlatform = FirebaseCorePlatform.instance; - - test('$MethodChannelFirebaseCore is the default instance', () { - expect(initialPlatform, isInstanceOf()); - }); - - test('getPlatformVersion', () async { - FirebaseCore firebaseCorePlugin = FirebaseCore(); - MockFirebaseCorePlatform fakePlatform = MockFirebaseCorePlatform(); - FirebaseCorePlatform.instance = fakePlatform; - - expect(await firebaseCorePlugin.getPlatformVersion(), '42'); - }); -} diff --git a/packages/firebase_core/firebase_core/pubspec.yaml b/packages/firebase_core/firebase_core/pubspec.yaml index 34f9d0dd4953..a010cc15f77d 100644 --- a/packages/firebase_core/firebase_core/pubspec.yaml +++ b/packages/firebase_core/firebase_core/pubspec.yaml @@ -37,6 +37,9 @@ flutter: pluginClass: FLTFirebaseCorePlugin web: default_package: firebase_core_web + windows: + pluginClass: FirebaseCorePluginCApi + firebase: google_services_gradle_plugin_version: "4.3.10" diff --git a/packages/firebase_core/firebase_core/firebase_core/windows/.gitignore b/packages/firebase_core/firebase_core/windows/.gitignore similarity index 100% rename from packages/firebase_core/firebase_core/firebase_core/windows/.gitignore rename to packages/firebase_core/firebase_core/windows/.gitignore diff --git a/packages/firebase_core/firebase_core/firebase_core/windows/CMakeLists.txt b/packages/firebase_core/firebase_core/windows/CMakeLists.txt similarity index 100% rename from packages/firebase_core/firebase_core/firebase_core/windows/CMakeLists.txt rename to packages/firebase_core/firebase_core/windows/CMakeLists.txt diff --git a/packages/firebase_core/firebase_core/firebase_core/windows/firebase_core_plugin.cpp b/packages/firebase_core/firebase_core/windows/firebase_core_plugin.cpp similarity index 100% rename from packages/firebase_core/firebase_core/firebase_core/windows/firebase_core_plugin.cpp rename to packages/firebase_core/firebase_core/windows/firebase_core_plugin.cpp diff --git a/packages/firebase_core/firebase_core/firebase_core/windows/firebase_core_plugin.h b/packages/firebase_core/firebase_core/windows/firebase_core_plugin.h similarity index 100% rename from packages/firebase_core/firebase_core/firebase_core/windows/firebase_core_plugin.h rename to packages/firebase_core/firebase_core/windows/firebase_core_plugin.h diff --git a/packages/firebase_core/firebase_core/firebase_core/windows/firebase_core_plugin_c_api.cpp b/packages/firebase_core/firebase_core/windows/firebase_core_plugin_c_api.cpp similarity index 100% rename from packages/firebase_core/firebase_core/firebase_core/windows/firebase_core_plugin_c_api.cpp rename to packages/firebase_core/firebase_core/windows/firebase_core_plugin_c_api.cpp diff --git a/packages/firebase_core/firebase_core/firebase_core/windows/include/firebase_core/firebase_core_plugin_c_api.h b/packages/firebase_core/firebase_core/windows/include/firebase_core/firebase_core_plugin_c_api.h similarity index 100% rename from packages/firebase_core/firebase_core/firebase_core/windows/include/firebase_core/firebase_core_plugin_c_api.h rename to packages/firebase_core/firebase_core/windows/include/firebase_core/firebase_core_plugin_c_api.h From 1e9d4736795997656e1c9bef3fcd8ff43474150a Mon Sep 17 00:00:00 2001 From: Guillaume Bernos Date: Tue, 14 Mar 2023 11:05:49 +0100 Subject: [PATCH 16/65] feat(core, windows): update pigeon --- .../firebase_core/firebase_core_platform_interface/pubspec.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/firebase_core/firebase_core_platform_interface/pubspec.yaml b/packages/firebase_core/firebase_core_platform_interface/pubspec.yaml index 1babada2b072..c35e4f208b9f 100644 --- a/packages/firebase_core/firebase_core_platform_interface/pubspec.yaml +++ b/packages/firebase_core/firebase_core_platform_interface/pubspec.yaml @@ -22,4 +22,4 @@ dependencies: dev_dependencies: mockito: ^5.0.0 - pigeon: ^3.1.5 + pigeon: ^9.0.6 From a3f796f7578a51b5a784413bf57cb5e71a6661c8 Mon Sep 17 00:00:00 2001 From: Guillaume Bernos Date: Tue, 14 Mar 2023 14:29:50 +0100 Subject: [PATCH 17/65] feat(core, windows): update pigeon --- .../core/GeneratedAndroidFirebaseCore.java | 276 +++++++------- .../firebase_core/ios/Classes/messages.g.h | 95 +++-- .../firebase_core/ios/Classes/messages.g.m | 339 +++++++----------- .../lib/src/pigeon/messages.pigeon.dart | 260 +++++++------- .../lib/src/pigeon/test_api.dart | 84 ++--- 5 files changed, 455 insertions(+), 599 deletions(-) diff --git a/packages/firebase_core/firebase_core/android/src/main/java/io/flutter/plugins/firebase/core/GeneratedAndroidFirebaseCore.java b/packages/firebase_core/firebase_core/android/src/main/java/io/flutter/plugins/firebase/core/GeneratedAndroidFirebaseCore.java index d3f4b5ed3b83..c19c5b8b4ca3 100644 --- a/packages/firebase_core/firebase_core/android/src/main/java/io/flutter/plugins/firebase/core/GeneratedAndroidFirebaseCore.java +++ b/packages/firebase_core/firebase_core/android/src/main/java/io/flutter/plugins/firebase/core/GeneratedAndroidFirebaseCore.java @@ -1,10 +1,4 @@ -/* - * Copyright 2022, the Chromium project authors. Please see the AUTHORS file - * for details. All rights reserved. Use of this source code is governed by a - * BSD-style license that can be found in the LICENSE file. - */ - -// Autogenerated from Pigeon (v3.2.0), do not edit directly. +// Autogenerated from Pigeon (v9.0.6), do not edit directly. // See also: https://pub.dev/packages/pigeon package io.flutter.plugins.firebase.core; @@ -19,6 +13,8 @@ import java.io.ByteArrayOutputStream; import java.nio.ByteBuffer; import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -26,9 +22,18 @@ /** Generated class from Pigeon. */ @SuppressWarnings({"unused", "unchecked", "CodeBlock2Expr", "RedundantSuppression"}) public class GeneratedAndroidFirebaseCore { + @NonNull + private static ArrayList wrapError(@NonNull Throwable exception) { + ArrayList errorList = new ArrayList(3); + errorList.add(exception.toString()); + errorList.add(exception.getClass().getSimpleName()); + errorList.add( + "Cause: " + exception.getCause() + ", Stacktrace: " + Log.getStackTraceString(exception)); + return errorList; + } /** Generated class from Pigeon that represents data sent in messages. */ - public static class PigeonFirebaseOptions { + public static final class PigeonFirebaseOptions { private @NonNull String apiKey; public @NonNull String getApiKey() { @@ -185,6 +190,7 @@ public void setAppGroupId(@Nullable String setterArg) { private PigeonFirebaseOptions() {} public static final class Builder { + private @Nullable String apiKey; public @NonNull Builder setApiKey(@NonNull String setterArg) { @@ -304,61 +310,61 @@ public static final class Builder { } @NonNull - Map toMap() { - Map toMapResult = new HashMap<>(); - toMapResult.put("apiKey", apiKey); - toMapResult.put("appId", appId); - toMapResult.put("messagingSenderId", messagingSenderId); - toMapResult.put("projectId", projectId); - toMapResult.put("authDomain", authDomain); - toMapResult.put("databaseURL", databaseURL); - toMapResult.put("storageBucket", storageBucket); - toMapResult.put("measurementId", measurementId); - toMapResult.put("trackingId", trackingId); - toMapResult.put("deepLinkURLScheme", deepLinkURLScheme); - toMapResult.put("androidClientId", androidClientId); - toMapResult.put("iosClientId", iosClientId); - toMapResult.put("iosBundleId", iosBundleId); - toMapResult.put("appGroupId", appGroupId); - return toMapResult; - } - - static @NonNull PigeonFirebaseOptions fromMap(@NonNull Map map) { + ArrayList toList() { + ArrayList toListResult = new ArrayList(14); + toListResult.add(apiKey); + toListResult.add(appId); + toListResult.add(messagingSenderId); + toListResult.add(projectId); + toListResult.add(authDomain); + toListResult.add(databaseURL); + toListResult.add(storageBucket); + toListResult.add(measurementId); + toListResult.add(trackingId); + toListResult.add(deepLinkURLScheme); + toListResult.add(androidClientId); + toListResult.add(iosClientId); + toListResult.add(iosBundleId); + toListResult.add(appGroupId); + return toListResult; + } + + static @NonNull PigeonFirebaseOptions fromList(@NonNull ArrayList list) { PigeonFirebaseOptions pigeonResult = new PigeonFirebaseOptions(); - Object apiKey = map.get("apiKey"); + Object apiKey = list.get(0); pigeonResult.setApiKey((String) apiKey); - Object appId = map.get("appId"); + Object appId = list.get(1); pigeonResult.setAppId((String) appId); - Object messagingSenderId = map.get("messagingSenderId"); + Object messagingSenderId = list.get(2); pigeonResult.setMessagingSenderId((String) messagingSenderId); - Object projectId = map.get("projectId"); + Object projectId = list.get(3); pigeonResult.setProjectId((String) projectId); - Object authDomain = map.get("authDomain"); + Object authDomain = list.get(4); pigeonResult.setAuthDomain((String) authDomain); - Object databaseURL = map.get("databaseURL"); + Object databaseURL = list.get(5); pigeonResult.setDatabaseURL((String) databaseURL); - Object storageBucket = map.get("storageBucket"); + Object storageBucket = list.get(6); pigeonResult.setStorageBucket((String) storageBucket); - Object measurementId = map.get("measurementId"); + Object measurementId = list.get(7); pigeonResult.setMeasurementId((String) measurementId); - Object trackingId = map.get("trackingId"); + Object trackingId = list.get(8); pigeonResult.setTrackingId((String) trackingId); - Object deepLinkURLScheme = map.get("deepLinkURLScheme"); + Object deepLinkURLScheme = list.get(9); pigeonResult.setDeepLinkURLScheme((String) deepLinkURLScheme); - Object androidClientId = map.get("androidClientId"); + Object androidClientId = list.get(10); pigeonResult.setAndroidClientId((String) androidClientId); - Object iosClientId = map.get("iosClientId"); + Object iosClientId = list.get(11); pigeonResult.setIosClientId((String) iosClientId); - Object iosBundleId = map.get("iosBundleId"); + Object iosBundleId = list.get(12); pigeonResult.setIosBundleId((String) iosBundleId); - Object appGroupId = map.get("appGroupId"); + Object appGroupId = list.get(13); pigeonResult.setAppGroupId((String) appGroupId); return pigeonResult; } } /** Generated class from Pigeon that represents data sent in messages. */ - public static class PigeonInitializeResponse { + public static final class PigeonInitializeResponse { private @NonNull String name; public @NonNull String getName() { @@ -412,6 +418,7 @@ public void setPluginConstants(@NonNull Map setterArg) { private PigeonInitializeResponse() {} public static final class Builder { + private @Nullable String name; public @NonNull Builder setName(@NonNull String setterArg) { @@ -451,25 +458,24 @@ public static final class Builder { } @NonNull - Map toMap() { - Map toMapResult = new HashMap<>(); - toMapResult.put("name", name); - toMapResult.put("options", (options == null) ? null : options.toMap()); - toMapResult.put("isAutomaticDataCollectionEnabled", isAutomaticDataCollectionEnabled); - toMapResult.put("pluginConstants", pluginConstants); - return toMapResult; + ArrayList toList() { + ArrayList toListResult = new ArrayList(4); + toListResult.add(name); + toListResult.add((options == null) ? null : options.toList()); + toListResult.add(isAutomaticDataCollectionEnabled); + toListResult.add(pluginConstants); + return toListResult; } - static @NonNull PigeonInitializeResponse fromMap(@NonNull Map map) { + static @NonNull PigeonInitializeResponse fromList(@NonNull ArrayList list) { PigeonInitializeResponse pigeonResult = new PigeonInitializeResponse(); - Object name = map.get("name"); + Object name = list.get(0); pigeonResult.setName((String) name); - Object options = map.get("options"); - pigeonResult.setOptions( - (options == null) ? null : PigeonFirebaseOptions.fromMap((Map) options)); - Object isAutomaticDataCollectionEnabled = map.get("isAutomaticDataCollectionEnabled"); + Object options = list.get(1); + pigeonResult.setOptions((options == null) ? null : PigeonFirebaseOptions.fromList((ArrayList) options)); + Object isAutomaticDataCollectionEnabled = list.get(2); pigeonResult.setIsAutomaticDataCollectionEnabled((Boolean) isAutomaticDataCollectionEnabled); - Object pluginConstants = map.get("pluginConstants"); + Object pluginConstants = list.get(3); pigeonResult.setPluginConstants((Map) pluginConstants); return pigeonResult; } @@ -487,27 +493,25 @@ private static class FirebaseCoreHostApiCodec extends StandardMessageCodec { private FirebaseCoreHostApiCodec() {} @Override - protected Object readValueOfType(byte type, ByteBuffer buffer) { + protected Object readValueOfType(byte type, @NonNull ByteBuffer buffer) { switch (type) { case (byte) 128: - return PigeonFirebaseOptions.fromMap((Map) readValue(buffer)); - + return PigeonFirebaseOptions.fromList((ArrayList) readValue(buffer)); case (byte) 129: - return PigeonInitializeResponse.fromMap((Map) readValue(buffer)); - + return PigeonInitializeResponse.fromList((ArrayList) readValue(buffer)); default: return super.readValueOfType(type, buffer); } } @Override - protected void writeValue(ByteArrayOutputStream stream, Object value) { + protected void writeValue(@NonNull ByteArrayOutputStream stream, Object value) { if (value instanceof PigeonFirebaseOptions) { stream.write(128); - writeValue(stream, ((PigeonFirebaseOptions) value).toMap()); + writeValue(stream, ((PigeonFirebaseOptions) value).toList()); } else if (value instanceof PigeonInitializeResponse) { stream.write(129); - writeValue(stream, ((PigeonInitializeResponse) value).toMap()); + writeValue(stream, ((PigeonInitializeResponse) value).toList()); } else { super.writeValue(stream, value); } @@ -516,10 +520,8 @@ protected void writeValue(ByteArrayOutputStream stream, Object value) { /** Generated interface from Pigeon that represents a handler of messages from Flutter. */ public interface FirebaseCoreHostApi { - void initializeApp( - @NonNull String appName, - @NonNull PigeonFirebaseOptions initializeAppRequest, - Result result); + + void initializeApp(@NonNull String appName, @NonNull PigeonFirebaseOptions initializeAppRequest, Result result); void initializeCore(Result> result); @@ -529,50 +531,44 @@ void initializeApp( static MessageCodec getCodec() { return FirebaseCoreHostApiCodec.INSTANCE; } - - /** - * Sets up an instance of `FirebaseCoreHostApi` to handle messages through the - * `binaryMessenger`. - */ + /**Sets up an instance of `FirebaseCoreHostApi` to handle messages through the `binaryMessenger`. */ static void setup(BinaryMessenger binaryMessenger, FirebaseCoreHostApi api) { { BasicMessageChannel channel = new BasicMessageChannel<>( - binaryMessenger, - "dev.flutter.pigeon.FirebaseCoreHostApi.initializeApp", - getCodec()); + binaryMessenger, "dev.flutter.pigeon.FirebaseCoreHostApi.initializeApp", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { - Map wrapped = new HashMap<>(); + ArrayList wrapped = new ArrayList(); try { ArrayList args = (ArrayList) message; + assert args != null; String appNameArg = (String) args.get(0); if (appNameArg == null) { throw new NullPointerException("appNameArg unexpectedly null."); } - PigeonFirebaseOptions initializeAppRequestArg = - (PigeonFirebaseOptions) args.get(1); + PigeonFirebaseOptions initializeAppRequestArg = (PigeonFirebaseOptions) args.get(1); if (initializeAppRequestArg == null) { throw new NullPointerException("initializeAppRequestArg unexpectedly null."); } Result resultCallback = new Result() { public void success(PigeonInitializeResponse result) { - wrapped.put("result", result); + wrapped.add(0, result); reply.reply(wrapped); } public void error(Throwable error) { - wrapped.put("error", wrapError(error)); - reply.reply(wrapped); + ArrayList wrappedError = wrapError(error); + reply.reply(wrappedError); } }; api.initializeApp(appNameArg, initializeAppRequestArg, resultCallback); } catch (Error | RuntimeException exception) { - wrapped.put("error", wrapError(exception)); - reply.reply(wrapped); + ArrayList wrappedError = wrapError(exception); + reply.reply(wrappedError); } }); } else { @@ -582,31 +578,29 @@ public void error(Throwable error) { { BasicMessageChannel channel = new BasicMessageChannel<>( - binaryMessenger, - "dev.flutter.pigeon.FirebaseCoreHostApi.initializeCore", - getCodec()); + binaryMessenger, "dev.flutter.pigeon.FirebaseCoreHostApi.initializeCore", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { - Map wrapped = new HashMap<>(); + ArrayList wrapped = new ArrayList(); try { Result> resultCallback = new Result>() { public void success(List result) { - wrapped.put("result", result); + wrapped.add(0, result); reply.reply(wrapped); } public void error(Throwable error) { - wrapped.put("error", wrapError(error)); - reply.reply(wrapped); + ArrayList wrappedError = wrapError(error); + reply.reply(wrappedError); } }; api.initializeCore(resultCallback); } catch (Error | RuntimeException exception) { - wrapped.put("error", wrapError(exception)); - reply.reply(wrapped); + ArrayList wrappedError = wrapError(exception); + reply.reply(wrappedError); } }); } else { @@ -616,31 +610,29 @@ public void error(Throwable error) { { BasicMessageChannel channel = new BasicMessageChannel<>( - binaryMessenger, - "dev.flutter.pigeon.FirebaseCoreHostApi.optionsFromResource", - getCodec()); + binaryMessenger, "dev.flutter.pigeon.FirebaseCoreHostApi.optionsFromResource", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { - Map wrapped = new HashMap<>(); + ArrayList wrapped = new ArrayList(); try { Result resultCallback = new Result() { public void success(PigeonFirebaseOptions result) { - wrapped.put("result", result); + wrapped.add(0, result); reply.reply(wrapped); } public void error(Throwable error) { - wrapped.put("error", wrapError(error)); - reply.reply(wrapped); + ArrayList wrappedError = wrapError(error); + reply.reply(wrappedError); } }; api.optionsFromResource(resultCallback); } catch (Error | RuntimeException exception) { - wrapped.put("error", wrapError(exception)); - reply.reply(wrapped); + ArrayList wrappedError = wrapError(exception); + reply.reply(wrappedError); } }); } else { @@ -649,44 +641,32 @@ public void error(Throwable error) { } } } - - private static class FirebaseAppHostApiCodec extends StandardMessageCodec { - public static final FirebaseAppHostApiCodec INSTANCE = new FirebaseAppHostApiCodec(); - - private FirebaseAppHostApiCodec() {} - } - /** Generated interface from Pigeon that represents a handler of messages from Flutter. */ public interface FirebaseAppHostApi { - void setAutomaticDataCollectionEnabled( - @NonNull String appName, @NonNull Boolean enabled, Result result); - void setAutomaticResourceManagementEnabled( - @NonNull String appName, @NonNull Boolean enabled, Result result); + void setAutomaticDataCollectionEnabled(@NonNull String appName, @NonNull Boolean enabled, Result result); + + void setAutomaticResourceManagementEnabled(@NonNull String appName, @NonNull Boolean enabled, Result result); void delete(@NonNull String appName, Result result); /** The codec used by FirebaseAppHostApi. */ static MessageCodec getCodec() { - return FirebaseAppHostApiCodec.INSTANCE; + return new StandardMessageCodec(); } - - /** - * Sets up an instance of `FirebaseAppHostApi` to handle messages through the `binaryMessenger`. - */ + /**Sets up an instance of `FirebaseAppHostApi` to handle messages through the `binaryMessenger`. */ static void setup(BinaryMessenger binaryMessenger, FirebaseAppHostApi api) { { BasicMessageChannel channel = new BasicMessageChannel<>( - binaryMessenger, - "dev.flutter.pigeon.FirebaseAppHostApi.setAutomaticDataCollectionEnabled", - getCodec()); + binaryMessenger, "dev.flutter.pigeon.FirebaseAppHostApi.setAutomaticDataCollectionEnabled", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { - Map wrapped = new HashMap<>(); + ArrayList wrapped = new ArrayList(); try { ArrayList args = (ArrayList) message; + assert args != null; String appNameArg = (String) args.get(0); if (appNameArg == null) { throw new NullPointerException("appNameArg unexpectedly null."); @@ -698,20 +678,20 @@ static void setup(BinaryMessenger binaryMessenger, FirebaseAppHostApi api) { Result resultCallback = new Result() { public void success(Void result) { - wrapped.put("result", null); + wrapped.add(0, null); reply.reply(wrapped); } public void error(Throwable error) { - wrapped.put("error", wrapError(error)); - reply.reply(wrapped); + ArrayList wrappedError = wrapError(error); + reply.reply(wrappedError); } }; api.setAutomaticDataCollectionEnabled(appNameArg, enabledArg, resultCallback); } catch (Error | RuntimeException exception) { - wrapped.put("error", wrapError(exception)); - reply.reply(wrapped); + ArrayList wrappedError = wrapError(exception); + reply.reply(wrappedError); } }); } else { @@ -721,15 +701,14 @@ public void error(Throwable error) { { BasicMessageChannel channel = new BasicMessageChannel<>( - binaryMessenger, - "dev.flutter.pigeon.FirebaseAppHostApi.setAutomaticResourceManagementEnabled", - getCodec()); + binaryMessenger, "dev.flutter.pigeon.FirebaseAppHostApi.setAutomaticResourceManagementEnabled", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { - Map wrapped = new HashMap<>(); + ArrayList wrapped = new ArrayList(); try { ArrayList args = (ArrayList) message; + assert args != null; String appNameArg = (String) args.get(0); if (appNameArg == null) { throw new NullPointerException("appNameArg unexpectedly null."); @@ -741,20 +720,20 @@ public void error(Throwable error) { Result resultCallback = new Result() { public void success(Void result) { - wrapped.put("result", null); + wrapped.add(0, null); reply.reply(wrapped); } public void error(Throwable error) { - wrapped.put("error", wrapError(error)); - reply.reply(wrapped); + ArrayList wrappedError = wrapError(error); + reply.reply(wrappedError); } }; api.setAutomaticResourceManagementEnabled(appNameArg, enabledArg, resultCallback); } catch (Error | RuntimeException exception) { - wrapped.put("error", wrapError(exception)); - reply.reply(wrapped); + ArrayList wrappedError = wrapError(exception); + reply.reply(wrappedError); } }); } else { @@ -768,9 +747,10 @@ public void error(Throwable error) { if (api != null) { channel.setMessageHandler( (message, reply) -> { - Map wrapped = new HashMap<>(); + ArrayList wrapped = new ArrayList(); try { ArrayList args = (ArrayList) message; + assert args != null; String appNameArg = (String) args.get(0); if (appNameArg == null) { throw new NullPointerException("appNameArg unexpectedly null."); @@ -778,20 +758,20 @@ public void error(Throwable error) { Result resultCallback = new Result() { public void success(Void result) { - wrapped.put("result", null); + wrapped.add(0, null); reply.reply(wrapped); } public void error(Throwable error) { - wrapped.put("error", wrapError(error)); - reply.reply(wrapped); + ArrayList wrappedError = wrapError(error); + reply.reply(wrappedError); } }; api.delete(appNameArg, resultCallback); } catch (Error | RuntimeException exception) { - wrapped.put("error", wrapError(exception)); - reply.reply(wrapped); + ArrayList wrappedError = wrapError(exception); + reply.reply(wrappedError); } }); } else { @@ -800,14 +780,4 @@ public void error(Throwable error) { } } } - - private static Map wrapError(Throwable exception) { - Map errorMap = new HashMap<>(); - errorMap.put("message", exception.toString()); - errorMap.put("code", exception.getClass().getSimpleName()); - errorMap.put( - "details", - "Cause: " + exception.getCause() + ", Stacktrace: " + Log.getStackTraceString(exception)); - return errorMap; - } } diff --git a/packages/firebase_core/firebase_core/ios/Classes/messages.g.h b/packages/firebase_core/firebase_core/ios/Classes/messages.g.h index 70cdb4f374a9..621dc1a79ccf 100644 --- a/packages/firebase_core/firebase_core/ios/Classes/messages.g.h +++ b/packages/firebase_core/firebase_core/ios/Classes/messages.g.h @@ -1,6 +1,8 @@ -// Autogenerated from Pigeon (v3.2.0), do not edit directly. +// Autogenerated from Pigeon (v9.0.6), do not edit directly. // See also: https://pub.dev/packages/pigeon + #import + @protocol FlutterBinaryMessenger; @protocol FlutterMessageCodec; @class FlutterError; @@ -15,79 +17,68 @@ NS_ASSUME_NONNULL_BEGIN /// `init` unavailable to enforce nonnull fields, see the `make` class method. - (instancetype)init NS_UNAVAILABLE; + (instancetype)makeWithApiKey:(NSString *)apiKey - appId:(NSString *)appId - messagingSenderId:(NSString *)messagingSenderId - projectId:(NSString *)projectId - authDomain:(nullable NSString *)authDomain - databaseURL:(nullable NSString *)databaseURL - storageBucket:(nullable NSString *)storageBucket - measurementId:(nullable NSString *)measurementId - trackingId:(nullable NSString *)trackingId - deepLinkURLScheme:(nullable NSString *)deepLinkURLScheme - androidClientId:(nullable NSString *)androidClientId - iosClientId:(nullable NSString *)iosClientId - iosBundleId:(nullable NSString *)iosBundleId - appGroupId:(nullable NSString *)appGroupId; -@property(nonatomic, copy) NSString *apiKey; -@property(nonatomic, copy) NSString *appId; -@property(nonatomic, copy) NSString *messagingSenderId; -@property(nonatomic, copy) NSString *projectId; -@property(nonatomic, copy, nullable) NSString *authDomain; -@property(nonatomic, copy, nullable) NSString *databaseURL; -@property(nonatomic, copy, nullable) NSString *storageBucket; -@property(nonatomic, copy, nullable) NSString *measurementId; -@property(nonatomic, copy, nullable) NSString *trackingId; -@property(nonatomic, copy, nullable) NSString *deepLinkURLScheme; -@property(nonatomic, copy, nullable) NSString *androidClientId; -@property(nonatomic, copy, nullable) NSString *iosClientId; -@property(nonatomic, copy, nullable) NSString *iosBundleId; -@property(nonatomic, copy, nullable) NSString *appGroupId; + appId:(NSString *)appId + messagingSenderId:(NSString *)messagingSenderId + projectId:(NSString *)projectId + authDomain:(nullable NSString *)authDomain + databaseURL:(nullable NSString *)databaseURL + storageBucket:(nullable NSString *)storageBucket + measurementId:(nullable NSString *)measurementId + trackingId:(nullable NSString *)trackingId + deepLinkURLScheme:(nullable NSString *)deepLinkURLScheme + androidClientId:(nullable NSString *)androidClientId + iosClientId:(nullable NSString *)iosClientId + iosBundleId:(nullable NSString *)iosBundleId + appGroupId:(nullable NSString *)appGroupId; +@property(nonatomic, copy) NSString * apiKey; +@property(nonatomic, copy) NSString * appId; +@property(nonatomic, copy) NSString * messagingSenderId; +@property(nonatomic, copy) NSString * projectId; +@property(nonatomic, copy, nullable) NSString * authDomain; +@property(nonatomic, copy, nullable) NSString * databaseURL; +@property(nonatomic, copy, nullable) NSString * storageBucket; +@property(nonatomic, copy, nullable) NSString * measurementId; +@property(nonatomic, copy, nullable) NSString * trackingId; +@property(nonatomic, copy, nullable) NSString * deepLinkURLScheme; +@property(nonatomic, copy, nullable) NSString * androidClientId; +@property(nonatomic, copy, nullable) NSString * iosClientId; +@property(nonatomic, copy, nullable) NSString * iosBundleId; +@property(nonatomic, copy, nullable) NSString * appGroupId; @end @interface PigeonInitializeResponse : NSObject /// `init` unavailable to enforce nonnull fields, see the `make` class method. - (instancetype)init NS_UNAVAILABLE; + (instancetype)makeWithName:(NSString *)name - options:(PigeonFirebaseOptions *)options + options:(PigeonFirebaseOptions *)options isAutomaticDataCollectionEnabled:(nullable NSNumber *)isAutomaticDataCollectionEnabled - pluginConstants:(NSDictionary *)pluginConstants; -@property(nonatomic, copy) NSString *name; -@property(nonatomic, strong) PigeonFirebaseOptions *options; -@property(nonatomic, strong, nullable) NSNumber *isAutomaticDataCollectionEnabled; -@property(nonatomic, strong) NSDictionary *pluginConstants; + pluginConstants:(NSDictionary *)pluginConstants; +@property(nonatomic, copy) NSString * name; +@property(nonatomic, strong) PigeonFirebaseOptions * options; +@property(nonatomic, strong, nullable) NSNumber * isAutomaticDataCollectionEnabled; +@property(nonatomic, strong) NSDictionary * pluginConstants; @end /// The codec used by FirebaseCoreHostApi. NSObject *FirebaseCoreHostApiGetCodec(void); @protocol FirebaseCoreHostApi -- (void)initializeAppAppName:(NSString *)appName - initializeAppRequest:(PigeonFirebaseOptions *)initializeAppRequest - completion:(void (^)(PigeonInitializeResponse *_Nullable, - FlutterError *_Nullable))completion; -- (void)initializeCoreWithCompletion:(void (^)(NSArray *_Nullable, - FlutterError *_Nullable))completion; -- (void)optionsFromResourceWithCompletion:(void (^)(PigeonFirebaseOptions *_Nullable, - FlutterError *_Nullable))completion; +- (void)initializeAppAppName:(NSString *)appName initializeAppRequest:(PigeonFirebaseOptions *)initializeAppRequest completion:(void (^)(PigeonInitializeResponse *_Nullable, FlutterError *_Nullable))completion; +- (void)initializeCoreWithCompletion:(void (^)(NSArray *_Nullable, FlutterError *_Nullable))completion; +- (void)optionsFromResourceWithCompletion:(void (^)(PigeonFirebaseOptions *_Nullable, FlutterError *_Nullable))completion; @end -extern void FirebaseCoreHostApiSetup(id binaryMessenger, - NSObject *_Nullable api); +extern void FirebaseCoreHostApiSetup(id binaryMessenger, NSObject *_Nullable api); /// The codec used by FirebaseAppHostApi. NSObject *FirebaseAppHostApiGetCodec(void); @protocol FirebaseAppHostApi -- (void)setAutomaticDataCollectionEnabledAppName:(NSString *)appName - enabled:(NSNumber *)enabled - completion:(void (^)(FlutterError *_Nullable))completion; -- (void)setAutomaticResourceManagementEnabledAppName:(NSString *)appName - enabled:(NSNumber *)enabled - completion:(void (^)(FlutterError *_Nullable))completion; +- (void)setAutomaticDataCollectionEnabledAppName:(NSString *)appName enabled:(NSNumber *)enabled completion:(void (^)(FlutterError *_Nullable))completion; +- (void)setAutomaticResourceManagementEnabledAppName:(NSString *)appName enabled:(NSNumber *)enabled completion:(void (^)(FlutterError *_Nullable))completion; - (void)deleteAppName:(NSString *)appName completion:(void (^)(FlutterError *_Nullable))completion; @end -extern void FirebaseAppHostApiSetup(id binaryMessenger, - NSObject *_Nullable api); +extern void FirebaseAppHostApiSetup(id binaryMessenger, NSObject *_Nullable api); NS_ASSUME_NONNULL_END diff --git a/packages/firebase_core/firebase_core/ios/Classes/messages.g.m b/packages/firebase_core/firebase_core/ios/Classes/messages.g.m index 1c22807964d1..8d6cda3d45af 100644 --- a/packages/firebase_core/firebase_core/ios/Classes/messages.g.m +++ b/packages/firebase_core/firebase_core/ios/Classes/messages.g.m @@ -1,33 +1,20 @@ -// Autogenerated from Pigeon (v3.2.0), do not edit directly. +// Autogenerated from Pigeon (v9.0.6), do not edit directly. // See also: https://pub.dev/packages/pigeon + #import "messages.g.h" -#if TARGET_OS_OSX -#import -#else #import -#endif #if !__has_feature(objc_arc) #error File requires ARC to be enabled. #endif -static NSDictionary *wrapResult(id result, FlutterError *error) { - NSDictionary *errorDict = (NSDictionary *)[NSNull null]; +static NSArray *wrapResult(id result, FlutterError *error) { if (error) { - errorDict = @{ - @"code" : (error.code ?: [NSNull null]), - @"message" : (error.message ?: [NSNull null]), - @"details" : (error.details ?: [NSNull null]), - }; + return @[ + error.code ?: [NSNull null], error.message ?: [NSNull null], error.details ?: [NSNull null] + ]; } - return @{ - @"result" : (result ?: [NSNull null]), - @"error" : errorDict, - }; -} -static id GetNullableObject(NSDictionary *dict, id key) { - id result = dict[key]; - return (result == [NSNull null]) ? nil : result; + return @[ result ?: [NSNull null] ]; } static id GetNullableObjectAtIndex(NSArray *array, NSInteger key) { id result = array[key]; @@ -35,32 +22,33 @@ static id GetNullableObjectAtIndex(NSArray *array, NSInteger key) { } @interface PigeonFirebaseOptions () -+ (PigeonFirebaseOptions *)fromMap:(NSDictionary *)dict; -+ (nullable PigeonFirebaseOptions *)nullableFromMap:(NSDictionary *)dict; -- (NSDictionary *)toMap; ++ (PigeonFirebaseOptions *)fromList:(NSArray *)list; ++ (nullable PigeonFirebaseOptions *)nullableFromList:(NSArray *)list; +- (NSArray *)toList; @end + @interface PigeonInitializeResponse () -+ (PigeonInitializeResponse *)fromMap:(NSDictionary *)dict; -+ (nullable PigeonInitializeResponse *)nullableFromMap:(NSDictionary *)dict; -- (NSDictionary *)toMap; ++ (PigeonInitializeResponse *)fromList:(NSArray *)list; ++ (nullable PigeonInitializeResponse *)nullableFromList:(NSArray *)list; +- (NSArray *)toList; @end @implementation PigeonFirebaseOptions + (instancetype)makeWithApiKey:(NSString *)apiKey - appId:(NSString *)appId - messagingSenderId:(NSString *)messagingSenderId - projectId:(NSString *)projectId - authDomain:(nullable NSString *)authDomain - databaseURL:(nullable NSString *)databaseURL - storageBucket:(nullable NSString *)storageBucket - measurementId:(nullable NSString *)measurementId - trackingId:(nullable NSString *)trackingId - deepLinkURLScheme:(nullable NSString *)deepLinkURLScheme - androidClientId:(nullable NSString *)androidClientId - iosClientId:(nullable NSString *)iosClientId - iosBundleId:(nullable NSString *)iosBundleId - appGroupId:(nullable NSString *)appGroupId { - PigeonFirebaseOptions *pigeonResult = [[PigeonFirebaseOptions alloc] init]; + appId:(NSString *)appId + messagingSenderId:(NSString *)messagingSenderId + projectId:(NSString *)projectId + authDomain:(nullable NSString *)authDomain + databaseURL:(nullable NSString *)databaseURL + storageBucket:(nullable NSString *)storageBucket + measurementId:(nullable NSString *)measurementId + trackingId:(nullable NSString *)trackingId + deepLinkURLScheme:(nullable NSString *)deepLinkURLScheme + androidClientId:(nullable NSString *)androidClientId + iosClientId:(nullable NSString *)iosClientId + iosBundleId:(nullable NSString *)iosBundleId + appGroupId:(nullable NSString *)appGroupId { + PigeonFirebaseOptions* pigeonResult = [[PigeonFirebaseOptions alloc] init]; pigeonResult.apiKey = apiKey; pigeonResult.appId = appId; pigeonResult.messagingSenderId = messagingSenderId; @@ -77,86 +65,84 @@ + (instancetype)makeWithApiKey:(NSString *)apiKey pigeonResult.appGroupId = appGroupId; return pigeonResult; } -+ (PigeonFirebaseOptions *)fromMap:(NSDictionary *)dict { ++ (PigeonFirebaseOptions *)fromList:(NSArray *)list { PigeonFirebaseOptions *pigeonResult = [[PigeonFirebaseOptions alloc] init]; - pigeonResult.apiKey = GetNullableObject(dict, @"apiKey"); + pigeonResult.apiKey = GetNullableObjectAtIndex(list, 0); NSAssert(pigeonResult.apiKey != nil, @""); - pigeonResult.appId = GetNullableObject(dict, @"appId"); + pigeonResult.appId = GetNullableObjectAtIndex(list, 1); NSAssert(pigeonResult.appId != nil, @""); - pigeonResult.messagingSenderId = GetNullableObject(dict, @"messagingSenderId"); + pigeonResult.messagingSenderId = GetNullableObjectAtIndex(list, 2); NSAssert(pigeonResult.messagingSenderId != nil, @""); - pigeonResult.projectId = GetNullableObject(dict, @"projectId"); + pigeonResult.projectId = GetNullableObjectAtIndex(list, 3); NSAssert(pigeonResult.projectId != nil, @""); - pigeonResult.authDomain = GetNullableObject(dict, @"authDomain"); - pigeonResult.databaseURL = GetNullableObject(dict, @"databaseURL"); - pigeonResult.storageBucket = GetNullableObject(dict, @"storageBucket"); - pigeonResult.measurementId = GetNullableObject(dict, @"measurementId"); - pigeonResult.trackingId = GetNullableObject(dict, @"trackingId"); - pigeonResult.deepLinkURLScheme = GetNullableObject(dict, @"deepLinkURLScheme"); - pigeonResult.androidClientId = GetNullableObject(dict, @"androidClientId"); - pigeonResult.iosClientId = GetNullableObject(dict, @"iosClientId"); - pigeonResult.iosBundleId = GetNullableObject(dict, @"iosBundleId"); - pigeonResult.appGroupId = GetNullableObject(dict, @"appGroupId"); + pigeonResult.authDomain = GetNullableObjectAtIndex(list, 4); + pigeonResult.databaseURL = GetNullableObjectAtIndex(list, 5); + pigeonResult.storageBucket = GetNullableObjectAtIndex(list, 6); + pigeonResult.measurementId = GetNullableObjectAtIndex(list, 7); + pigeonResult.trackingId = GetNullableObjectAtIndex(list, 8); + pigeonResult.deepLinkURLScheme = GetNullableObjectAtIndex(list, 9); + pigeonResult.androidClientId = GetNullableObjectAtIndex(list, 10); + pigeonResult.iosClientId = GetNullableObjectAtIndex(list, 11); + pigeonResult.iosBundleId = GetNullableObjectAtIndex(list, 12); + pigeonResult.appGroupId = GetNullableObjectAtIndex(list, 13); return pigeonResult; } -+ (nullable PigeonFirebaseOptions *)nullableFromMap:(NSDictionary *)dict { - return (dict) ? [PigeonFirebaseOptions fromMap:dict] : nil; ++ (nullable PigeonFirebaseOptions *)nullableFromList:(NSArray *)list { + return (list) ? [PigeonFirebaseOptions fromList:list] : nil; } -- (NSDictionary *)toMap { - return @{ - @"apiKey" : (self.apiKey ?: [NSNull null]), - @"appId" : (self.appId ?: [NSNull null]), - @"messagingSenderId" : (self.messagingSenderId ?: [NSNull null]), - @"projectId" : (self.projectId ?: [NSNull null]), - @"authDomain" : (self.authDomain ?: [NSNull null]), - @"databaseURL" : (self.databaseURL ?: [NSNull null]), - @"storageBucket" : (self.storageBucket ?: [NSNull null]), - @"measurementId" : (self.measurementId ?: [NSNull null]), - @"trackingId" : (self.trackingId ?: [NSNull null]), - @"deepLinkURLScheme" : (self.deepLinkURLScheme ?: [NSNull null]), - @"androidClientId" : (self.androidClientId ?: [NSNull null]), - @"iosClientId" : (self.iosClientId ?: [NSNull null]), - @"iosBundleId" : (self.iosBundleId ?: [NSNull null]), - @"appGroupId" : (self.appGroupId ?: [NSNull null]), - }; +- (NSArray *)toList { + return @[ + (self.apiKey ?: [NSNull null]), + (self.appId ?: [NSNull null]), + (self.messagingSenderId ?: [NSNull null]), + (self.projectId ?: [NSNull null]), + (self.authDomain ?: [NSNull null]), + (self.databaseURL ?: [NSNull null]), + (self.storageBucket ?: [NSNull null]), + (self.measurementId ?: [NSNull null]), + (self.trackingId ?: [NSNull null]), + (self.deepLinkURLScheme ?: [NSNull null]), + (self.androidClientId ?: [NSNull null]), + (self.iosClientId ?: [NSNull null]), + (self.iosBundleId ?: [NSNull null]), + (self.appGroupId ?: [NSNull null]), + ]; } @end @implementation PigeonInitializeResponse + (instancetype)makeWithName:(NSString *)name - options:(PigeonFirebaseOptions *)options + options:(PigeonFirebaseOptions *)options isAutomaticDataCollectionEnabled:(nullable NSNumber *)isAutomaticDataCollectionEnabled - pluginConstants:(NSDictionary *)pluginConstants { - PigeonInitializeResponse *pigeonResult = [[PigeonInitializeResponse alloc] init]; + pluginConstants:(NSDictionary *)pluginConstants { + PigeonInitializeResponse* pigeonResult = [[PigeonInitializeResponse alloc] init]; pigeonResult.name = name; pigeonResult.options = options; pigeonResult.isAutomaticDataCollectionEnabled = isAutomaticDataCollectionEnabled; pigeonResult.pluginConstants = pluginConstants; return pigeonResult; } -+ (PigeonInitializeResponse *)fromMap:(NSDictionary *)dict { ++ (PigeonInitializeResponse *)fromList:(NSArray *)list { PigeonInitializeResponse *pigeonResult = [[PigeonInitializeResponse alloc] init]; - pigeonResult.name = GetNullableObject(dict, @"name"); + pigeonResult.name = GetNullableObjectAtIndex(list, 0); NSAssert(pigeonResult.name != nil, @""); - pigeonResult.options = - [PigeonFirebaseOptions nullableFromMap:GetNullableObject(dict, @"options")]; + pigeonResult.options = [PigeonFirebaseOptions nullableFromList:(GetNullableObjectAtIndex(list, 1))]; NSAssert(pigeonResult.options != nil, @""); - pigeonResult.isAutomaticDataCollectionEnabled = - GetNullableObject(dict, @"isAutomaticDataCollectionEnabled"); - pigeonResult.pluginConstants = GetNullableObject(dict, @"pluginConstants"); + pigeonResult.isAutomaticDataCollectionEnabled = GetNullableObjectAtIndex(list, 2); + pigeonResult.pluginConstants = GetNullableObjectAtIndex(list, 3); NSAssert(pigeonResult.pluginConstants != nil, @""); return pigeonResult; } -+ (nullable PigeonInitializeResponse *)nullableFromMap:(NSDictionary *)dict { - return (dict) ? [PigeonInitializeResponse fromMap:dict] : nil; ++ (nullable PigeonInitializeResponse *)nullableFromList:(NSArray *)list { + return (list) ? [PigeonInitializeResponse fromList:list] : nil; } -- (NSDictionary *)toMap { - return @{ - @"name" : (self.name ?: [NSNull null]), - @"options" : (self.options ? [self.options toMap] : [NSNull null]), - @"isAutomaticDataCollectionEnabled" : (self.isAutomaticDataCollectionEnabled ?: [NSNull null]), - @"pluginConstants" : (self.pluginConstants ?: [NSNull null]), - }; +- (NSArray *)toList { + return @[ + (self.name ?: [NSNull null]), + (self.options ? [self.options toList] : [NSNull null]), + (self.isAutomaticDataCollectionEnabled ?: [NSNull null]), + (self.pluginConstants ?: [NSNull null]), + ]; } @end @@ -165,12 +151,10 @@ @interface FirebaseCoreHostApiCodecReader : FlutterStandardReader @implementation FirebaseCoreHostApiCodecReader - (nullable id)readValueOfType:(UInt8)type { switch (type) { - case 128: - return [PigeonFirebaseOptions fromMap:[self readValue]]; - - case 129: - return [PigeonInitializeResponse fromMap:[self readValue]]; - + case 128: + return [PigeonFirebaseOptions fromList:[self readValue]]; + case 129: + return [PigeonInitializeResponse fromList:[self readValue]]; default: return [super readValueOfType:type]; } @@ -183,10 +167,10 @@ @implementation FirebaseCoreHostApiCodecWriter - (void)writeValue:(id)value { if ([value isKindOfClass:[PigeonFirebaseOptions class]]) { [self writeByte:128]; - [self writeValue:[value toMap]]; + [self writeValue:[value toList]]; } else if ([value isKindOfClass:[PigeonInitializeResponse class]]) { [self writeByte:129]; - [self writeValue:[value toMap]]; + [self writeValue:[value toList]]; } else { [super writeValue:value]; } @@ -205,57 +189,46 @@ - (FlutterStandardReader *)readerWithData:(NSData *)data { @end NSObject *FirebaseCoreHostApiGetCodec() { - static dispatch_once_t sPred = 0; static FlutterStandardMessageCodec *sSharedObject = nil; + static dispatch_once_t sPred = 0; dispatch_once(&sPred, ^{ - FirebaseCoreHostApiCodecReaderWriter *readerWriter = - [[FirebaseCoreHostApiCodecReaderWriter alloc] init]; + FirebaseCoreHostApiCodecReaderWriter *readerWriter = [[FirebaseCoreHostApiCodecReaderWriter alloc] init]; sSharedObject = [FlutterStandardMessageCodec codecWithReaderWriter:readerWriter]; }); return sSharedObject; } -void FirebaseCoreHostApiSetup(id binaryMessenger, - NSObject *api) { +void FirebaseCoreHostApiSetup(id binaryMessenger, NSObject *api) { { - FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] - initWithName:@"dev.flutter.pigeon.FirebaseCoreHostApi.initializeApp" + FlutterBasicMessageChannel *channel = + [[FlutterBasicMessageChannel alloc] + initWithName:@"dev.flutter.pigeon.FirebaseCoreHostApi.initializeApp" binaryMessenger:binaryMessenger - codec:FirebaseCoreHostApiGetCodec()]; + codec:FirebaseCoreHostApiGetCodec()]; if (api) { - NSCAssert([api respondsToSelector:@selector(initializeAppAppName: - initializeAppRequest:completion:)], - @"FirebaseCoreHostApi api (%@) doesn't respond to " - @"@selector(initializeAppAppName:initializeAppRequest:completion:)", - api); + NSCAssert([api respondsToSelector:@selector(initializeAppAppName:initializeAppRequest:completion:)], @"FirebaseCoreHostApi api (%@) doesn't respond to @selector(initializeAppAppName:initializeAppRequest:completion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; NSString *arg_appName = GetNullableObjectAtIndex(args, 0); PigeonFirebaseOptions *arg_initializeAppRequest = GetNullableObjectAtIndex(args, 1); - [api initializeAppAppName:arg_appName - initializeAppRequest:arg_initializeAppRequest - completion:^(PigeonInitializeResponse *_Nullable output, - FlutterError *_Nullable error) { - callback(wrapResult(output, error)); - }]; + [api initializeAppAppName:arg_appName initializeAppRequest:arg_initializeAppRequest completion:^(PigeonInitializeResponse *_Nullable output, FlutterError *_Nullable error) { + callback(wrapResult(output, error)); + }]; }]; } else { [channel setMessageHandler:nil]; } } { - FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] - initWithName:@"dev.flutter.pigeon.FirebaseCoreHostApi.initializeCore" + FlutterBasicMessageChannel *channel = + [[FlutterBasicMessageChannel alloc] + initWithName:@"dev.flutter.pigeon.FirebaseCoreHostApi.initializeCore" binaryMessenger:binaryMessenger - codec:FirebaseCoreHostApiGetCodec()]; + codec:FirebaseCoreHostApiGetCodec()]; if (api) { - NSCAssert([api respondsToSelector:@selector(initializeCoreWithCompletion:)], - @"FirebaseCoreHostApi api (%@) doesn't respond to " - @"@selector(initializeCoreWithCompletion:)", - api); + NSCAssert([api respondsToSelector:@selector(initializeCoreWithCompletion:)], @"FirebaseCoreHostApi api (%@) doesn't respond to @selector(initializeCoreWithCompletion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { - [api initializeCoreWithCompletion:^(NSArray *_Nullable output, - FlutterError *_Nullable error) { + [api initializeCoreWithCompletion:^(NSArray *_Nullable output, FlutterError *_Nullable error) { callback(wrapResult(output, error)); }]; }]; @@ -264,18 +237,15 @@ void FirebaseCoreHostApiSetup(id binaryMessenger, } } { - FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] - initWithName:@"dev.flutter.pigeon.FirebaseCoreHostApi.optionsFromResource" + FlutterBasicMessageChannel *channel = + [[FlutterBasicMessageChannel alloc] + initWithName:@"dev.flutter.pigeon.FirebaseCoreHostApi.optionsFromResource" binaryMessenger:binaryMessenger - codec:FirebaseCoreHostApiGetCodec()]; + codec:FirebaseCoreHostApiGetCodec()]; if (api) { - NSCAssert([api respondsToSelector:@selector(optionsFromResourceWithCompletion:)], - @"FirebaseCoreHostApi api (%@) doesn't respond to " - @"@selector(optionsFromResourceWithCompletion:)", - api); + NSCAssert([api respondsToSelector:@selector(optionsFromResourceWithCompletion:)], @"FirebaseCoreHostApi api (%@) doesn't respond to @selector(optionsFromResourceWithCompletion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { - [api optionsFromResourceWithCompletion:^(PigeonFirebaseOptions *_Nullable output, - FlutterError *_Nullable error) { + [api optionsFromResourceWithCompletion:^(PigeonFirebaseOptions *_Nullable output, FlutterError *_Nullable error) { callback(wrapResult(output, error)); }]; }]; @@ -284,108 +254,67 @@ void FirebaseCoreHostApiSetup(id binaryMessenger, } } } -@interface FirebaseAppHostApiCodecReader : FlutterStandardReader -@end -@implementation FirebaseAppHostApiCodecReader -@end - -@interface FirebaseAppHostApiCodecWriter : FlutterStandardWriter -@end -@implementation FirebaseAppHostApiCodecWriter -@end - -@interface FirebaseAppHostApiCodecReaderWriter : FlutterStandardReaderWriter -@end -@implementation FirebaseAppHostApiCodecReaderWriter -- (FlutterStandardWriter *)writerWithData:(NSMutableData *)data { - return [[FirebaseAppHostApiCodecWriter alloc] initWithData:data]; -} -- (FlutterStandardReader *)readerWithData:(NSData *)data { - return [[FirebaseAppHostApiCodecReader alloc] initWithData:data]; -} -@end - NSObject *FirebaseAppHostApiGetCodec() { - static dispatch_once_t sPred = 0; static FlutterStandardMessageCodec *sSharedObject = nil; - dispatch_once(&sPred, ^{ - FirebaseAppHostApiCodecReaderWriter *readerWriter = - [[FirebaseAppHostApiCodecReaderWriter alloc] init]; - sSharedObject = [FlutterStandardMessageCodec codecWithReaderWriter:readerWriter]; - }); + sSharedObject = [FlutterStandardMessageCodec sharedInstance]; return sSharedObject; } -void FirebaseAppHostApiSetup(id binaryMessenger, - NSObject *api) { +void FirebaseAppHostApiSetup(id binaryMessenger, NSObject *api) { { - FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] - initWithName:@"dev.flutter.pigeon.FirebaseAppHostApi.setAutomaticDataCollectionEnabled" + FlutterBasicMessageChannel *channel = + [[FlutterBasicMessageChannel alloc] + initWithName:@"dev.flutter.pigeon.FirebaseAppHostApi.setAutomaticDataCollectionEnabled" binaryMessenger:binaryMessenger - codec:FirebaseAppHostApiGetCodec()]; + codec:FirebaseAppHostApiGetCodec()]; if (api) { - NSCAssert([api respondsToSelector:@selector - (setAutomaticDataCollectionEnabledAppName:enabled:completion:)], - @"FirebaseAppHostApi api (%@) doesn't respond to " - @"@selector(setAutomaticDataCollectionEnabledAppName:enabled:completion:)", - api); + NSCAssert([api respondsToSelector:@selector(setAutomaticDataCollectionEnabledAppName:enabled:completion:)], @"FirebaseAppHostApi api (%@) doesn't respond to @selector(setAutomaticDataCollectionEnabledAppName:enabled:completion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; NSString *arg_appName = GetNullableObjectAtIndex(args, 0); NSNumber *arg_enabled = GetNullableObjectAtIndex(args, 1); - [api setAutomaticDataCollectionEnabledAppName:arg_appName - enabled:arg_enabled - completion:^(FlutterError *_Nullable error) { - callback(wrapResult(nil, error)); - }]; + [api setAutomaticDataCollectionEnabledAppName:arg_appName enabled:arg_enabled completion:^(FlutterError *_Nullable error) { + callback(wrapResult(nil, error)); + }]; }]; } else { [channel setMessageHandler:nil]; } } { - FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] - initWithName: - @"dev.flutter.pigeon.FirebaseAppHostApi.setAutomaticResourceManagementEnabled" + FlutterBasicMessageChannel *channel = + [[FlutterBasicMessageChannel alloc] + initWithName:@"dev.flutter.pigeon.FirebaseAppHostApi.setAutomaticResourceManagementEnabled" binaryMessenger:binaryMessenger - codec:FirebaseAppHostApiGetCodec()]; + codec:FirebaseAppHostApiGetCodec()]; if (api) { - NSCAssert([api respondsToSelector:@selector - (setAutomaticResourceManagementEnabledAppName:enabled:completion:)], - @"FirebaseAppHostApi api (%@) doesn't respond to " - @"@selector(setAutomaticResourceManagementEnabledAppName:enabled:completion:)", - api); + NSCAssert([api respondsToSelector:@selector(setAutomaticResourceManagementEnabledAppName:enabled:completion:)], @"FirebaseAppHostApi api (%@) doesn't respond to @selector(setAutomaticResourceManagementEnabledAppName:enabled:completion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; NSString *arg_appName = GetNullableObjectAtIndex(args, 0); NSNumber *arg_enabled = GetNullableObjectAtIndex(args, 1); - [api setAutomaticResourceManagementEnabledAppName:arg_appName - enabled:arg_enabled - completion:^(FlutterError *_Nullable error) { - callback(wrapResult(nil, error)); - }]; + [api setAutomaticResourceManagementEnabledAppName:arg_appName enabled:arg_enabled completion:^(FlutterError *_Nullable error) { + callback(wrapResult(nil, error)); + }]; }]; } else { [channel setMessageHandler:nil]; } } { - FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] - initWithName:@"dev.flutter.pigeon.FirebaseAppHostApi.delete" + FlutterBasicMessageChannel *channel = + [[FlutterBasicMessageChannel alloc] + initWithName:@"dev.flutter.pigeon.FirebaseAppHostApi.delete" binaryMessenger:binaryMessenger - codec:FirebaseAppHostApiGetCodec()]; + codec:FirebaseAppHostApiGetCodec()]; if (api) { - NSCAssert( - [api respondsToSelector:@selector(deleteAppName:completion:)], - @"FirebaseAppHostApi api (%@) doesn't respond to @selector(deleteAppName:completion:)", - api); + NSCAssert([api respondsToSelector:@selector(deleteAppName:completion:)], @"FirebaseAppHostApi api (%@) doesn't respond to @selector(deleteAppName:completion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; NSString *arg_appName = GetNullableObjectAtIndex(args, 0); - [api deleteAppName:arg_appName - completion:^(FlutterError *_Nullable error) { - callback(wrapResult(nil, error)); - }]; + [api deleteAppName:arg_appName completion:^(FlutterError *_Nullable error) { + callback(wrapResult(nil, error)); + }]; }]; } else { [channel setMessageHandler:nil]; diff --git a/packages/firebase_core/firebase_core_platform_interface/lib/src/pigeon/messages.pigeon.dart b/packages/firebase_core/firebase_core_platform_interface/lib/src/pigeon/messages.pigeon.dart index 9420915342de..034242fe27b6 100644 --- a/packages/firebase_core/firebase_core_platform_interface/lib/src/pigeon/messages.pigeon.dart +++ b/packages/firebase_core/firebase_core_platform_interface/lib/src/pigeon/messages.pigeon.dart @@ -1,15 +1,11 @@ -// Copyright 2022, the Chromium project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -// Autogenerated from Pigeon (v3.2.0), do not edit directly. +// Autogenerated from Pigeon (v9.0.6), do not edit directly. // See also: https://pub.dev/packages/pigeon -// ignore_for_file: public_member_api_docs, non_constant_identifier_names, avoid_as, unused_import, unnecessary_parenthesis, prefer_null_aware_operators, omit_local_variable_types, unused_shown_name -// @dart = 2.12 +// ignore_for_file: public_member_api_docs, non_constant_identifier_names, avoid_as, unused_import, unnecessary_parenthesis, prefer_null_aware_operators, omit_local_variable_types, unused_shown_name, unnecessary_import + import 'dart:async'; -import 'dart:typed_data' show Uint8List, Int32List, Int64List, Float64List; +import 'dart:typed_data' show Float64List, Int32List, Int64List, Uint8List; -import 'package:flutter/foundation.dart' show WriteBuffer, ReadBuffer; +import 'package:flutter/foundation.dart' show ReadBuffer, WriteBuffer; import 'package:flutter/services.dart'; class PigeonFirebaseOptions { @@ -31,56 +27,69 @@ class PigeonFirebaseOptions { }); String apiKey; + String appId; + String messagingSenderId; + String projectId; + String? authDomain; + String? databaseURL; + String? storageBucket; + String? measurementId; + String? trackingId; + String? deepLinkURLScheme; + String? androidClientId; + String? iosClientId; + String? iosBundleId; + String? appGroupId; Object encode() { - final Map pigeonMap = {}; - pigeonMap['apiKey'] = apiKey; - pigeonMap['appId'] = appId; - pigeonMap['messagingSenderId'] = messagingSenderId; - pigeonMap['projectId'] = projectId; - pigeonMap['authDomain'] = authDomain; - pigeonMap['databaseURL'] = databaseURL; - pigeonMap['storageBucket'] = storageBucket; - pigeonMap['measurementId'] = measurementId; - pigeonMap['trackingId'] = trackingId; - pigeonMap['deepLinkURLScheme'] = deepLinkURLScheme; - pigeonMap['androidClientId'] = androidClientId; - pigeonMap['iosClientId'] = iosClientId; - pigeonMap['iosBundleId'] = iosBundleId; - pigeonMap['appGroupId'] = appGroupId; - return pigeonMap; + return [ + apiKey, + appId, + messagingSenderId, + projectId, + authDomain, + databaseURL, + storageBucket, + measurementId, + trackingId, + deepLinkURLScheme, + androidClientId, + iosClientId, + iosBundleId, + appGroupId, + ]; } - static PigeonFirebaseOptions decode(Object message) { - final Map pigeonMap = message as Map; + static PigeonFirebaseOptions decode(Object result) { + result as List; return PigeonFirebaseOptions( - apiKey: pigeonMap['apiKey']! as String, - appId: pigeonMap['appId']! as String, - messagingSenderId: pigeonMap['messagingSenderId']! as String, - projectId: pigeonMap['projectId']! as String, - authDomain: pigeonMap['authDomain'] as String?, - databaseURL: pigeonMap['databaseURL'] as String?, - storageBucket: pigeonMap['storageBucket'] as String?, - measurementId: pigeonMap['measurementId'] as String?, - trackingId: pigeonMap['trackingId'] as String?, - deepLinkURLScheme: pigeonMap['deepLinkURLScheme'] as String?, - androidClientId: pigeonMap['androidClientId'] as String?, - iosClientId: pigeonMap['iosClientId'] as String?, - iosBundleId: pigeonMap['iosBundleId'] as String?, - appGroupId: pigeonMap['appGroupId'] as String?, + apiKey: result[0]! as String, + appId: result[1]! as String, + messagingSenderId: result[2]! as String, + projectId: result[3]! as String, + authDomain: result[4] as String?, + databaseURL: result[5] as String?, + storageBucket: result[6] as String?, + measurementId: result[7] as String?, + trackingId: result[8] as String?, + deepLinkURLScheme: result[9] as String?, + androidClientId: result[10] as String?, + iosClientId: result[11] as String?, + iosBundleId: result[12] as String?, + appGroupId: result[13] as String?, ); } } @@ -94,29 +103,29 @@ class PigeonInitializeResponse { }); String name; + PigeonFirebaseOptions options; + bool? isAutomaticDataCollectionEnabled; + Map pluginConstants; Object encode() { - final Map pigeonMap = {}; - pigeonMap['name'] = name; - pigeonMap['options'] = options.encode(); - pigeonMap['isAutomaticDataCollectionEnabled'] = - isAutomaticDataCollectionEnabled; - pigeonMap['pluginConstants'] = pluginConstants; - return pigeonMap; + return [ + name, + options.encode(), + isAutomaticDataCollectionEnabled, + pluginConstants, + ]; } - static PigeonInitializeResponse decode(Object message) { - final Map pigeonMap = message as Map; + static PigeonInitializeResponse decode(Object result) { + result as List; return PigeonInitializeResponse( - name: pigeonMap['name']! as String, - options: PigeonFirebaseOptions.decode(pigeonMap['options']!), - isAutomaticDataCollectionEnabled: - pigeonMap['isAutomaticDataCollectionEnabled'] as bool?, - pluginConstants: (pigeonMap['pluginConstants'] as Map?)! - .cast(), + name: result[0]! as String, + options: PigeonFirebaseOptions.decode(result[1]! as List), + isAutomaticDataCollectionEnabled: result[2] as bool?, + pluginConstants: (result[3] as Map?)!.cast(), ); } } @@ -139,12 +148,10 @@ class _FirebaseCoreHostApiCodec extends StandardMessageCodec { @override Object? readValueOfType(int type, ReadBuffer buffer) { switch (type) { - case 128: + case 128: return PigeonFirebaseOptions.decode(readValue(buffer)!); - - case 129: + case 129: return PigeonInitializeResponse.decode(readValue(buffer)!); - default: return super.readValueOfType(type, buffer); } @@ -157,39 +164,34 @@ class FirebaseCoreHostApi { /// BinaryMessenger will be used which routes to the host platform. FirebaseCoreHostApi({BinaryMessenger? binaryMessenger}) : _binaryMessenger = binaryMessenger; - final BinaryMessenger? _binaryMessenger; static const MessageCodec codec = _FirebaseCoreHostApiCodec(); - Future initializeApp(String arg_appName, - PigeonFirebaseOptions arg_initializeAppRequest) async { + Future initializeApp(String arg_appName, PigeonFirebaseOptions arg_initializeAppRequest) async { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.FirebaseCoreHostApi.initializeApp', codec, binaryMessenger: _binaryMessenger); - final Map? replyMap = - await channel.send([arg_appName, arg_initializeAppRequest]) - as Map?; - if (replyMap == null) { + final List? replyList = + await channel.send([arg_appName, arg_initializeAppRequest]) as List?; + if (replyList == null) { throw PlatformException( code: 'channel-error', message: 'Unable to establish connection on channel.', ); - } else if (replyMap['error'] != null) { - final Map error = - (replyMap['error'] as Map?)!; + } else if (replyList.length > 1) { throw PlatformException( - code: (error['code'] as String?)!, - message: error['message'] as String?, - details: error['details'], + code: replyList[0]! as String, + message: replyList[1] as String?, + details: replyList[2], ); - } else if (replyMap['result'] == null) { + } else if (replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { - return (replyMap['result'] as PigeonInitializeResponse?)!; + return (replyList[0] as PigeonInitializeResponse?)!; } } @@ -197,29 +199,26 @@ class FirebaseCoreHostApi { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.FirebaseCoreHostApi.initializeCore', codec, binaryMessenger: _binaryMessenger); - final Map? replyMap = - await channel.send(null) as Map?; - if (replyMap == null) { + final List? replyList = + await channel.send(null) as List?; + if (replyList == null) { throw PlatformException( code: 'channel-error', message: 'Unable to establish connection on channel.', ); - } else if (replyMap['error'] != null) { - final Map error = - (replyMap['error'] as Map?)!; + } else if (replyList.length > 1) { throw PlatformException( - code: (error['code'] as String?)!, - message: error['message'] as String?, - details: error['details'], + code: replyList[0]! as String, + message: replyList[1] as String?, + details: replyList[2], ); - } else if (replyMap['result'] == null) { + } else if (replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { - return (replyMap['result'] as List?)! - .cast(); + return (replyList[0] as List?)!.cast(); } } @@ -227,93 +226,78 @@ class FirebaseCoreHostApi { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.FirebaseCoreHostApi.optionsFromResource', codec, binaryMessenger: _binaryMessenger); - final Map? replyMap = - await channel.send(null) as Map?; - if (replyMap == null) { + final List? replyList = + await channel.send(null) as List?; + if (replyList == null) { throw PlatformException( code: 'channel-error', message: 'Unable to establish connection on channel.', ); - } else if (replyMap['error'] != null) { - final Map error = - (replyMap['error'] as Map?)!; + } else if (replyList.length > 1) { throw PlatformException( - code: (error['code'] as String?)!, - message: error['message'] as String?, - details: error['details'], + code: replyList[0]! as String, + message: replyList[1] as String?, + details: replyList[2], ); - } else if (replyMap['result'] == null) { + } else if (replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { - return (replyMap['result'] as PigeonFirebaseOptions?)!; + return (replyList[0] as PigeonFirebaseOptions?)!; } } } -class _FirebaseAppHostApiCodec extends StandardMessageCodec { - const _FirebaseAppHostApiCodec(); -} - class FirebaseAppHostApi { /// Constructor for [FirebaseAppHostApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. FirebaseAppHostApi({BinaryMessenger? binaryMessenger}) : _binaryMessenger = binaryMessenger; - final BinaryMessenger? _binaryMessenger; - static const MessageCodec codec = _FirebaseAppHostApiCodec(); + static const MessageCodec codec = StandardMessageCodec(); - Future setAutomaticDataCollectionEnabled( - String arg_appName, bool arg_enabled) async { + Future setAutomaticDataCollectionEnabled(String arg_appName, bool arg_enabled) async { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.FirebaseAppHostApi.setAutomaticDataCollectionEnabled', - codec, + 'dev.flutter.pigeon.FirebaseAppHostApi.setAutomaticDataCollectionEnabled', codec, binaryMessenger: _binaryMessenger); - final Map? replyMap = await channel - .send([arg_appName, arg_enabled]) as Map?; - if (replyMap == null) { + final List? replyList = + await channel.send([arg_appName, arg_enabled]) as List?; + if (replyList == null) { throw PlatformException( code: 'channel-error', message: 'Unable to establish connection on channel.', ); - } else if (replyMap['error'] != null) { - final Map error = - (replyMap['error'] as Map?)!; + } else if (replyList.length > 1) { throw PlatformException( - code: (error['code'] as String?)!, - message: error['message'] as String?, - details: error['details'], + code: replyList[0]! as String, + message: replyList[1] as String?, + details: replyList[2], ); } else { return; } } - Future setAutomaticResourceManagementEnabled( - String arg_appName, bool arg_enabled) async { + Future setAutomaticResourceManagementEnabled(String arg_appName, bool arg_enabled) async { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.FirebaseAppHostApi.setAutomaticResourceManagementEnabled', - codec, + 'dev.flutter.pigeon.FirebaseAppHostApi.setAutomaticResourceManagementEnabled', codec, binaryMessenger: _binaryMessenger); - final Map? replyMap = await channel - .send([arg_appName, arg_enabled]) as Map?; - if (replyMap == null) { + final List? replyList = + await channel.send([arg_appName, arg_enabled]) as List?; + if (replyList == null) { throw PlatformException( code: 'channel-error', message: 'Unable to establish connection on channel.', ); - } else if (replyMap['error'] != null) { - final Map error = - (replyMap['error'] as Map?)!; + } else if (replyList.length > 1) { throw PlatformException( - code: (error['code'] as String?)!, - message: error['message'] as String?, - details: error['details'], + code: replyList[0]! as String, + message: replyList[1] as String?, + details: replyList[2], ); } else { return; @@ -324,20 +308,18 @@ class FirebaseAppHostApi { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.FirebaseAppHostApi.delete', codec, binaryMessenger: _binaryMessenger); - final Map? replyMap = - await channel.send([arg_appName]) as Map?; - if (replyMap == null) { + final List? replyList = + await channel.send([arg_appName]) as List?; + if (replyList == null) { throw PlatformException( code: 'channel-error', message: 'Unable to establish connection on channel.', ); - } else if (replyMap['error'] != null) { - final Map error = - (replyMap['error'] as Map?)!; + } else if (replyList.length > 1) { throw PlatformException( - code: (error['code'] as String?)!, - message: error['message'] as String?, - details: error['details'], + code: replyList[0]! as String, + message: replyList[1] as String?, + details: replyList[2], ); } else { return; diff --git a/packages/firebase_core/firebase_core_platform_interface/lib/src/pigeon/test_api.dart b/packages/firebase_core/firebase_core_platform_interface/lib/src/pigeon/test_api.dart index 95751f138e27..617ae9eb93ee 100644 --- a/packages/firebase_core/firebase_core_platform_interface/lib/src/pigeon/test_api.dart +++ b/packages/firebase_core/firebase_core_platform_interface/lib/src/pigeon/test_api.dart @@ -1,15 +1,10 @@ -// Copyright 2022, the Chromium project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -// Autogenerated from Pigeon (v3.2.0), do not edit directly. +// Autogenerated from Pigeon (v9.0.6), do not edit directly. // See also: https://pub.dev/packages/pigeon -// ignore_for_file: public_member_api_docs, non_constant_identifier_names, avoid_as, unused_import, unnecessary_parenthesis +// ignore_for_file: public_member_api_docs, non_constant_identifier_names, avoid_as, unused_import, unnecessary_parenthesis, unnecessary_import // ignore_for_file: avoid_relative_lib_imports -// @dart = 2.12 import 'dart:async'; -import 'dart:typed_data' show Uint8List, Int32List, Int64List, Float64List; -import 'package:flutter/foundation.dart' show WriteBuffer, ReadBuffer; +import 'dart:typed_data' show Float64List, Int32List, Int64List, Uint8List; +import 'package:flutter/foundation.dart' show ReadBuffer, WriteBuffer; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; @@ -33,12 +28,10 @@ class _TestFirebaseCoreHostApiCodec extends StandardMessageCodec { @override Object? readValueOfType(int type, ReadBuffer buffer) { switch (type) { - case 128: + case 128: return PigeonFirebaseOptions.decode(readValue(buffer)!); - - case 129: + case 129: return PigeonInitializeResponse.decode(readValue(buffer)!); - default: return super.readValueOfType(type, buffer); } @@ -48,12 +41,13 @@ class _TestFirebaseCoreHostApiCodec extends StandardMessageCodec { abstract class TestFirebaseCoreHostApi { static const MessageCodec codec = _TestFirebaseCoreHostApiCodec(); - Future initializeApp( - String appName, PigeonFirebaseOptions initializeAppRequest); + Future initializeApp(String appName, PigeonFirebaseOptions initializeAppRequest); + Future> initializeCore(); + Future optionsFromResource(); - static void setup(TestFirebaseCoreHostApi? api, - {BinaryMessenger? binaryMessenger}) { + + static void setup(TestFirebaseCoreHostApi? api, {BinaryMessenger? binaryMessenger}) { { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.FirebaseCoreHostApi.initializeApp', codec, @@ -63,18 +57,16 @@ abstract class TestFirebaseCoreHostApi { } else { channel.setMockMessageHandler((Object? message) async { assert(message != null, - 'Argument for dev.flutter.pigeon.FirebaseCoreHostApi.initializeApp was null.'); + 'Argument for dev.flutter.pigeon.FirebaseCoreHostApi.initializeApp was null.'); final List args = (message as List?)!; final String? arg_appName = (args[0] as String?); assert(arg_appName != null, 'Argument for dev.flutter.pigeon.FirebaseCoreHostApi.initializeApp was null, expected non-null String.'); - final PigeonFirebaseOptions? arg_initializeAppRequest = - (args[1] as PigeonFirebaseOptions?); + final PigeonFirebaseOptions? arg_initializeAppRequest = (args[1] as PigeonFirebaseOptions?); assert(arg_initializeAppRequest != null, 'Argument for dev.flutter.pigeon.FirebaseCoreHostApi.initializeApp was null, expected non-null PigeonFirebaseOptions.'); - final PigeonInitializeResponse output = - await api.initializeApp(arg_appName!, arg_initializeAppRequest!); - return {'result': output}; + final PigeonInitializeResponse output = await api.initializeApp(arg_appName!, arg_initializeAppRequest!); + return [output]; }); } } @@ -87,9 +79,8 @@ abstract class TestFirebaseCoreHostApi { } else { channel.setMockMessageHandler((Object? message) async { // ignore message - final List output = - await api.initializeCore(); - return {'result': output}; + final List output = await api.initializeCore(); + return [output]; }); } } @@ -103,37 +94,33 @@ abstract class TestFirebaseCoreHostApi { channel.setMockMessageHandler((Object? message) async { // ignore message final PigeonFirebaseOptions output = await api.optionsFromResource(); - return {'result': output}; + return [output]; }); } } } } -class _TestFirebaseAppHostApiCodec extends StandardMessageCodec { - const _TestFirebaseAppHostApiCodec(); -} - abstract class TestFirebaseAppHostApi { - static const MessageCodec codec = _TestFirebaseAppHostApiCodec(); + static const MessageCodec codec = StandardMessageCodec(); Future setAutomaticDataCollectionEnabled(String appName, bool enabled); - Future setAutomaticResourceManagementEnabled( - String appName, bool enabled); + + Future setAutomaticResourceManagementEnabled(String appName, bool enabled); + Future delete(String appName); - static void setup(TestFirebaseAppHostApi? api, - {BinaryMessenger? binaryMessenger}) { + + static void setup(TestFirebaseAppHostApi? api, {BinaryMessenger? binaryMessenger}) { { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.FirebaseAppHostApi.setAutomaticDataCollectionEnabled', - codec, + 'dev.flutter.pigeon.FirebaseAppHostApi.setAutomaticDataCollectionEnabled', codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMockMessageHandler(null); } else { channel.setMockMessageHandler((Object? message) async { assert(message != null, - 'Argument for dev.flutter.pigeon.FirebaseAppHostApi.setAutomaticDataCollectionEnabled was null.'); + 'Argument for dev.flutter.pigeon.FirebaseAppHostApi.setAutomaticDataCollectionEnabled was null.'); final List args = (message as List?)!; final String? arg_appName = (args[0] as String?); assert(arg_appName != null, @@ -141,23 +128,21 @@ abstract class TestFirebaseAppHostApi { final bool? arg_enabled = (args[1] as bool?); assert(arg_enabled != null, 'Argument for dev.flutter.pigeon.FirebaseAppHostApi.setAutomaticDataCollectionEnabled was null, expected non-null bool.'); - await api.setAutomaticDataCollectionEnabled( - arg_appName!, arg_enabled!); - return {}; + await api.setAutomaticDataCollectionEnabled(arg_appName!, arg_enabled!); + return []; }); } } { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.FirebaseAppHostApi.setAutomaticResourceManagementEnabled', - codec, + 'dev.flutter.pigeon.FirebaseAppHostApi.setAutomaticResourceManagementEnabled', codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMockMessageHandler(null); } else { channel.setMockMessageHandler((Object? message) async { assert(message != null, - 'Argument for dev.flutter.pigeon.FirebaseAppHostApi.setAutomaticResourceManagementEnabled was null.'); + 'Argument for dev.flutter.pigeon.FirebaseAppHostApi.setAutomaticResourceManagementEnabled was null.'); final List args = (message as List?)!; final String? arg_appName = (args[0] as String?); assert(arg_appName != null, @@ -165,9 +150,8 @@ abstract class TestFirebaseAppHostApi { final bool? arg_enabled = (args[1] as bool?); assert(arg_enabled != null, 'Argument for dev.flutter.pigeon.FirebaseAppHostApi.setAutomaticResourceManagementEnabled was null, expected non-null bool.'); - await api.setAutomaticResourceManagementEnabled( - arg_appName!, arg_enabled!); - return {}; + await api.setAutomaticResourceManagementEnabled(arg_appName!, arg_enabled!); + return []; }); } } @@ -180,13 +164,13 @@ abstract class TestFirebaseAppHostApi { } else { channel.setMockMessageHandler((Object? message) async { assert(message != null, - 'Argument for dev.flutter.pigeon.FirebaseAppHostApi.delete was null.'); + 'Argument for dev.flutter.pigeon.FirebaseAppHostApi.delete was null.'); final List args = (message as List?)!; final String? arg_appName = (args[0] as String?); assert(arg_appName != null, 'Argument for dev.flutter.pigeon.FirebaseAppHostApi.delete was null, expected non-null String.'); await api.delete(arg_appName!); - return {}; + return []; }); } } From f40b408e905a674f3365051cb1f20c9512454a5b Mon Sep 17 00:00:00 2001 From: Guillaume Bernos Date: Tue, 14 Mar 2023 14:32:55 +0100 Subject: [PATCH 18/65] feat(core, windows): update pigeon --- .../core/GeneratedAndroidFirebaseCore.java | 51 ++++-- .../firebase_core/ios/Classes/messages.g.h | 91 +++++----- .../firebase_core/ios/Classes/messages.g.m | 164 +++++++++++------- .../windows/firebase_core_plugin.cpp | 4 +- .../windows/firebase_core_plugin.h | 4 +- .../lib/src/pigeon/messages.pigeon.dart | 42 +++-- .../lib/src/pigeon/test_api.dart | 45 +++-- 7 files changed, 239 insertions(+), 162 deletions(-) diff --git a/packages/firebase_core/firebase_core/android/src/main/java/io/flutter/plugins/firebase/core/GeneratedAndroidFirebaseCore.java b/packages/firebase_core/firebase_core/android/src/main/java/io/flutter/plugins/firebase/core/GeneratedAndroidFirebaseCore.java index c19c5b8b4ca3..5710a21f0950 100644 --- a/packages/firebase_core/firebase_core/android/src/main/java/io/flutter/plugins/firebase/core/GeneratedAndroidFirebaseCore.java +++ b/packages/firebase_core/firebase_core/android/src/main/java/io/flutter/plugins/firebase/core/GeneratedAndroidFirebaseCore.java @@ -13,9 +13,6 @@ import java.io.ByteArrayOutputStream; import java.nio.ByteBuffer; import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; import java.util.List; import java.util.Map; @@ -28,7 +25,7 @@ private static ArrayList wrapError(@NonNull Throwable exception) { errorList.add(exception.toString()); errorList.add(exception.getClass().getSimpleName()); errorList.add( - "Cause: " + exception.getCause() + ", Stacktrace: " + Log.getStackTraceString(exception)); + "Cause: " + exception.getCause() + ", Stacktrace: " + Log.getStackTraceString(exception)); return errorList; } @@ -472,7 +469,8 @@ ArrayList toList() { Object name = list.get(0); pigeonResult.setName((String) name); Object options = list.get(1); - pigeonResult.setOptions((options == null) ? null : PigeonFirebaseOptions.fromList((ArrayList) options)); + pigeonResult.setOptions( + (options == null) ? null : PigeonFirebaseOptions.fromList((ArrayList) options)); Object isAutomaticDataCollectionEnabled = list.get(2); pigeonResult.setIsAutomaticDataCollectionEnabled((Boolean) isAutomaticDataCollectionEnabled); Object pluginConstants = list.get(3); @@ -521,7 +519,10 @@ protected void writeValue(@NonNull ByteArrayOutputStream stream, Object value) { /** Generated interface from Pigeon that represents a handler of messages from Flutter. */ public interface FirebaseCoreHostApi { - void initializeApp(@NonNull String appName, @NonNull PigeonFirebaseOptions initializeAppRequest, Result result); + void initializeApp( + @NonNull String appName, + @NonNull PigeonFirebaseOptions initializeAppRequest, + Result result); void initializeCore(Result> result); @@ -531,12 +532,17 @@ public interface FirebaseCoreHostApi { static MessageCodec getCodec() { return FirebaseCoreHostApiCodec.INSTANCE; } - /**Sets up an instance of `FirebaseCoreHostApi` to handle messages through the `binaryMessenger`. */ + /** + * Sets up an instance of `FirebaseCoreHostApi` to handle messages through the + * `binaryMessenger`. + */ static void setup(BinaryMessenger binaryMessenger, FirebaseCoreHostApi api) { { BasicMessageChannel channel = new BasicMessageChannel<>( - binaryMessenger, "dev.flutter.pigeon.FirebaseCoreHostApi.initializeApp", getCodec()); + binaryMessenger, + "dev.flutter.pigeon.FirebaseCoreHostApi.initializeApp", + getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { @@ -548,7 +554,8 @@ static void setup(BinaryMessenger binaryMessenger, FirebaseCoreHostApi api) { if (appNameArg == null) { throw new NullPointerException("appNameArg unexpectedly null."); } - PigeonFirebaseOptions initializeAppRequestArg = (PigeonFirebaseOptions) args.get(1); + PigeonFirebaseOptions initializeAppRequestArg = + (PigeonFirebaseOptions) args.get(1); if (initializeAppRequestArg == null) { throw new NullPointerException("initializeAppRequestArg unexpectedly null."); } @@ -578,7 +585,9 @@ public void error(Throwable error) { { BasicMessageChannel channel = new BasicMessageChannel<>( - binaryMessenger, "dev.flutter.pigeon.FirebaseCoreHostApi.initializeCore", getCodec()); + binaryMessenger, + "dev.flutter.pigeon.FirebaseCoreHostApi.initializeCore", + getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { @@ -610,7 +619,9 @@ public void error(Throwable error) { { BasicMessageChannel channel = new BasicMessageChannel<>( - binaryMessenger, "dev.flutter.pigeon.FirebaseCoreHostApi.optionsFromResource", getCodec()); + binaryMessenger, + "dev.flutter.pigeon.FirebaseCoreHostApi.optionsFromResource", + getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { @@ -644,9 +655,11 @@ public void error(Throwable error) { /** Generated interface from Pigeon that represents a handler of messages from Flutter. */ public interface FirebaseAppHostApi { - void setAutomaticDataCollectionEnabled(@NonNull String appName, @NonNull Boolean enabled, Result result); + void setAutomaticDataCollectionEnabled( + @NonNull String appName, @NonNull Boolean enabled, Result result); - void setAutomaticResourceManagementEnabled(@NonNull String appName, @NonNull Boolean enabled, Result result); + void setAutomaticResourceManagementEnabled( + @NonNull String appName, @NonNull Boolean enabled, Result result); void delete(@NonNull String appName, Result result); @@ -654,12 +667,16 @@ public interface FirebaseAppHostApi { static MessageCodec getCodec() { return new StandardMessageCodec(); } - /**Sets up an instance of `FirebaseAppHostApi` to handle messages through the `binaryMessenger`. */ + /** + * Sets up an instance of `FirebaseAppHostApi` to handle messages through the `binaryMessenger`. + */ static void setup(BinaryMessenger binaryMessenger, FirebaseAppHostApi api) { { BasicMessageChannel channel = new BasicMessageChannel<>( - binaryMessenger, "dev.flutter.pigeon.FirebaseAppHostApi.setAutomaticDataCollectionEnabled", getCodec()); + binaryMessenger, + "dev.flutter.pigeon.FirebaseAppHostApi.setAutomaticDataCollectionEnabled", + getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { @@ -701,7 +718,9 @@ public void error(Throwable error) { { BasicMessageChannel channel = new BasicMessageChannel<>( - binaryMessenger, "dev.flutter.pigeon.FirebaseAppHostApi.setAutomaticResourceManagementEnabled", getCodec()); + binaryMessenger, + "dev.flutter.pigeon.FirebaseAppHostApi.setAutomaticResourceManagementEnabled", + getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { diff --git a/packages/firebase_core/firebase_core/ios/Classes/messages.g.h b/packages/firebase_core/firebase_core/ios/Classes/messages.g.h index 621dc1a79ccf..9a98f1fe9b10 100644 --- a/packages/firebase_core/firebase_core/ios/Classes/messages.g.h +++ b/packages/firebase_core/firebase_core/ios/Classes/messages.g.h @@ -17,68 +17,79 @@ NS_ASSUME_NONNULL_BEGIN /// `init` unavailable to enforce nonnull fields, see the `make` class method. - (instancetype)init NS_UNAVAILABLE; + (instancetype)makeWithApiKey:(NSString *)apiKey - appId:(NSString *)appId - messagingSenderId:(NSString *)messagingSenderId - projectId:(NSString *)projectId - authDomain:(nullable NSString *)authDomain - databaseURL:(nullable NSString *)databaseURL - storageBucket:(nullable NSString *)storageBucket - measurementId:(nullable NSString *)measurementId - trackingId:(nullable NSString *)trackingId - deepLinkURLScheme:(nullable NSString *)deepLinkURLScheme - androidClientId:(nullable NSString *)androidClientId - iosClientId:(nullable NSString *)iosClientId - iosBundleId:(nullable NSString *)iosBundleId - appGroupId:(nullable NSString *)appGroupId; -@property(nonatomic, copy) NSString * apiKey; -@property(nonatomic, copy) NSString * appId; -@property(nonatomic, copy) NSString * messagingSenderId; -@property(nonatomic, copy) NSString * projectId; -@property(nonatomic, copy, nullable) NSString * authDomain; -@property(nonatomic, copy, nullable) NSString * databaseURL; -@property(nonatomic, copy, nullable) NSString * storageBucket; -@property(nonatomic, copy, nullable) NSString * measurementId; -@property(nonatomic, copy, nullable) NSString * trackingId; -@property(nonatomic, copy, nullable) NSString * deepLinkURLScheme; -@property(nonatomic, copy, nullable) NSString * androidClientId; -@property(nonatomic, copy, nullable) NSString * iosClientId; -@property(nonatomic, copy, nullable) NSString * iosBundleId; -@property(nonatomic, copy, nullable) NSString * appGroupId; + appId:(NSString *)appId + messagingSenderId:(NSString *)messagingSenderId + projectId:(NSString *)projectId + authDomain:(nullable NSString *)authDomain + databaseURL:(nullable NSString *)databaseURL + storageBucket:(nullable NSString *)storageBucket + measurementId:(nullable NSString *)measurementId + trackingId:(nullable NSString *)trackingId + deepLinkURLScheme:(nullable NSString *)deepLinkURLScheme + androidClientId:(nullable NSString *)androidClientId + iosClientId:(nullable NSString *)iosClientId + iosBundleId:(nullable NSString *)iosBundleId + appGroupId:(nullable NSString *)appGroupId; +@property(nonatomic, copy) NSString *apiKey; +@property(nonatomic, copy) NSString *appId; +@property(nonatomic, copy) NSString *messagingSenderId; +@property(nonatomic, copy) NSString *projectId; +@property(nonatomic, copy, nullable) NSString *authDomain; +@property(nonatomic, copy, nullable) NSString *databaseURL; +@property(nonatomic, copy, nullable) NSString *storageBucket; +@property(nonatomic, copy, nullable) NSString *measurementId; +@property(nonatomic, copy, nullable) NSString *trackingId; +@property(nonatomic, copy, nullable) NSString *deepLinkURLScheme; +@property(nonatomic, copy, nullable) NSString *androidClientId; +@property(nonatomic, copy, nullable) NSString *iosClientId; +@property(nonatomic, copy, nullable) NSString *iosBundleId; +@property(nonatomic, copy, nullable) NSString *appGroupId; @end @interface PigeonInitializeResponse : NSObject /// `init` unavailable to enforce nonnull fields, see the `make` class method. - (instancetype)init NS_UNAVAILABLE; + (instancetype)makeWithName:(NSString *)name - options:(PigeonFirebaseOptions *)options + options:(PigeonFirebaseOptions *)options isAutomaticDataCollectionEnabled:(nullable NSNumber *)isAutomaticDataCollectionEnabled - pluginConstants:(NSDictionary *)pluginConstants; -@property(nonatomic, copy) NSString * name; -@property(nonatomic, strong) PigeonFirebaseOptions * options; -@property(nonatomic, strong, nullable) NSNumber * isAutomaticDataCollectionEnabled; -@property(nonatomic, strong) NSDictionary * pluginConstants; + pluginConstants:(NSDictionary *)pluginConstants; +@property(nonatomic, copy) NSString *name; +@property(nonatomic, strong) PigeonFirebaseOptions *options; +@property(nonatomic, strong, nullable) NSNumber *isAutomaticDataCollectionEnabled; +@property(nonatomic, strong) NSDictionary *pluginConstants; @end /// The codec used by FirebaseCoreHostApi. NSObject *FirebaseCoreHostApiGetCodec(void); @protocol FirebaseCoreHostApi -- (void)initializeAppAppName:(NSString *)appName initializeAppRequest:(PigeonFirebaseOptions *)initializeAppRequest completion:(void (^)(PigeonInitializeResponse *_Nullable, FlutterError *_Nullable))completion; -- (void)initializeCoreWithCompletion:(void (^)(NSArray *_Nullable, FlutterError *_Nullable))completion; -- (void)optionsFromResourceWithCompletion:(void (^)(PigeonFirebaseOptions *_Nullable, FlutterError *_Nullable))completion; +- (void)initializeAppAppName:(NSString *)appName + initializeAppRequest:(PigeonFirebaseOptions *)initializeAppRequest + completion:(void (^)(PigeonInitializeResponse *_Nullable, + FlutterError *_Nullable))completion; +- (void)initializeCoreWithCompletion:(void (^)(NSArray *_Nullable, + FlutterError *_Nullable))completion; +- (void)optionsFromResourceWithCompletion:(void (^)(PigeonFirebaseOptions *_Nullable, + FlutterError *_Nullable))completion; @end -extern void FirebaseCoreHostApiSetup(id binaryMessenger, NSObject *_Nullable api); +extern void FirebaseCoreHostApiSetup(id binaryMessenger, + NSObject *_Nullable api); /// The codec used by FirebaseAppHostApi. NSObject *FirebaseAppHostApiGetCodec(void); @protocol FirebaseAppHostApi -- (void)setAutomaticDataCollectionEnabledAppName:(NSString *)appName enabled:(NSNumber *)enabled completion:(void (^)(FlutterError *_Nullable))completion; -- (void)setAutomaticResourceManagementEnabledAppName:(NSString *)appName enabled:(NSNumber *)enabled completion:(void (^)(FlutterError *_Nullable))completion; +- (void)setAutomaticDataCollectionEnabledAppName:(NSString *)appName + enabled:(NSNumber *)enabled + completion:(void (^)(FlutterError *_Nullable))completion; +- (void)setAutomaticResourceManagementEnabledAppName:(NSString *)appName + enabled:(NSNumber *)enabled + completion:(void (^)(FlutterError *_Nullable))completion; - (void)deleteAppName:(NSString *)appName completion:(void (^)(FlutterError *_Nullable))completion; @end -extern void FirebaseAppHostApiSetup(id binaryMessenger, NSObject *_Nullable api); +extern void FirebaseAppHostApiSetup(id binaryMessenger, + NSObject *_Nullable api); NS_ASSUME_NONNULL_END diff --git a/packages/firebase_core/firebase_core/ios/Classes/messages.g.m b/packages/firebase_core/firebase_core/ios/Classes/messages.g.m index 8d6cda3d45af..f1bc91f423b8 100644 --- a/packages/firebase_core/firebase_core/ios/Classes/messages.g.m +++ b/packages/firebase_core/firebase_core/ios/Classes/messages.g.m @@ -35,20 +35,20 @@ - (NSArray *)toList; @implementation PigeonFirebaseOptions + (instancetype)makeWithApiKey:(NSString *)apiKey - appId:(NSString *)appId - messagingSenderId:(NSString *)messagingSenderId - projectId:(NSString *)projectId - authDomain:(nullable NSString *)authDomain - databaseURL:(nullable NSString *)databaseURL - storageBucket:(nullable NSString *)storageBucket - measurementId:(nullable NSString *)measurementId - trackingId:(nullable NSString *)trackingId - deepLinkURLScheme:(nullable NSString *)deepLinkURLScheme - androidClientId:(nullable NSString *)androidClientId - iosClientId:(nullable NSString *)iosClientId - iosBundleId:(nullable NSString *)iosBundleId - appGroupId:(nullable NSString *)appGroupId { - PigeonFirebaseOptions* pigeonResult = [[PigeonFirebaseOptions alloc] init]; + appId:(NSString *)appId + messagingSenderId:(NSString *)messagingSenderId + projectId:(NSString *)projectId + authDomain:(nullable NSString *)authDomain + databaseURL:(nullable NSString *)databaseURL + storageBucket:(nullable NSString *)storageBucket + measurementId:(nullable NSString *)measurementId + trackingId:(nullable NSString *)trackingId + deepLinkURLScheme:(nullable NSString *)deepLinkURLScheme + androidClientId:(nullable NSString *)androidClientId + iosClientId:(nullable NSString *)iosClientId + iosBundleId:(nullable NSString *)iosBundleId + appGroupId:(nullable NSString *)appGroupId { + PigeonFirebaseOptions *pigeonResult = [[PigeonFirebaseOptions alloc] init]; pigeonResult.apiKey = apiKey; pigeonResult.appId = appId; pigeonResult.messagingSenderId = messagingSenderId; @@ -112,10 +112,10 @@ - (NSArray *)toList { @implementation PigeonInitializeResponse + (instancetype)makeWithName:(NSString *)name - options:(PigeonFirebaseOptions *)options + options:(PigeonFirebaseOptions *)options isAutomaticDataCollectionEnabled:(nullable NSNumber *)isAutomaticDataCollectionEnabled - pluginConstants:(NSDictionary *)pluginConstants { - PigeonInitializeResponse* pigeonResult = [[PigeonInitializeResponse alloc] init]; + pluginConstants:(NSDictionary *)pluginConstants { + PigeonInitializeResponse *pigeonResult = [[PigeonInitializeResponse alloc] init]; pigeonResult.name = name; pigeonResult.options = options; pigeonResult.isAutomaticDataCollectionEnabled = isAutomaticDataCollectionEnabled; @@ -126,7 +126,8 @@ + (PigeonInitializeResponse *)fromList:(NSArray *)list { PigeonInitializeResponse *pigeonResult = [[PigeonInitializeResponse alloc] init]; pigeonResult.name = GetNullableObjectAtIndex(list, 0); NSAssert(pigeonResult.name != nil, @""); - pigeonResult.options = [PigeonFirebaseOptions nullableFromList:(GetNullableObjectAtIndex(list, 1))]; + pigeonResult.options = + [PigeonFirebaseOptions nullableFromList:(GetNullableObjectAtIndex(list, 1))]; NSAssert(pigeonResult.options != nil, @""); pigeonResult.isAutomaticDataCollectionEnabled = GetNullableObjectAtIndex(list, 2); pigeonResult.pluginConstants = GetNullableObjectAtIndex(list, 3); @@ -151,9 +152,9 @@ @interface FirebaseCoreHostApiCodecReader : FlutterStandardReader @implementation FirebaseCoreHostApiCodecReader - (nullable id)readValueOfType:(UInt8)type { switch (type) { - case 128: + case 128: return [PigeonFirebaseOptions fromList:[self readValue]]; - case 129: + case 129: return [PigeonInitializeResponse fromList:[self readValue]]; default: return [super readValueOfType:type]; @@ -192,43 +193,54 @@ - (FlutterStandardReader *)readerWithData:(NSData *)data { static FlutterStandardMessageCodec *sSharedObject = nil; static dispatch_once_t sPred = 0; dispatch_once(&sPred, ^{ - FirebaseCoreHostApiCodecReaderWriter *readerWriter = [[FirebaseCoreHostApiCodecReaderWriter alloc] init]; + FirebaseCoreHostApiCodecReaderWriter *readerWriter = + [[FirebaseCoreHostApiCodecReaderWriter alloc] init]; sSharedObject = [FlutterStandardMessageCodec codecWithReaderWriter:readerWriter]; }); return sSharedObject; } -void FirebaseCoreHostApiSetup(id binaryMessenger, NSObject *api) { +void FirebaseCoreHostApiSetup(id binaryMessenger, + NSObject *api) { { - FlutterBasicMessageChannel *channel = - [[FlutterBasicMessageChannel alloc] - initWithName:@"dev.flutter.pigeon.FirebaseCoreHostApi.initializeApp" + FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] + initWithName:@"dev.flutter.pigeon.FirebaseCoreHostApi.initializeApp" binaryMessenger:binaryMessenger - codec:FirebaseCoreHostApiGetCodec()]; + codec:FirebaseCoreHostApiGetCodec()]; if (api) { - NSCAssert([api respondsToSelector:@selector(initializeAppAppName:initializeAppRequest:completion:)], @"FirebaseCoreHostApi api (%@) doesn't respond to @selector(initializeAppAppName:initializeAppRequest:completion:)", api); + NSCAssert([api respondsToSelector:@selector(initializeAppAppName: + initializeAppRequest:completion:)], + @"FirebaseCoreHostApi api (%@) doesn't respond to " + @"@selector(initializeAppAppName:initializeAppRequest:completion:)", + api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; NSString *arg_appName = GetNullableObjectAtIndex(args, 0); PigeonFirebaseOptions *arg_initializeAppRequest = GetNullableObjectAtIndex(args, 1); - [api initializeAppAppName:arg_appName initializeAppRequest:arg_initializeAppRequest completion:^(PigeonInitializeResponse *_Nullable output, FlutterError *_Nullable error) { - callback(wrapResult(output, error)); - }]; + [api initializeAppAppName:arg_appName + initializeAppRequest:arg_initializeAppRequest + completion:^(PigeonInitializeResponse *_Nullable output, + FlutterError *_Nullable error) { + callback(wrapResult(output, error)); + }]; }]; } else { [channel setMessageHandler:nil]; } } { - FlutterBasicMessageChannel *channel = - [[FlutterBasicMessageChannel alloc] - initWithName:@"dev.flutter.pigeon.FirebaseCoreHostApi.initializeCore" + FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] + initWithName:@"dev.flutter.pigeon.FirebaseCoreHostApi.initializeCore" binaryMessenger:binaryMessenger - codec:FirebaseCoreHostApiGetCodec()]; + codec:FirebaseCoreHostApiGetCodec()]; if (api) { - NSCAssert([api respondsToSelector:@selector(initializeCoreWithCompletion:)], @"FirebaseCoreHostApi api (%@) doesn't respond to @selector(initializeCoreWithCompletion:)", api); + NSCAssert([api respondsToSelector:@selector(initializeCoreWithCompletion:)], + @"FirebaseCoreHostApi api (%@) doesn't respond to " + @"@selector(initializeCoreWithCompletion:)", + api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { - [api initializeCoreWithCompletion:^(NSArray *_Nullable output, FlutterError *_Nullable error) { + [api initializeCoreWithCompletion:^(NSArray *_Nullable output, + FlutterError *_Nullable error) { callback(wrapResult(output, error)); }]; }]; @@ -237,15 +249,18 @@ void FirebaseCoreHostApiSetup(id binaryMessenger, NSObje } } { - FlutterBasicMessageChannel *channel = - [[FlutterBasicMessageChannel alloc] - initWithName:@"dev.flutter.pigeon.FirebaseCoreHostApi.optionsFromResource" + FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] + initWithName:@"dev.flutter.pigeon.FirebaseCoreHostApi.optionsFromResource" binaryMessenger:binaryMessenger - codec:FirebaseCoreHostApiGetCodec()]; + codec:FirebaseCoreHostApiGetCodec()]; if (api) { - NSCAssert([api respondsToSelector:@selector(optionsFromResourceWithCompletion:)], @"FirebaseCoreHostApi api (%@) doesn't respond to @selector(optionsFromResourceWithCompletion:)", api); + NSCAssert([api respondsToSelector:@selector(optionsFromResourceWithCompletion:)], + @"FirebaseCoreHostApi api (%@) doesn't respond to " + @"@selector(optionsFromResourceWithCompletion:)", + api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { - [api optionsFromResourceWithCompletion:^(PigeonFirebaseOptions *_Nullable output, FlutterError *_Nullable error) { + [api optionsFromResourceWithCompletion:^(PigeonFirebaseOptions *_Nullable output, + FlutterError *_Nullable error) { callback(wrapResult(output, error)); }]; }]; @@ -260,61 +275,76 @@ void FirebaseCoreHostApiSetup(id binaryMessenger, NSObje return sSharedObject; } -void FirebaseAppHostApiSetup(id binaryMessenger, NSObject *api) { +void FirebaseAppHostApiSetup(id binaryMessenger, + NSObject *api) { { - FlutterBasicMessageChannel *channel = - [[FlutterBasicMessageChannel alloc] - initWithName:@"dev.flutter.pigeon.FirebaseAppHostApi.setAutomaticDataCollectionEnabled" + FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] + initWithName:@"dev.flutter.pigeon.FirebaseAppHostApi.setAutomaticDataCollectionEnabled" binaryMessenger:binaryMessenger - codec:FirebaseAppHostApiGetCodec()]; + codec:FirebaseAppHostApiGetCodec()]; if (api) { - NSCAssert([api respondsToSelector:@selector(setAutomaticDataCollectionEnabledAppName:enabled:completion:)], @"FirebaseAppHostApi api (%@) doesn't respond to @selector(setAutomaticDataCollectionEnabledAppName:enabled:completion:)", api); + NSCAssert([api respondsToSelector:@selector + (setAutomaticDataCollectionEnabledAppName:enabled:completion:)], + @"FirebaseAppHostApi api (%@) doesn't respond to " + @"@selector(setAutomaticDataCollectionEnabledAppName:enabled:completion:)", + api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; NSString *arg_appName = GetNullableObjectAtIndex(args, 0); NSNumber *arg_enabled = GetNullableObjectAtIndex(args, 1); - [api setAutomaticDataCollectionEnabledAppName:arg_appName enabled:arg_enabled completion:^(FlutterError *_Nullable error) { - callback(wrapResult(nil, error)); - }]; + [api setAutomaticDataCollectionEnabledAppName:arg_appName + enabled:arg_enabled + completion:^(FlutterError *_Nullable error) { + callback(wrapResult(nil, error)); + }]; }]; } else { [channel setMessageHandler:nil]; } } { - FlutterBasicMessageChannel *channel = - [[FlutterBasicMessageChannel alloc] - initWithName:@"dev.flutter.pigeon.FirebaseAppHostApi.setAutomaticResourceManagementEnabled" + FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] + initWithName: + @"dev.flutter.pigeon.FirebaseAppHostApi.setAutomaticResourceManagementEnabled" binaryMessenger:binaryMessenger - codec:FirebaseAppHostApiGetCodec()]; + codec:FirebaseAppHostApiGetCodec()]; if (api) { - NSCAssert([api respondsToSelector:@selector(setAutomaticResourceManagementEnabledAppName:enabled:completion:)], @"FirebaseAppHostApi api (%@) doesn't respond to @selector(setAutomaticResourceManagementEnabledAppName:enabled:completion:)", api); + NSCAssert([api respondsToSelector:@selector + (setAutomaticResourceManagementEnabledAppName:enabled:completion:)], + @"FirebaseAppHostApi api (%@) doesn't respond to " + @"@selector(setAutomaticResourceManagementEnabledAppName:enabled:completion:)", + api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; NSString *arg_appName = GetNullableObjectAtIndex(args, 0); NSNumber *arg_enabled = GetNullableObjectAtIndex(args, 1); - [api setAutomaticResourceManagementEnabledAppName:arg_appName enabled:arg_enabled completion:^(FlutterError *_Nullable error) { - callback(wrapResult(nil, error)); - }]; + [api setAutomaticResourceManagementEnabledAppName:arg_appName + enabled:arg_enabled + completion:^(FlutterError *_Nullable error) { + callback(wrapResult(nil, error)); + }]; }]; } else { [channel setMessageHandler:nil]; } } { - FlutterBasicMessageChannel *channel = - [[FlutterBasicMessageChannel alloc] - initWithName:@"dev.flutter.pigeon.FirebaseAppHostApi.delete" + FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] + initWithName:@"dev.flutter.pigeon.FirebaseAppHostApi.delete" binaryMessenger:binaryMessenger - codec:FirebaseAppHostApiGetCodec()]; + codec:FirebaseAppHostApiGetCodec()]; if (api) { - NSCAssert([api respondsToSelector:@selector(deleteAppName:completion:)], @"FirebaseAppHostApi api (%@) doesn't respond to @selector(deleteAppName:completion:)", api); + NSCAssert( + [api respondsToSelector:@selector(deleteAppName:completion:)], + @"FirebaseAppHostApi api (%@) doesn't respond to @selector(deleteAppName:completion:)", + api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; NSString *arg_appName = GetNullableObjectAtIndex(args, 0); - [api deleteAppName:arg_appName completion:^(FlutterError *_Nullable error) { - callback(wrapResult(nil, error)); - }]; + [api deleteAppName:arg_appName + completion:^(FlutterError *_Nullable error) { + callback(wrapResult(nil, error)); + }]; }]; } else { [channel setMessageHandler:nil]; diff --git a/packages/firebase_core/firebase_core/windows/firebase_core_plugin.cpp b/packages/firebase_core/firebase_core/windows/firebase_core_plugin.cpp index 7dd2b9945a72..03f7e887904c 100644 --- a/packages/firebase_core/firebase_core/windows/firebase_core_plugin.cpp +++ b/packages/firebase_core/firebase_core/windows/firebase_core_plugin.cpp @@ -2,11 +2,11 @@ // This must be included before many other Windows headers. #include + #include "firebase/app.h" // For getPlatformVersion; remove unless needed for your plugin implementation. #include - #include #include #include @@ -43,7 +43,7 @@ void FirebaseCorePlugin::HandleMethodCall( const flutter::MethodCall &method_call, std::unique_ptr> result) { if (method_call.method_name().compare("getPlatformVersion") == 0) { - App* app = App::Create(); + App *app = App::Create(); std::cout << static_cast(reinterpret_cast(app)); std::ostringstream version_stream; version_stream << "Windows "; diff --git a/packages/firebase_core/firebase_core/windows/firebase_core_plugin.h b/packages/firebase_core/firebase_core/windows/firebase_core_plugin.h index fe99490af2c2..52794b6a0e51 100644 --- a/packages/firebase_core/firebase_core/windows/firebase_core_plugin.h +++ b/packages/firebase_core/firebase_core/windows/firebase_core_plugin.h @@ -17,8 +17,8 @@ class FirebaseCorePlugin : public flutter::Plugin { virtual ~FirebaseCorePlugin(); // Disallow copy and assign. - FirebaseCorePlugin(const FirebaseCorePlugin&) = delete; - FirebaseCorePlugin& operator=(const FirebaseCorePlugin&) = delete; + FirebaseCorePlugin(const FirebaseCorePlugin &) = delete; + FirebaseCorePlugin &operator=(const FirebaseCorePlugin &) = delete; private: // Called when a method is called on this plugin's channel from Dart. diff --git a/packages/firebase_core/firebase_core_platform_interface/lib/src/pigeon/messages.pigeon.dart b/packages/firebase_core/firebase_core_platform_interface/lib/src/pigeon/messages.pigeon.dart index 034242fe27b6..9e0bd88c15d7 100644 --- a/packages/firebase_core/firebase_core_platform_interface/lib/src/pigeon/messages.pigeon.dart +++ b/packages/firebase_core/firebase_core_platform_interface/lib/src/pigeon/messages.pigeon.dart @@ -125,7 +125,8 @@ class PigeonInitializeResponse { name: result[0]! as String, options: PigeonFirebaseOptions.decode(result[1]! as List), isAutomaticDataCollectionEnabled: result[2] as bool?, - pluginConstants: (result[3] as Map?)!.cast(), + pluginConstants: + (result[3] as Map?)!.cast(), ); } } @@ -148,9 +149,9 @@ class _FirebaseCoreHostApiCodec extends StandardMessageCodec { @override Object? readValueOfType(int type, ReadBuffer buffer) { switch (type) { - case 128: + case 128: return PigeonFirebaseOptions.decode(readValue(buffer)!); - case 129: + case 129: return PigeonInitializeResponse.decode(readValue(buffer)!); default: return super.readValueOfType(type, buffer); @@ -168,12 +169,14 @@ class FirebaseCoreHostApi { static const MessageCodec codec = _FirebaseCoreHostApiCodec(); - Future initializeApp(String arg_appName, PigeonFirebaseOptions arg_initializeAppRequest) async { + Future initializeApp(String arg_appName, + PigeonFirebaseOptions arg_initializeAppRequest) async { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.FirebaseCoreHostApi.initializeApp', codec, binaryMessenger: _binaryMessenger); final List? replyList = - await channel.send([arg_appName, arg_initializeAppRequest]) as List?; + await channel.send([arg_appName, arg_initializeAppRequest]) + as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -199,8 +202,7 @@ class FirebaseCoreHostApi { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.FirebaseCoreHostApi.initializeCore', codec, binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send(null) as List?; + final List? replyList = await channel.send(null) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -218,7 +220,8 @@ class FirebaseCoreHostApi { message: 'Host platform returned null value for non-null return value.', ); } else { - return (replyList[0] as List?)!.cast(); + return (replyList[0] as List?)! + .cast(); } } @@ -226,8 +229,7 @@ class FirebaseCoreHostApi { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.FirebaseCoreHostApi.optionsFromResource', codec, binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send(null) as List?; + final List? replyList = await channel.send(null) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -260,12 +262,14 @@ class FirebaseAppHostApi { static const MessageCodec codec = StandardMessageCodec(); - Future setAutomaticDataCollectionEnabled(String arg_appName, bool arg_enabled) async { + Future setAutomaticDataCollectionEnabled( + String arg_appName, bool arg_enabled) async { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.FirebaseAppHostApi.setAutomaticDataCollectionEnabled', codec, + 'dev.flutter.pigeon.FirebaseAppHostApi.setAutomaticDataCollectionEnabled', + codec, binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send([arg_appName, arg_enabled]) as List?; + final List? replyList = await channel + .send([arg_appName, arg_enabled]) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -282,12 +286,14 @@ class FirebaseAppHostApi { } } - Future setAutomaticResourceManagementEnabled(String arg_appName, bool arg_enabled) async { + Future setAutomaticResourceManagementEnabled( + String arg_appName, bool arg_enabled) async { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.FirebaseAppHostApi.setAutomaticResourceManagementEnabled', codec, + 'dev.flutter.pigeon.FirebaseAppHostApi.setAutomaticResourceManagementEnabled', + codec, binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send([arg_appName, arg_enabled]) as List?; + final List? replyList = await channel + .send([arg_appName, arg_enabled]) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', diff --git a/packages/firebase_core/firebase_core_platform_interface/lib/src/pigeon/test_api.dart b/packages/firebase_core/firebase_core_platform_interface/lib/src/pigeon/test_api.dart index 617ae9eb93ee..0b9065036612 100644 --- a/packages/firebase_core/firebase_core_platform_interface/lib/src/pigeon/test_api.dart +++ b/packages/firebase_core/firebase_core_platform_interface/lib/src/pigeon/test_api.dart @@ -28,9 +28,9 @@ class _TestFirebaseCoreHostApiCodec extends StandardMessageCodec { @override Object? readValueOfType(int type, ReadBuffer buffer) { switch (type) { - case 128: + case 128: return PigeonFirebaseOptions.decode(readValue(buffer)!); - case 129: + case 129: return PigeonInitializeResponse.decode(readValue(buffer)!); default: return super.readValueOfType(type, buffer); @@ -41,13 +41,15 @@ class _TestFirebaseCoreHostApiCodec extends StandardMessageCodec { abstract class TestFirebaseCoreHostApi { static const MessageCodec codec = _TestFirebaseCoreHostApiCodec(); - Future initializeApp(String appName, PigeonFirebaseOptions initializeAppRequest); + Future initializeApp( + String appName, PigeonFirebaseOptions initializeAppRequest); Future> initializeCore(); Future optionsFromResource(); - static void setup(TestFirebaseCoreHostApi? api, {BinaryMessenger? binaryMessenger}) { + static void setup(TestFirebaseCoreHostApi? api, + {BinaryMessenger? binaryMessenger}) { { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.FirebaseCoreHostApi.initializeApp', codec, @@ -57,15 +59,17 @@ abstract class TestFirebaseCoreHostApi { } else { channel.setMockMessageHandler((Object? message) async { assert(message != null, - 'Argument for dev.flutter.pigeon.FirebaseCoreHostApi.initializeApp was null.'); + 'Argument for dev.flutter.pigeon.FirebaseCoreHostApi.initializeApp was null.'); final List args = (message as List?)!; final String? arg_appName = (args[0] as String?); assert(arg_appName != null, 'Argument for dev.flutter.pigeon.FirebaseCoreHostApi.initializeApp was null, expected non-null String.'); - final PigeonFirebaseOptions? arg_initializeAppRequest = (args[1] as PigeonFirebaseOptions?); + final PigeonFirebaseOptions? arg_initializeAppRequest = + (args[1] as PigeonFirebaseOptions?); assert(arg_initializeAppRequest != null, 'Argument for dev.flutter.pigeon.FirebaseCoreHostApi.initializeApp was null, expected non-null PigeonFirebaseOptions.'); - final PigeonInitializeResponse output = await api.initializeApp(arg_appName!, arg_initializeAppRequest!); + final PigeonInitializeResponse output = + await api.initializeApp(arg_appName!, arg_initializeAppRequest!); return [output]; }); } @@ -79,7 +83,8 @@ abstract class TestFirebaseCoreHostApi { } else { channel.setMockMessageHandler((Object? message) async { // ignore message - final List output = await api.initializeCore(); + final List output = + await api.initializeCore(); return [output]; }); } @@ -106,21 +111,24 @@ abstract class TestFirebaseAppHostApi { Future setAutomaticDataCollectionEnabled(String appName, bool enabled); - Future setAutomaticResourceManagementEnabled(String appName, bool enabled); + Future setAutomaticResourceManagementEnabled( + String appName, bool enabled); Future delete(String appName); - static void setup(TestFirebaseAppHostApi? api, {BinaryMessenger? binaryMessenger}) { + static void setup(TestFirebaseAppHostApi? api, + {BinaryMessenger? binaryMessenger}) { { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.FirebaseAppHostApi.setAutomaticDataCollectionEnabled', codec, + 'dev.flutter.pigeon.FirebaseAppHostApi.setAutomaticDataCollectionEnabled', + codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMockMessageHandler(null); } else { channel.setMockMessageHandler((Object? message) async { assert(message != null, - 'Argument for dev.flutter.pigeon.FirebaseAppHostApi.setAutomaticDataCollectionEnabled was null.'); + 'Argument for dev.flutter.pigeon.FirebaseAppHostApi.setAutomaticDataCollectionEnabled was null.'); final List args = (message as List?)!; final String? arg_appName = (args[0] as String?); assert(arg_appName != null, @@ -128,21 +136,23 @@ abstract class TestFirebaseAppHostApi { final bool? arg_enabled = (args[1] as bool?); assert(arg_enabled != null, 'Argument for dev.flutter.pigeon.FirebaseAppHostApi.setAutomaticDataCollectionEnabled was null, expected non-null bool.'); - await api.setAutomaticDataCollectionEnabled(arg_appName!, arg_enabled!); + await api.setAutomaticDataCollectionEnabled( + arg_appName!, arg_enabled!); return []; }); } } { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.FirebaseAppHostApi.setAutomaticResourceManagementEnabled', codec, + 'dev.flutter.pigeon.FirebaseAppHostApi.setAutomaticResourceManagementEnabled', + codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMockMessageHandler(null); } else { channel.setMockMessageHandler((Object? message) async { assert(message != null, - 'Argument for dev.flutter.pigeon.FirebaseAppHostApi.setAutomaticResourceManagementEnabled was null.'); + 'Argument for dev.flutter.pigeon.FirebaseAppHostApi.setAutomaticResourceManagementEnabled was null.'); final List args = (message as List?)!; final String? arg_appName = (args[0] as String?); assert(arg_appName != null, @@ -150,7 +160,8 @@ abstract class TestFirebaseAppHostApi { final bool? arg_enabled = (args[1] as bool?); assert(arg_enabled != null, 'Argument for dev.flutter.pigeon.FirebaseAppHostApi.setAutomaticResourceManagementEnabled was null, expected non-null bool.'); - await api.setAutomaticResourceManagementEnabled(arg_appName!, arg_enabled!); + await api.setAutomaticResourceManagementEnabled( + arg_appName!, arg_enabled!); return []; }); } @@ -164,7 +175,7 @@ abstract class TestFirebaseAppHostApi { } else { channel.setMockMessageHandler((Object? message) async { assert(message != null, - 'Argument for dev.flutter.pigeon.FirebaseAppHostApi.delete was null.'); + 'Argument for dev.flutter.pigeon.FirebaseAppHostApi.delete was null.'); final List args = (message as List?)!; final String? arg_appName = (args[0] as String?); assert(arg_appName != null, From eee05da909964160151e90038b1d4df5848b5e6a Mon Sep 17 00:00:00 2001 From: Guillaume Bernos Date: Tue, 14 Mar 2023 14:36:43 +0100 Subject: [PATCH 19/65] feat(core, windows): update pigeon --- .../core/GeneratedAndroidFirebaseCore.java | 3 + .../firebase_core/ios/Classes/messages.g.h | 3 + .../firebase_core/ios/Classes/messages.g.m | 3 + .../firebase_core/windows/messages.g.cpp | 667 ++++++++++++++++++ .../firebase_core/windows/messages.g.h | 249 +++++++ .../lib/src/pigeon/messages.pigeon.dart | 3 + .../lib/src/pigeon/test_api.dart | 3 + .../pigeons/copyright.txt | 3 + .../pigeons/messages.dart | 4 + 9 files changed, 938 insertions(+) create mode 100644 packages/firebase_core/firebase_core/windows/messages.g.cpp create mode 100644 packages/firebase_core/firebase_core/windows/messages.g.h create mode 100644 packages/firebase_core/firebase_core_platform_interface/pigeons/copyright.txt diff --git a/packages/firebase_core/firebase_core/android/src/main/java/io/flutter/plugins/firebase/core/GeneratedAndroidFirebaseCore.java b/packages/firebase_core/firebase_core/android/src/main/java/io/flutter/plugins/firebase/core/GeneratedAndroidFirebaseCore.java index 5710a21f0950..cfd9421325b8 100644 --- a/packages/firebase_core/firebase_core/android/src/main/java/io/flutter/plugins/firebase/core/GeneratedAndroidFirebaseCore.java +++ b/packages/firebase_core/firebase_core/android/src/main/java/io/flutter/plugins/firebase/core/GeneratedAndroidFirebaseCore.java @@ -1,3 +1,6 @@ +// Copyright 2023, the Chromium project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. // Autogenerated from Pigeon (v9.0.6), do not edit directly. // See also: https://pub.dev/packages/pigeon diff --git a/packages/firebase_core/firebase_core/ios/Classes/messages.g.h b/packages/firebase_core/firebase_core/ios/Classes/messages.g.h index 9a98f1fe9b10..d9dc465d55b9 100644 --- a/packages/firebase_core/firebase_core/ios/Classes/messages.g.h +++ b/packages/firebase_core/firebase_core/ios/Classes/messages.g.h @@ -1,3 +1,6 @@ +// Copyright 2023, the Chromium project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. // Autogenerated from Pigeon (v9.0.6), do not edit directly. // See also: https://pub.dev/packages/pigeon diff --git a/packages/firebase_core/firebase_core/ios/Classes/messages.g.m b/packages/firebase_core/firebase_core/ios/Classes/messages.g.m index f1bc91f423b8..7d9fe2a2cee5 100644 --- a/packages/firebase_core/firebase_core/ios/Classes/messages.g.m +++ b/packages/firebase_core/firebase_core/ios/Classes/messages.g.m @@ -1,3 +1,6 @@ +// Copyright 2023, the Chromium project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. // Autogenerated from Pigeon (v9.0.6), do not edit directly. // See also: https://pub.dev/packages/pigeon diff --git a/packages/firebase_core/firebase_core/windows/messages.g.cpp b/packages/firebase_core/firebase_core/windows/messages.g.cpp new file mode 100644 index 000000000000..921801b19b47 --- /dev/null +++ b/packages/firebase_core/firebase_core/windows/messages.g.cpp @@ -0,0 +1,667 @@ +// Copyright 2023, the Chromium project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Autogenerated from Pigeon (v9.0.6), do not edit directly. +// See also: https://pub.dev/packages/pigeon + +#undef _HAS_EXCEPTIONS + +#include "messages.g.h" + +#include +#include +#include +#include + +#include +#include +#include + +namespace firebase_core_windows { +using flutter::BasicMessageChannel; +using flutter::CustomEncodableValue; +using flutter::EncodableList; +using flutter::EncodableMap; +using flutter::EncodableValue; + +// PigeonFirebaseOptions + +const std::string& PigeonFirebaseOptions::api_key() const { return api_key_; } +void PigeonFirebaseOptions::set_api_key(std::string_view value_arg) { + api_key_ = value_arg; +} + +const std::string& PigeonFirebaseOptions::app_id() const { return app_id_; } +void PigeonFirebaseOptions::set_app_id(std::string_view value_arg) { + app_id_ = value_arg; +} + +const std::string& PigeonFirebaseOptions::messaging_sender_id() const { + return messaging_sender_id_; +} +void PigeonFirebaseOptions::set_messaging_sender_id( + std::string_view value_arg) { + messaging_sender_id_ = value_arg; +} + +const std::string& PigeonFirebaseOptions::project_id() const { + return project_id_; +} +void PigeonFirebaseOptions::set_project_id(std::string_view value_arg) { + project_id_ = value_arg; +} + +const std::string* PigeonFirebaseOptions::auth_domain() const { + return auth_domain_ ? &(*auth_domain_) : nullptr; +} +void PigeonFirebaseOptions::set_auth_domain(const std::string_view* value_arg) { + auth_domain_ = + value_arg ? std::optional(*value_arg) : std::nullopt; +} +void PigeonFirebaseOptions::set_auth_domain(std::string_view value_arg) { + auth_domain_ = value_arg; +} + +const std::string* PigeonFirebaseOptions::database_u_r_l() const { + return database_u_r_l_ ? &(*database_u_r_l_) : nullptr; +} +void PigeonFirebaseOptions::set_database_u_r_l( + const std::string_view* value_arg) { + database_u_r_l_ = + value_arg ? std::optional(*value_arg) : std::nullopt; +} +void PigeonFirebaseOptions::set_database_u_r_l(std::string_view value_arg) { + database_u_r_l_ = value_arg; +} + +const std::string* PigeonFirebaseOptions::storage_bucket() const { + return storage_bucket_ ? &(*storage_bucket_) : nullptr; +} +void PigeonFirebaseOptions::set_storage_bucket( + const std::string_view* value_arg) { + storage_bucket_ = + value_arg ? std::optional(*value_arg) : std::nullopt; +} +void PigeonFirebaseOptions::set_storage_bucket(std::string_view value_arg) { + storage_bucket_ = value_arg; +} + +const std::string* PigeonFirebaseOptions::measurement_id() const { + return measurement_id_ ? &(*measurement_id_) : nullptr; +} +void PigeonFirebaseOptions::set_measurement_id( + const std::string_view* value_arg) { + measurement_id_ = + value_arg ? std::optional(*value_arg) : std::nullopt; +} +void PigeonFirebaseOptions::set_measurement_id(std::string_view value_arg) { + measurement_id_ = value_arg; +} + +const std::string* PigeonFirebaseOptions::tracking_id() const { + return tracking_id_ ? &(*tracking_id_) : nullptr; +} +void PigeonFirebaseOptions::set_tracking_id(const std::string_view* value_arg) { + tracking_id_ = + value_arg ? std::optional(*value_arg) : std::nullopt; +} +void PigeonFirebaseOptions::set_tracking_id(std::string_view value_arg) { + tracking_id_ = value_arg; +} + +const std::string* PigeonFirebaseOptions::deep_link_u_r_l_scheme() const { + return deep_link_u_r_l_scheme_ ? &(*deep_link_u_r_l_scheme_) : nullptr; +} +void PigeonFirebaseOptions::set_deep_link_u_r_l_scheme( + const std::string_view* value_arg) { + deep_link_u_r_l_scheme_ = + value_arg ? std::optional(*value_arg) : std::nullopt; +} +void PigeonFirebaseOptions::set_deep_link_u_r_l_scheme( + std::string_view value_arg) { + deep_link_u_r_l_scheme_ = value_arg; +} + +const std::string* PigeonFirebaseOptions::android_client_id() const { + return android_client_id_ ? &(*android_client_id_) : nullptr; +} +void PigeonFirebaseOptions::set_android_client_id( + const std::string_view* value_arg) { + android_client_id_ = + value_arg ? std::optional(*value_arg) : std::nullopt; +} +void PigeonFirebaseOptions::set_android_client_id(std::string_view value_arg) { + android_client_id_ = value_arg; +} + +const std::string* PigeonFirebaseOptions::ios_client_id() const { + return ios_client_id_ ? &(*ios_client_id_) : nullptr; +} +void PigeonFirebaseOptions::set_ios_client_id( + const std::string_view* value_arg) { + ios_client_id_ = + value_arg ? std::optional(*value_arg) : std::nullopt; +} +void PigeonFirebaseOptions::set_ios_client_id(std::string_view value_arg) { + ios_client_id_ = value_arg; +} + +const std::string* PigeonFirebaseOptions::ios_bundle_id() const { + return ios_bundle_id_ ? &(*ios_bundle_id_) : nullptr; +} +void PigeonFirebaseOptions::set_ios_bundle_id( + const std::string_view* value_arg) { + ios_bundle_id_ = + value_arg ? std::optional(*value_arg) : std::nullopt; +} +void PigeonFirebaseOptions::set_ios_bundle_id(std::string_view value_arg) { + ios_bundle_id_ = value_arg; +} + +const std::string* PigeonFirebaseOptions::app_group_id() const { + return app_group_id_ ? &(*app_group_id_) : nullptr; +} +void PigeonFirebaseOptions::set_app_group_id( + const std::string_view* value_arg) { + app_group_id_ = + value_arg ? std::optional(*value_arg) : std::nullopt; +} +void PigeonFirebaseOptions::set_app_group_id(std::string_view value_arg) { + app_group_id_ = value_arg; +} + +EncodableList PigeonFirebaseOptions::ToEncodableList() const { + EncodableList list; + list.reserve(14); + list.push_back(EncodableValue(api_key_)); + list.push_back(EncodableValue(app_id_)); + list.push_back(EncodableValue(messaging_sender_id_)); + list.push_back(EncodableValue(project_id_)); + list.push_back(auth_domain_ ? EncodableValue(*auth_domain_) + : EncodableValue()); + list.push_back(database_u_r_l_ ? EncodableValue(*database_u_r_l_) + : EncodableValue()); + list.push_back(storage_bucket_ ? EncodableValue(*storage_bucket_) + : EncodableValue()); + list.push_back(measurement_id_ ? EncodableValue(*measurement_id_) + : EncodableValue()); + list.push_back(tracking_id_ ? EncodableValue(*tracking_id_) + : EncodableValue()); + list.push_back(deep_link_u_r_l_scheme_ + ? EncodableValue(*deep_link_u_r_l_scheme_) + : EncodableValue()); + list.push_back(android_client_id_ ? EncodableValue(*android_client_id_) + : EncodableValue()); + list.push_back(ios_client_id_ ? EncodableValue(*ios_client_id_) + : EncodableValue()); + list.push_back(ios_bundle_id_ ? EncodableValue(*ios_bundle_id_) + : EncodableValue()); + list.push_back(app_group_id_ ? EncodableValue(*app_group_id_) + : EncodableValue()); + return list; +} + +PigeonFirebaseOptions::PigeonFirebaseOptions() {} + +PigeonFirebaseOptions::PigeonFirebaseOptions(const EncodableList& list) { + auto& encodable_api_key = list[0]; + if (const std::string* pointer_api_key = + std::get_if(&encodable_api_key)) { + api_key_ = *pointer_api_key; + } + auto& encodable_app_id = list[1]; + if (const std::string* pointer_app_id = + std::get_if(&encodable_app_id)) { + app_id_ = *pointer_app_id; + } + auto& encodable_messaging_sender_id = list[2]; + if (const std::string* pointer_messaging_sender_id = + std::get_if(&encodable_messaging_sender_id)) { + messaging_sender_id_ = *pointer_messaging_sender_id; + } + auto& encodable_project_id = list[3]; + if (const std::string* pointer_project_id = + std::get_if(&encodable_project_id)) { + project_id_ = *pointer_project_id; + } + auto& encodable_auth_domain = list[4]; + if (const std::string* pointer_auth_domain = + std::get_if(&encodable_auth_domain)) { + auth_domain_ = *pointer_auth_domain; + } + auto& encodable_database_u_r_l = list[5]; + if (const std::string* pointer_database_u_r_l = + std::get_if(&encodable_database_u_r_l)) { + database_u_r_l_ = *pointer_database_u_r_l; + } + auto& encodable_storage_bucket = list[6]; + if (const std::string* pointer_storage_bucket = + std::get_if(&encodable_storage_bucket)) { + storage_bucket_ = *pointer_storage_bucket; + } + auto& encodable_measurement_id = list[7]; + if (const std::string* pointer_measurement_id = + std::get_if(&encodable_measurement_id)) { + measurement_id_ = *pointer_measurement_id; + } + auto& encodable_tracking_id = list[8]; + if (const std::string* pointer_tracking_id = + std::get_if(&encodable_tracking_id)) { + tracking_id_ = *pointer_tracking_id; + } + auto& encodable_deep_link_u_r_l_scheme = list[9]; + if (const std::string* pointer_deep_link_u_r_l_scheme = + std::get_if(&encodable_deep_link_u_r_l_scheme)) { + deep_link_u_r_l_scheme_ = *pointer_deep_link_u_r_l_scheme; + } + auto& encodable_android_client_id = list[10]; + if (const std::string* pointer_android_client_id = + std::get_if(&encodable_android_client_id)) { + android_client_id_ = *pointer_android_client_id; + } + auto& encodable_ios_client_id = list[11]; + if (const std::string* pointer_ios_client_id = + std::get_if(&encodable_ios_client_id)) { + ios_client_id_ = *pointer_ios_client_id; + } + auto& encodable_ios_bundle_id = list[12]; + if (const std::string* pointer_ios_bundle_id = + std::get_if(&encodable_ios_bundle_id)) { + ios_bundle_id_ = *pointer_ios_bundle_id; + } + auto& encodable_app_group_id = list[13]; + if (const std::string* pointer_app_group_id = + std::get_if(&encodable_app_group_id)) { + app_group_id_ = *pointer_app_group_id; + } +} + +// PigeonInitializeResponse + +const std::string& PigeonInitializeResponse::name() const { return name_; } +void PigeonInitializeResponse::set_name(std::string_view value_arg) { + name_ = value_arg; +} + +const PigeonFirebaseOptions& PigeonInitializeResponse::options() const { + return options_; +} +void PigeonInitializeResponse::set_options( + const PigeonFirebaseOptions& value_arg) { + options_ = value_arg; +} + +const bool* PigeonInitializeResponse::is_automatic_data_collection_enabled() + const { + return is_automatic_data_collection_enabled_ + ? &(*is_automatic_data_collection_enabled_) + : nullptr; +} +void PigeonInitializeResponse::set_is_automatic_data_collection_enabled( + const bool* value_arg) { + is_automatic_data_collection_enabled_ = + value_arg ? std::optional(*value_arg) : std::nullopt; +} +void PigeonInitializeResponse::set_is_automatic_data_collection_enabled( + bool value_arg) { + is_automatic_data_collection_enabled_ = value_arg; +} + +const EncodableMap& PigeonInitializeResponse::plugin_constants() const { + return plugin_constants_; +} +void PigeonInitializeResponse::set_plugin_constants( + const EncodableMap& value_arg) { + plugin_constants_ = value_arg; +} + +EncodableList PigeonInitializeResponse::ToEncodableList() const { + EncodableList list; + list.reserve(4); + list.push_back(EncodableValue(name_)); + list.push_back(EncodableValue(options_.ToEncodableList())); + list.push_back(is_automatic_data_collection_enabled_ + ? EncodableValue(*is_automatic_data_collection_enabled_) + : EncodableValue()); + list.push_back(EncodableValue(plugin_constants_)); + return list; +} + +PigeonInitializeResponse::PigeonInitializeResponse() {} + +PigeonInitializeResponse::PigeonInitializeResponse(const EncodableList& list) { + auto& encodable_name = list[0]; + if (const std::string* pointer_name = + std::get_if(&encodable_name)) { + name_ = *pointer_name; + } + auto& encodable_options = list[1]; + if (const EncodableList* pointer_options = + std::get_if(&encodable_options)) { + options_ = PigeonFirebaseOptions(*pointer_options); + } + auto& encodable_is_automatic_data_collection_enabled = list[2]; + if (const bool* pointer_is_automatic_data_collection_enabled = + std::get_if(&encodable_is_automatic_data_collection_enabled)) { + is_automatic_data_collection_enabled_ = + *pointer_is_automatic_data_collection_enabled; + } + auto& encodable_plugin_constants = list[3]; + if (const EncodableMap* pointer_plugin_constants = + std::get_if(&encodable_plugin_constants)) { + plugin_constants_ = *pointer_plugin_constants; + } +} + +FirebaseCoreHostApiCodecSerializer::FirebaseCoreHostApiCodecSerializer() {} +EncodableValue FirebaseCoreHostApiCodecSerializer::ReadValueOfType( + uint8_t type, flutter::ByteStreamReader* stream) const { + switch (type) { + case 128: + return CustomEncodableValue( + PigeonFirebaseOptions(std::get(ReadValue(stream)))); + case 129: + return CustomEncodableValue( + PigeonInitializeResponse(std::get(ReadValue(stream)))); + default: + return flutter::StandardCodecSerializer::ReadValueOfType(type, stream); + } +} + +void FirebaseCoreHostApiCodecSerializer::WriteValue( + const EncodableValue& value, flutter::ByteStreamWriter* stream) const { + if (const CustomEncodableValue* custom_value = + std::get_if(&value)) { + if (custom_value->type() == typeid(PigeonFirebaseOptions)) { + stream->WriteByte(128); + WriteValue( + EncodableValue(std::any_cast(*custom_value) + .ToEncodableList()), + stream); + return; + } + if (custom_value->type() == typeid(PigeonInitializeResponse)) { + stream->WriteByte(129); + WriteValue( + EncodableValue(std::any_cast(*custom_value) + .ToEncodableList()), + stream); + return; + } + } + flutter::StandardCodecSerializer::WriteValue(value, stream); +} + +/// The codec used by FirebaseCoreHostApi. +const flutter::StandardMessageCodec& FirebaseCoreHostApi::GetCodec() { + return flutter::StandardMessageCodec::GetInstance( + &FirebaseCoreHostApiCodecSerializer::GetInstance()); +} + +// Sets up an instance of `FirebaseCoreHostApi` to handle messages through the +// `binary_messenger`. +void FirebaseCoreHostApi::SetUp(flutter::BinaryMessenger* binary_messenger, + FirebaseCoreHostApi* api) { + { + auto channel = std::make_unique>( + binary_messenger, + "dev.flutter.pigeon.FirebaseCoreHostApi.initializeApp", &GetCodec()); + if (api != nullptr) { + channel->SetMessageHandler( + [api](const EncodableValue& message, + const flutter::MessageReply& reply) { + try { + const auto& args = std::get(message); + const auto& encodable_app_name_arg = args.at(0); + if (encodable_app_name_arg.IsNull()) { + reply(WrapError("app_name_arg unexpectedly null.")); + return; + } + const auto& app_name_arg = + std::get(encodable_app_name_arg); + const auto& encodable_initialize_app_request_arg = args.at(1); + if (encodable_initialize_app_request_arg.IsNull()) { + reply( + WrapError("initialize_app_request_arg unexpectedly null.")); + return; + } + const auto& initialize_app_request_arg = + std::any_cast( + std::get( + encodable_initialize_app_request_arg)); + api->InitializeApp( + app_name_arg, initialize_app_request_arg, + [reply](ErrorOr&& output) { + if (output.has_error()) { + reply(WrapError(output.error())); + return; + } + EncodableList wrapped; + wrapped.push_back( + CustomEncodableValue(std::move(output).TakeValue())); + reply(EncodableValue(std::move(wrapped))); + }); + } catch (const std::exception& exception) { + reply(WrapError(exception.what())); + } + }); + } else { + channel->SetMessageHandler(nullptr); + } + } + { + auto channel = std::make_unique>( + binary_messenger, + "dev.flutter.pigeon.FirebaseCoreHostApi.initializeCore", &GetCodec()); + if (api != nullptr) { + channel->SetMessageHandler( + [api](const EncodableValue& message, + const flutter::MessageReply& reply) { + try { + api->InitializeCore([reply](ErrorOr&& output) { + if (output.has_error()) { + reply(WrapError(output.error())); + return; + } + EncodableList wrapped; + wrapped.push_back( + EncodableValue(std::move(output).TakeValue())); + reply(EncodableValue(std::move(wrapped))); + }); + } catch (const std::exception& exception) { + reply(WrapError(exception.what())); + } + }); + } else { + channel->SetMessageHandler(nullptr); + } + } + { + auto channel = std::make_unique>( + binary_messenger, + "dev.flutter.pigeon.FirebaseCoreHostApi.optionsFromResource", + &GetCodec()); + if (api != nullptr) { + channel->SetMessageHandler( + [api](const EncodableValue& message, + const flutter::MessageReply& reply) { + try { + api->OptionsFromResource( + [reply](ErrorOr&& output) { + if (output.has_error()) { + reply(WrapError(output.error())); + return; + } + EncodableList wrapped; + wrapped.push_back( + CustomEncodableValue(std::move(output).TakeValue())); + reply(EncodableValue(std::move(wrapped))); + }); + } catch (const std::exception& exception) { + reply(WrapError(exception.what())); + } + }); + } else { + channel->SetMessageHandler(nullptr); + } + } +} + +EncodableValue FirebaseCoreHostApi::WrapError(std::string_view error_message) { + return EncodableValue( + EncodableList{EncodableValue(std::string(error_message)), + EncodableValue("Error"), EncodableValue()}); +} +EncodableValue FirebaseCoreHostApi::WrapError(const FlutterError& error) { + return EncodableValue(EncodableList{EncodableValue(error.message()), + EncodableValue(error.code()), + error.details()}); +} + +/// The codec used by FirebaseAppHostApi. +const flutter::StandardMessageCodec& FirebaseAppHostApi::GetCodec() { + return flutter::StandardMessageCodec::GetInstance( + &flutter::StandardCodecSerializer::GetInstance()); +} + +// Sets up an instance of `FirebaseAppHostApi` to handle messages through the +// `binary_messenger`. +void FirebaseAppHostApi::SetUp(flutter::BinaryMessenger* binary_messenger, + FirebaseAppHostApi* api) { + { + auto channel = std::make_unique>( + binary_messenger, + "dev.flutter.pigeon.FirebaseAppHostApi." + "setAutomaticDataCollectionEnabled", + &GetCodec()); + if (api != nullptr) { + channel->SetMessageHandler( + [api](const EncodableValue& message, + const flutter::MessageReply& reply) { + try { + const auto& args = std::get(message); + const auto& encodable_app_name_arg = args.at(0); + if (encodable_app_name_arg.IsNull()) { + reply(WrapError("app_name_arg unexpectedly null.")); + return; + } + const auto& app_name_arg = + std::get(encodable_app_name_arg); + const auto& encodable_enabled_arg = args.at(1); + if (encodable_enabled_arg.IsNull()) { + reply(WrapError("enabled_arg unexpectedly null.")); + return; + } + const auto& enabled_arg = std::get(encodable_enabled_arg); + api->SetAutomaticDataCollectionEnabled( + app_name_arg, enabled_arg, + [reply](std::optional&& output) { + if (output.has_value()) { + reply(WrapError(output.value())); + return; + } + EncodableList wrapped; + wrapped.push_back(EncodableValue()); + reply(EncodableValue(std::move(wrapped))); + }); + } catch (const std::exception& exception) { + reply(WrapError(exception.what())); + } + }); + } else { + channel->SetMessageHandler(nullptr); + } + } + { + auto channel = std::make_unique>( + binary_messenger, + "dev.flutter.pigeon.FirebaseAppHostApi." + "setAutomaticResourceManagementEnabled", + &GetCodec()); + if (api != nullptr) { + channel->SetMessageHandler( + [api](const EncodableValue& message, + const flutter::MessageReply& reply) { + try { + const auto& args = std::get(message); + const auto& encodable_app_name_arg = args.at(0); + if (encodable_app_name_arg.IsNull()) { + reply(WrapError("app_name_arg unexpectedly null.")); + return; + } + const auto& app_name_arg = + std::get(encodable_app_name_arg); + const auto& encodable_enabled_arg = args.at(1); + if (encodable_enabled_arg.IsNull()) { + reply(WrapError("enabled_arg unexpectedly null.")); + return; + } + const auto& enabled_arg = std::get(encodable_enabled_arg); + api->SetAutomaticResourceManagementEnabled( + app_name_arg, enabled_arg, + [reply](std::optional&& output) { + if (output.has_value()) { + reply(WrapError(output.value())); + return; + } + EncodableList wrapped; + wrapped.push_back(EncodableValue()); + reply(EncodableValue(std::move(wrapped))); + }); + } catch (const std::exception& exception) { + reply(WrapError(exception.what())); + } + }); + } else { + channel->SetMessageHandler(nullptr); + } + } + { + auto channel = std::make_unique>( + binary_messenger, "dev.flutter.pigeon.FirebaseAppHostApi.delete", + &GetCodec()); + if (api != nullptr) { + channel->SetMessageHandler( + [api](const EncodableValue& message, + const flutter::MessageReply& reply) { + try { + const auto& args = std::get(message); + const auto& encodable_app_name_arg = args.at(0); + if (encodable_app_name_arg.IsNull()) { + reply(WrapError("app_name_arg unexpectedly null.")); + return; + } + const auto& app_name_arg = + std::get(encodable_app_name_arg); + api->Delete(app_name_arg, + [reply](std::optional&& output) { + if (output.has_value()) { + reply(WrapError(output.value())); + return; + } + EncodableList wrapped; + wrapped.push_back(EncodableValue()); + reply(EncodableValue(std::move(wrapped))); + }); + } catch (const std::exception& exception) { + reply(WrapError(exception.what())); + } + }); + } else { + channel->SetMessageHandler(nullptr); + } + } +} + +EncodableValue FirebaseAppHostApi::WrapError(std::string_view error_message) { + return EncodableValue( + EncodableList{EncodableValue(std::string(error_message)), + EncodableValue("Error"), EncodableValue()}); +} +EncodableValue FirebaseAppHostApi::WrapError(const FlutterError& error) { + return EncodableValue(EncodableList{EncodableValue(error.message()), + EncodableValue(error.code()), + error.details()}); +} + +} // namespace firebase_core_windows diff --git a/packages/firebase_core/firebase_core/windows/messages.g.h b/packages/firebase_core/firebase_core/windows/messages.g.h new file mode 100644 index 000000000000..e38a5a5081e8 --- /dev/null +++ b/packages/firebase_core/firebase_core/windows/messages.g.h @@ -0,0 +1,249 @@ +// Copyright 2023, the Chromium project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Autogenerated from Pigeon (v9.0.6), do not edit directly. +// See also: https://pub.dev/packages/pigeon + +#ifndef PIGEON_MESSAGES_G_H_ +#define PIGEON_MESSAGES_G_H_ +#include +#include +#include +#include + +#include +#include +#include + +namespace firebase_core_windows { + +// Generated class from Pigeon. + +class FlutterError { + public: + explicit FlutterError(const std::string& code) : code_(code) {} + explicit FlutterError(const std::string& code, const std::string& message) + : code_(code), message_(message) {} + explicit FlutterError(const std::string& code, const std::string& message, + const flutter::EncodableValue& details) + : code_(code), message_(message), details_(details) {} + + const std::string& code() const { return code_; } + const std::string& message() const { return message_; } + const flutter::EncodableValue& details() const { return details_; } + + private: + std::string code_; + std::string message_; + flutter::EncodableValue details_; +}; + +template +class ErrorOr { + public: + ErrorOr(const T& rhs) { new (&v_) T(rhs); } + ErrorOr(const T&& rhs) { v_ = std::move(rhs); } + ErrorOr(const FlutterError& rhs) { new (&v_) FlutterError(rhs); } + ErrorOr(const FlutterError&& rhs) { v_ = std::move(rhs); } + + bool has_error() const { return std::holds_alternative(v_); } + const T& value() const { return std::get(v_); }; + const FlutterError& error() const { return std::get(v_); }; + + private: + friend class FirebaseCoreHostApi; + friend class FirebaseAppHostApi; + ErrorOr() = default; + T TakeValue() && { return std::get(std::move(v_)); } + + std::variant v_; +}; + +// Generated class from Pigeon that represents data sent in messages. +class PigeonFirebaseOptions { + public: + PigeonFirebaseOptions(); + const std::string& api_key() const; + void set_api_key(std::string_view value_arg); + + const std::string& app_id() const; + void set_app_id(std::string_view value_arg); + + const std::string& messaging_sender_id() const; + void set_messaging_sender_id(std::string_view value_arg); + + const std::string& project_id() const; + void set_project_id(std::string_view value_arg); + + const std::string* auth_domain() const; + void set_auth_domain(const std::string_view* value_arg); + void set_auth_domain(std::string_view value_arg); + + const std::string* database_u_r_l() const; + void set_database_u_r_l(const std::string_view* value_arg); + void set_database_u_r_l(std::string_view value_arg); + + const std::string* storage_bucket() const; + void set_storage_bucket(const std::string_view* value_arg); + void set_storage_bucket(std::string_view value_arg); + + const std::string* measurement_id() const; + void set_measurement_id(const std::string_view* value_arg); + void set_measurement_id(std::string_view value_arg); + + const std::string* tracking_id() const; + void set_tracking_id(const std::string_view* value_arg); + void set_tracking_id(std::string_view value_arg); + + const std::string* deep_link_u_r_l_scheme() const; + void set_deep_link_u_r_l_scheme(const std::string_view* value_arg); + void set_deep_link_u_r_l_scheme(std::string_view value_arg); + + const std::string* android_client_id() const; + void set_android_client_id(const std::string_view* value_arg); + void set_android_client_id(std::string_view value_arg); + + const std::string* ios_client_id() const; + void set_ios_client_id(const std::string_view* value_arg); + void set_ios_client_id(std::string_view value_arg); + + const std::string* ios_bundle_id() const; + void set_ios_bundle_id(const std::string_view* value_arg); + void set_ios_bundle_id(std::string_view value_arg); + + const std::string* app_group_id() const; + void set_app_group_id(const std::string_view* value_arg); + void set_app_group_id(std::string_view value_arg); + + private: + PigeonFirebaseOptions(const flutter::EncodableList& list); + flutter::EncodableList ToEncodableList() const; + friend class PigeonInitializeResponse; + friend class FirebaseCoreHostApi; + friend class FirebaseCoreHostApiCodecSerializer; + friend class FirebaseAppHostApi; + friend class FirebaseAppHostApiCodecSerializer; + std::string api_key_; + std::string app_id_; + std::string messaging_sender_id_; + std::string project_id_; + std::optional auth_domain_; + std::optional database_u_r_l_; + std::optional storage_bucket_; + std::optional measurement_id_; + std::optional tracking_id_; + std::optional deep_link_u_r_l_scheme_; + std::optional android_client_id_; + std::optional ios_client_id_; + std::optional ios_bundle_id_; + std::optional app_group_id_; +}; + +// Generated class from Pigeon that represents data sent in messages. +class PigeonInitializeResponse { + public: + PigeonInitializeResponse(); + const std::string& name() const; + void set_name(std::string_view value_arg); + + const PigeonFirebaseOptions& options() const; + void set_options(const PigeonFirebaseOptions& value_arg); + + const bool* is_automatic_data_collection_enabled() const; + void set_is_automatic_data_collection_enabled(const bool* value_arg); + void set_is_automatic_data_collection_enabled(bool value_arg); + + const flutter::EncodableMap& plugin_constants() const; + void set_plugin_constants(const flutter::EncodableMap& value_arg); + + private: + PigeonInitializeResponse(const flutter::EncodableList& list); + flutter::EncodableList ToEncodableList() const; + friend class FirebaseCoreHostApi; + friend class FirebaseCoreHostApiCodecSerializer; + friend class FirebaseAppHostApi; + friend class FirebaseAppHostApiCodecSerializer; + std::string name_; + PigeonFirebaseOptions options_; + std::optional is_automatic_data_collection_enabled_; + flutter::EncodableMap plugin_constants_; +}; + +class FirebaseCoreHostApiCodecSerializer + : public flutter::StandardCodecSerializer { + public: + inline static FirebaseCoreHostApiCodecSerializer& GetInstance() { + static FirebaseCoreHostApiCodecSerializer sInstance; + return sInstance; + } + + FirebaseCoreHostApiCodecSerializer(); + + public: + void WriteValue(const flutter::EncodableValue& value, + flutter::ByteStreamWriter* stream) const override; + + protected: + flutter::EncodableValue ReadValueOfType( + uint8_t type, flutter::ByteStreamReader* stream) const override; +}; + +// Generated interface from Pigeon that represents a handler of messages from +// Flutter. +class FirebaseCoreHostApi { + public: + FirebaseCoreHostApi(const FirebaseCoreHostApi&) = delete; + FirebaseCoreHostApi& operator=(const FirebaseCoreHostApi&) = delete; + virtual ~FirebaseCoreHostApi() {} + virtual void InitializeApp( + const std::string& app_name, + const PigeonFirebaseOptions& initialize_app_request, + std::function reply)> result) = 0; + virtual void InitializeCore( + std::function reply)> result) = 0; + virtual void OptionsFromResource( + std::function reply)> result) = 0; + + // The codec used by FirebaseCoreHostApi. + static const flutter::StandardMessageCodec& GetCodec(); + // Sets up an instance of `FirebaseCoreHostApi` to handle messages through the + // `binary_messenger`. + static void SetUp(flutter::BinaryMessenger* binary_messenger, + FirebaseCoreHostApi* api); + static flutter::EncodableValue WrapError(std::string_view error_message); + static flutter::EncodableValue WrapError(const FlutterError& error); + + protected: + FirebaseCoreHostApi() = default; +}; +// Generated interface from Pigeon that represents a handler of messages from +// Flutter. +class FirebaseAppHostApi { + public: + FirebaseAppHostApi(const FirebaseAppHostApi&) = delete; + FirebaseAppHostApi& operator=(const FirebaseAppHostApi&) = delete; + virtual ~FirebaseAppHostApi() {} + virtual void SetAutomaticDataCollectionEnabled( + const std::string& app_name, bool enabled, + std::function reply)> result) = 0; + virtual void SetAutomaticResourceManagementEnabled( + const std::string& app_name, bool enabled, + std::function reply)> result) = 0; + virtual void Delete( + const std::string& app_name, + std::function reply)> result) = 0; + + // The codec used by FirebaseAppHostApi. + static const flutter::StandardMessageCodec& GetCodec(); + // Sets up an instance of `FirebaseAppHostApi` to handle messages through the + // `binary_messenger`. + static void SetUp(flutter::BinaryMessenger* binary_messenger, + FirebaseAppHostApi* api); + static flutter::EncodableValue WrapError(std::string_view error_message); + static flutter::EncodableValue WrapError(const FlutterError& error); + + protected: + FirebaseAppHostApi() = default; +}; +} // namespace firebase_core_windows +#endif // PIGEON_MESSAGES_G_H_ diff --git a/packages/firebase_core/firebase_core_platform_interface/lib/src/pigeon/messages.pigeon.dart b/packages/firebase_core/firebase_core_platform_interface/lib/src/pigeon/messages.pigeon.dart index 9e0bd88c15d7..a7ad812dab6e 100644 --- a/packages/firebase_core/firebase_core_platform_interface/lib/src/pigeon/messages.pigeon.dart +++ b/packages/firebase_core/firebase_core_platform_interface/lib/src/pigeon/messages.pigeon.dart @@ -1,3 +1,6 @@ +// Copyright 2023, the Chromium project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. // Autogenerated from Pigeon (v9.0.6), do not edit directly. // See also: https://pub.dev/packages/pigeon // ignore_for_file: public_member_api_docs, non_constant_identifier_names, avoid_as, unused_import, unnecessary_parenthesis, prefer_null_aware_operators, omit_local_variable_types, unused_shown_name, unnecessary_import diff --git a/packages/firebase_core/firebase_core_platform_interface/lib/src/pigeon/test_api.dart b/packages/firebase_core/firebase_core_platform_interface/lib/src/pigeon/test_api.dart index 0b9065036612..cde69f942086 100644 --- a/packages/firebase_core/firebase_core_platform_interface/lib/src/pigeon/test_api.dart +++ b/packages/firebase_core/firebase_core_platform_interface/lib/src/pigeon/test_api.dart @@ -1,3 +1,6 @@ +// Copyright 2023, the Chromium project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. // Autogenerated from Pigeon (v9.0.6), do not edit directly. // See also: https://pub.dev/packages/pigeon // ignore_for_file: public_member_api_docs, non_constant_identifier_names, avoid_as, unused_import, unnecessary_parenthesis, unnecessary_import diff --git a/packages/firebase_core/firebase_core_platform_interface/pigeons/copyright.txt b/packages/firebase_core/firebase_core_platform_interface/pigeons/copyright.txt new file mode 100644 index 000000000000..42fc84b1210b --- /dev/null +++ b/packages/firebase_core/firebase_core_platform_interface/pigeons/copyright.txt @@ -0,0 +1,3 @@ +Copyright 2023, the Chromium project authors. Please see the AUTHORS file +for details. All rights reserved. Use of this source code is governed by a +BSD-style license that can be found in the LICENSE file. \ No newline at end of file diff --git a/packages/firebase_core/firebase_core_platform_interface/pigeons/messages.dart b/packages/firebase_core/firebase_core_platform_interface/pigeons/messages.dart index cc877df589de..00fa0d744802 100644 --- a/packages/firebase_core/firebase_core_platform_interface/pigeons/messages.dart +++ b/packages/firebase_core/firebase_core_platform_interface/pigeons/messages.dart @@ -17,6 +17,10 @@ import 'package:pigeon/pigeon.dart'; ), objcHeaderOut: '../firebase_core/ios/Classes/messages.g.h', objcSourceOut: '../firebase_core/ios/Classes/messages.g.m', + cppHeaderOut: '../firebase_core/windows/messages.g.h', + cppSourceOut: '../firebase_core/windows/messages.g.cpp', + cppOptions: CppOptions(namespace: 'firebase_core_windows'), + copyrightHeader: 'pigeons/copyright.txt', ), ) class PigeonFirebaseOptions { From a8ed44f29fd59c95ad2f0473d3474595af9ae194 Mon Sep 17 00:00:00 2001 From: Guillaume Bernos Date: Mon, 20 Mar 2023 10:26:47 +0100 Subject: [PATCH 20/65] feat: merge with main package --- .../firebase_core/example/.metadata | 24 +- .../example/lib/firebase_options.dart | 3 + .../example/test/widget_test.dart | 23 +- .../example/windows/.gitignore | 0 .../example/windows/CMakeLists.txt | 1 + .../example/windows/flutter/CMakeLists.txt | 0 .../flutter/generated_plugin_registrant.cc | 0 .../flutter/generated_plugin_registrant.h | 0 .../windows/flutter/generated_plugins.cmake | 0 .../example/windows/runner/CMakeLists.txt | 0 .../example/windows/runner/Runner.rc | 0 .../example/windows/runner/flutter_window.cpp | 0 .../example/windows/runner/flutter_window.h | 0 .../runner}/google-services-desktop.json | 0 .../example/windows/runner/main.cpp | 0 .../example/windows/runner/resource.h | 0 .../windows/runner/resources/app_icon.ico | Bin .../windows/runner/runner.exe.manifest | 0 .../example/windows/runner/utils.cpp | 0 .../example/windows/runner/utils.h | 0 .../example/windows/runner/win32_window.cpp | 0 .../example/windows/runner/win32_window.h | 0 .../firebase_core/firebase_core/.gitignore | 30 - .../firebase_core/firebase_core/.metadata | 30 - .../firebase_core/.vscode/settings.json | 3 - .../firebase_core/firebase_core/CHANGELOG.md | 3 - .../firebase_core/GoogleService-Info.plist | 38 - .../firebase_core/firebase_core/LICENSE | 1 - .../firebase_core/firebase_core/README.md | 15 - .../firebase_core/analysis_options.yaml | 4 - .../firebase_core/example/.gitignore | 44 - .../firebase_core/example/README.md | 16 - .../example/analysis_options.yaml | 29 - .../example/bin/CMakeFiles/generate.stamp | 1 - .../bin/CMakeFiles/generate.stamp.depend | 5 - .../firebase_core/example/bin/INSTALL.vcxproj | 165 --- .../example/bin/INSTALL.vcxproj.filters | 13 - .../example/bin/cmake_install.cmake | 34 - .../firebase_core/example/lib/main.dart | 63 - .../firebase_core/example/linux/.gitignore | 1 - .../example/linux/CMakeLists.txt | 150 --- .../example/linux/flutter/CMakeLists.txt | 88 -- .../flutter/generated_plugin_registrant.cc | 15 - .../flutter/generated_plugin_registrant.h | 15 - .../linux/flutter/generated_plugins.cmake | 24 - .../firebase_core/example/linux/main.cc | 6 - .../example/linux/my_application.cc | 104 -- .../example/linux/my_application.h | 18 - .../firebase_core/example/pubspec.yaml | 83 -- .../runner/google-services-desktop.json | 37 - .../firebase_core/firebase/admob.h | 215 --- .../firebase/admob/banner_view.h | 427 ------ .../firebase/admob/interstitial_ad.h | 259 ---- .../firebase/admob/native_express_ad_view.h | 446 ------ .../firebase/admob/rewarded_video.h | 407 ------ .../firebase_core/firebase/admob/types.h | 244 ---- .../firebase_core/firebase/analytics.h | 569 -------- .../firebase/analytics/event_names.h | 472 ------- .../firebase/analytics/parameter_names.h | 755 ----------- .../firebase/analytics/user_property_names.h | 50 - .../firebase_core/firebase/app.h | 787 ----------- .../firebase_core/firebase/auth.h | 939 ------------- .../firebase_core/firebase/auth/credential.h | 633 --------- .../firebase_core/firebase/auth/types.h | 473 ------- .../firebase_core/firebase/auth/user.h | 501 ------- .../firebase_core/firebase/database.h | 199 --- .../firebase_core/firebase/database/common.h | 83 -- .../firebase/database/data_snapshot.h | 205 --- .../firebase/database/database_reference.h | 477 ------- .../firebase/database/disconnection.h | 156 --- .../firebase/database/listener.h | 112 -- .../firebase/database/mutable_data.h | 165 --- .../firebase_core/firebase/database/query.h | 358 ----- .../firebase/database/transaction.h | 102 -- .../firebase_core/firebase/dynamic_links.h | 117 -- .../firebase/dynamic_links/components.h | 336 ----- .../firebase_core/firebase/firestore.h | 458 ------- .../firebase/firestore/collection_reference.h | 183 --- .../firebase/firestore/document_change.h | 203 --- .../firebase/firestore/document_reference.h | 351 ----- .../firebase/firestore/document_snapshot.h | 297 ---- .../firebase/firestore/field_path.h | 205 --- .../firebase/firestore/field_value.h | 436 ------ .../firebase/firestore/firestore_errors.h | 116 -- .../firebase/firestore/firestore_version.h | 29 - .../firebase/firestore/geo_point.h | 120 -- .../firestore/listener_registration.h | 130 -- .../firestore/load_bundle_task_progress.h | 101 -- .../firebase/firestore/map_field_value.h | 37 - .../firebase/firestore/metadata_changes.h | 41 - .../firebase_core/firebase/firestore/query.h | 683 ---------- .../firebase/firestore/query_snapshot.h | 194 --- .../firebase/firestore/set_options.h | 161 --- .../firebase/firestore/settings.h | 247 ---- .../firebase/firestore/snapshot_metadata.h | 159 --- .../firebase_core/firebase/firestore/source.h | 59 - .../firebase/firestore/timestamp.h | 252 ---- .../firebase/firestore/transaction.h | 143 -- .../firebase/firestore/transaction_options.h | 137 -- .../firebase/firestore/write_batch.h | 188 --- .../firebase_core/firebase/functions.h | 115 -- .../firebase/functions/callable_reference.h | 124 -- .../firebase/functions/callable_result.h | 96 -- .../firebase_core/firebase/functions/common.h | 202 --- .../firebase_core/firebase/future.h | 533 -------- .../firebase_core/firebase/gma.h | 207 --- .../firebase_core/firebase/gma/ad_view.h | 267 ---- .../firebase/gma/interstitial_ad.h | 128 -- .../firebase_core/firebase/gma/rewarded_ad.h | 152 --- .../firebase_core/firebase/gma/types.h | 939 ------------- .../firebase_core/firebase/installations.h | 123 -- .../firebase_core/firebase/internal/common.h | 128 -- .../firebase/internal/future_impl.h | 359 ----- .../firebase_core/firebase/internal/mutex.h | 100 -- .../firebase/internal/platform.h | 110 -- .../firebase/internal/type_traits.h | 134 -- .../firebase_core/firebase/log.h | 54 - .../firebase_core/firebase/messaging.h | 728 ---------- .../firebase_core/firebase/remote_config.h | 526 -------- .../firebase_core/firebase/storage.h | 161 --- .../firebase_core/firebase/storage/common.h | 62 - .../firebase/storage/controller.h | 146 -- .../firebase_core/firebase/storage/listener.h | 74 - .../firebase_core/firebase/storage/metadata.h | 276 ---- .../firebase/storage/storage_reference.h | 361 ----- .../firebase_core/firebase/util.h | 101 -- .../firebase_core/firebase/variant.h | 1197 ----------------- .../firebase_core/firebase/version.h | 68 - .../generate_xml_from_google_services_json.py | 496 ------- .../firebase_core/generated_bindings.dart | 26 - .../google-services-desktop.json | 37 - .../firebase_core/lib/firebase_core.dart | 8 - .../lib/firebase_core_method_channel.dart | 17 - .../lib/firebase_core_platform_interface.dart | 29 - .../firebase_core/linux/CMakeLists.txt | 47 - .../linux/firebase_core_plugin.cc | 70 - .../firebase_core/firebase_core_plugin.h | 26 - .../firebase_core/firebase_core/pubspec.yaml | 36 - .../firebase_core_method_channel_test.dart | 24 - .../test/firebase_core_test.dart | 29 - .../firebase_core/windows/.gitignore | 17 - .../firebase_core/windows/CMakeLists.txt | 61 - .../windows/firebase_core_plugin.cpp | 63 - .../windows/firebase_core_plugin.h | 32 - .../windows/firebase_core_plugin_c_api.cpp | 12 - .../firebase_core_plugin_c_api.h | 23 - 146 files changed, 39 insertions(+), 23988 deletions(-) rename packages/firebase_core/firebase_core/{firebase_core => }/example/test/widget_test.dart (53%) rename packages/firebase_core/firebase_core/{firebase_core => }/example/windows/.gitignore (100%) rename packages/firebase_core/firebase_core/{firebase_core => }/example/windows/CMakeLists.txt (97%) rename packages/firebase_core/firebase_core/{firebase_core => }/example/windows/flutter/CMakeLists.txt (100%) rename packages/firebase_core/firebase_core/{firebase_core => }/example/windows/flutter/generated_plugin_registrant.cc (100%) rename packages/firebase_core/firebase_core/{firebase_core => }/example/windows/flutter/generated_plugin_registrant.h (100%) rename packages/firebase_core/firebase_core/{firebase_core => }/example/windows/flutter/generated_plugins.cmake (100%) rename packages/firebase_core/firebase_core/{firebase_core => }/example/windows/runner/CMakeLists.txt (100%) rename packages/firebase_core/firebase_core/{firebase_core => }/example/windows/runner/Runner.rc (100%) rename packages/firebase_core/firebase_core/{firebase_core => }/example/windows/runner/flutter_window.cpp (100%) rename packages/firebase_core/firebase_core/{firebase_core => }/example/windows/runner/flutter_window.h (100%) rename packages/firebase_core/firebase_core/{firebase_core/example => example/windows/runner}/google-services-desktop.json (100%) rename packages/firebase_core/firebase_core/{firebase_core => }/example/windows/runner/main.cpp (100%) rename packages/firebase_core/firebase_core/{firebase_core => }/example/windows/runner/resource.h (100%) rename packages/firebase_core/firebase_core/{firebase_core => }/example/windows/runner/resources/app_icon.ico (100%) rename packages/firebase_core/firebase_core/{firebase_core => }/example/windows/runner/runner.exe.manifest (100%) rename packages/firebase_core/firebase_core/{firebase_core => }/example/windows/runner/utils.cpp (100%) rename packages/firebase_core/firebase_core/{firebase_core => }/example/windows/runner/utils.h (100%) rename packages/firebase_core/firebase_core/{firebase_core => }/example/windows/runner/win32_window.cpp (100%) rename packages/firebase_core/firebase_core/{firebase_core => }/example/windows/runner/win32_window.h (100%) delete mode 100644 packages/firebase_core/firebase_core/firebase_core/.gitignore delete mode 100644 packages/firebase_core/firebase_core/firebase_core/.metadata delete mode 100644 packages/firebase_core/firebase_core/firebase_core/.vscode/settings.json delete mode 100644 packages/firebase_core/firebase_core/firebase_core/CHANGELOG.md delete mode 100644 packages/firebase_core/firebase_core/firebase_core/GoogleService-Info.plist delete mode 100644 packages/firebase_core/firebase_core/firebase_core/LICENSE delete mode 100644 packages/firebase_core/firebase_core/firebase_core/README.md delete mode 100644 packages/firebase_core/firebase_core/firebase_core/analysis_options.yaml delete mode 100644 packages/firebase_core/firebase_core/firebase_core/example/.gitignore delete mode 100644 packages/firebase_core/firebase_core/firebase_core/example/README.md delete mode 100644 packages/firebase_core/firebase_core/firebase_core/example/analysis_options.yaml delete mode 100644 packages/firebase_core/firebase_core/firebase_core/example/bin/CMakeFiles/generate.stamp delete mode 100644 packages/firebase_core/firebase_core/firebase_core/example/bin/CMakeFiles/generate.stamp.depend delete mode 100644 packages/firebase_core/firebase_core/firebase_core/example/bin/INSTALL.vcxproj delete mode 100644 packages/firebase_core/firebase_core/firebase_core/example/bin/INSTALL.vcxproj.filters delete mode 100644 packages/firebase_core/firebase_core/firebase_core/example/bin/cmake_install.cmake delete mode 100644 packages/firebase_core/firebase_core/firebase_core/example/lib/main.dart delete mode 100644 packages/firebase_core/firebase_core/firebase_core/example/linux/.gitignore delete mode 100644 packages/firebase_core/firebase_core/firebase_core/example/linux/CMakeLists.txt delete mode 100644 packages/firebase_core/firebase_core/firebase_core/example/linux/flutter/CMakeLists.txt delete mode 100644 packages/firebase_core/firebase_core/firebase_core/example/linux/flutter/generated_plugin_registrant.cc delete mode 100644 packages/firebase_core/firebase_core/firebase_core/example/linux/flutter/generated_plugin_registrant.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/example/linux/flutter/generated_plugins.cmake delete mode 100644 packages/firebase_core/firebase_core/firebase_core/example/linux/main.cc delete mode 100644 packages/firebase_core/firebase_core/firebase_core/example/linux/my_application.cc delete mode 100644 packages/firebase_core/firebase_core/firebase_core/example/linux/my_application.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/example/pubspec.yaml delete mode 100644 packages/firebase_core/firebase_core/firebase_core/example/windows/runner/google-services-desktop.json delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/admob.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/admob/banner_view.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/admob/interstitial_ad.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/admob/native_express_ad_view.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/admob/rewarded_video.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/admob/types.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/analytics.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/analytics/event_names.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/analytics/parameter_names.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/analytics/user_property_names.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/app.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/auth.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/auth/credential.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/auth/types.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/auth/user.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/database.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/database/common.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/database/data_snapshot.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/database/database_reference.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/database/disconnection.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/database/listener.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/database/mutable_data.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/database/query.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/database/transaction.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/dynamic_links.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/dynamic_links/components.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/collection_reference.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/document_change.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/document_reference.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/document_snapshot.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/field_path.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/field_value.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/firestore_errors.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/firestore_version.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/geo_point.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/listener_registration.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/load_bundle_task_progress.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/map_field_value.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/metadata_changes.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/query.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/query_snapshot.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/set_options.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/settings.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/snapshot_metadata.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/source.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/timestamp.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/transaction.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/transaction_options.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/write_batch.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/functions.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/functions/callable_reference.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/functions/callable_result.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/functions/common.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/future.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/gma.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/gma/ad_view.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/gma/interstitial_ad.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/gma/rewarded_ad.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/gma/types.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/installations.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/internal/common.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/internal/future_impl.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/internal/mutex.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/internal/platform.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/internal/type_traits.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/log.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/messaging.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/remote_config.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/storage.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/storage/common.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/storage/controller.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/storage/listener.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/storage/metadata.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/storage/storage_reference.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/util.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/variant.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/version.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/generate_xml_from_google_services_json.py delete mode 100644 packages/firebase_core/firebase_core/firebase_core/generated_bindings.dart delete mode 100644 packages/firebase_core/firebase_core/firebase_core/google-services-desktop.json delete mode 100644 packages/firebase_core/firebase_core/firebase_core/lib/firebase_core.dart delete mode 100644 packages/firebase_core/firebase_core/firebase_core/lib/firebase_core_method_channel.dart delete mode 100644 packages/firebase_core/firebase_core/firebase_core/lib/firebase_core_platform_interface.dart delete mode 100644 packages/firebase_core/firebase_core/firebase_core/linux/CMakeLists.txt delete mode 100644 packages/firebase_core/firebase_core/firebase_core/linux/firebase_core_plugin.cc delete mode 100644 packages/firebase_core/firebase_core/firebase_core/linux/include/firebase_core/firebase_core_plugin.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/pubspec.yaml delete mode 100644 packages/firebase_core/firebase_core/firebase_core/test/firebase_core_method_channel_test.dart delete mode 100644 packages/firebase_core/firebase_core/firebase_core/test/firebase_core_test.dart delete mode 100644 packages/firebase_core/firebase_core/firebase_core/windows/.gitignore delete mode 100644 packages/firebase_core/firebase_core/firebase_core/windows/CMakeLists.txt delete mode 100644 packages/firebase_core/firebase_core/firebase_core/windows/firebase_core_plugin.cpp delete mode 100644 packages/firebase_core/firebase_core/firebase_core/windows/firebase_core_plugin.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/windows/firebase_core_plugin_c_api.cpp delete mode 100644 packages/firebase_core/firebase_core/firebase_core/windows/include/firebase_core/firebase_core_plugin_c_api.h diff --git a/packages/firebase_core/firebase_core/example/.metadata b/packages/firebase_core/firebase_core/example/.metadata index 4adf4bf025f8..3993ce7b7531 100644 --- a/packages/firebase_core/firebase_core/example/.metadata +++ b/packages/firebase_core/firebase_core/example/.metadata @@ -1,10 +1,30 @@ # This file tracks properties of this Flutter project. # Used by Flutter tool to assess capabilities and perform upgrades etc. # -# This file should be version controlled and should not be manually edited. +# This file should be version controlled. version: - revision: f139b11009aeb8ed2a3a3aa8b0066e482709dde3 + revision: 12cb4eb7a009f52b347b62ade7cb4854b926af72 channel: stable project_type: app + +# Tracks metadata for the flutter migrate command +migration: + platforms: + - platform: root + create_revision: 12cb4eb7a009f52b347b62ade7cb4854b926af72 + base_revision: 12cb4eb7a009f52b347b62ade7cb4854b926af72 + - platform: windows + create_revision: 12cb4eb7a009f52b347b62ade7cb4854b926af72 + base_revision: 12cb4eb7a009f52b347b62ade7cb4854b926af72 + + # User provided section + + # List of Local paths (relative to this file) that should be + # ignored by the migrate tool. + # + # Files that are not part of the templates will be ignored by default. + unmanaged_files: + - 'lib/main.dart' + - 'ios/Runner.xcodeproj/project.pbxproj' diff --git a/packages/firebase_core/firebase_core/example/lib/firebase_options.dart b/packages/firebase_core/firebase_core/example/lib/firebase_options.dart index da380a3ec8bb..63c4c8857ca7 100644 --- a/packages/firebase_core/firebase_core/example/lib/firebase_options.dart +++ b/packages/firebase_core/firebase_core/example/lib/firebase_options.dart @@ -30,6 +30,9 @@ class DefaultFirebaseOptions { return ios; case TargetPlatform.macOS: return macos; + // TODO(Lyokone): FIX + case TargetPlatform.windows: + return android; default: throw UnsupportedError( 'DefaultFirebaseOptions are not supported for this platform.', diff --git a/packages/firebase_core/firebase_core/firebase_core/example/test/widget_test.dart b/packages/firebase_core/firebase_core/example/test/widget_test.dart similarity index 53% rename from packages/firebase_core/firebase_core/firebase_core/example/test/widget_test.dart rename to packages/firebase_core/firebase_core/example/test/widget_test.dart index d343f68407e8..092d222f7e16 100644 --- a/packages/firebase_core/firebase_core/firebase_core/example/test/widget_test.dart +++ b/packages/firebase_core/firebase_core/example/test/widget_test.dart @@ -8,20 +8,23 @@ import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; -import 'package:firebase_core_example/main.dart'; +import 'package:example/main.dart'; void main() { - testWidgets('Verify Platform version', (WidgetTester tester) async { + testWidgets('Counter increments smoke test', (WidgetTester tester) async { // Build our app and trigger a frame. await tester.pumpWidget(const MyApp()); - // Verify that platform version is retrieved. - expect( - find.byWidgetPredicate( - (Widget widget) => widget is Text && - widget.data!.startsWith('Running on:'), - ), - findsOneWidget, - ); + // Verify that our counter starts at 0. + expect(find.text('0'), findsOneWidget); + expect(find.text('1'), findsNothing); + + // Tap the '+' icon and trigger a frame. + await tester.tap(find.byIcon(Icons.add)); + await tester.pump(); + + // Verify that our counter has incremented. + expect(find.text('0'), findsNothing); + expect(find.text('1'), findsOneWidget); }); } diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/.gitignore b/packages/firebase_core/firebase_core/example/windows/.gitignore similarity index 100% rename from packages/firebase_core/firebase_core/firebase_core/example/windows/.gitignore rename to packages/firebase_core/firebase_core/example/windows/.gitignore diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/CMakeLists.txt b/packages/firebase_core/firebase_core/example/windows/CMakeLists.txt similarity index 97% rename from packages/firebase_core/firebase_core/firebase_core/example/windows/CMakeLists.txt rename to packages/firebase_core/firebase_core/example/windows/CMakeLists.txt index ddf92aa378e1..55f6cda64bf2 100644 --- a/packages/firebase_core/firebase_core/firebase_core/example/windows/CMakeLists.txt +++ b/packages/firebase_core/firebase_core/example/windows/CMakeLists.txt @@ -28,6 +28,7 @@ set(CMAKE_EXE_LINKER_FLAGS_PROFILE "${CMAKE_EXE_LINKER_FLAGS_RELEASE}") set(CMAKE_SHARED_LINKER_FLAGS_PROFILE "${CMAKE_SHARED_LINKER_FLAGS_RELEASE}") set(CMAKE_C_FLAGS_PROFILE "${CMAKE_C_FLAGS_RELEASE}") set(CMAKE_CXX_FLAGS_PROFILE "${CMAKE_CXX_FLAGS_RELEASE}") +set(FIREBASE_CPP_SDK_DIR "c:/Users/guill/Downloads/firebase_cpp_sdk_10.5.0/firebase_cpp_sdk") # Use Unicode for all projects. add_definitions(-DUNICODE -D_UNICODE) diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/flutter/CMakeLists.txt b/packages/firebase_core/firebase_core/example/windows/flutter/CMakeLists.txt similarity index 100% rename from packages/firebase_core/firebase_core/firebase_core/example/windows/flutter/CMakeLists.txt rename to packages/firebase_core/firebase_core/example/windows/flutter/CMakeLists.txt diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/flutter/generated_plugin_registrant.cc b/packages/firebase_core/firebase_core/example/windows/flutter/generated_plugin_registrant.cc similarity index 100% rename from packages/firebase_core/firebase_core/firebase_core/example/windows/flutter/generated_plugin_registrant.cc rename to packages/firebase_core/firebase_core/example/windows/flutter/generated_plugin_registrant.cc diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/flutter/generated_plugin_registrant.h b/packages/firebase_core/firebase_core/example/windows/flutter/generated_plugin_registrant.h similarity index 100% rename from packages/firebase_core/firebase_core/firebase_core/example/windows/flutter/generated_plugin_registrant.h rename to packages/firebase_core/firebase_core/example/windows/flutter/generated_plugin_registrant.h diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/flutter/generated_plugins.cmake b/packages/firebase_core/firebase_core/example/windows/flutter/generated_plugins.cmake similarity index 100% rename from packages/firebase_core/firebase_core/firebase_core/example/windows/flutter/generated_plugins.cmake rename to packages/firebase_core/firebase_core/example/windows/flutter/generated_plugins.cmake diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/CMakeLists.txt b/packages/firebase_core/firebase_core/example/windows/runner/CMakeLists.txt similarity index 100% rename from packages/firebase_core/firebase_core/firebase_core/example/windows/runner/CMakeLists.txt rename to packages/firebase_core/firebase_core/example/windows/runner/CMakeLists.txt diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/Runner.rc b/packages/firebase_core/firebase_core/example/windows/runner/Runner.rc similarity index 100% rename from packages/firebase_core/firebase_core/firebase_core/example/windows/runner/Runner.rc rename to packages/firebase_core/firebase_core/example/windows/runner/Runner.rc diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/flutter_window.cpp b/packages/firebase_core/firebase_core/example/windows/runner/flutter_window.cpp similarity index 100% rename from packages/firebase_core/firebase_core/firebase_core/example/windows/runner/flutter_window.cpp rename to packages/firebase_core/firebase_core/example/windows/runner/flutter_window.cpp diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/flutter_window.h b/packages/firebase_core/firebase_core/example/windows/runner/flutter_window.h similarity index 100% rename from packages/firebase_core/firebase_core/firebase_core/example/windows/runner/flutter_window.h rename to packages/firebase_core/firebase_core/example/windows/runner/flutter_window.h diff --git a/packages/firebase_core/firebase_core/firebase_core/example/google-services-desktop.json b/packages/firebase_core/firebase_core/example/windows/runner/google-services-desktop.json similarity index 100% rename from packages/firebase_core/firebase_core/firebase_core/example/google-services-desktop.json rename to packages/firebase_core/firebase_core/example/windows/runner/google-services-desktop.json diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/main.cpp b/packages/firebase_core/firebase_core/example/windows/runner/main.cpp similarity index 100% rename from packages/firebase_core/firebase_core/firebase_core/example/windows/runner/main.cpp rename to packages/firebase_core/firebase_core/example/windows/runner/main.cpp diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/resource.h b/packages/firebase_core/firebase_core/example/windows/runner/resource.h similarity index 100% rename from packages/firebase_core/firebase_core/firebase_core/example/windows/runner/resource.h rename to packages/firebase_core/firebase_core/example/windows/runner/resource.h diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/resources/app_icon.ico b/packages/firebase_core/firebase_core/example/windows/runner/resources/app_icon.ico similarity index 100% rename from packages/firebase_core/firebase_core/firebase_core/example/windows/runner/resources/app_icon.ico rename to packages/firebase_core/firebase_core/example/windows/runner/resources/app_icon.ico diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/runner.exe.manifest b/packages/firebase_core/firebase_core/example/windows/runner/runner.exe.manifest similarity index 100% rename from packages/firebase_core/firebase_core/firebase_core/example/windows/runner/runner.exe.manifest rename to packages/firebase_core/firebase_core/example/windows/runner/runner.exe.manifest diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/utils.cpp b/packages/firebase_core/firebase_core/example/windows/runner/utils.cpp similarity index 100% rename from packages/firebase_core/firebase_core/firebase_core/example/windows/runner/utils.cpp rename to packages/firebase_core/firebase_core/example/windows/runner/utils.cpp diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/utils.h b/packages/firebase_core/firebase_core/example/windows/runner/utils.h similarity index 100% rename from packages/firebase_core/firebase_core/firebase_core/example/windows/runner/utils.h rename to packages/firebase_core/firebase_core/example/windows/runner/utils.h diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/win32_window.cpp b/packages/firebase_core/firebase_core/example/windows/runner/win32_window.cpp similarity index 100% rename from packages/firebase_core/firebase_core/firebase_core/example/windows/runner/win32_window.cpp rename to packages/firebase_core/firebase_core/example/windows/runner/win32_window.cpp diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/win32_window.h b/packages/firebase_core/firebase_core/example/windows/runner/win32_window.h similarity index 100% rename from packages/firebase_core/firebase_core/firebase_core/example/windows/runner/win32_window.h rename to packages/firebase_core/firebase_core/example/windows/runner/win32_window.h diff --git a/packages/firebase_core/firebase_core/firebase_core/.gitignore b/packages/firebase_core/firebase_core/firebase_core/.gitignore deleted file mode 100644 index 96486fd93024..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/.gitignore +++ /dev/null @@ -1,30 +0,0 @@ -# Miscellaneous -*.class -*.log -*.pyc -*.swp -.DS_Store -.atom/ -.buildlog/ -.history -.svn/ -migrate_working_dir/ - -# IntelliJ related -*.iml -*.ipr -*.iws -.idea/ - -# The .vscode folder contains launch configuration and tasks you configure in -# VS Code which you may wish to be included in version control, so this line -# is commented out by default. -#.vscode/ - -# Flutter/Dart/Pub related -# Libraries should not include pubspec.lock, per https://dart.dev/guides/libraries/private-files#pubspeclock. -/pubspec.lock -**/doc/api/ -.dart_tool/ -.packages -build/ diff --git a/packages/firebase_core/firebase_core/firebase_core/.metadata b/packages/firebase_core/firebase_core/firebase_core/.metadata deleted file mode 100644 index 97ef0fff36d0..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/.metadata +++ /dev/null @@ -1,30 +0,0 @@ -# This file tracks properties of this Flutter project. -# Used by Flutter tool to assess capabilities and perform upgrades etc. -# -# This file should be version controlled. - -version: - revision: 12cb4eb7a009f52b347b62ade7cb4854b926af72 - channel: stable - -project_type: plugin - -# Tracks metadata for the flutter migrate command -migration: - platforms: - - platform: root - create_revision: 12cb4eb7a009f52b347b62ade7cb4854b926af72 - base_revision: 12cb4eb7a009f52b347b62ade7cb4854b926af72 - - platform: windows - create_revision: 12cb4eb7a009f52b347b62ade7cb4854b926af72 - base_revision: 12cb4eb7a009f52b347b62ade7cb4854b926af72 - - # User provided section - - # List of Local paths (relative to this file) that should be - # ignored by the migrate tool. - # - # Files that are not part of the templates will be ignored by default. - unmanaged_files: - - 'lib/main.dart' - - 'ios/Runner.xcodeproj/project.pbxproj' diff --git a/packages/firebase_core/firebase_core/firebase_core/.vscode/settings.json b/packages/firebase_core/firebase_core/firebase_core/.vscode/settings.json deleted file mode 100644 index deec1e1d3994..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/.vscode/settings.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "cmake.sourceDirectory": "${workspaceFolder}/linux" -} diff --git a/packages/firebase_core/firebase_core/firebase_core/CHANGELOG.md b/packages/firebase_core/firebase_core/firebase_core/CHANGELOG.md deleted file mode 100644 index 41cc7d8192ec..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/CHANGELOG.md +++ /dev/null @@ -1,3 +0,0 @@ -## 0.0.1 - -* TODO: Describe initial release. diff --git a/packages/firebase_core/firebase_core/firebase_core/GoogleService-Info.plist b/packages/firebase_core/firebase_core/firebase_core/GoogleService-Info.plist deleted file mode 100644 index f325ead98dbc..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/GoogleService-Info.plist +++ /dev/null @@ -1,38 +0,0 @@ - - - - - CLIENT_ID - 406099696497-134k3722m01rtrsklhf3b7k8sqa5r7in.apps.googleusercontent.com - REVERSED_CLIENT_ID - com.googleusercontent.apps.406099696497-134k3722m01rtrsklhf3b7k8sqa5r7in - ANDROID_CLIENT_ID - 406099696497-17qn06u8a0dc717u8ul7s49ampk13lul.apps.googleusercontent.com - API_KEY - AIzaSyDooSUGSf63Ghq02_iIhtnmwMDs4HlWS6c - GCM_SENDER_ID - 406099696497 - PLIST_VERSION - 1 - BUNDLE_ID - io.flutter.plugins.firebase.auth.example - PROJECT_ID - flutterfire-e2e-tests - STORAGE_BUCKET - flutterfire-e2e-tests.appspot.com - IS_ADS_ENABLED - - IS_ANALYTICS_ENABLED - - IS_APPINVITE_ENABLED - - IS_GCM_ENABLED - - IS_SIGNIN_ENABLED - - GOOGLE_APP_ID - 1:406099696497:ios:58cbc26aca8e5cf83574d0 - DATABASE_URL - https://flutterfire-e2e-tests-default-rtdb.europe-west1.firebasedatabase.app - - \ No newline at end of file diff --git a/packages/firebase_core/firebase_core/firebase_core/LICENSE b/packages/firebase_core/firebase_core/firebase_core/LICENSE deleted file mode 100644 index ba75c69f7f21..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/LICENSE +++ /dev/null @@ -1 +0,0 @@ -TODO: Add your license here. diff --git a/packages/firebase_core/firebase_core/firebase_core/README.md b/packages/firebase_core/firebase_core/firebase_core/README.md deleted file mode 100644 index b373aba55a5f..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/README.md +++ /dev/null @@ -1,15 +0,0 @@ -# firebase_core - -A new Flutter plugin project. - -## Getting Started - -This project is a starting point for a Flutter -[plug-in package](https://flutter.dev/developing-packages/), -a specialized package that includes platform-specific implementation code for -Android and/or iOS. - -For help getting started with Flutter development, view the -[online documentation](https://flutter.dev/docs), which offers tutorials, -samples, guidance on mobile development, and a full API reference. - diff --git a/packages/firebase_core/firebase_core/firebase_core/analysis_options.yaml b/packages/firebase_core/firebase_core/firebase_core/analysis_options.yaml deleted file mode 100644 index a5744c1cfbe7..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/analysis_options.yaml +++ /dev/null @@ -1,4 +0,0 @@ -include: package:flutter_lints/flutter.yaml - -# Additional information about this file can be found at -# https://dart.dev/guides/language/analysis-options diff --git a/packages/firebase_core/firebase_core/firebase_core/example/.gitignore b/packages/firebase_core/firebase_core/firebase_core/example/.gitignore deleted file mode 100644 index 24476c5d1eb5..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/example/.gitignore +++ /dev/null @@ -1,44 +0,0 @@ -# Miscellaneous -*.class -*.log -*.pyc -*.swp -.DS_Store -.atom/ -.buildlog/ -.history -.svn/ -migrate_working_dir/ - -# IntelliJ related -*.iml -*.ipr -*.iws -.idea/ - -# The .vscode folder contains launch configuration and tasks you configure in -# VS Code which you may wish to be included in version control, so this line -# is commented out by default. -#.vscode/ - -# Flutter/Dart/Pub related -**/doc/api/ -**/ios/Flutter/.last_build_id -.dart_tool/ -.flutter-plugins -.flutter-plugins-dependencies -.packages -.pub-cache/ -.pub/ -/build/ - -# Symbolication related -app.*.symbols - -# Obfuscation related -app.*.map.json - -# Android Studio will place build artifacts here -/android/app/debug -/android/app/profile -/android/app/release diff --git a/packages/firebase_core/firebase_core/firebase_core/example/README.md b/packages/firebase_core/firebase_core/firebase_core/example/README.md deleted file mode 100644 index d1f452146bce..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/example/README.md +++ /dev/null @@ -1,16 +0,0 @@ -# firebase_core_example - -Demonstrates how to use the firebase_core plugin. - -## Getting Started - -This project is a starting point for a Flutter application. - -A few resources to get you started if this is your first Flutter project: - -- [Lab: Write your first Flutter app](https://docs.flutter.dev/get-started/codelab) -- [Cookbook: Useful Flutter samples](https://docs.flutter.dev/cookbook) - -For help getting started with Flutter development, view the -[online documentation](https://docs.flutter.dev/), which offers tutorials, -samples, guidance on mobile development, and a full API reference. diff --git a/packages/firebase_core/firebase_core/firebase_core/example/analysis_options.yaml b/packages/firebase_core/firebase_core/firebase_core/example/analysis_options.yaml deleted file mode 100644 index 61b6c4de17c9..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/example/analysis_options.yaml +++ /dev/null @@ -1,29 +0,0 @@ -# This file configures the analyzer, which statically analyzes Dart code to -# check for errors, warnings, and lints. -# -# The issues identified by the analyzer are surfaced in the UI of Dart-enabled -# IDEs (https://dart.dev/tools#ides-and-editors). The analyzer can also be -# invoked from the command line by running `flutter analyze`. - -# The following line activates a set of recommended lints for Flutter apps, -# packages, and plugins designed to encourage good coding practices. -include: package:flutter_lints/flutter.yaml - -linter: - # The lint rules applied to this project can be customized in the - # section below to disable rules from the `package:flutter_lints/flutter.yaml` - # included above or to enable additional rules. A list of all available lints - # and their documentation is published at - # https://dart-lang.github.io/linter/lints/index.html. - # - # Instead of disabling a lint rule for the entire project in the - # section below, it can also be suppressed for a single line of code - # or a specific dart file by using the `// ignore: name_of_lint` and - # `// ignore_for_file: name_of_lint` syntax on the line or in the file - # producing the lint. - rules: - # avoid_print: false # Uncomment to disable the `avoid_print` rule - # prefer_single_quotes: true # Uncomment to enable the `prefer_single_quotes` rule - -# Additional information about this file can be found at -# https://dart.dev/guides/language/analysis-options diff --git a/packages/firebase_core/firebase_core/firebase_core/example/bin/CMakeFiles/generate.stamp b/packages/firebase_core/firebase_core/firebase_core/example/bin/CMakeFiles/generate.stamp deleted file mode 100644 index 9b5f49fa9f14..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/example/bin/CMakeFiles/generate.stamp +++ /dev/null @@ -1 +0,0 @@ -# CMake generation timestamp file for this directory. diff --git a/packages/firebase_core/firebase_core/firebase_core/example/bin/CMakeFiles/generate.stamp.depend b/packages/firebase_core/firebase_core/firebase_core/example/bin/CMakeFiles/generate.stamp.depend deleted file mode 100644 index 5b8da13f857a..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/example/bin/CMakeFiles/generate.stamp.depend +++ /dev/null @@ -1,5 +0,0 @@ -# CMake generation dependency list for this directory. -C:/Program Files/Microsoft Visual Studio/2022/Community/Common7/IDE/CommonExtensions/Microsoft/CMake/CMake/share/cmake-3.25/Modules/FindPackageHandleStandardArgs.cmake -C:/Program Files/Microsoft Visual Studio/2022/Community/Common7/IDE/CommonExtensions/Microsoft/CMake/CMake/share/cmake-3.25/Modules/FindPackageMessage.cmake -C:/Program Files/Microsoft Visual Studio/2022/Community/Common7/IDE/CommonExtensions/Microsoft/CMake/CMake/share/cmake-3.25/Modules/FindPkgConfig.cmake -C:/Users/guill/Downloads/firebase_cpp_sdk_10.5.0/firebase_cpp_sdk/CMakeLists.txt diff --git a/packages/firebase_core/firebase_core/firebase_core/example/bin/INSTALL.vcxproj b/packages/firebase_core/firebase_core/firebase_core/example/bin/INSTALL.vcxproj deleted file mode 100644 index 05091bebad78..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/example/bin/INSTALL.vcxproj +++ /dev/null @@ -1,165 +0,0 @@ - - - - x64 - - - - Debug - x64 - - - Profile - x64 - - - Release - x64 - - - - {B2284ACE-B264-3C77-ADAD-5516EBC85159} - Win32Proj - 10.0.22000.0 - x64 - INSTALL - NoUpgrade - - - - Utility - MultiByte - v143 - - - Utility - MultiByte - v143 - - - Utility - MultiByte - v143 - - - - - - - - - - <_ProjectFileVersion>10.0.20506.1 - $(Platform)\$(Configuration)\$(ProjectName)\ - $(Platform)\$(Configuration)\$(ProjectName)\ - $(Platform)\$(Configuration)\$(ProjectName)\ - - - - Always - - setlocal -"C:\Program Files\Microsoft Visual Studio\2022\Community\Common7\IDE\CommonExtensions\Microsoft\CMake\CMake\bin\cmake.exe" -DBUILD_TYPE=$(Configuration) -P cmake_install.cmake -if %errorlevel% neq 0 goto :cmEnd -:cmEnd -endlocal & call :cmErrorLevel %errorlevel% & goto :cmDone -:cmErrorLevel -exit /b %1 -:cmDone -if %errorlevel% neq 0 goto :VCEnd - - - - - Always - - setlocal -"C:\Program Files\Microsoft Visual Studio\2022\Community\Common7\IDE\CommonExtensions\Microsoft\CMake\CMake\bin\cmake.exe" -DBUILD_TYPE=$(Configuration) -P cmake_install.cmake -if %errorlevel% neq 0 goto :cmEnd -:cmEnd -endlocal & call :cmErrorLevel %errorlevel% & goto :cmDone -:cmErrorLevel -exit /b %1 -:cmDone -if %errorlevel% neq 0 goto :VCEnd - - - - - Always - - setlocal -"C:\Program Files\Microsoft Visual Studio\2022\Community\Common7\IDE\CommonExtensions\Microsoft\CMake\CMake\bin\cmake.exe" -DBUILD_TYPE=$(Configuration) -P cmake_install.cmake -if %errorlevel% neq 0 goto :cmEnd -:cmEnd -endlocal & call :cmErrorLevel %errorlevel% & goto :cmDone -:cmErrorLevel -exit /b %1 -:cmDone -if %errorlevel% neq 0 goto :VCEnd - - - - - - setlocal -cd . -if %errorlevel% neq 0 goto :cmEnd -:cmEnd -endlocal & call :cmErrorLevel %errorlevel% & goto :cmDone -:cmErrorLevel -exit /b %1 -:cmDone -if %errorlevel% neq 0 goto :VCEnd - %(AdditionalInputs) - C:\Users\guill\Developer\flutterfire\packages\firebase_core\firebase_core\firebase_core\example\bin\CMakeFiles\INSTALL_force - false - false - - setlocal -cd . -if %errorlevel% neq 0 goto :cmEnd -:cmEnd -endlocal & call :cmErrorLevel %errorlevel% & goto :cmDone -:cmErrorLevel -exit /b %1 -:cmDone -if %errorlevel% neq 0 goto :VCEnd - %(AdditionalInputs) - C:\Users\guill\Developer\flutterfire\packages\firebase_core\firebase_core\firebase_core\example\bin\CMakeFiles\INSTALL_force - false - false - - setlocal -cd . -if %errorlevel% neq 0 goto :cmEnd -:cmEnd -endlocal & call :cmErrorLevel %errorlevel% & goto :cmDone -:cmErrorLevel -exit /b %1 -:cmDone -if %errorlevel% neq 0 goto :VCEnd - %(AdditionalInputs) - C:\Users\guill\Developer\flutterfire\packages\firebase_core\firebase_core\firebase_core\example\bin\CMakeFiles\INSTALL_force - false - false - - - - - {DC08768F-F57C-313C-94F0-E16194F54223} - ZERO_CHECK - false - Never - - - {DF648812-5598-379C-A5B5-8A3EAC6BC5B0} - ALL_BUILD - false - Never - - - - - - \ No newline at end of file diff --git a/packages/firebase_core/firebase_core/firebase_core/example/bin/INSTALL.vcxproj.filters b/packages/firebase_core/firebase_core/firebase_core/example/bin/INSTALL.vcxproj.filters deleted file mode 100644 index 69fed1abf535..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/example/bin/INSTALL.vcxproj.filters +++ /dev/null @@ -1,13 +0,0 @@ - - - - - CMake Rules - - - - - {EAE753BC-CF7B-3081-8331-9EFFB2F8D8A5} - - - diff --git a/packages/firebase_core/firebase_core/firebase_core/example/bin/cmake_install.cmake b/packages/firebase_core/firebase_core/firebase_core/example/bin/cmake_install.cmake deleted file mode 100644 index 8cf9b6c06b96..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/example/bin/cmake_install.cmake +++ /dev/null @@ -1,34 +0,0 @@ -# Install script for directory: C:/Users/guill/Downloads/firebase_cpp_sdk_10.5.0/firebase_cpp_sdk - -# Set the install prefix -if(NOT DEFINED CMAKE_INSTALL_PREFIX) - set(CMAKE_INSTALL_PREFIX "$") -endif() -string(REGEX REPLACE "/$" "" CMAKE_INSTALL_PREFIX "${CMAKE_INSTALL_PREFIX}") - -# Set the install configuration name. -if(NOT DEFINED CMAKE_INSTALL_CONFIG_NAME) - if(BUILD_TYPE) - string(REGEX REPLACE "^[^A-Za-z0-9_]+" "" - CMAKE_INSTALL_CONFIG_NAME "${BUILD_TYPE}") - else() - set(CMAKE_INSTALL_CONFIG_NAME "Release") - endif() - message(STATUS "Install configuration: \"${CMAKE_INSTALL_CONFIG_NAME}\"") -endif() - -# Set the component getting installed. -if(NOT CMAKE_INSTALL_COMPONENT) - if(COMPONENT) - message(STATUS "Install component: \"${COMPONENT}\"") - set(CMAKE_INSTALL_COMPONENT "${COMPONENT}") - else() - set(CMAKE_INSTALL_COMPONENT) - endif() -endif() - -# Is this installation the result of a crosscompile? -if(NOT DEFINED CMAKE_CROSSCOMPILING) - set(CMAKE_CROSSCOMPILING "FALSE") -endif() - diff --git a/packages/firebase_core/firebase_core/firebase_core/example/lib/main.dart b/packages/firebase_core/firebase_core/firebase_core/example/lib/main.dart deleted file mode 100644 index 4e2b473ad9e0..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/example/lib/main.dart +++ /dev/null @@ -1,63 +0,0 @@ -import 'package:flutter/material.dart'; -import 'dart:async'; - -import 'package:flutter/services.dart'; -import 'package:firebase_core/firebase_core.dart'; - -void main() { - runApp(const MyApp()); -} - -class MyApp extends StatefulWidget { - const MyApp({super.key}); - - @override - State createState() => _MyAppState(); -} - -class _MyAppState extends State { - String _platformVersion = 'Unknown'; - final _firebaseCorePlugin = FirebaseCore(); - - @override - void initState() { - super.initState(); - initPlatformState(); - } - - // Platform messages are asynchronous, so we initialize in an async method. - Future initPlatformState() async { - String platformVersion; - // Platform messages may fail, so we use a try/catch PlatformException. - // We also handle the message potentially returning null. - try { - platformVersion = - await _firebaseCorePlugin.getPlatformVersion() ?? 'Unknown platform version'; - } on PlatformException { - platformVersion = 'Failed to get platform version.'; - } - - // If the widget was removed from the tree while the asynchronous platform - // message was in flight, we want to discard the reply rather than calling - // setState to update our non-existent appearance. - if (!mounted) return; - - setState(() { - _platformVersion = platformVersion; - }); - } - - @override - Widget build(BuildContext context) { - return MaterialApp( - home: Scaffold( - appBar: AppBar( - title: const Text('Plugin example app'), - ), - body: Center( - child: Text('Running on: $_platformVersion\n'), - ), - ), - ); - } -} diff --git a/packages/firebase_core/firebase_core/firebase_core/example/linux/.gitignore b/packages/firebase_core/firebase_core/firebase_core/example/linux/.gitignore deleted file mode 100644 index d3896c98444f..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/example/linux/.gitignore +++ /dev/null @@ -1 +0,0 @@ -flutter/ephemeral diff --git a/packages/firebase_core/firebase_core/firebase_core/example/linux/CMakeLists.txt b/packages/firebase_core/firebase_core/firebase_core/example/linux/CMakeLists.txt deleted file mode 100644 index 9ae42276201e..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/example/linux/CMakeLists.txt +++ /dev/null @@ -1,150 +0,0 @@ -# Project-level configuration. -cmake_minimum_required(VERSION 3.10) -project(runner LANGUAGES CXX) - -# The name of the executable created for the application. Change this to change -# the on-disk name of your application. -set(BINARY_NAME "firebase_core_example") -# The unique GTK application identifier for this application. See: -# https://wiki.gnome.org/HowDoI/ChooseApplicationID -set(APPLICATION_ID "com.example.firebase_core") - -# Explicitly opt in to modern CMake behaviors to avoid warnings with recent -# versions of CMake. -cmake_policy(SET CMP0063 NEW) - -# Load bundled libraries from the lib/ directory relative to the binary. -set(CMAKE_INSTALL_RPATH "$ORIGIN/lib") - -# Root filesystem for cross-building. -if(FLUTTER_TARGET_PLATFORM_SYSROOT) - set(CMAKE_SYSROOT ${FLUTTER_TARGET_PLATFORM_SYSROOT}) - set(CMAKE_FIND_ROOT_PATH ${CMAKE_SYSROOT}) - set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) - set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY) - set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) - set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) -endif() - -# Define build configuration options. -if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) - set(CMAKE_BUILD_TYPE "Debug" CACHE - STRING "Flutter build mode" FORCE) - set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS - "Debug" "Profile" "Release") -endif() - -# Compilation settings that should be applied to most targets. -# -# Be cautious about adding new options here, as plugins use this function by -# default. In most cases, you should add new options to specific targets instead -# of modifying this function. -function(APPLY_STANDARD_SETTINGS TARGET) - target_compile_features(${TARGET} PUBLIC cxx_std_14) - target_compile_options(${TARGET} PRIVATE -Wall -Werror) - target_compile_options(${TARGET} PRIVATE "$<$>:-O3>") - target_compile_definitions(${TARGET} PRIVATE "$<$>:NDEBUG>") -endfunction() - -# Flutter library and tool build rules. -set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") -add_subdirectory(${FLUTTER_MANAGED_DIR}) - -# Add Firebase libraries to the target using the function from the SDK. -add_subdirectory(${FIREBASE_CPP_SDK_DIR} bin/ EXCLUDE_FROM_ALL) - -# The Firebase C++ library `firebase_app` is required, -# and it must always be listed last. - -# Add the Firebase SDKs for the products you want to use in your app -# For example, to use Firebase Authentication and Firebase Realtime Database -set(firebase_libs firebase_auth firebase_database firebase_app) -target_link_libraries(${target_name} "${firebase_libs}") - - -# System-level dependencies. -find_package(PkgConfig REQUIRED) -pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) - -add_definitions(-DAPPLICATION_ID="${APPLICATION_ID}") - -# Define the application target. To change its name, change BINARY_NAME above, -# not the value here, or `flutter run` will no longer work. -# -# Any new source files that you add to the application should be added here. -add_executable(${BINARY_NAME} - "main.cc" - "my_application.cc" - "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" -) - -# Apply the standard set of build settings. This can be removed for applications -# that need different build settings. -apply_standard_settings(${BINARY_NAME}) - -# Add dependency libraries. Add any application-specific dependencies here. -target_link_libraries(${BINARY_NAME} PRIVATE flutter) -target_link_libraries(${BINARY_NAME} PRIVATE PkgConfig::GTK) - -# Run the Flutter tool portions of the build. This must not be removed. -add_dependencies(${BINARY_NAME} flutter_assemble) - -# Only the install-generated bundle's copy of the executable will launch -# correctly, since the resources must in the right relative locations. To avoid -# people trying to run the unbundled copy, put it in a subdirectory instead of -# the default top-level location. -set_target_properties(${BINARY_NAME} - PROPERTIES - RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/intermediates_do_not_run" -) - -# Generated plugin build rules, which manage building the plugins and adding -# them to the application. -include(flutter/generated_plugins.cmake) - - -# === Installation === -# By default, "installing" just makes a relocatable bundle in the build -# directory. -set(BUILD_BUNDLE_DIR "${PROJECT_BINARY_DIR}/bundle") -if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) - set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) -endif() - -# Start with a clean build bundle directory every time. -install(CODE " - file(REMOVE_RECURSE \"${BUILD_BUNDLE_DIR}/\") - " COMPONENT Runtime) - -set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") -set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}/lib") - -install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" - COMPONENT Runtime) - -install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" - COMPONENT Runtime) - -install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" - COMPONENT Runtime) - -foreach(bundled_library ${PLUGIN_BUNDLED_LIBRARIES}) - install(FILES "${bundled_library}" - DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" - COMPONENT Runtime) -endforeach(bundled_library) - -# Fully re-copy the assets directory on each build to avoid having stale files -# from a previous install. -set(FLUTTER_ASSET_DIR_NAME "flutter_assets") -install(CODE " - file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") - " COMPONENT Runtime) -install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" - DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) - -# Install the AOT library on non-Debug builds only. -if(NOT CMAKE_BUILD_TYPE MATCHES "Debug") - install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" - COMPONENT Runtime) -endif() diff --git a/packages/firebase_core/firebase_core/firebase_core/example/linux/flutter/CMakeLists.txt b/packages/firebase_core/firebase_core/firebase_core/example/linux/flutter/CMakeLists.txt deleted file mode 100644 index d5bd01648a96..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/example/linux/flutter/CMakeLists.txt +++ /dev/null @@ -1,88 +0,0 @@ -# This file controls Flutter-level build steps. It should not be edited. -cmake_minimum_required(VERSION 3.10) - -set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") - -# Configuration provided via flutter tool. -include(${EPHEMERAL_DIR}/generated_config.cmake) - -# TODO: Move the rest of this into files in ephemeral. See -# https://github.com/flutter/flutter/issues/57146. - -# Serves the same purpose as list(TRANSFORM ... PREPEND ...), -# which isn't available in 3.10. -function(list_prepend LIST_NAME PREFIX) - set(NEW_LIST "") - foreach(element ${${LIST_NAME}}) - list(APPEND NEW_LIST "${PREFIX}${element}") - endforeach(element) - set(${LIST_NAME} "${NEW_LIST}" PARENT_SCOPE) -endfunction() - -# === Flutter Library === -# System-level dependencies. -find_package(PkgConfig REQUIRED) -pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) -pkg_check_modules(GLIB REQUIRED IMPORTED_TARGET glib-2.0) -pkg_check_modules(GIO REQUIRED IMPORTED_TARGET gio-2.0) - -set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/libflutter_linux_gtk.so") - -# Published to parent scope for install step. -set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) -set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) -set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) -set(AOT_LIBRARY "${PROJECT_DIR}/build/lib/libapp.so" PARENT_SCOPE) - -list(APPEND FLUTTER_LIBRARY_HEADERS - "fl_basic_message_channel.h" - "fl_binary_codec.h" - "fl_binary_messenger.h" - "fl_dart_project.h" - "fl_engine.h" - "fl_json_message_codec.h" - "fl_json_method_codec.h" - "fl_message_codec.h" - "fl_method_call.h" - "fl_method_channel.h" - "fl_method_codec.h" - "fl_method_response.h" - "fl_plugin_registrar.h" - "fl_plugin_registry.h" - "fl_standard_message_codec.h" - "fl_standard_method_codec.h" - "fl_string_codec.h" - "fl_value.h" - "fl_view.h" - "flutter_linux.h" -) -list_prepend(FLUTTER_LIBRARY_HEADERS "${EPHEMERAL_DIR}/flutter_linux/") -add_library(flutter INTERFACE) -target_include_directories(flutter INTERFACE - "${EPHEMERAL_DIR}" -) -target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}") -target_link_libraries(flutter INTERFACE - PkgConfig::GTK - PkgConfig::GLIB - PkgConfig::GIO -) -add_dependencies(flutter flutter_assemble) - -# === Flutter tool backend === -# _phony_ is a non-existent file to force this command to run every time, -# since currently there's no way to get a full input/output list from the -# flutter tool. -add_custom_command( - OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} - ${CMAKE_CURRENT_BINARY_DIR}/_phony_ - COMMAND ${CMAKE_COMMAND} -E env - ${FLUTTER_TOOL_ENVIRONMENT} - "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.sh" - ${FLUTTER_TARGET_PLATFORM} ${CMAKE_BUILD_TYPE} - VERBATIM -) -add_custom_target(flutter_assemble DEPENDS - "${FLUTTER_LIBRARY}" - ${FLUTTER_LIBRARY_HEADERS} -) diff --git a/packages/firebase_core/firebase_core/firebase_core/example/linux/flutter/generated_plugin_registrant.cc b/packages/firebase_core/firebase_core/firebase_core/example/linux/flutter/generated_plugin_registrant.cc deleted file mode 100644 index 15034725064f..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/example/linux/flutter/generated_plugin_registrant.cc +++ /dev/null @@ -1,15 +0,0 @@ -// -// Generated file. Do not edit. -// - -// clang-format off - -#include "generated_plugin_registrant.h" - -#include - -void fl_register_plugins(FlPluginRegistry* registry) { - g_autoptr(FlPluginRegistrar) firebase_core_registrar = - fl_plugin_registry_get_registrar_for_plugin(registry, "FirebaseCorePlugin"); - firebase_core_plugin_register_with_registrar(firebase_core_registrar); -} diff --git a/packages/firebase_core/firebase_core/firebase_core/example/linux/flutter/generated_plugin_registrant.h b/packages/firebase_core/firebase_core/firebase_core/example/linux/flutter/generated_plugin_registrant.h deleted file mode 100644 index e0f0a47bc08f..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/example/linux/flutter/generated_plugin_registrant.h +++ /dev/null @@ -1,15 +0,0 @@ -// -// Generated file. Do not edit. -// - -// clang-format off - -#ifndef GENERATED_PLUGIN_REGISTRANT_ -#define GENERATED_PLUGIN_REGISTRANT_ - -#include - -// Registers Flutter plugins. -void fl_register_plugins(FlPluginRegistry* registry); - -#endif // GENERATED_PLUGIN_REGISTRANT_ diff --git a/packages/firebase_core/firebase_core/firebase_core/example/linux/flutter/generated_plugins.cmake b/packages/firebase_core/firebase_core/firebase_core/example/linux/flutter/generated_plugins.cmake deleted file mode 100644 index 1d55b5b0bf79..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/example/linux/flutter/generated_plugins.cmake +++ /dev/null @@ -1,24 +0,0 @@ -# -# Generated file, do not edit. -# - -list(APPEND FLUTTER_PLUGIN_LIST - firebase_core -) - -list(APPEND FLUTTER_FFI_PLUGIN_LIST -) - -set(PLUGIN_BUNDLED_LIBRARIES) - -foreach(plugin ${FLUTTER_PLUGIN_LIST}) - add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/linux plugins/${plugin}) - target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) - list(APPEND PLUGIN_BUNDLED_LIBRARIES $) - list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) -endforeach(plugin) - -foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST}) - add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/linux plugins/${ffi_plugin}) - list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries}) -endforeach(ffi_plugin) diff --git a/packages/firebase_core/firebase_core/firebase_core/example/linux/main.cc b/packages/firebase_core/firebase_core/firebase_core/example/linux/main.cc deleted file mode 100644 index e7c5c5437037..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/example/linux/main.cc +++ /dev/null @@ -1,6 +0,0 @@ -#include "my_application.h" - -int main(int argc, char** argv) { - g_autoptr(MyApplication) app = my_application_new(); - return g_application_run(G_APPLICATION(app), argc, argv); -} diff --git a/packages/firebase_core/firebase_core/firebase_core/example/linux/my_application.cc b/packages/firebase_core/firebase_core/firebase_core/example/linux/my_application.cc deleted file mode 100644 index b699538ff8ee..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/example/linux/my_application.cc +++ /dev/null @@ -1,104 +0,0 @@ -#include "my_application.h" - -#include -#ifdef GDK_WINDOWING_X11 -#include -#endif - -#include "flutter/generated_plugin_registrant.h" - -struct _MyApplication { - GtkApplication parent_instance; - char** dart_entrypoint_arguments; -}; - -G_DEFINE_TYPE(MyApplication, my_application, GTK_TYPE_APPLICATION) - -// Implements GApplication::activate. -static void my_application_activate(GApplication* application) { - MyApplication* self = MY_APPLICATION(application); - GtkWindow* window = - GTK_WINDOW(gtk_application_window_new(GTK_APPLICATION(application))); - - // Use a header bar when running in GNOME as this is the common style used - // by applications and is the setup most users will be using (e.g. Ubuntu - // desktop). - // If running on X and not using GNOME then just use a traditional title bar - // in case the window manager does more exotic layout, e.g. tiling. - // If running on Wayland assume the header bar will work (may need changing - // if future cases occur). - gboolean use_header_bar = TRUE; -#ifdef GDK_WINDOWING_X11 - GdkScreen* screen = gtk_window_get_screen(window); - if (GDK_IS_X11_SCREEN(screen)) { - const gchar* wm_name = gdk_x11_screen_get_window_manager_name(screen); - if (g_strcmp0(wm_name, "GNOME Shell") != 0) { - use_header_bar = FALSE; - } - } -#endif - if (use_header_bar) { - GtkHeaderBar* header_bar = GTK_HEADER_BAR(gtk_header_bar_new()); - gtk_widget_show(GTK_WIDGET(header_bar)); - gtk_header_bar_set_title(header_bar, "firebase_core_example"); - gtk_header_bar_set_show_close_button(header_bar, TRUE); - gtk_window_set_titlebar(window, GTK_WIDGET(header_bar)); - } else { - gtk_window_set_title(window, "firebase_core_example"); - } - - gtk_window_set_default_size(window, 1280, 720); - gtk_widget_show(GTK_WIDGET(window)); - - g_autoptr(FlDartProject) project = fl_dart_project_new(); - fl_dart_project_set_dart_entrypoint_arguments(project, self->dart_entrypoint_arguments); - - FlView* view = fl_view_new(project); - gtk_widget_show(GTK_WIDGET(view)); - gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(view)); - - fl_register_plugins(FL_PLUGIN_REGISTRY(view)); - - gtk_widget_grab_focus(GTK_WIDGET(view)); -} - -// Implements GApplication::local_command_line. -static gboolean my_application_local_command_line(GApplication* application, gchar*** arguments, int* exit_status) { - MyApplication* self = MY_APPLICATION(application); - // Strip out the first argument as it is the binary name. - self->dart_entrypoint_arguments = g_strdupv(*arguments + 1); - - g_autoptr(GError) error = nullptr; - if (!g_application_register(application, nullptr, &error)) { - g_warning("Failed to register: %s", error->message); - *exit_status = 1; - return TRUE; - } - - g_application_activate(application); - *exit_status = 0; - - return TRUE; -} - -// Implements GObject::dispose. -static void my_application_dispose(GObject* object) { - MyApplication* self = MY_APPLICATION(object); - g_clear_pointer(&self->dart_entrypoint_arguments, g_strfreev); - G_OBJECT_CLASS(my_application_parent_class)->dispose(object); -} - -static void my_application_class_init(MyApplicationClass* klass) { - G_APPLICATION_CLASS(klass)->activate = my_application_activate; - G_APPLICATION_CLASS(klass)->local_command_line = my_application_local_command_line; - G_OBJECT_CLASS(klass)->dispose = my_application_dispose; -} - -static void my_application_init(MyApplication* self) {} - -MyApplication* my_application_new() { - return MY_APPLICATION(g_object_new(my_application_get_type(), - "application-id", APPLICATION_ID, - "flags", G_APPLICATION_NON_UNIQUE, - nullptr)); -} diff --git a/packages/firebase_core/firebase_core/firebase_core/example/linux/my_application.h b/packages/firebase_core/firebase_core/firebase_core/example/linux/my_application.h deleted file mode 100644 index 72271d5e4170..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/example/linux/my_application.h +++ /dev/null @@ -1,18 +0,0 @@ -#ifndef FLUTTER_MY_APPLICATION_H_ -#define FLUTTER_MY_APPLICATION_H_ - -#include - -G_DECLARE_FINAL_TYPE(MyApplication, my_application, MY, APPLICATION, - GtkApplication) - -/** - * my_application_new: - * - * Creates a new Flutter-based application. - * - * Returns: a new #MyApplication. - */ -MyApplication* my_application_new(); - -#endif // FLUTTER_MY_APPLICATION_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/example/pubspec.yaml b/packages/firebase_core/firebase_core/firebase_core/example/pubspec.yaml deleted file mode 100644 index dd3d2b2c7b7e..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/example/pubspec.yaml +++ /dev/null @@ -1,83 +0,0 @@ -name: firebase_core_example -description: Demonstrates how to use the firebase_core plugin. -# The following line prevents the package from being accidentally published to -# pub.dev using `flutter pub publish`. This is preferred for private packages. -publish_to: 'none' # Remove this line if you wish to publish to pub.dev - -environment: - sdk: '>=2.19.2 <3.0.0' - -# Dependencies specify other packages that your package needs in order to work. -# To automatically upgrade your package dependencies to the latest versions -# consider running `flutter pub upgrade --major-versions`. Alternatively, -# dependencies can be manually updated by changing the version numbers below to -# the latest version available on pub.dev. To see which dependencies have newer -# versions available, run `flutter pub outdated`. -dependencies: - flutter: - sdk: flutter - - firebase_core: - # When depending on this package from a real application you should use: - # firebase_core: ^x.y.z - # See https://dart.dev/tools/pub/dependencies#version-constraints - # The example app is bundled with the plugin so we use a path dependency on - # the parent directory to use the current plugin's version. - path: ../ - - # The following adds the Cupertino Icons font to your application. - # Use with the CupertinoIcons class for iOS style icons. - cupertino_icons: ^1.0.2 - -dev_dependencies: - flutter_test: - sdk: flutter - - # The "flutter_lints" package below contains a set of recommended lints to - # encourage good coding practices. The lint set provided by the package is - # activated in the `analysis_options.yaml` file located at the root of your - # package. See that file for information about deactivating specific lint - # rules and activating additional ones. - flutter_lints: ^2.0.0 - -# For information on the generic Dart part of this file, see the -# following page: https://dart.dev/tools/pub/pubspec - -# The following section is specific to Flutter packages. -flutter: - - # The following line ensures that the Material Icons font is - # included with your application, so that you can use the icons in - # the material Icons class. - uses-material-design: true - - # To add assets to your application, add an assets section, like this: - # assets: - # - images/a_dot_burr.jpeg - # - images/a_dot_ham.jpeg - - # An image asset can refer to one or more resolution-specific "variants", see - # https://flutter.dev/assets-and-images/#resolution-aware - - # For details regarding adding assets from package dependencies, see - # https://flutter.dev/assets-and-images/#from-packages - - # To add custom fonts to your application, add a fonts section here, - # in this "flutter" section. Each entry in this list should have a - # "family" key with the font family name, and a "fonts" key with a - # list giving the asset and other descriptors for the font. For - # example: - # fonts: - # - family: Schyler - # fonts: - # - asset: fonts/Schyler-Regular.ttf - # - asset: fonts/Schyler-Italic.ttf - # style: italic - # - family: Trajan Pro - # fonts: - # - asset: fonts/TrajanPro.ttf - # - asset: fonts/TrajanPro_Bold.ttf - # weight: 700 - # - # For details regarding fonts from package dependencies, - # see https://flutter.dev/custom-fonts/#from-packages diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/google-services-desktop.json b/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/google-services-desktop.json deleted file mode 100644 index a3bf216f4de0..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/google-services-desktop.json +++ /dev/null @@ -1,37 +0,0 @@ -{ - "project_info": { - "project_number": "406099696497", - "firebase_url": "https://flutterfire-e2e-tests-default-rtdb.europe-west1.firebasedatabase.app", - "project_id": "flutterfire-e2e-tests", - "storage_bucket": "flutterfire-e2e-tests.appspot.com" - }, - "client": [ - { - "client_info": { - "mobilesdk_app_id": "1:406099696497:ios:58cbc26aca8e5cf83574d0", - "android_client_info": { - "package_name": "io.flutter.plugins.firebase.auth.example" - } - }, - "oauth_client": [ - { - "client_id": "406099696497-134k3722m01rtrsklhf3b7k8sqa5r7in.apps.googleusercontent.com" - } - ], - "api_key": [ - { - "current_key": "AIzaSyDooSUGSf63Ghq02_iIhtnmwMDs4HlWS6c" - } - ], - "services": { - "analytics_service": { - "status": 0 - }, - "appinvite_service": { - "status": 1 - } - } - } - ], - "configuration_version": "1" -} \ No newline at end of file diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/admob.h b/packages/firebase_core/firebase_core/firebase_core/firebase/admob.h deleted file mode 100644 index 957c86b7e168..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/admob.h +++ /dev/null @@ -1,215 +0,0 @@ -/* - * Copyright 2016 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_H_ -#define FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_H_ - -#include "firebase/internal/platform.h" - -#if FIREBASE_PLATFORM_ANDROID -#include -#endif // FIREBASE_PLATFORM_ANDROID - -#include "firebase/admob/banner_view.h" -#include "firebase/admob/interstitial_ad.h" -#include "firebase/admob/rewarded_video.h" -#include "firebase/admob/types.h" -#include "firebase/app.h" -#include "firebase/internal/common.h" - -#if !defined(DOXYGEN) && !defined(SWIG) -FIREBASE_APP_REGISTER_CALLBACKS_REFERENCE(admob) -#endif // !defined(DOXYGEN) && !defined(SWIG) - -namespace firebase { - -/// @deprecated The functionality in the firebase::admob namespace -/// has been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the new -/// SDK in our migration guide. -/// -/// @brief API for AdMob with Firebase. -/// -/// The AdMob API allows you to load and display mobile ads using the Google -/// Mobile Ads SDK. Each ad format has its own header file. -namespace admob { - -/// @deprecated -/// @brief Initializes AdMob via Firebase. -/// -/// The functionality in the firebase::admob namespace has -/// been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the -/// new SDK in our migration -/// guide. -/// -/// @param app The Firebase app for which to initialize mobile ads. -/// -/// @return kInitResultSuccess if initialization succeeded, or -/// kInitResultFailedMissingDependency on Android if Google Play services is not -/// available on the current device and the Google Mobile Ads SDK requires -/// Google Play services (for example, when using 'play-services-ads-lite'). -FIREBASE_DEPRECATED InitResult Initialize(const ::firebase::App& app); - -/// @deprecated -/// @brief Initializes AdMob via Firebase with the publisher's AdMob app ID. -/// -/// The functionality in the firebase::admob namespace has -/// been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the -/// new SDK in our migration -/// guide. -/// -/// Initializing the Google Mobile Ads SDK with the AdMob app ID at app launch -/// allows the SDK to fetch app-level settings and perform configuration tasks -/// as early as possible. This can help reduce latency for the initial ad -/// request. AdMob app IDs are unique identifiers given to mobile apps when -/// they're registered in the AdMob console. To find your app ID in the AdMob -/// console, click the App management (https://apps.admob.com/#account/appmgmt:) -/// option under the settings dropdown (located in the upper right-hand corner). -/// App IDs have the form ca-app-pub-XXXXXXXXXXXXXXXX~NNNNNNNNNN. -/// -/// @param[in] app The Firebase app for which to initialize mobile ads. -/// @param[in] admob_app_id The publisher's AdMob app ID. -/// -/// @return kInitResultSuccess if initialization succeeded, or -/// kInitResultFailedMissingDependency on Android if Google Play services is not -/// available on the current device and the Google Mobile Ads SDK requires -/// Google Play services (for example, when using 'play-services-ads-lite'). -FIREBASE_DEPRECATED InitResult Initialize(const ::firebase::App& app, - const char* admob_app_id); - -#if FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) -/// @deprecated -/// @brief Initializes AdMob without Firebase for Android. -/// -/// The functionality in the firebase::admob namespace has -/// been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the -/// new SDK in our migration -/// guide. -/// -/// The arguments to @ref Initialize are platform-specific so the caller must do -/// something like this: -/// @code -/// #if defined(__ANDROID__) -/// firebase::admob::Initialize(jni_env, activity); -/// #else -/// firebase::admob::Initialize(); -/// #endif -/// @endcode -/// -/// @param[in] jni_env JNIEnv pointer. -/// @param[in] activity Activity used to start the application. -/// -/// @return kInitResultSuccess if initialization succeeded, or -/// kInitResultFailedMissingDependency on Android if Google Play services is not -/// available on the current device and the AdMob SDK requires -/// Google Play services (for example when using 'play-services-ads-lite'). -FIREBASE_DEPRECATED InitResult Initialize(JNIEnv* jni_env, jobject activity); - -/// @deprecated -/// @brief Initializes AdMob via Firebase with the publisher's AdMob app ID. -/// -/// The functionality in the firebase::admob namespace has -/// been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the -/// new SDK in our migration -/// guide. -/// -/// Initializing the Google Mobile Ads SDK with the AdMob app ID at app launch -/// allows the SDK to fetch app-level settings and perform configuration tasks -/// as early as possible. This can help reduce latency for the initial ad -/// request. AdMob app IDs are unique identifiers given to mobile apps when -/// they're registered in the AdMob console. To find your app ID in the AdMob -/// console, click the App management (https://apps.admob.com/#account/appmgmt:) -/// option under the settings dropdown (located in the upper right-hand corner). -/// App IDs have the form ca-app-pub-XXXXXXXXXXXXXXXX~NNNNNNNNNN. -/// -/// The arguments to @ref Initialize are platform-specific so the caller must do -/// something like this: -/// @code -/// #if defined(__ANDROID__) -/// firebase::admob::Initialize(jni_env, activity, admob_app_id); -/// #else -/// firebase::admob::Initialize(admob_app_id); -/// #endif -/// @endcode -/// -/// @param[in] jni_env JNIEnv pointer. -/// @param[in] activity Activity used to start the application. -/// @param[in] admob_app_id The publisher's AdMob app ID. -/// -/// @return kInitResultSuccess if initialization succeeded, or -/// kInitResultFailedMissingDependency on Android if Google Play services is not -/// available on the current device and the AdMob SDK requires -/// Google Play services (for example when using 'play-services-ads-lite'). -FIREBASE_DEPRECATED InitResult Initialize(JNIEnv* jni_env, jobject activity, - const char* admob_app_id); -#endif // defined(__ANDROID__) || defined(DOXYGEN) -#if !FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) -/// @deprecated -/// @brief Initializes AdMob without Firebase for iOS. -/// -/// The functionality in the firebase::admob namespace has -/// been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the -/// new SDK in our migration -/// guide. -FIREBASE_DEPRECATED InitResult Initialize(); - -/// @deprecated -/// @brief Initializes AdMob with the publisher's AdMob app ID and without -/// Firebase for iOS. -/// -/// The functionality in the firebase::admob namespace has -/// been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the -/// new SDK in our migration -/// guide. -/// -/// Initializing the Google Mobile Ads SDK with the AdMob app ID at app launch -/// allows the SDK to fetch app-level settings and perform configuration tasks -/// as early as possible. This can help reduce latency for the initial ad -/// request. AdMob app IDs are unique identifiers given to mobile apps when -/// they're registered in the AdMob console. To find your app ID in the AdMob -/// console, click the App management (https://apps.admob.com/#account/appmgmt:) -/// option under the settings dropdown (located in the upper right-hand corner). -/// App IDs have the form ca-app-pub-XXXXXXXXXXXXXXXX~NNNNNNNNNN. -/// -/// @param[in] admob_app_id The publisher's AdMob app ID. -/// -/// @return kInitResultSuccess if initialization succeeded -FIREBASE_DEPRECATED InitResult Initialize(const char* admob_app_id); -#endif // !defined(__ANDROID__) || defined(DOXYGEN) - -/// @deprecated -/// @brief Terminate AdMob. -/// -/// The functionality in the firebase::admob namespace has -/// been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the -/// new SDK in our migration -/// guide. -/// -/// Frees resources associated with AdMob that were allocated during -/// @ref firebase::admob::Initialize(). -FIREBASE_DEPRECATED void Terminate(); - -} // namespace admob -} // namespace firebase - -#endif // FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/admob/banner_view.h b/packages/firebase_core/firebase_core/firebase_core/firebase/admob/banner_view.h deleted file mode 100644 index 2d691f2d3a77..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/admob/banner_view.h +++ /dev/null @@ -1,427 +0,0 @@ -/* - * Copyright 2016 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_BANNER_VIEW_H_ -#define FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_BANNER_VIEW_H_ - -#include "firebase/admob/types.h" -#include "firebase/future.h" -#include "firebase/internal/common.h" - -namespace firebase { -namespace admob { - -namespace internal { -// Forward declaration for platform-specific data, implemented in each library. -class BannerViewInternal; -} // namespace internal - -/// @deprecated The functionality in the firebase::admob namespace -/// has been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the new -/// SDK in our migration guide. -/// -/// @brief Loads and displays AdMob banner ads. -/// -/// Each BannerView object corresponds to a single AdMob banner placement. There -/// are methods to load an ad, move it, show it and hide it, and retrieve the -/// bounds of the ad onscreen. -/// -/// BannerView objects maintain a presentation state that indicates whether -/// or not they're currently onscreen, as well as a set of bounds (stored in a -/// @ref BoundingBox struct), but otherwise provide information about -/// their current state through Futures. Methods like @ref Initialize, -/// @ref LoadAd, and @ref Hide each have a corresponding @ref Future from which -/// the result of the last call can be determined. The two variants of -/// @ref MoveTo share a single result @ref Future, since they're essentially the -/// same action. -/// -/// In addition, applications can create their own subclasses of -/// @ref BannerView::Listener, pass an instance to the @ref SetListener method, -/// and receive callbacks whenever the presentation state or bounding box of the -/// ad changes. -/// -/// For example, you could initialize, load, and show a banner view while -/// checking the result of the previous action at each step as follows: -/// -/// @code -/// namespace admob = ::firebase::admob; -/// admob::BannerView* banner_view = new admob::BannerView(); -/// banner_view->Initialize(ad_parent, "YOUR_AD_UNIT_ID", desired_ad_size) -/// @endcode -/// -/// Then, later: -/// -/// @code -/// if (banner_view->InitializeLastResult().status() == -/// ::firebase::kFutureStatusComplete && -/// banner_view->InitializeLastResult().error() == -/// firebase::admob::kAdMobErrorNone) { -/// banner_view->LoadAd(your_ad_request); -/// } -/// @endcode -/// -class BannerView { - public: -#ifdef INTERNAL_EXPERIMENTAL -// LINT.IfChange -#endif // INTERNAL_EXPERIMENTAL - /// @deprecated - /// @brief The presentation state of a @ref BannerView. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - enum PresentationState { - /// BannerView is currently hidden. - kPresentationStateHidden = 0, - /// BannerView is visible, but does not contain an ad. - kPresentationStateVisibleWithoutAd, - /// BannerView is visible and contains an ad. - kPresentationStateVisibleWithAd, - /// BannerView is visible and has opened a partial overlay on the screen. - kPresentationStateOpenedPartialOverlay, - /// BannerView is completely covering the screen or has caused focus to - /// leave the application (for example, when opening an external browser - /// during a clickthrough). - kPresentationStateCoveringUI, - }; -#ifdef INTERNAL_EXPERIMENTAL -// LINT.ThenChange(//depot_firebase_cpp/admob/client/cpp/src_java/com/google/firebase/admob/internal/cpp/ConstantsHelper.java) -#endif // INTERNAL_EXPERIMENTAL - -#ifdef INTERNAL_EXPERIMENTAL -// LINT.IfChange -#endif // INTERNAL_EXPERIMENTAL - /// @deprecated - /// @brief The possible screen positions for a @ref BannerView. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - enum Position { - /// Top of the screen, horizontally centered. - kPositionTop = 0, - /// Bottom of the screen, horizontally centered. - kPositionBottom, - /// Top-left corner of the screen. - kPositionTopLeft, - /// Top-right corner of the screen. - kPositionTopRight, - /// Bottom-left corner of the screen. - kPositionBottomLeft, - /// Bottom-right corner of the screen. - kPositionBottomRight, - }; -#ifdef INTERNAL_EXPERIMENTAL -// LINT.ThenChange(//depot_firebase_cpp/admob/client/cpp/src_java/com/google/firebase/admob/internal/cpp/ConstantsHelper.java) -#endif // INTERNAL_EXPERIMENTAL - - /// @deprecated - /// @brief A listener class that developers can extend and pass to a @ref - /// BannerView object's @ref SetListener method to be notified of changes to - /// the presentation state and bounding box. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - class Listener { - public: - /// @deprecated - /// @brief This method is called when the @ref BannerView object's - /// presentation state changes. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - /// @param[in] banner_view The banner view whose presentation state changed. - /// @param[in] state The new presentation state. - virtual void OnPresentationStateChanged(BannerView* banner_view, - PresentationState state) = 0; - /// @deprecated - /// @brief This method is called when the @ref BannerView object's bounding - /// box changes. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - /// @param[in] banner_view The banner view whose bounding box changed. - /// @param[in] box The new bounding box. - virtual void OnBoundingBoxChanged(BannerView* banner_view, - BoundingBox box) = 0; - virtual ~Listener(); - }; - - /// @deprecated - /// @brief Creates an uninitialized @ref BannerView object. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - /// - /// @ref Initialize must be called before the object is used. - FIREBASE_DEPRECATED BannerView(); - - ~BannerView(); - - /// @deprecated - /// @brief Initializes the @ref BannerView object. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - /// @param[in] parent The platform-specific UI element that will host the ad. - /// @param[in] ad_unit_id The ad unit ID to use when requesting ads. - /// @param[in] size The desired ad size for the banner. - FIREBASE_DEPRECATED Future Initialize(AdParent parent, - const char* ad_unit_id, - AdSize size); - - /// @deprecated - /// @brief Returns a @ref Future that has the status of the last call to - /// @ref Initialize. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - FIREBASE_DEPRECATED Future InitializeLastResult() const; - - /// @deprecated - /// @brief Begins an asynchronous request for an ad. If successful, the ad - /// will automatically be displayed in the BannerView. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - /// @param[in] request An AdRequest struct with information about the request - /// to be made (such as targeting info). - FIREBASE_DEPRECATED Future LoadAd(const AdRequest& request); - - /// @deprecated - /// @brief Returns a @ref Future containing the status of the last call to - /// @ref LoadAd. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - FIREBASE_DEPRECATED Future LoadAdLastResult() const; - - /// @deprecated - /// @brief Hides the BannerView. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - FIREBASE_DEPRECATED Future Hide(); - - /// @deprecated - /// @brief Returns a @ref Future containing the status of the last call to - /// @ref Hide. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - FIREBASE_DEPRECATED Future HideLastResult() const; - - /// @deprecated - /// @brief Shows the @ref BannerView. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - FIREBASE_DEPRECATED Future Show(); - - /// @deprecated - /// @brief Returns a @ref Future containing the status of the last call to - /// @ref Show. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - FIREBASE_DEPRECATED Future ShowLastResult() const; - - /// @deprecated - /// @brief Pauses the @ref BannerView. Should be called whenever the C++ - /// engine pauses or the application loses focus. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - FIREBASE_DEPRECATED Future Pause(); - - /// @deprecated - /// @brief Returns a @ref Future containing the status of the last call to - /// @ref Pause. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - FIREBASE_DEPRECATED Future PauseLastResult() const; - - /// @deprecated - /// @brief Resumes the @ref BannerView after pausing. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - FIREBASE_DEPRECATED Future Resume(); - - /// @deprecated - /// @brief Returns a @ref Future containing the status of the last call to - /// @ref Resume. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - FIREBASE_DEPRECATED Future ResumeLastResult() const; - - /// @deprecated - /// @brief Cleans up and deallocates any resources used by the @ref - /// BannerView. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - FIREBASE_DEPRECATED Future Destroy(); - - /// @deprecated - /// @brief Returns a @ref Future containing the status of the last call to - /// @ref Destroy. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - FIREBASE_DEPRECATED Future DestroyLastResult() const; - - /// @deprecated - /// @brief Moves the @ref BannerView so that its top-left corner is located at - /// (x, y). Coordinates are in pixels from the top-left corner of the screen. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - /// @param[in] x The desired horizontal coordinate. - /// @param[in] y The desired vertical coordinate. - FIREBASE_DEPRECATED Future MoveTo(int x, int y); - - /// @deprecated - /// @brief Moves the @ref BannerView so that it's located at the given - /// pre-defined position. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - /// @param[in] position The pre-defined position to which to move the - /// @ref BannerView. - FIREBASE_DEPRECATED Future MoveTo(Position position); - - /// @deprecated - /// @brief Returns a @ref Future containing the status of the last call to - /// either version of @ref MoveTo. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - FIREBASE_DEPRECATED Future MoveToLastResult() const; - - /// @deprecated - /// @brief Returns the current presentation state of the @ref BannerView. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - /// @return The current presentation state. - FIREBASE_DEPRECATED PresentationState presentation_state() const; - - /// @deprecated - /// @brief Retrieves the @ref BannerView's current onscreen size and location. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - FIREBASE_DEPRECATED BoundingBox bounding_box() const; - - /// @deprecated - /// @brief Sets the @ref Listener for this object. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - /// @param[in] listener A valid BannerView::Listener to receive callbacks. - FIREBASE_DEPRECATED void SetListener(Listener* listener); - - private: - // An internal, platform-specific implementation object that this class uses - // to interact with the Google Mobile Ads SDKs for iOS and Android. - internal::BannerViewInternal* internal_; -}; - -} // namespace admob -} // namespace firebase - -#endif // FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_BANNER_VIEW_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/admob/interstitial_ad.h b/packages/firebase_core/firebase_core/firebase_core/firebase/admob/interstitial_ad.h deleted file mode 100644 index b201ab7c3487..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/admob/interstitial_ad.h +++ /dev/null @@ -1,259 +0,0 @@ -/* - * Copyright 2016 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_INTERSTITIAL_AD_H_ -#define FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_INTERSTITIAL_AD_H_ - -#include "firebase/admob/types.h" -#include "firebase/future.h" -#include "firebase/internal/common.h" - -namespace firebase { -namespace admob { - -namespace internal { -// Forward declaration for platform-specific data, implemented in each library. -class InterstitialAdInternal; -} // namespace internal - -/// @deprecated The functionality in the firebase::admob namespace -/// has been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the new -/// SDK in our migration guide. -/// -/// @brief Loads and displays AdMob interstitial ads. -/// -/// @ref InterstitialAd is a single-use object that can load and show a -/// single AdMob interstitial ad. -/// -/// InterstitialAd objects maintain a presentation state that indicates whether -/// or not they're currently onscreen, but otherwise provide information about -/// their current state through Futures. @ref Initialize, @ref LoadAd, and -/// @ref Show each have a corresponding @ref Future from which you can determine -/// result of the previous call. -/// -/// In addition, applications can create their own subclasses of -/// @ref InterstitialAd::Listener, pass an instance to the @ref SetListener -/// method, and receive callbacks whenever the presentation state changes. -/// -/// Here's how one might initialize, load, and show an interstitial ad while -/// checking against the result of the previous action at each step: -/// -/// @code -/// namespace admob = ::firebase::admob; -/// admob::InterstitialAd* interstitial = new admob::InterstitialAd(); -/// interstitial->Initialize(ad_parent, "YOUR_AD_UNIT_ID") -/// @endcode -/// -/// Then, later: -/// -/// @code -/// if (interstitial->InitializeLastResult().status() == -/// ::firebase::kFutureStatusComplete && -/// interstitial->InitializeLastResult().error() == -/// firebase::admob::kAdMobErrorNone) { -/// interstitial->LoadAd(my_ad_request); -/// } -/// @endcode -/// -/// And after that: -/// -/// @code -/// if (interstitial->LoadAdLastResult().status() == -/// ::firebase::kFutureStatusComplete && -/// interstitial->LoadAdLastResult().error() == -/// firebase::admob::kAdMobErrorNone)) { -/// interstitial->Show(); -/// } -/// @endcode -/// -class InterstitialAd { - public: -#ifdef INTERNAL_EXPERIMENTAL -// LINT.IfChange -#endif // INTERNAL_EXPERIMENTAL - /// @deprecated - /// @brief The presentation states of an @ref InterstitialAd. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - enum PresentationState { - /// InterstitialAd is not currently being shown. - kPresentationStateHidden = 0, - /// InterstitialAd is being shown or has caused focus to leave the - /// application (for example, when opening an external browser during a - /// clickthrough). - kPresentationStateCoveringUI, - }; -#ifdef INTERNAL_EXPERIMENTAL -// LINT.ThenChange(//depot_firebase_cpp/admob/client/cpp/src_java/com/google/firebase/admob/internal/cpp/InterstitialAdHelper.java) -#endif // INTERNAL_EXPERIMENTAL - - /// @deprecated - /// @brief A listener class that developers can extend and pass to an - /// @ref InterstitialAd object's @ref SetListener method to be notified of - /// presentation state changes. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - /// @param[in] interstitial_ad The interstitial ad whose presentation state - /// changed. - /// @param[in] state The new presentation state. - virtual void OnPresentationStateChanged(InterstitialAd* interstitial_ad, - PresentationState state) = 0; - virtual ~Listener(); - }; - - /// @deprecated - /// @brief Creates an uninitialized @ref InterstitialAd object. - /// @ref Initialize must be called before the object is used. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - FIREBASE_DEPRECATED InterstitialAd(); - - ~InterstitialAd(); - - /// @deprecated - /// @brief Initialize the @ref InterstitialAd object. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - /// @param[in] parent The platform-specific UI element that will host the ad. - /// @param[in] ad_unit_id The ad unit ID to use in loading the ad. - FIREBASE_DEPRECATED Future Initialize(AdParent parent, - const char* ad_unit_id); - - /// @deprecated - /// @brief Returns a @ref Future containing the status of the last call to - /// @ref Initialize. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - FIREBASE_DEPRECATED Future InitializeLastResult() const; - - /// @deprecated - /// @brief Begins an asynchronous request for an ad. - /// - /// The @ref InterstitialAd::presentation_state method can be used to track - /// the progress of the request. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - /// @param[in] request An AdRequest struct with information about the request - /// to be made (such as targeting info). - FIREBASE_DEPRECATED Future LoadAd(const AdRequest& request); - - /// @deprecated - /// @brief Returns a @ref Future containing the status of the last call to - /// @ref LoadAd. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - FIREBASE_DEPRECATED Future LoadAdLastResult() const; - - /// @deprecated - /// @brief Shows the @ref InterstitialAd. This should not be called unless an - /// ad has already been loaded. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - FIREBASE_DEPRECATED Future Show(); - - /// @deprecated - /// @brief Returns a @ref Future containing the status of the last call to - /// @ref Show. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - FIREBASE_DEPRECATED Future ShowLastResult() const; - - /// @deprecated - /// @brief Returns the current presentation state of the @ref InterstitialAd. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - /// @return The current presentation state. - FIREBASE_DEPRECATED PresentationState presentation_state() const; - - /// @deprecated - /// @brief Sets the @ref Listener for this @ref InterstitialAd. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - /// @param[in] listener A valid InterstititalAd::Listener to receive - /// callbacks. - FIREBASE_DEPRECATED void SetListener(Listener* listener); - - private: - // An internal, platform-specific implementation object that this class uses - // to interact with the Google Mobile Ads SDKs for iOS and Android. - internal::InterstitialAdInternal* internal_; -}; - -} // namespace admob -} // namespace firebase - -#endif // FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_INTERSTITIAL_AD_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/admob/native_express_ad_view.h b/packages/firebase_core/firebase_core/firebase_core/firebase/admob/native_express_ad_view.h deleted file mode 100644 index 7e571967825e..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/admob/native_express_ad_view.h +++ /dev/null @@ -1,446 +0,0 @@ -/* - * Copyright 2016 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_NATIVE_EXPRESS_AD_VIEW_H_ -#define FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_NATIVE_EXPRESS_AD_VIEW_H_ - -#include "firebase/admob/types.h" -#include "firebase/future.h" -#include "firebase/internal/common.h" - -namespace firebase { -namespace admob { - -namespace internal { -// Forward declaration for platform-specific data, implemented in each library. -class NativeExpressAdViewInternal; -} // namespace internal - -/// @deprecated The functionality in the firebase::admob namespace -/// has been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the new -/// SDK in our migration guide. -/// Native Express Ads has been discontinued, and are no longer served. -/// -/// @brief Loads and displays ads from AdMob Native Ads Express. -/// -/// Each NativeExpressAdView object corresponds to a single AdMob Native Express -/// ad placement. There are methods to load an ad, move it, show it and hide it, -/// and retrieve the bounds of the ad onscreen. -/// -/// NativeExpressAdView objects maintain a presentation state that indicates -/// whether or not they're currently onscreen, as well as a set of bounds -/// (stored in a @ref BoundingBox struct), but otherwise provide information -/// about their current state through Futures. Methods like @ref Initialize, -/// @ref LoadAd, and @ref Hide each have a corresponding @ref Future from which -/// the result of the last call can be determined. The two variants of -/// @ref MoveTo share a single result @ref Future, since they're essentially the -/// same action. -/// -/// In addition, applications can create their own subclasses of -/// @ref NativeExpressAdView::Listener, pass an instance to the @ref SetListener -/// method, and receive callbacks whenever the presentation state or bounding -/// box of the ad changes. -/// -/// For example, you could initialize, load, and show a native express ad view -/// while checking the result of the previous action at each step as follows: -/// -/// @code -/// namespace admob = ::firebase::admob; -/// admob::NativeExpressAdView* ad_view = new admob::NativeExpressAdView(); -/// ad_view->Initialize(ad_parent, "YOUR_AD_UNIT_ID", desired_ad_size) -/// @endcode -/// -/// Then, later: -/// -/// @code -/// if (ad_view->InitializeLastResult().Status() == -/// ::firebase::kFutureStatusComplete && -/// ad_view->InitializeLastResult().Error() == -/// firebase::admob::kAdMobErrorNone) { -/// ad_view->LoadAd(your_ad_request); -/// } -/// @endcode -class NativeExpressAdView { - public: -#ifdef INTERNAL_EXPERIMENTAL -// LINT.IfChange -#endif // INTERNAL_EXPERIMENTAL - /// @deprecated - /// @brief The presentation state of a @ref NativeExpressAdView. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - enum PresentationState { - /// NativeExpressAdView is currently hidden. - kPresentationStateHidden = 0, - /// NativeExpressAdView is visible, but does not contain an ad. - kPresentationStateVisibleWithoutAd, - /// NativeExpressAdView is visible and contains an ad. - kPresentationStateVisibleWithAd, - /// NativeExpressAdView is visible and has opened a partial overlay on the - /// screen. - kPresentationStateOpenedPartialOverlay, - /// NativeExpressAdView is completely covering the screen or has caused - /// focus to leave the application (for example, when opening an external - /// browser during a clickthrough). - kPresentationStateCoveringUI, - }; -#ifdef INTERNAL_EXPERIMENTAL -// LINT.ThenChange(//depot_firebase_cpp/admob/client/cpp/src_java/com/google/firebase/admob/internal/cpp/ConstantsHelper.java) -#endif // INTERNAL_EXPERIMENTAL - -#ifdef INTERNAL_EXPERIMENTAL -// LINT.IfChange -#endif // INTERNAL_EXPERIMENTAL - /// @deprecated - /// @brief The possible screen positions for a @ref NativeExpressAdView. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - enum Position { - /// Top of the screen, horizontally centered. - kPositionTop = 0, - /// Bottom of the screen, horizontally centered. - kPositionBottom, - /// Top-left corner of the screen. - kPositionTopLeft, - /// Top-right corner of the screen. - kPositionTopRight, - /// Bottom-left corner of the screen. - kPositionBottomLeft, - /// Bottom-right corner of the screen. - kPositionBottomRight, - }; -#ifdef INTERNAL_EXPERIMENTAL -// LINT.ThenChange(//depot_firebase_cpp/admob/client/cpp/src_java/com/google/firebase/admob/internal/cpp/ConstantsHelper.java) -#endif // INTERNAL_EXPERIMENTAL - - /// @deprecated - /// @brief A listener class that developers can extend and pass to a - /// @ref NativeExpressAdView object's @ref SetListener method to be notified - /// of changes to the presentation state and bounding box. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - class Listener { - public: - /// @deprecated - /// @brief This method is called when the @ref NativeExpressAdView object's - /// presentation state changes. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - /// @param[in] ad_view The native express ad view whose presentation state - /// changed. - /// @param[in] state The new presentation state. - FIREBASE_DEPRECATED virtual void OnPresentationStateChanged( - NativeExpressAdView* ad_view, PresentationState state) = 0; - - /// @deprecated - /// @brief This method is called when the @ref NativeExpressAdView object's - /// bounding box changes. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - /// - /// @ref Initialize must be called before the object is used. - FIREBASE_DEPRECATED NativeExpressAdView(); - - ~NativeExpressAdView(); - - /// @deprecated - /// @brief Initializes the @ref NativeExpressAdView object. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - /// @param[in] parent The platform-specific UI element that will host the ad. - /// @param[in] ad_unit_id The ad unit ID to use when requesting ads. - /// @param[in] size The desired ad size for the native express ad. - FIREBASE_DEPRECATED Future Initialize(AdParent parent, - const char* ad_unit_id, - AdSize size); - - /// @deprecated - /// @brief Returns a @ref Future that has the status of the last call to - /// @ref Initialize. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - FIREBASE_DEPRECATED Future InitializeLastResult() const; - - /// @deprecated - /// @brief Begins an asynchronous request for an ad. If successful, the ad - /// will automatically be displayed in the NativeExpressAdView. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - /// @param[in] request An AdRequest struct with information about the request - /// to be made (such as targeting info). - FIREBASE_DEPRECATED Future LoadAd(const AdRequest& request); - - /// @deprecated - /// @brief Returns a @ref Future containing the status of the last call to - /// @ref LoadAd. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - FIREBASE_DEPRECATED Future LoadAdLastResult() const; - - /// @deprecated - /// @brief Hides the NativeExpressAdView. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - FIREBASE_DEPRECATED Future Hide(); - - /// @deprecated - /// @brief Returns a @ref Future containing the status of the last call to - /// @ref Hide. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - FIREBASE_DEPRECATED Future HideLastResult() const; - - /// @deprecated - /// @brief Shows the @ref NativeExpressAdView. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - FIREBASE_DEPRECATED Future Show(); - - /// @deprecated - /// @brief Returns a @ref Future containing the status of the last call to - /// @ref Show. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - FIREBASE_DEPRECATED Future ShowLastResult() const; - - /// @deprecated - /// @brief Pauses the @ref NativeExpressAdView. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - /// - /// Should be called whenever the C++ engine pauses or the application loses - /// focus. - FIREBASE_DEPRECATED Future Pause(); - - /// @deprecated - /// @brief Returns a @ref Future containing the status of the last call to - /// @ref Pause. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - FIREBASE_DEPRECATED Future PauseLastResult() const; - - /// @deprecated - /// @brief Resumes the @ref NativeExpressAdView after pausing. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - FIREBASE_DEPRECATED Future Resume(); - - /// @deprecated - /// @brief Returns a @ref Future containing the status of the last call to - /// @ref Resume. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - FIREBASE_DEPRECATED Future ResumeLastResult() const; - - /// @deprecated - /// @brief Cleans up and deallocates any resources used by the - /// @ref NativeExpressAdView. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - FIREBASE_DEPRECATED Future Destroy(); - - /// @deprecated - /// @brief Returns a @ref Future containing the status of the last call to - /// @ref Destroy. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - FIREBASE_DEPRECATED Future DestroyLastResult() const; - - /// @deprecated - /// @brief Moves the @ref NativeExpressAdView so that its top-left corner is - /// located at (x, y). Coordinates are in pixels from the top-left corner of - /// the screen. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - /// - /// When built for Android, the library will not display an ad on top of or - /// beneath an Activity's status bar. If a call to MoveTo would result in an - /// overlap, the @ref NativeExpressAdView is placed just below the status bar, - /// so no overlap occurs. - /// @param[in] x The desired horizontal coordinate. - /// @param[in] y The desired vertical coordinate. - FIREBASE_DEPRECATED Future MoveTo(int x, int y); - - /// @deprecated - /// @brief Moves the @ref NativeExpressAdView so that it's located at the - /// given pre-defined position. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - /// @param[in] position The pre-defined position to which to move the - /// @ref NativeExpressAdView. - FIREBASE_DEPRECATED Future MoveTo(Position position); - - /// @deprecated - /// @brief Returns a @ref Future containing the status of the last call to - /// either version of @ref MoveTo. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - FIREBASE_DEPRECATED Future MoveToLastResult() const; - - /// @deprecated - /// @brief Returns the current presentation state of the - /// @ref NativeExpressAdView. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - /// @return The current presentation state. - FIREBASE_DEPRECATED PresentationState GetPresentationState() const; - - /// @deprecated - /// @brief Retrieves the @ref NativeExpressAdView's current onscreen size and - /// location. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - /// @return The current size and location. Values are in pixels, and location - /// coordinates originate from the top-left corner of the screen. - FIREBASE_DEPRECATED BoundingBox GetBoundingBox() const; - - /// @deprecated - /// @brief Sets the @ref Listener for this object. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - /// @param[in] listener A valid NativeExpressAdView::Listener to receive - /// callbacks. - FIREBASE_DEPRECATED void SetListener(Listener* listener); - - private: - // An internal, platform-specific implementation object that this class uses - // to interact with the Google Mobile Ads SDKs for iOS and Android. - internal::NativeExpressAdViewInternal* internal_; -}; - -} // namespace admob -} // namespace firebase - -#endif // FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_NATIVE_EXPRESS_AD_VIEW_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/admob/rewarded_video.h b/packages/firebase_core/firebase_core/firebase_core/firebase/admob/rewarded_video.h deleted file mode 100644 index 32bea80b5550..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/admob/rewarded_video.h +++ /dev/null @@ -1,407 +0,0 @@ -/* - * Copyright 2016 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_REWARDED_VIDEO_H_ -#define FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_REWARDED_VIDEO_H_ - -#include -#include - -#include "firebase/admob/types.h" -#include "firebase/future.h" - -namespace firebase { - -// Forward declaration of Firebase's internal Mutex. -class Mutex; - -namespace admob { - -/// @deprecated The functionality in the firebase::admob namespace -/// has been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the new -/// SDK in our migration guide. -/// -/// @brief Loads and displays rewarded video ads via AdMob mediation. -/// -/// The rewarded_video namespace contains methods to load and display rewarded -/// video ads via the Google Mobile Ads SDK. The underlying SDK objects for -/// rewarded video on Android and iOS are singletons, so there are no objects -/// to represent individual ads here. Instead, methods in the rewarded_video -/// namespace are invoked to initialize, load, and show. -/// -/// The basic steps for loading and displaying an ad are: -/// -/// 1. Call @ref Initialize to init the library and mediation adapters. -/// 2. Call @ref LoadAd to load an ad (some SDKs may have cached an ad at init -/// time). -/// 3. Call @ref Show to show the ad to the user. -/// 4. Repeat steps 2 and 3 as desired. -/// 5. Call @ref Destroy when your app is completely finished showing rewarded -/// video ads. -/// -/// Note that Initialize must be the very first thing called, and @ref Destroy -/// must be the very last. -/// -/// The library maintains a presentation state that indicates whether or not an -/// ad is currently onscreen, but otherwise provides information about its -/// current state through Futures. @ref Initialize, @ref LoadAd, and so on each -/// have a corresponding @ref Future from which apps can determine the result of -/// the previous call. -/// -/// In addition, applications can create their own subclasses of @ref Listener, -/// pass an instance to the @ref SetListener method, and receive callbacks -/// whenever the presentation state changes or an ad has been viewed in full and -/// the user is due a reward. -/// -/// Here's how one might initialize, load, and show a rewarded video ad while -/// checking against the result of the previous action at each step: -/// -/// @code -/// firebase::admob::rewarded_video::Initialize(); -/// @endcode -/// -/// Then, later: -/// -/// @code -/// if (firebase::admob::rewarded_video::InitializeLastResult().status() == -/// firebase::kFutureStatusComplete && -/// firebase::admob::rewarded_video::InitializeLastResult().error() == -/// firebase::admob::kAdMobErrorNone) { -/// firebase::admob::rewarded_video::LoadAd(my_ad_unit_str, my_ad_request); -/// } -/// @endcode -/// -/// And after that: -/// -/// @code -/// if (firebase::admob::rewarded_video::LoadAdLastResult().status() == -/// firebase::kFutureStatusComplete && -/// firebase::admob::rewarded_video::LoadAdLastResult().error() == -/// firebase::admob::kAdMobErrorNone) { -/// firebase::admob::rewarded_video::Show(my_ad_parent); -/// } -/// @endcode -namespace rewarded_video { -#ifdef INTERNAL_EXPERIMENTAL -// LINT.IfChange -#endif // INTERNAL_EXPERIMENTAL -/// @deprecated -/// @brief The possible presentation states for rewarded video. -/// -/// The functionality in the firebase::admob namespace has -/// been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the -/// new SDK in our migration -/// guide. -enum PresentationState { - /// No ad is currently being shown. - kPresentationStateHidden = 0, - /// A rewarded video ad is completely covering the screen or has caused - /// focus to leave the application (for example, when opening an external - /// browser during a clickthrough), but the video associated with the ad has - /// yet to begin playing. - kPresentationStateCoveringUI, - /// All of the above conditions are true *except* that the video associated - /// with the ad began playing at some point in the past. - kPresentationStateVideoHasStarted, - /// The rewarded video has played and completed. - kPresentationStateVideoHasCompleted, -}; -#ifdef INTERNAL_EXPERIMENTAL -// LINT.ThenChange(//depot_firebase_cpp/admob/client/cpp/src_java/com/google/firebase/admob/internal/cpp/RewardedVideoHelper.java) -#endif // INTERNAL_EXPERIMENTAL - -/// @deprecated -/// @brief A reward to be given to the user in exchange for watching a rewarded -/// video ad. -/// -/// The functionality in the firebase::admob namespace has -/// been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the -/// new SDK in our migration -/// guide. -struct RewardItem { - /// The reward amount. - float amount; - /// A string description of the type of reward (such as "coins" or "points"). - std::string reward_type; -}; - -/// @deprecated -/// @brief A listener class that developers can extend and pass to @ref -/// SetListener to be notified of rewards and changes to the presentation state. -/// -/// The functionality in the firebase::admob namespace has -/// been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the -/// new SDK in our migration -/// guide. -class Listener { - public: - /// @deprecated - /// @brief Invoked when the user should be given a reward for watching an ad. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - /// @param[in] reward The user's reward. - FIREBASE_DEPRECATED virtual void OnRewarded(RewardItem reward) = 0; - - /// @deprecated - /// @brief Invoked when the presentation state of the ad changes. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - /// @param[in] state The new presentation state. - FIREBASE_DEPRECATED virtual void OnPresentationStateChanged( - PresentationState state) = 0; - - virtual ~Listener(); -}; - -/// @deprecated -/// @brief A polling-based listener that developers can instantiate and pass to -/// @ref SetListener in order to queue rewards for later retrieval. -/// -/// The functionality in the firebase::admob namespace has -/// been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the -/// new SDK in our migration -/// guide. -/// -/// The @ref PollReward method should be used to retrieve awards granted by the -/// Mobile Ads SDK and queued by this class. -/// @ref rewarded_video::presentation_state can be used to poll the current -/// presentation state, so no additional method has been added for it. -class PollableRewardListener : public Listener { - public: - /// @deprecated - /// @brief Default constructor. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - FIREBASE_DEPRECATED PollableRewardListener(); - ~PollableRewardListener(); - - /// @deprecated - /// @brief Invoked when the user should be given a reward for watching an ad. - /// - /// Deprecated. The functionality in the firebase::admob - /// namespace has been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the new - /// SDK in our migration - /// guide. - FIREBASE_DEPRECATED void OnRewarded(RewardItem reward); - - /// @deprecated - /// @brief nvoked when the presentation state of the ad changes. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - FIREBASE_DEPRECATED void OnPresentationStateChanged(PresentationState state); - - /// @deprecated - /// @brief Pop the oldest queued reward, and copy its data into the provided - /// RewardItem. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - /// - /// If no reward is available, the struct is unchanged. - /// @param reward Pointer to a struct that reward data can be copied into. - /// @returns true if a reward was popped and data was copied, false otherwise. - FIREBASE_DEPRECATED bool PollReward(RewardItem* reward); - - private: - Mutex* mutex_; - - // Rewards granted by the Mobile Ads SDK. - std::queue rewards_; -}; - -/// @deprecated -/// @brief Initializes rewarded video. This must be the first method invoked in -/// this namespace. -/// -/// The functionality in the firebase::admob namespace has -/// been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the -/// new SDK in our migration -/// guide. -FIREBASE_DEPRECATED Future Initialize(); - -/// @deprecated -/// @brief Returns a @ref Future that has the status of the last call to -/// @ref Initialize. -/// -/// The functionality in the firebase::admob namespace has -/// been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the -/// new SDK in our migration -/// guide. -FIREBASE_DEPRECATED Future InitializeLastResult(); - -/// @deprecated -/// @brief Begins an asynchronous request for an ad. -/// -/// The functionality in the firebase::admob namespace has -/// been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the -/// new SDK in our migration -/// guide. -/// @param[in] ad_unit_id The ad unit ID to use in the request. -/// @param[in] request An AdRequest struct with information about the request -/// to be made (such as targeting info). -FIREBASE_DEPRECATED Future LoadAd(const char* ad_unit_id, - const AdRequest& request); - -/// @deprecated -/// @brief Returns a @ref Future containing the status of the last call to -/// @ref LoadAd. -/// -/// The functionality in the firebase::admob namespace has -/// been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the -/// new SDK in our migration -/// guide. -FIREBASE_DEPRECATED Future LoadAdLastResult(); - -/// @deprecated -/// @brief Shows an ad, assuming one has loaded. -/// -/// The functionality in the firebase::admob namespace has -/// been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the -/// new SDK in our migration -/// guide. -/// -/// @ref LoadAd must be called before this method. -/// @param[in] parent An @ref AdParent that is a reference to an iOS -/// UIView or an Android Activity. -FIREBASE_DEPRECATED Future Show(AdParent parent); - -/// @deprecated -/// @brief Returns a @ref Future containing the status of the last call to -/// @ref Show. -/// -/// Deprecated. The functionality in the firebase::admob -/// namespace has been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the new -/// SDK in our migration -/// guide. -FIREBASE_DEPRECATED Future ShowLastResult(); - -/// @deprecated -/// @brief Pauses any background processing associated with rewarded video. -/// -/// The functionality in the firebase::admob namespace has -/// been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the -/// new SDK in our migration -/// guide. -/// -/// Should be called whenever the C++ engine pauses or the application loses -/// focus. -FIREBASE_DEPRECATED Future Pause(); - -/// @deprecated -/// @brief Returns a @ref Future containing the status of the last call to -/// @ref Pause. -/// -/// The functionality in the firebase::admob namespace has -/// been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the -/// new SDK in our migration -/// guide. -FIREBASE_DEPRECATED Future PauseLastResult(); - -/// @deprecated -/// @brief Resumes the rewarded video system after pausing. -/// -/// The functionality in the firebase::admob namespace has -/// been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the -/// new SDK in our migration -/// guide. -FIREBASE_DEPRECATED Future Resume(); - -/// @deprecated -/// @brief Returns a @ref Future containing the status of the last call to -/// @ref Resume. -/// -/// The functionality in the firebase::admob namespace has -/// been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the -/// new SDK in our migration -/// guide. -FIREBASE_DEPRECATED Future ResumeLastResult(); - -/// @deprecated -/// @brief Cleans up and deallocates any resources used by rewarded video. -/// -/// The functionality in the firebase::admob namespace has -/// been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the -/// new SDK in our migration -/// guide. -/// -/// No other methods in rewarded_video should be called once this method has -/// been invoked. The system is closed for business at that point. -FIREBASE_DEPRECATED void Destroy(); - -/// @deprecated -/// @brief Returns the current presentation state, indicating if an ad is -/// visible or if a video has started playing. -/// -/// The functionality in the firebase::admob namespace has -/// been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the -/// new SDK in our migration -/// guide. -/// @return The current presentation state. -FIREBASE_DEPRECATED PresentationState presentation_state(); - -/// @deprecated -/// @brief Sets the @ref Listener that should receive callbacks. -/// -/// The functionality in the firebase::admob namespace has -/// been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the -/// new SDK in our migration -/// guide. -/// @param[in] listener A valid Listener. -FIREBASE_DEPRECATED void SetListener(Listener* listener); - -} // namespace rewarded_video -} // namespace admob -} // namespace firebase - -#endif // FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_REWARDED_VIDEO_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/admob/types.h b/packages/firebase_core/firebase_core/firebase_core/firebase/admob/types.h deleted file mode 100644 index 21a8379f2d96..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/admob/types.h +++ /dev/null @@ -1,244 +0,0 @@ -/* - * Copyright 2016 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_TYPES_H_ -#define FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_TYPES_H_ - -#include "firebase/internal/platform.h" - -#if FIREBASE_PLATFORM_ANDROID -#include -#elif FIREBASE_PLATFORM_IOS || FIREBASE_PLATFORM_TVOS -extern "C" { -#include -} // extern "C" -#endif // FIREBASE_PLATFORM_ANDROID, FIREBASE_PLATFORM_IOS, - // FIREBASE_PLATFORM_TVOS - -namespace firebase { -namespace admob { - -/// @deprecated The functionality in the firebase::admob namespace -/// has been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the new -/// SDK in our migration guide. -/// -/// @brief This is a platform specific datatype that is required to create an -/// AdMob ad. -/// -/// The following defines the datatype on each platform: -///
    -///
  • Android: A `jobject` which references an Android Activity.
  • -///
  • iOS: An `id` which references an iOS UIView.
  • -///
-/// -#if FIREBASE_PLATFORM_ANDROID -/// An Android Activity from Java. -typedef jobject AdParent; -#elif FIREBASE_PLATFORM_IOS || FIREBASE_PLATFORM_TVOS -/// A pointer to an iOS UIView. -typedef id AdParent; -#else -/// A void pointer for stub classes. -typedef void *AdParent; -#endif // FIREBASE_PLATFORM_ANDROID, FIREBASE_PLATFORM_IOS, - // FIREBASE_PLATFORM_TVOS - -#ifdef INTERNAL_EXPERIMENTAL -// LINT.IfChange -#endif // INTERNAL_EXPERIMENTAL -/// @deprecated -/// @brief Error codes returned by Future::error(). -/// -/// The functionality in the firebase::admob namespace has -/// been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the -/// new SDK in our migration -/// guide. -enum AdMobError { - /// Call completed successfully. - kAdMobErrorNone, - /// The ad has not been fully initialized. - kAdMobErrorUninitialized, - /// The ad is already initialized (repeat call). - kAdMobErrorAlreadyInitialized, - /// A call has failed because an ad is currently loading. - kAdMobErrorLoadInProgress, - /// A call to load an ad has failed due to an internal SDK error. - kAdMobErrorInternalError, - /// A call to load an ad has failed due to an invalid request. - kAdMobErrorInvalidRequest, - /// A call to load an ad has failed due to a network error. - kAdMobErrorNetworkError, - /// A call to load an ad has failed because no ad was available to serve. - kAdMobErrorNoFill, - /// An attempt has been made to show an ad on an Android Activity that has - /// no window token (such as one that's not done initializing). - kAdMobErrorNoWindowToken, - /// Fallback error for any unidentified cases. - kAdMobErrorUnknown, -}; -#ifdef INTERNAL_EXPERIMENTAL -// LINT.ThenChange(//depot_firebase_cpp/admob/client/cpp/src_java/com/google/firebase/admob/internal/cpp/ConstantsHelper.java) -#endif // INTERNAL_EXPERIMENTAL - -/// @deprecated -/// @brief Types of ad sizes. -/// -/// The functionality in the firebase::admob namespace has -/// been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the -/// new SDK in our migration -/// guide. -enum AdSizeType { kAdSizeStandard = 0 }; - -/// @deprecated -/// @brief An ad size value to be used in requesting ads. -/// -/// The functionality in the firebase::admob namespace has -/// been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the -/// new SDK in our migration -/// guide. -struct AdSize { - /// The type of ad size. - AdSizeType ad_size_type; - /// Height of the ad (in points or dp). - int height; - /// Width of the ad (in points or dp). - int width; -}; - -/// @deprecated -/// @brief Gender information used as part of the -/// @ref firebase::admob::AdRequest struct. -/// -/// The functionality in the firebase::admob namespace has -/// been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the -/// new SDK in our migration -/// guide. -enum Gender { - /// The gender of the current user is unknown or unspecified by the - /// publisher. - kGenderUnknown = 0, - /// The current user is known to be male. - kGenderMale, - /// The current user is known to be female. - kGenderFemale -}; - -/// @deprecated -/// @brief Indicates whether an ad request is considered tagged for -/// child-directed treatment. -/// -/// The functionality in the firebase::admob namespace has -/// been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the -/// new SDK in our migration -/// guide. -enum ChildDirectedTreatmentState { - /// The child-directed status for the request is not indicated. - kChildDirectedTreatmentStateUnknown = 0, - /// The request is tagged for child-directed treatment. - kChildDirectedTreatmentStateTagged, - /// The request is not tagged for child-directed treatment. - kChildDirectedTreatmentStateNotTagged -}; - -/// @deprecated -/// @brief Generic Key-Value container used for the "extras" values in an -/// @ref firebase::admob::AdRequest. -/// -/// The functionality in the firebase::admob namespace has -/// been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the -/// new SDK in our migration -/// guide. -struct KeyValuePair { - /// The name for an "extra." - const char *key; - /// The value for an "extra." - const char *value; -}; - -/// @deprecated -/// @brief The information needed to request an ad. -/// -/// The functionality in the firebase::admob namespace has -/// been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the -/// new SDK in our migration -/// guide. -struct AdRequest { - /// An array of test device IDs specifying devices that test ads will be - /// returned for. - const char **test_device_ids; - /// The number of entries in the array referenced by test_device_ids. - unsigned int test_device_id_count; - /// An array of keywords or phrases describing the current user activity, such - /// as "Sports Scores" or "Football." - const char **keywords; - /// The number of entries in the array referenced by keywords. - unsigned int keyword_count; - /// A @ref KeyValuePair specifying additional parameters accepted by an ad - /// network. - const KeyValuePair *extras; - /// The number of entries in the array referenced by extras. - unsigned int extras_count; - /// The day the user was born. Specify the user's birthday to increase ad - /// relevancy. - int birthday_day; - /// The month the user was born. Specify the user's birthday to increase ad - /// relevancy. - int birthday_month; - /// The year the user was born. Specify the user's birthday to increase ad - /// relevancy. - int birthday_year; - /// The user's @ref Gender. Specify the user's gender to increase ad - /// relevancy. - Gender gender; - /// Specifies whether the request should be considered as child-directed for - /// purposes of the Children’s Online Privacy Protection Act (COPPA). - ChildDirectedTreatmentState tagged_for_child_directed_treatment; -}; - -/// @deprecated -/// @brief The screen location and dimensions of an ad view once it has been -/// initialized. -/// -/// The functionality in the firebase::admob namespace has -/// been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the -/// new SDK in our migration -/// guide. -struct BoundingBox { - /// Default constructor which initializes all member variables to 0. - BoundingBox() : height(0), width(0), x(0), y(0) {} - /// Height of the ad in pixels. - int height; - /// Width of the ad in pixels. - int width; - /// Horizontal position of the ad in pixels from the left. - int x; - /// Vertical position of the ad in pixels from the top. - int y; -}; - -} // namespace admob -} // namespace firebase - -#endif // FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_TYPES_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/analytics.h b/packages/firebase_core/firebase_core/firebase_core/firebase/analytics.h deleted file mode 100644 index 973890b20fce..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/analytics.h +++ /dev/null @@ -1,569 +0,0 @@ -/* - * Copyright 2016 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_ANALYTICS_SRC_INCLUDE_FIREBASE_ANALYTICS_H_ -#define FIREBASE_ANALYTICS_SRC_INCLUDE_FIREBASE_ANALYTICS_H_ - -#include -#include -#include -#include - -#include "firebase/app.h" -#include "firebase/future.h" -#include "firebase/internal/common.h" -#include "firebase/variant.h" - -#if !defined(DOXYGEN) && !defined(SWIG) -FIREBASE_APP_REGISTER_CALLBACKS_REFERENCE(analytics) -#endif // !defined(DOXYGEN) && !defined(SWIG) - -/// @brief Namespace that encompasses all Firebase APIs. -namespace firebase { - -/// @brief Firebase Analytics API. -/// -/// See the developer guides for general -/// information on using Firebase Analytics in your apps. -namespace analytics { - -/// @brief Event parameter. -/// -/// Parameters supply information that contextualize events (see @ref LogEvent). -/// You can associate up to 25 unique Parameters with each event type (name). -/// -/// -/// @if swig_examples -/// Common event types are provided as static properties of the -/// FirebaseAnalytics class (e.g FirebaseAnalytics.EventPostScore) where -/// parameters of these events are also provided in this FirebaseAnalytics -/// class (e.g FirebaseAnalytics.ParameterScore). -/// -/// You are not limited to the set of event types and parameter names -/// suggested in FirebaseAnalytics class properties. Additional Parameters can -/// be supplied for suggested event types or custom Parameters for custom event -/// types. -/// @endif -/// -/// @if cpp_examples -/// Common event types (names) are suggested in @ref event_names -/// (%event_names.h) with parameters of common event types defined in -/// @ref parameter_names (%parameter_names.h). -/// -/// You are not limited to the set of event types and parameter names suggested -/// in @ref event_names (%event_names.h) and %parameter_names.h respectively. -/// Additional Parameters can be supplied for suggested event types or custom -/// Parameters for custom event types. -/// @endif -/// -/// Parameter names must be a combination of letters and digits -/// (matching the regular expression [a-zA-Z0-9]) between 1 and 40 characters -/// long starting with a letter [a-zA-Z] character. The "firebase_", -/// "google_" and "ga_" prefixes are reserved and should not be used. -/// -/// Parameter string values can be up to 100 characters long. -/// -/// -/// @if swig_examples -/// An array of Parameter class instances can be passed to LogEvent in order -/// to associate parameters's of an event with values where each value can be -/// a double, 64-bit integer or string. -/// @endif -/// -/// @if cpp_examples -/// An array of this structure is passed to LogEvent in order to associate -/// parameter's of an event (Parameter::name) with values (Parameter::value) -/// where each value can be a double, 64-bit integer or string. -/// @endif -/// -/// For example, a game may log an achievement event along with the -/// character the player is using and the level they're currently on: -/// -/// -/// @if swig_examples -/// @code{.cs} -/// using Firebase.Analytics; -/// -/// int currentLevel = GetCurrentLevel(); -/// Parameter[] AchievementParameters = { -/// new Parameter(FirebaseAnalytics.ParameterAchievementID, -/// "ultimate_wizard"), -/// new Parameter(FirebaseAnalytics.ParameterCharacter, "mysterion"), -/// new Parameter(FirebaseAnalytics.ParameterLevel, currentLevel), -/// }; -/// FirebaseAnalytics.LogEvent(FirebaseAnalytics.EventLevelUp, -/// AchievementParameters); -/// @endcode -/// @endif -/// -/// @if cpp_examples -/// @code{.cpp} -/// using namespace firebase::analytics; -/// int64_t current_level = GetCurrentLevel(); -/// const Parameter achievement_parameters[] = { -/// Parameter(kParameterAchievementID, "ultimate_wizard"), -/// Parameter(kParameterCharacter, "mysterion"), -/// Parameter(kParameterLevel, current_level), -/// }; -/// LogEvent(kEventUnlockAchievement, achievement_parameters, -/// sizeof(achievement_parameters) / -/// sizeof(achievement_parameters[0])); -/// @endcode -/// @endif -/// -struct Parameter { -#ifndef SWIG - /// Construct an empty parameter. - /// - /// This is provided to allow initialization after construction. - Parameter() : name(nullptr) {} -#endif // !SWIG - -// -// We don't want to pull in Variant in the C# interface. -// -#ifndef SWIG - /// Construct a parameter. - /// - /// @param parameter_name Name of the parameter (see Parameter::name). - /// @param parameter_value Value for the parameter. Variants can - /// hold numbers and strings. - Parameter(const char* parameter_name, Variant parameter_value) - : name(parameter_name) { - value = parameter_value; - } -#endif // !SWIG - - /// Construct a 64-bit integer parameter. - /// - /// @param parameter_name Name of the parameter. - /// @if cpp_examples - /// (see Parameter::name). - /// @endif - /// - /// @if swig_examples - /// Parameter names must be a combination of letters and digits - /// (matching the regular expression [a-zA-Z0-9]) between 1 and 40 characters - /// long starting with a letter [a-zA-Z] character. - /// @endif - /// - /// @param parameter_value Integer value for the parameter. - Parameter(const char* parameter_name, int parameter_value) - : name(parameter_name) { - value = parameter_value; - } - - /// Construct a 64-bit integer parameter. - /// - /// @param parameter_name Name of the parameter. - /// @if cpp_examples - /// (see Parameter::name). - /// @endif - /// - /// @if swig_examples - /// Parameter names must be a combination of letters and digits - /// (matching the regular expression [a-zA-Z0-9]) between 1 and 40 characters - /// long starting with a letter [a-zA-Z] character. - /// @endif - /// - /// @param parameter_value Integer value for the parameter. - Parameter(const char* parameter_name, int64_t parameter_value) - : name(parameter_name) { - value = parameter_value; - } - - /// Construct a floating point parameter. - /// - /// @param parameter_name Name of the parameter. - /// @if cpp_examples - /// (see Parameter::name). - /// @endif - /// - /// @if swig_examples - /// Parameter names must be a combination of letters and digits - /// (matching the regular expression [a-zA-Z0-9]) between 1 and 40 characters - /// long starting with a letter [a-zA-Z] character. - /// @endif - /// - /// @param parameter_value Floating point value for the parameter. - Parameter(const char* parameter_name, double parameter_value) - : name(parameter_name) { - value = parameter_value; - } - - /// Construct a string parameter. - /// - /// @param parameter_name Name of the parameter. - /// @if cpp_examples - /// (see Parameter::name). - /// @endif - /// - /// @if swig_examples - /// Parameter names must be a combination of letters and digits - /// (matching the regular expression [a-zA-Z0-9]) between 1 and 40 characters - /// long starting with a letter [a-zA-Z] character. - /// @endif - /// - /// @param parameter_value String value for the parameter, can be up to 100 - /// characters long. - Parameter(const char* parameter_name, const char* parameter_value) - : name(parameter_name) { - value = parameter_value; - } - -#ifndef SWIG - // - // Skipping implementation values because the C# API members are - // immutable, and there's no other need to read these values in - // C#. The class just needs to be passed to the C++ layers. - // This also avoids having to solve the nested union, which is - // unsupported in swig. - // - - /// @brief Name of the parameter. - /// - /// Parameter names must be a combination of letters and digits - /// (matching the regular expression [a-zA-Z0-9]) between 1 and 40 characters - /// long starting with a letter [a-zA-Z] character. The "firebase_", - /// "google_" and "ga_" prefixes are reserved and should not be used. - const char* name; - /// @brief Value of the parameter. - /// - /// See firebase::Variant for usage information. - /// @note String values can be up to 100 characters long. - Variant value; -#endif // SWIG -}; - -/// @brief Initialize the Analytics API. -/// -/// This must be called prior to calling any other methods in the -/// firebase::analytics namespace. -/// -/// @param[in] app Default @ref firebase::App instance. -/// -/// @see firebase::App::GetInstance(). -void Initialize(const App& app); - -/// @brief Terminate the Analytics API. -/// -/// Cleans up resources associated with the API. -void Terminate(); - -/// @brief Sets whether analytics collection is enabled for this app on this -/// device. -/// -/// This setting is persisted across app sessions. By default it is enabled. -/// -/// @param[in] enabled true to enable analytics collection, false to disable. -void SetAnalyticsCollectionEnabled(bool enabled); - -/// @brief The type of consent to set. -/// -/// Supported consent types are kConsentTypeAdStorage and -/// kConsentTypeAnalyticsStorage. Omitting a type retains its previous status. -enum ConsentType { kConsentTypeAdStorage = 0, kConsentTypeAnalyticsStorage }; - -/// @brief The status value of the consent type. -/// -/// Supported statuses are kConsentStatusGranted and kConsentStatusDenied. -enum ConsentStatus { kConsentStatusGranted = 0, kConsentStatusDenied }; - -/// @brief Sets the applicable end user consent state (e.g., for device -/// identifiers) for this app on this device. -/// -/// Use the consent map to specify individual consent type values. Settings are -/// persisted across app sessions. By default consent types are set to -/// "granted". -void SetConsent(const std::map& consent_settings); - -/// @brief Log an event with one string parameter. -/// -/// @param[in] name Name of the event to log. Should contain 1 to 40 -/// alphanumeric characters or underscores. The name must start with an -/// alphabetic character. Some event names are reserved. -/// -/// @if swig_examples -/// See the FirebaseAnalytics.Event properties for the list of reserved event -/// names. -/// @endif -/// -/// @if cpp_examples -/// See @ref event_names (%event_names.h) for the list of reserved event names. -/// @endif -/// The "firebase_" prefix is reserved and should not be used. Note that event -/// names are case-sensitive and that logging two events whose names differ -/// only in case will result in two distinct events. -/// @param[in] parameter_name Name of the parameter to log. -/// For more information, see @ref Parameter. -/// @param[in] parameter_value Value of the parameter to log. -/// -/// -/// @if swig_examples -/// @see LogEvent(string, Parameter[]) -/// @endif -/// -/// @if cpp_examples -/// @see LogEvent(const char*, const Parameter*, size_t) -/// @endif -void LogEvent(const char* name, const char* parameter_name, - const char* parameter_value); - -/// @brief Log an event with one float parameter. -/// -/// @param[in] name Name of the event to log. Should contain 1 to 40 -/// alphanumeric characters or underscores. The name must start with an -/// alphabetic character. Some event names are reserved. -/// -/// @if swig_examples -/// See the FirebaseAnalytics.Event properties for the list of reserved event -/// names. -/// @endif -/// -/// @if cpp_examples -/// See @ref event_names (%event_names.h) for the list of reserved event names. -/// @endif -/// The "firebase_" prefix is reserved and should not be used. Note that event -/// names are case-sensitive and that logging two events whose names differ -/// only in case will result in two distinct events. -/// @param[in] parameter_name Name of the parameter to log. -/// For more information, see @ref Parameter. -/// @param[in] parameter_value Value of the parameter to log. -/// -/// -/// @if swig_examples -/// @see LogEvent(string, Parameter[]) -/// @endif -/// -/// @if cpp_examples -/// @see LogEvent(const char*, const Parameter*, size_t) -/// @endif -void LogEvent(const char* name, const char* parameter_name, - const double parameter_value); - -/// @brief Log an event with one 64-bit integer parameter. -/// -/// @param[in] name Name of the event to log. Should contain 1 to 40 -/// alphanumeric characters or underscores. The name must start with an -/// alphabetic character. Some event names are reserved. -/// -/// @if swig_examples -/// See the FirebaseAnalytics.Event properties for the list of reserved event -/// names. -/// @endif -/// -/// @if cpp_examples -/// See @ref event_names (%event_names.h) for the list of reserved event names. -/// @endif -/// The "firebase_" prefix is reserved and should not be used. Note that event -/// names are case-sensitive and that logging two events whose names differ -/// only in case will result in two distinct events. -/// @param[in] parameter_name Name of the parameter to log. -/// For more information, see @ref Parameter. -/// @param[in] parameter_value Value of the parameter to log. -/// -/// -/// @if swig_examples -/// @see LogEvent(string, Parameter[]) -/// @endif -/// -/// @if cpp_examples -/// @see LogEvent(const char*, const Parameter*, size_t) -/// @endif -void LogEvent(const char* name, const char* parameter_name, - const int64_t parameter_value); - -/// @brief Log an event with one integer parameter -/// (stored as a 64-bit integer). -/// -/// @param[in] name Name of the event to log. Should contain 1 to 40 -/// alphanumeric characters or underscores. The name must start with an -/// alphabetic character. Some event names are reserved. -/// -/// @if swig_examples -/// See the FirebaseAnalytics.Event properties for the list of reserved event -/// names. -/// @endif -/// -/// @if cpp_examples -/// See @ref event_names (%event_names.h) for the list of reserved event names. -/// @endif -/// The "firebase_" prefix is reserved and should not be used. Note that event -/// names are case-sensitive and that logging two events whose names differ -/// only in case will result in two distinct events. -/// @param[in] parameter_name Name of the parameter to log. -/// For more information, see @ref Parameter. -/// @param[in] parameter_value Value of the parameter to log. -/// -/// -/// @if swig_examples -/// @see LogEvent(string, Parameter[]) -/// @endif -/// -/// @if cpp_examples -/// @see LogEvent(const char*, const Parameter*, size_t) -/// @endif -void LogEvent(const char* name, const char* parameter_name, - const int parameter_value); - -/// @brief Log an event with no parameters. -/// -/// @param[in] name Name of the event to log. Should contain 1 to 40 -/// alphanumeric characters or underscores. The name must start with an -/// alphabetic character. Some event names are reserved. -/// -/// @if swig_examples -/// See the FirebaseAnalytics.Event properties for the list of reserved event -/// names. -/// @endif -/// -/// @if cpp_examples -/// See @ref event_names (%event_names.h) for the list of reserved event names. -/// @endif -/// The "firebase_" prefix is reserved and should not be used. Note that event -/// names are case-sensitive and that logging two events whose names differ -/// only in case will result in two distinct events. -/// -/// -/// @if swig_examples -/// @see LogEvent(string, Parameter[]) -/// @endif -/// -/// @if cpp_examples -/// @see LogEvent(const char*, const Parameter*, size_t) -/// @endif -void LogEvent(const char* name); - -// clang-format off -#ifdef SWIG -// Modify the following overload with unsafe, so that we can do some pinning -// in the C# code. -%csmethodmodifiers LogEvent "public unsafe" -#endif // SWIG -// clang-format on - -/// @brief Log an event with associated parameters. -/// -/// An Event is an important occurrence in your app that you want to -/// measure. You can report up to 500 different types of events per app and -/// you can associate up to 25 unique parameters with each Event type. -/// -/// Some common events are documented in @ref event_names (%event_names.h), -/// but you may also choose to specify custom event types that are associated -/// with your specific app. -/// -/// @param[in] name Name of the event to log. Should contain 1 to 40 -/// alphanumeric characters or underscores. The name must start with an -/// alphabetic character. Some event names are reserved. See @ref event_names -/// (%event_names.h) for the list of reserved event names. The "firebase_" -/// prefix is reserved and should not be used. Note that event names are -/// case-sensitive and that logging two events whose names differ only in -/// case will result in two distinct events. -/// @param[in] parameters Array of Parameter structures. -/// @param[in] number_of_parameters Number of elements in the parameters -/// array. -void LogEvent(const char* name, const Parameter* parameters, - size_t number_of_parameters); - -/// Initiates on-device conversion measurement given a user email address on iOS -/// and tvOS (no-op on Android). On iOS and tvOS, this method requires the -/// dependency GoogleAppMeasurementOnDeviceConversion to be linked in, -/// otherwise the invocation results in a no-op. -/// @param[in] email_address User email address. Include a domain name for all -/// email addresses (e.g. gmail.com or hotmail.co.jp). -void InitiateOnDeviceConversionMeasurementWithEmailAddress( - const char* email_address); - -/// @brief Set a user property to the given value. -/// -/// Properties associated with a user allow a developer to segment users -/// into groups that are useful to their application. Up to 25 properties -/// can be associated with a user. -/// -/// Suggested property names are listed @ref user_property_names -/// (%user_property_names.h) but you're not limited to this set. For example, -/// the "gamertype" property could be used to store the type of player where -/// a range of values could be "casual", "mid_core", or "core". -/// -/// @param[in] name Name of the user property to set. This must be a -/// combination of letters and digits (matching the regular expression -/// [a-zA-Z0-9] between 1 and 40 characters long starting with a letter -/// [a-zA-Z] character. -/// @param[in] property Value to set the user property to. Set this -/// argument to NULL or nullptr to remove the user property. The value can be -/// between 1 to 100 characters long. -void SetUserProperty(const char* name, const char* property); - -/// @brief Sets the user ID property. -/// -/// This feature must be used in accordance with -/// Google's Privacy -/// Policy -/// -/// @param[in] user_id The user ID associated with the user of this app on this -/// device. The user ID must be non-empty and no more than 256 characters long. -/// Setting user_id to NULL or nullptr removes the user ID. -void SetUserId(const char* user_id); - -/// @brief Sets the duration of inactivity that terminates the current session. -/// -/// @note The default value is 1800000 (30 minutes). -/// -/// @param milliseconds The duration of inactivity that terminates the current -/// session. -void SetSessionTimeoutDuration(int64_t milliseconds); - -/// Clears all analytics data for this app from the device and resets the app -/// instance id. -void ResetAnalyticsData(); - -/// Get the instance ID from the analytics service. -/// -/// @note This is *not* the same ID as the ID returned by -/// @if cpp_examples -/// firebase::instance_id::InstanceId. -/// @else -/// Firebase.InstanceId.FirebaseInstanceId. -/// @endif -/// -/// @returns Object which can be used to retrieve the analytics instance ID. -Future GetAnalyticsInstanceId(); - -/// Get the result of the most recent GetAnalyticsInstanceId() call. -/// -/// @returns Object which can be used to retrieve the analytics instance ID. -Future GetAnalyticsInstanceIdLastResult(); - -/// Asynchronously retrieves the identifier of the current app -/// session. -/// -/// The session ID retrieval could fail due to Analytics collection -/// disabled, or if the app session was expired. -/// -/// @returns Object which can be used to retrieve the identifier of the current -/// app session. -Future GetSessionId(); - -/// Get the result of the most recent GetSessionId() call. -/// -/// @returns Object which can be used to retrieve the identifier of the current -/// app session. -Future GetSessionIdLastResult(); - -} // namespace analytics -} // namespace firebase - -#endif // FIREBASE_ANALYTICS_SRC_INCLUDE_FIREBASE_ANALYTICS_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/analytics/event_names.h b/packages/firebase_core/firebase_core/firebase_core/firebase/analytics/event_names.h deleted file mode 100644 index 4f1d4e5a0e2b..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/analytics/event_names.h +++ /dev/null @@ -1,472 +0,0 @@ -// Copyright 2023 Google Inc. All Rights Reserved. - -#ifndef FIREBASE_ANALYTICS_CLIENT_CPP_INCLUDE_FIREBASE_ANALYTICS_EVENT_NAMES_H_ -#define FIREBASE_ANALYTICS_CLIENT_CPP_INCLUDE_FIREBASE_ANALYTICS_EVENT_NAMES_H_ - -/// @brief Namespace that encompasses all Firebase APIs. -namespace firebase { -/// @brief Firebase Analytics API. -namespace analytics { - - - -/// @defgroup event_names Analytics Events -/// -/// Predefined event names. -/// -/// An Event is an important occurrence in your app that you want to -/// measure. You can report up to 500 different types of Events per app -/// and you can associate up to 25 unique parameters with each Event type. -/// Some common events are suggested below, but you may also choose to -/// specify custom Event types that are associated with your specific app. -/// Each event type is identified by a unique name. Event names can be up -/// to 40 characters long, may only contain alphanumeric characters and -/// underscores ("_"), and must start with an alphabetic character. The -/// "firebase_", "google_", and "ga_" prefixes are reserved and should not -/// be used. -/// @{ - - -/// Ad Impression event. This event signifies when a user sees an ad -/// impression. Note: If you supply the @c AnalyticsParameterValue -/// parameter, you must also supply the @c AnalyticsParameterCurrency -/// parameter so that revenue metrics can be computed accurately. Params: -/// -///
    -///
  • @c AnalyticsParameterAdPlatform (String) (optional)
  • -///
  • @c AnalyticsParameterAdFormat (String) (optional)
  • -///
  • @c AnalyticsParameterAdSource (String) (optional)
  • -///
  • @c AnalyticsParameterAdUnitName (String) (optional)
  • -///
  • @c AnalyticsParameterCurrency (String) (optional)
  • -///
  • @c AnalyticsParameterValue (Double) (optional)
  • -///
-static const char*const kEventAdImpression = - "ad_impression"; - -/// Add Payment Info event. This event signifies that a user has submitted -/// their payment information. Note: If you supply the @c -/// AnalyticsParameterValue parameter, you must also supply the @c -/// AnalyticsParameterCurrency parameter so that revenue metrics can be -/// computed accurately. Params: -/// -///
    -///
  • @c AnalyticsParameterCoupon (String) (optional)
  • -///
  • @c AnalyticsParameterCurrency (String) (optional)
  • -///
  • @c AnalyticsParameterItems ([[String: Any]]) (optional)
  • -///
  • @c AnalyticsParameterPaymentType (String) (optional)
  • -///
  • @c AnalyticsParameterValue (Double) (optional)
  • -///
-static const char*const kEventAddPaymentInfo = - "add_payment_info"; - -/// Add Shipping Info event. This event signifies that a user has -/// submitted their shipping information. Note: If you supply the @c -/// AnalyticsParameterValue parameter, you must also supply the @c -/// AnalyticsParameterCurrency parameter so that revenue metrics can be -/// computed accurately. Params: -/// -///
    -///
  • @c AnalyticsParameterCoupon (String) (optional)
  • -///
  • @c AnalyticsParameterCurrency (String) (optional)
  • -///
  • @c AnalyticsParameterItems ([[String: Any]]) (optional)
  • -///
  • @c AnalyticsParameterShippingTier (String) (optional)
  • -///
  • @c AnalyticsParameterValue (Double) (optional)
  • -///
-static const char*const kEventAddShippingInfo = - "add_shipping_info"; - -/// E-Commerce Add To Cart event. This event signifies that an item(s) was -/// added to a cart for purchase. Add this event to a funnel with @c -/// AnalyticsEventPurchase to gauge the effectiveness of your -/// checParameter(kout, If you supply the @c AnalyticsParameterValue -/// parameter), you must also supply the @c AnalyticsParameterCurrency -/// parameter so that revenue metrics can be computed accurately. Params: -/// -///
    -///
  • @c AnalyticsParameterCurrency (String) (optional)
  • -///
  • @c AnalyticsParameterItems ([[String: Any]]) (optional)
  • -///
  • @c AnalyticsParameterValue (Double) (optional)
  • -///
-static const char*const kEventAddToCart = "add_to_cart"; - -/// E-Commerce Add To Wishlist event. This event signifies that an item -/// was added to a wishlist. Use this event to identify popular gift -/// items. Note: If you supply the @c AnalyticsParameterValue parameter, -/// you must also supply the @c AnalyticsParameterCurrency parameter so -/// that revenue metrics can be computed accurately. Params: -/// -///
    -///
  • @c AnalyticsParameterCurrency (String) (optional)
  • -///
  • @c AnalyticsParameterItems ([[String: Any]]) (optional)
  • -///
  • @c AnalyticsParameterValue (Double) (optional)
  • -///
-static const char*const kEventAddToWishlist = - "add_to_wishlist"; - -/// App Open event. By logging this event when an App becomes active, -/// developers can understand how often users leave and return during the -/// course of a Session. Although Sessions are automatically reported, -/// this event can provide further clarification around the continuous -/// engagement of app-users. -static const char*const kEventAppOpen = "app_open"; - -/// E-Commerce Begin Checkout event. This event signifies that a user has -/// begun the process of checking out. Add this event to a funnel with -/// your @c AnalyticsEventPurchase event to gauge the effectiveness of -/// your checkout process. Note: If you supply the @c -/// AnalyticsParameterValue parameter, you must also supply the @c -/// AnalyticsParameterCurrency parameter so that revenue metrics can be -/// computed accurately. Params: -/// -///
    -///
  • @c AnalyticsParameterCoupon (String) (optional)
  • -///
  • @c AnalyticsParameterCurrency (String) (optional)
  • -///
  • @c AnalyticsParameterItems ([[String: Any]]) (optional)
  • -///
  • @c AnalyticsParameterValue (Double) (optional)
  • -///
-static const char*const kEventBeginCheckout = - "begin_checkout"; - -/// Campaign Detail event. Log this event to supply the referral details -/// of a re-engagement campaign. Note: you must supply at least one of the -/// required parameters AnalyticsParameterSource, AnalyticsParameterMedium -/// or AnalyticsParameterCampaign. Params: -/// -///
    -///
  • @c AnalyticsParameterSource (String)
  • -///
  • @c AnalyticsParameterMedium (String)
  • -///
  • @c AnalyticsParameterCampaign (String)
  • -///
  • @c AnalyticsParameterTerm (String) (optional)
  • -///
  • @c AnalyticsParameterContent (String) (optional)
  • -///
  • @c AnalyticsParameterAdNetworkClickID (String) (optional)
  • -///
  • @c AnalyticsParameterCP1 (String) (optional)
  • -///
  • @c AnalyticsParameterCampaignID (String) (optional)
  • -///
  • @c AnalyticsParameterCreativeFormat (String) (optional)
  • -///
  • @c AnalyticsParameterMarketingTactic (String) (optional)
  • -///
  • @c AnalyticsParameterSourcePlatform (String) (optional)
  • -///
-static const char*const kEventCampaignDetails = - "campaign_details"; - -/// Earn Virtual Currency event. This event tracks the awarding of virtual -/// currency in your app. Log this along with @c -/// AnalyticsEventSpendVirtualCurrency to better understand your virtual -/// economy. Params: -/// -///
    -///
  • @c AnalyticsParameterVirtualCurrencyName (String)
  • -///
  • @c AnalyticsParameterValue (Int or Double)
  • -///
-static const char*const kEventEarnVirtualCurrency - = "earn_virtual_currency"; - -/// Generate Lead event. Log this event when a lead has been generated in -/// the app to understand the efficacy of your install and re-engagement -/// campaigns. Note: If you supply the @c AnalyticsParameterValue -/// parameter, you must also supply the @c AnalyticsParameterCurrency -/// parameter so that revenue metrics can be computed accurately. Params: -/// -///
    -///
  • @c AnalyticsParameterCurrency (String) (optional)
  • -///
  • @c AnalyticsParameterValue (Double) (optional)
  • -///
-static const char*const kEventGenerateLead = - "generate_lead"; - -/// Join Group event. Log this event when a user joins a group such as a -/// guild, team or family. Use this event to analyze how popular certain -/// groups or social features are in your app. Params: -/// -///
    -///
  • @c AnalyticsParameterGroupID (String)
  • -///
-static const char*const kEventJoinGroup = "join_group"; - -/// Level End event. Log this event when the user finishes a level. -/// Params: -/// -///
    -///
  • @c AnalyticsParameterLevelName (String)
  • -///
  • @c AnalyticsParameterSuccess (String)
  • -///
-static const char*const kEventLevelEnd = "level_end"; - -/// Level Start event. Log this event when the user starts a new level. -/// Params: -/// -///
    -///
  • @c AnalyticsParameterLevelName (String)
  • -///
-static const char*const kEventLevelStart = "level_start"; - -/// Level Up event. This event signifies that a player has leveled up in -/// your gaming app. It can help you gauge the level distribution of your -/// userbase and help you identify certain levels that are difficult to -/// pass. Params: -/// -///
    -///
  • @c AnalyticsParameterLevel (Int)
  • -///
  • @c AnalyticsParameterCharacter (String) (optional)
  • -///
-static const char*const kEventLevelUp = "level_up"; - -/// Login event. Apps with a login feature can report this event to -/// signify that a user has logged in. -static const char*const kEventLogin = "login"; - -/// Post Score event. Log this event when the user posts a score in your -/// gaming app. This event can help you understand how users are actually -/// performing in your game and it can help you correlate high scores with -/// certain audiences or behaviors. Params: -/// -///
    -///
  • @c AnalyticsParameterScore (Int)
  • -///
  • @c AnalyticsParameterLevel (Int) (optional)
  • -///
  • @c AnalyticsParameterCharacter (String) (optional)
  • -///
-static const char*const kEventPostScore = "post_score"; - -/// E-Commerce Purchase event. This event signifies that an item(s) was -/// purchased by a user. Note: This is different from the in-app purchase -/// event, which is reported automatically for App Store-based apps. Note: -/// If you supply the @c AnalyticsParameterValue parameter, you must also -/// supply the @c AnalyticsParameterCurrency parameter so that revenue -/// metrics can be computed accurately. Params: -/// -///
    -///
  • @c AnalyticsParameterAffiliation (String) (optional)
  • -///
  • @c AnalyticsParameterCoupon (String) (optional)
  • -///
  • @c AnalyticsParameterCurrency (String) (optional)
  • -///
  • @c AnalyticsParameterEndDate (String) (optional)
  • -///
  • @c AnalyticsParameterItemID (String) (optional)
  • -///
  • @c AnalyticsParameterItems ([[String: Any]]) (optional)
  • -///
  • @c AnalyticsParameterShipping (Double) (optional)
  • -///
  • @c AnalyticsParameterStartDate (String) (optional)
  • -///
  • @c AnalyticsParameterTax (Double) (optional)
  • -///
  • @c AnalyticsParameterTransactionID (String) (optional)
  • -///
  • @c AnalyticsParameterValue (Double) (optional)
  • -///
-static const char*const kEventPurchase = "purchase"; - -/// E-Commerce Refund event. This event signifies that a refund was -/// issued. Note: If you supply the @c AnalyticsParameterValue parameter, -/// you must also supply the @c AnalyticsParameterCurrency parameter so -/// that revenue metrics can be computed accurately. Params: -/// -///
    -///
  • @c AnalyticsParameterAffiliation (String) (optional)
  • -///
  • @c AnalyticsParameterCoupon (String) (optional)
  • -///
  • @c AnalyticsParameterCurrency (String) (optional)
  • -///
  • @c AnalyticsParameterItems ([[String: Any]]) (optional)
  • -///
  • @c AnalyticsParameterShipping (Double) (optional)
  • -///
  • @c AnalyticsParameterTax (Double) (optional)
  • -///
  • @c AnalyticsParameterTransactionID (String) (optional)
  • -///
  • @c AnalyticsParameterValue (Double) (optional)
  • -///
-static const char*const kEventRefund = "refund"; - -/// E-Commerce Remove from Cart event. This event signifies that an -/// item(s) was removed from a cart. Note: If you supply the @c -/// AnalyticsParameterValue parameter, you must also supply the @c -/// AnalyticsParameterCurrency parameter so that revenue metrics can be -/// computed accurately. Params: -/// -///
    -///
  • @c AnalyticsParameterCurrency (String) (optional)
  • -///
  • @c AnalyticsParameterItems ([[String: Any]]) (optional)
  • -///
  • @c AnalyticsParameterValue (Double) (optional)
  • -///
-static const char*const kEventRemoveFromCart = - "remove_from_cart"; - -/// Screen View event. This event signifies a screen view. Use this when a -/// screen transition occurs. This event can be logged irrespective of -/// whether automatic screen tracking is enabled. Params: -/// -///
    -///
  • @c AnalyticsParameterScreenClass (String) (optional)
  • -///
  • @c AnalyticsParameterScreenName (String) (optional)
  • -///
-static const char*const kEventScreenView = "screen_view"; - -/// Search event. Apps that support search features can use this event to -/// contextualize search operations by supplying the appropriate, -/// corresponding parameters. This event can help you identify the most -/// popular content in your app. Params: -/// -///
    -///
  • @c AnalyticsParameterSearchTerm (String)
  • -///
  • @c AnalyticsParameterStartDate (String) (optional)
  • -///
  • @c AnalyticsParameterEndDate (String) (optional)
  • -///
  • @c AnalyticsParameterNumberOfNights (Int) (optional) for hotel bookings
  • -///
  • @c AnalyticsParameterNumberOfRooms (Int) (optional) for hotel bookings
  • -///
  • @c AnalyticsParameterNumberOfPassengers (Int) (optional) for travel bookings
  • -///
  • @c AnalyticsParameterOrigin (String) (optional)
  • -///
  • @c AnalyticsParameterDestination (String) (optional)
  • -///
  • @c AnalyticsParameterTravelClass (String) (optional) for travel bookings
  • -///
-static const char*const kEventSearch = "search"; - -/// Select Content event. This general purpose event signifies that a user -/// has selected some content of a certain type in an app. The content can -/// be any object in your app. This event can help you identify popular -/// content and categories of content in your app. Params: -/// -///
    -///
  • @c AnalyticsParameterContentType (String)
  • -///
  • @c AnalyticsParameterItemID (String)
  • -///
-static const char*const kEventSelectContent = - "select_content"; - -/// Select Item event. This event signifies that an item was selected by a -/// user from a list. Use the appropriate parameters to contextualize the -/// event. Use this event to discover the most popular items selected. -/// Params: -/// -///
    -///
  • @c AnalyticsParameterItems ([[String: Any]]) (optional)
  • -///
  • @c AnalyticsParameterItemListID (String) (optional)
  • -///
  • @c AnalyticsParameterItemListName (String) (optional)
  • -///
-static const char*const kEventSelectItem = "select_item"; - -/// Select promotion event. This event signifies that a user has selected -/// a promotion offer. Use the appropriate parameters to contextualize the -/// event, such as the item(s) for which the promotion applies. Params: -/// -///
    -///
  • @c AnalyticsParameterCreativeName (String) (optional)
  • -///
  • @c AnalyticsParameterCreativeSlot (String) (optional)
  • -///
  • @c AnalyticsParameterItems ([[String: Any]]) (optional)
  • -///
  • @c AnalyticsParameterLocationID (String) (optional)
  • -///
  • @c AnalyticsParameterPromotionID (String) (optional)
  • -///
  • @c AnalyticsParameterPromotionName (String) (optional)
  • -///
-static const char*const kEventSelectPromotion = - "select_promotion"; - -/// Share event. Apps with social features can log the Share event to -/// identify the most viral content. Params: -/// -///
    -///
  • @c AnalyticsParameterContentType (String)
  • -///
  • @c AnalyticsParameterItemID (String)
  • -///
-static const char*const kEventShare = "share"; - -/// Sign Up event. This event indicates that a user has signed up for an -/// account in your app. The parameter signifies the method by which the -/// user signed up. Use this event to understand the different behaviors -/// between logged in and logged out users. Params: -/// -///
    -///
  • @c AnalyticsParameterMethod (String)
  • -///
-static const char*const kEventSignUp = "sign_up"; - -/// Spend Virtual Currency event. This event tracks the sale of virtual -/// goods in your app and can help you identify which virtual goods are -/// the most popular objects of purchase. Params: -/// -///
    -///
  • @c AnalyticsParameterItemName (String)
  • -///
  • @c AnalyticsParameterVirtualCurrencyName (String)
  • -///
  • @c AnalyticsParameterValue (Int or Double)
  • -///
-static const char*const kEventSpendVirtualCurrency - = "spend_virtual_currency"; - -/// Tutorial Begin event. This event signifies the start of the -/// on-boarding process in your app. Use this in a funnel with @c -/// AnalyticsEventTutorialComplete to understand how many users complete -/// this process and move on to the full app experience. -static const char*const kEventTutorialBegin = - "tutorial_begin"; - -/// Tutorial End event. Use this event to signify the user's completion of -/// your app's on-boarding process. Add this to a funnel with @c -/// AnalyticsEventTutorialBegin to gauge the completion rate of your -/// on-boarding process. -static const char*const kEventTutorialComplete = - "tutorial_complete"; - -/// Unlock Achievement event. Log this event when the user has unlocked an -/// achievement in your game. Since achievements generally represent the -/// breadth of a gaming experience, this event can help you understand how -/// many users are experiencing all that your game has to offer. Params: -/// -///
    -///
  • @c AnalyticsParameterAchievementID (String)
  • -///
-static const char*const kEventUnlockAchievement = - "unlock_achievement"; - -/// E-commerce View Cart event. This event signifies that a user has -/// viewed their cart. Use this to analyze your purchase funnel. Note: If -/// you supply the @c AnalyticsParameterValue parameter, you must also -/// supply the @c AnalyticsParameterCurrency parameter so that revenue -/// metrics can be computed accurately. Params: -/// -///
    -///
  • @c AnalyticsParameterCurrency (String) (optional)
  • -///
  • @c AnalyticsParameterItems ([[String: Any]]) (optional)
  • -///
  • @c AnalyticsParameterValue (Double) (optional)
  • -///
-static const char*const kEventViewCart = "view_cart"; - -/// View Item event. This event signifies that a user has viewed an item. -/// Use the appropriate parameters to contextualize the event. Use this -/// event to discover the most popular items viewed in your app. Note: If -/// you supply the @c AnalyticsParameterValue parameter, you must also -/// supply the @c AnalyticsParameterCurrency parameter so that revenue -/// metrics can be computed accurately. Params: -/// -///
    -///
  • @c AnalyticsParameterCurrency (String) (optional)
  • -///
  • @c AnalyticsParameterItems ([[String: Any]]) (optional)
  • -///
  • @c AnalyticsParameterValue (Double) (optional)
  • -///
-static const char*const kEventViewItem = "view_item"; - -/// View Item List event. Log this event when a user sees a list of items -/// or offerings. Params: -/// -///
    -///
  • @c AnalyticsParameterItems ([[String: Any]]) (optional)
  • -///
  • @c AnalyticsParameterItemListID (String) (optional)
  • -///
  • @c AnalyticsParameterItemListName (String) (optional)
  • -///
-static const char*const kEventViewItemList = - "view_item_list"; - -/// View Promotion event. This event signifies that a promotion was shown -/// to a user. Add this event to a funnel with the @c -/// AnalyticsEventAddToCart and @c AnalyticsEventPurchase to gauge your -/// conversion process. Params: -/// -///
    -///
  • @c AnalyticsParameterCreativeName (String) (optional)
  • -///
  • @c AnalyticsParameterCreativeSlot (String) (optional)
  • -///
  • @c AnalyticsParameterItems ([[String: Any]]) (optional)
  • -///
  • @c AnalyticsParameterLocationID (String) (optional)
  • -///
  • @c AnalyticsParameterPromotionID (String) (optional)
  • -///
  • @c AnalyticsParameterPromotionName (String) (optional)
  • -///
-static const char*const kEventViewPromotion = - "view_promotion"; - -/// View Search Results event. Log this event when the user has been -/// presented with the results of a search. Params: -/// -///
    -///
  • @c AnalyticsParameterSearchTerm (String)
  • -///
-static const char*const kEventViewSearchResults = - "view_search_results"; -/// @} - -} // namespace analytics -} // namespace firebase - -#endif // FIREBASE_ANALYTICS_CLIENT_CPP_INCLUDE_FIREBASE_ANALYTICS_EVENT_NAMES_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/analytics/parameter_names.h b/packages/firebase_core/firebase_core/firebase_core/firebase/analytics/parameter_names.h deleted file mode 100644 index fcc43c22fbc8..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/analytics/parameter_names.h +++ /dev/null @@ -1,755 +0,0 @@ -// Copyright 2023 Google Inc. All Rights Reserved. - -#ifndef FIREBASE_ANALYTICS_CLIENT_CPP_INCLUDE_FIREBASE_ANALYTICS_PARAMETER_NAMES_H_ -#define FIREBASE_ANALYTICS_CLIENT_CPP_INCLUDE_FIREBASE_ANALYTICS_PARAMETER_NAMES_H_ - -/// @brief Namespace that encompasses all Firebase APIs. -namespace firebase { -/// @brief Firebase Analytics API. -namespace analytics { - - - -/// @defgroup parameter_names Analytics Parameters -/// -/// Predefined event parameter names. -/// -/// Params supply information that contextualize Events. You can associate -/// up to 25 unique Params with each Event type. Some Params are suggested -/// below for certain common Events, but you are not limited to these. You -/// may supply extra Params for suggested Events or custom Params for -/// Custom events. Param names can be up to 40 characters long, may only -/// contain alphanumeric characters and underscores ("_"), and must start -/// with an alphabetic character. Param values can be up to 100 characters -/// long. The "firebase_", "google_", and "ga_" prefixes are reserved and -/// should not be used. -/// @{ - - -/// Game achievement ID (String). -/// @code -/// let params = [ -/// AnalyticsParameterAchievementID : "10_matches_won", -/// // ... -/// ] -/// @endcode -static const char*const kParameterAchievementID = - "achievement_id"; - -/// The ad format (e.g. Banner, Interstitial, Rewarded, Native, Rewarded -/// Interstitial, Instream). (String). -/// @code -/// let params = [ -/// AnalyticsParameterAdFormat : "Banner", -/// // ... -/// ] -/// @endcode -static const char*const kParameterAdFormat = - "ad_format"; - -/// Ad Network Click ID (String). Used for network-specific click IDs -/// which vary in format. -/// @code -/// let params = [ -/// AnalyticsParameterAdNetworParameter(kClickID, "1234567"), -/// // ... -/// ] -/// @endcode -static const char*const kParameterAdNetworkClickID - = "aclid"; - -/// The ad platform (e.g. MoPub, IronSource) (String). -/// @code -/// let params = [ -/// AnalyticsParameterAdPlatform : "MoPub", -/// // ... -/// ] -/// @endcode -static const char*const kParameterAdPlatform = - "ad_platform"; - -/// The ad source (e.g. AdColony) (String). -/// @code -/// let params = [ -/// AnalyticsParameterAdSource : "AdColony", -/// // ... -/// ] -/// @endcode -static const char*const kParameterAdSource = - "ad_source"; - -/// The ad unit name (e.g. Banner_03) (String). -/// @code -/// let params = [ -/// AnalyticsParameterAdUnitName : "Banner_03", -/// // ... -/// ] -/// @endcode -static const char*const kParameterAdUnitName = - "ad_unit_name"; - -/// A product affiliation to designate a supplying company or brick and -/// mortar store location -/// (String). @code -/// let params = [ -/// AnalyticsParameterAffiliation : "Google Store", -/// // ... -/// ] -/// @endcode -static const char*const kParameterAffiliation = - "affiliation"; - -/// Campaign custom parameter (String). Used as a method of capturing -/// custom data in a campaign. Use varies by network. -/// @code -/// let params = [ -/// AnalyticsParameterCP1 : "custom_data", -/// // ... -/// ] -/// @endcode -static const char*const kParameterCP1 = "cp1"; - -/// The individual campaign name, slogan, promo code, etc. Some networks -/// have pre-defined macro to capture campaign information, otherwise can -/// be populated by developer. Highly Recommended (String). -/// @code -/// let params = [ -/// AnalyticsParameterCampaign : "winter_promotion", -/// // ... -/// ] -/// @endcode -static const char*const kParameterCampaign = - "campaign"; - -/// Campaign ID (String). Used for keyword analysis to identify a specific -/// product promotion or strategic campaign. This is a required key for -/// GA4 data import. -/// @code -/// let params = [ -/// AnalyticsParameterCampaignID : "7877652710", -/// // ... -/// ] -/// @endcode -static const char*const kParameterCampaignID = - "campaign_id"; - -/// Character used in game (String). -/// @code -/// let params = [ -/// AnalyticsParameterCharacter : "beat_boss", -/// // ... -/// ] -/// @endcode -static const char*const kParameterCharacter = - "character"; - -/// Campaign content (String). -static const char*const kParameterContent = "content"; - -/// Type of content selected (String). -/// @code -/// let params = [ -/// AnalyticsParameterContentType : "news article", -/// // ... -/// ] -/// @endcode -static const char*const kParameterContentType = - "content_type"; - -/// Coupon code used for a purchase (String). -/// @code -/// let params = [ -/// AnalyticsParameterCoupon : "SUMMER_FUN", -/// // ... -/// ] -/// @endcode -static const char*const kParameterCoupon = "coupon"; - -/// Creative Format (String). Used to identify the high-level -/// classification of the type of ad served by a specific campaign. -/// @code -/// let params = [ -/// AnalyticsParameterCreativeFormat : "display", -/// // ... -/// ] -/// @endcode -static const char*const kParameterCreativeFormat = - "creative_format"; - -/// The name of a creative used in a promotional spot (String). -/// @code -/// let params = [ -/// AnalyticsParameterCreativeName : "Summer Sale", -/// // ... -/// ] -/// @endcode -static const char*const kParameterCreativeName = - "creative_name"; - -/// The name of a creative slot (String). -/// @code -/// let params = [ -/// AnalyticsParameterCreativeSlot : "summer_banner2", -/// // ... -/// ] -/// @endcode -static const char*const kParameterCreativeSlot = - "creative_slot"; - -/// Currency of the purchase or items associated with the event, in -/// 3-letter -/// ISO_4217 format (String). -/// @code -/// let params = [ -/// AnalyticsParameterCurrency : "USD", -/// // ... -/// ] -/// @endcode -static const char*const kParameterCurrency = - "currency"; - -/// Flight or Travel destination (String). -/// @code -/// let params = [ -/// AnalyticsParameterDestination : "Mountain View, CA", -/// // ... -/// ] -/// @endcode -static const char*const kParameterDestination = - "destination"; - -/// Monetary value of discount associated with a purchase (Double). -/// @code -/// let params = [ -/// AnalyticsParameterDiscount : 2.0, -/// AnalyticsParameterCurrency : "USD", // e.g. $2.00 USD -/// // ... -/// ] -/// @endcode -static const char*const kParameterDiscount = - "discount"; - -/// The arrival date, check-out date or rental end date for the item. This -/// should be in YYYY-MM-DD format (String). -/// @code -/// let params = [ -/// AnalyticsParameterEndDate : "2015-09-14", -/// // ... -/// ] -/// @endcode -static const char*const kParameterEndDate = "end_date"; - -/// Indicates that the associated event should either extend the current -/// session or start a new session if no session was active when the event -/// was logged. Specify 1 to extend the current session or to start a new -/// session; any other value will not extend or start a session. -/// @code -/// let params = [ -/// AnalyticsParameterExtendSession : 1, -/// // ... -/// ] -/// @endcode -static const char*const kParameterExtendSession = - "extend_session"; - -/// Flight number for travel events (String). -/// @code -/// let params = [ -/// AnalyticsParameterFlightNumber : "ZZ800", -/// // ... -/// ] -/// @endcode -static const char*const kParameterFlightNumber = - "flight_number"; - -/// Group/clan/guild ID (String). -/// @code -/// let params = [ -/// AnalyticsParameterGroupID : "g1", -/// // ... -/// ] -/// @endcode -static const char*const kParameterGroupID = "group_id"; - -/// The index of the item in a list (Int). -/// @code -/// let params = [ -/// AnalyticsParameterIndex : 5, -/// // ... -/// ] -/// @endcode -static const char*const kParameterIndex = "index"; - -/// Item brand (String). -/// @code -/// let params = [ -/// AnalyticsParameterItemBrand : "Google", -/// // ... -/// ] -/// @endcode -static const char*const kParameterItemBrand = - "item_brand"; - -/// Item category (context-specific) (String). -/// @code -/// let params = [ -/// AnalyticsParameterItemCategory : "pants", -/// // ... -/// ] -/// @endcode -static const char*const kParameterItemCategory = - "item_category"; - -/// Item Category (context-specific) (String). -/// @code -/// let params = [ -/// AnalyticsParameterItemCategory2 : "pants", -/// // ... -/// ] -/// @endcode -static const char*const kParameterItemCategory2 = - "item_category2"; - -/// Item Category (context-specific) (String). -/// @code -/// let params = [ -/// AnalyticsParameterItemCategory3 : "pants", -/// // ... -/// ] -/// @endcode -static const char*const kParameterItemCategory3 = - "item_category3"; - -/// Item Category (context-specific) (String). -/// @code -/// let params = [ -/// AnalyticsParameterItemCategory4 : "pants", -/// // ... -/// ] -/// @endcode -static const char*const kParameterItemCategory4 = - "item_category4"; - -/// Item Category (context-specific) (String). -/// @code -/// let params = [ -/// AnalyticsParameterItemCategory5 : "pants", -/// // ... -/// ] -/// @endcode -static const char*const kParameterItemCategory5 = - "item_category5"; - -/// Item ID (context-specific) (String). -/// @code -/// let params = [ -/// AnalyticsParameterItemID : "SKU_12345", -/// // ... -/// ] -/// @endcode -static const char*const kParameterItemID = "item_id"; - -/// The ID of the list in which the item was presented to the -/// user (String). -/// @code -/// let params = [ -/// AnalyticsParameterItemListID : "ABC123", -/// // ... -/// ] -/// @endcode -static const char*const kParameterItemListID = - "item_list_id"; - -/// The name of the list in which the item was presented to the user -/// (String). -/// @code -/// let params = [ -/// AnalyticsParameterItemListName : "Related products", -/// // ... -/// ] -/// @endcode -static const char*const kParameterItemListName = - "item_list_name"; - -/// Item Name (context-specific) (String). -/// @code -/// let params = [ -/// AnalyticsParameterItemName : "jeggings", -/// // ... -/// ] -/// @endcode -static const char*const kParameterItemName = - "item_name"; - -/// Item variant (String). -/// @code -/// let params = [ -/// AnalyticsParameterItemVariant : "Black", -/// // ... -/// ] -/// @endcode -static const char*const kParameterItemVariant = - "item_variant"; - -/// The list of items involved in the transaction expressed as `[[String: -/// Any]]`. -/// @code -/// let params = [ -/// AnalyticsParameterItems : [ -/// [AnalyticsParameterItemName : "jeggings", AnalyticsParameterItemCategory : "pants"], -/// [AnalyticsParameterItemName : "boots", AnalyticsParameterItemCategory : "shoes"], -/// ], -/// ] -/// @endcode -static const char*const kParameterItems = "items"; - -/// Level in game (Int). -/// @code -/// let params = [ -/// AnalyticsParameterLevel : 42, -/// // ... -/// ] -/// @endcode -static const char*const kParameterLevel = "level"; - -/// The name of a level in a game (String). -/// @code -/// let params = [ -/// AnalyticsParameterLevelName : "room_1", -/// // ... -/// ] -/// @endcode -static const char*const kParameterLevelName = - "level_name"; - -/// Location (String). The Google Place ID -/// that corresponds to the associated event. Alternatively, you can supply your own custom -/// Location ID. -/// @code -/// let params = [ -/// AnalyticsParameterLocation : "ChIJiyj437sx3YAR9kUWC8QkLzQ", -/// // ... -/// ] -/// @endcode -static const char*const kParameterLocation = - "location"; - -/// The location associated with the event. Preferred to be the Google -/// Place ID that corresponds to the -/// associated item but could be overridden to a custom location ID -/// string.(String). -/// @code -/// let params = [ -/// AnalyticsParameterLocationID : "ChIJiyj437sx3YAR9kUWC8QkLzQ", -/// // ... -/// ] -/// @endcode -static const char*const kParameterLocationID = - "location_id"; - -/// Marketing Tactic (String). Used to identify the targeting criteria -/// applied to a specific campaign. -/// @code -/// let params = [ -/// AnalyticsParameterMarParameter(ketingTactic, "Remarketing"), -/// // ... -/// ] -/// @endcode -static const char*const kParameterMarketingTactic - = "marketing_tactic"; - -/// The advertising or marParameter(keting, cpc, banner, email), push. -/// Highly recommended (String). -/// @code -/// let params = [ -/// AnalyticsParameterMedium : "email", -/// // ... -/// ] -/// @endcode -static const char*const kParameterMedium = "medium"; - -/// A particular approach used in an operation; for example, "facebook" or -/// "email" in the context of a sign_up or login event. (String). -/// @code -/// let params = [ -/// AnalyticsParameterMethod : "google", -/// // ... -/// ] -/// @endcode -static const char*const kParameterMethod = "method"; - -/// Number of nights staying at hotel (Int). -/// @code -/// let params = [ -/// AnalyticsParameterNumberOfNights : 3, -/// // ... -/// ] -/// @endcode -static const char*const kParameterNumberOfNights - = "number_of_nights"; - -/// Number of passengers traveling (Int). -/// @code -/// let params = [ -/// AnalyticsParameterNumberOfPassengers : 11, -/// // ... -/// ] -/// @endcode -static const char*const kParameterNumberOfPassengers - = "number_of_passengers"; - -/// Number of rooms for travel events (Int). -/// @code -/// let params = [ -/// AnalyticsParameterNumberOfRooms : 2, -/// // ... -/// ] -/// @endcode -static const char*const kParameterNumberOfRooms = - "number_of_rooms"; - -/// Flight or Travel origin (String). -/// @code -/// let params = [ -/// AnalyticsParameterOrigin : "Mountain View, CA", -/// // ... -/// ] -/// @endcode -static const char*const kParameterOrigin = "origin"; - -/// The chosen method of payment (String). -/// @code -/// let params = [ -/// AnalyticsParameterPaymentType : "Visa", -/// // ... -/// ] -/// @endcode -static const char*const kParameterPaymentType = - "payment_type"; - -/// Purchase price (Double). -/// @code -/// let params = [ -/// AnalyticsParameterPrice : 1.0, -/// AnalyticsParameterCurrency : "USD", // e.g. $1.00 USD -/// // ... -/// ] -/// @endcode -static const char*const kParameterPrice = "price"; - -/// The ID of a product promotion (String). -/// @code -/// let params = [ -/// AnalyticsParameterPromotionID : "ABC123", -/// // ... -/// ] -/// @endcode -static const char*const kParameterPromotionID = - "promotion_id"; - -/// The name of a product promotion (String). -/// @code -/// let params = [ -/// AnalyticsParameterPromotionName : "Summer Sale", -/// // ... -/// ] -/// @endcode -static const char*const kParameterPromotionName = - "promotion_name"; - -/// Purchase quantity (Int). -/// @code -/// let params = [ -/// AnalyticsParameterQuantity : 1, -/// // ... -/// ] -/// @endcode -static const char*const kParameterQuantity = - "quantity"; - -/// Score in game (Int). -/// @code -/// let params = [ -/// AnalyticsParameterScore : 4200, -/// // ... -/// ] -/// @endcode -static const char*const kParameterScore = "score"; - -/// Current screen class, such as the class name of the UIViewController, -/// logged with screen_view event and added to every event (String). -/// @code -/// let params = [ -/// AnalyticsParameterScreenClass : "LoginViewController", -/// // ... -/// ] -/// @endcode -static const char*const kParameterScreenClass = - "screen_class"; - -/// Current screen name, such as the name of the UIViewController, logged -/// with screen_view event and added to every event (String). -/// @code -/// let params = [ -/// AnalyticsParameterScreenName : "LoginView", -/// // ... -/// ] -/// @endcode -static const char*const kParameterScreenName = - "screen_name"; - -/// The search string/keywords used (String). -/// @code -/// let params = [ -/// AnalyticsParameterSearchTerm : "periodic table", -/// // ... -/// ] -/// @endcode -static const char*const kParameterSearchTerm = - "search_term"; - -/// Shipping cost associated with a transaction (Double). -/// @code -/// let params = [ -/// AnalyticsParameterShipping : 5.99, -/// AnalyticsParameterCurrency : "USD", // e.g. $5.99 USD -/// // ... -/// ] -/// @endcode -static const char*const kParameterShipping = - "shipping"; - -/// The shipping tier (e.g. Ground, Air, Next-day) selected for delivery -/// of the purchased item (String). -/// @code -/// let params = [ -/// AnalyticsParameterShippingTier : "Ground", -/// // ... -/// ] -/// @endcode -static const char*const kParameterShippingTier = - "shipping_tier"; - -/// The origin of your traffic, such as an Ad network (for example, -/// google) or partner (urban airship). Identify the advertiser, site, -/// publication, etc. that is sending traffic to your property. Highly -/// recommended (String). -/// @code -/// let params = [ -/// AnalyticsParameterSource : "InMobi", -/// // ... -/// ] -/// @endcode -static const char*const kParameterSource = "source"; - -/// Source Platform (String). Used to identify the platform responsible -/// for directing traffic to a given Analytics property (e.g., a buying -/// platform where budgets, targeting criteria, etc. are set, a platform -/// for managing organic traffic data, etc.). -/// @code -/// let params = [ -/// AnalyticsParameterSourcePlatform : "sa360", -/// // ... -/// ] -/// @endcode -static const char*const kParameterSourcePlatform = - "source_platform"; - -/// The departure date, check-in date or rental start date for the item. -/// This should be in YYYY-MM-DD format (String). -/// @code -/// let params = [ -/// AnalyticsParameterStartDate : "2015-09-14", -/// // ... -/// ] -/// @endcode -static const char*const kParameterStartDate = - "start_date"; - -/// The result of an operation. Specify 1 to indicate success and 0 to -/// indicate failure (Int). -/// @code -/// let params = [ -/// AnalyticsParameterSuccess : 1, -/// // ... -/// ] -/// @endcode -static const char*const kParameterSuccess = "success"; - -/// Tax cost associated with a transaction (Double). -/// @code -/// let params = [ -/// AnalyticsParameterTax : 2.43, -/// AnalyticsParameterCurrency : "USD", // e.g. $2.43 USD -/// // ... -/// ] -/// @endcode -static const char*const kParameterTax = "tax"; - -/// If you're manually tagging keyword campaigns, you should use utm_term -/// to specify the keyword (String). -/// @code -/// let params = [ -/// AnalyticsParameterTerm : "game", -/// // ... -/// ] -/// @endcode -static const char*const kParameterTerm = "term"; - -/// The unique identifier of a transaction (String). -/// @code -/// let params = [ -/// AnalyticsParameterTransactionID : "T12345", -/// // ... -/// ] -/// @endcode -static const char*const kParameterTransactionID = - "transaction_id"; - -/// Travel class (String). -/// @code -/// let params = [ -/// AnalyticsParameterTravelClass : "business", -/// // ... -/// ] -/// @endcode -static const char*const kParameterTravelClass = - "travel_class"; - -/// A context-specific numeric value which is accumulated automatically -/// for each event type. This is a general purpose parameter that is -/// useful for accumulating a key metric that pertains to an event. -/// Examples include revenue, distance, time and points. Value should be -/// specified as Int or Double. Notes: Values for pre-defined -/// currency-related events (such as @c AnalyticsEventAddToCart) should be -/// supplied using Double and must be accompanied by a @c -/// AnalyticsParameterCurrency parameter. The valid range of accumulated -/// values is [-9,223,372,036,854.77, 9,223,372,036,854.77]. Supplying a -/// non-numeric value, omitting the corresponding @c -/// AnalyticsParameterCurrency parameter, or supplying an invalid -/// currency code for conversion events will cause that -/// conversion to be omitted from reporting. -/// @code -/// let params = [ -/// AnalyticsParameterValue : 3.99, -/// AnalyticsParameterCurrency : "USD", // e.g. $3.99 USD -/// // ... -/// ] -/// @endcode -static const char*const kParameterValue = "value"; - -/// Name of virtual currency type (String). -/// @code -/// let params = [ -/// AnalyticsParameterVirtualCurrencyName : "virtual_currency_name", -/// // ... -/// ] -/// @endcode -static const char*const kParameterVirtualCurrencyName - = "virtual_currency_name"; -/// @} - -} // namespace analytics -} // namespace firebase - -#endif // FIREBASE_ANALYTICS_CLIENT_CPP_INCLUDE_FIREBASE_ANALYTICS_PARAMETER_NAMES_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/analytics/user_property_names.h b/packages/firebase_core/firebase_core/firebase_core/firebase/analytics/user_property_names.h deleted file mode 100644 index 155fea86e6f9..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/analytics/user_property_names.h +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright 2023 Google Inc. All Rights Reserved. - -#ifndef FIREBASE_ANALYTICS_CLIENT_CPP_INCLUDE_FIREBASE_ANALYTICS_USER_PROPERTY_NAMES_H_ -#define FIREBASE_ANALYTICS_CLIENT_CPP_INCLUDE_FIREBASE_ANALYTICS_USER_PROPERTY_NAMES_H_ - -/// @brief Namespace that encompasses all Firebase APIs. -namespace firebase { -/// @brief Firebase Analytics API. -namespace analytics { - - - -/// @defgroup user_property_names Analytics User Properties -/// -/// Predefined user property names. -/// -/// A UserProperty is an attribute that describes the app-user. By -/// supplying UserProperties, you can later analyze different behaviors of -/// various segments of your userbase. You may supply up to 25 unique -/// UserProperties per app, and you can use the name and value of your -/// choosing for each one. UserProperty names can be up to 24 characters -/// long, may only contain alphanumeric characters and underscores ("_"), -/// and must start with an alphabetic character. UserProperty values can -/// be up to 36 characters long. The "firebase_", "google_", and "ga_" -/// prefixes are reserved and should not be used. -/// @{ - - -/// Indicates whether events logged by Google Analytics can be used to -/// personalize ads for the user. Set to "YES" to enable, or "NO" to -/// disable. Default is enabled. See the -/// documentation for -/// more details and information about related settings. -/// -/// @code -/// Analytics.setUserProperty("NO", forName: AnalyticsUserPropertyAllowAdPersonalizationSignals) -/// @endcode -static const char*const kUserPropertyAllowAdPersonalizationSignals - = "allow_personalized_ads"; - -/// The method used to sign in. For example, "google", "facebook" or -/// "twitter". -static const char*const kUserPropertySignUpMethod - = "sign_up_method"; -/// @} - -} // namespace analytics -} // namespace firebase - -#endif // FIREBASE_ANALYTICS_CLIENT_CPP_INCLUDE_FIREBASE_ANALYTICS_USER_PROPERTY_NAMES_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/app.h b/packages/firebase_core/firebase_core/firebase_core/firebase/app.h deleted file mode 100644 index 0501f38ac0c8..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/app.h +++ /dev/null @@ -1,787 +0,0 @@ -/* - * Copyright 2016 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_APP_SRC_INCLUDE_FIREBASE_APP_H_ -#define FIREBASE_APP_SRC_INCLUDE_FIREBASE_APP_H_ - -#include "firebase/internal/platform.h" - -#if FIREBASE_PLATFORM_ANDROID -#include -#endif // FIREBASE_PLATFORM_ANDROID - -#include -#include -#include - -#if FIREBASE_PLATFORM_IOS || FIREBASE_PLATFORM_TVOS -#ifdef __OBJC__ -@class FIRApp; -#endif // __OBJC__ -#endif // FIREBASE_PLATFORM_IOS - -namespace firebase { - -#ifdef FIREBASE_LINUX_BUILD_CONFIG_STRING -// Check to see if the shared object compiler string matches the input -void CheckCompilerString(const char* input); -#endif // FIREBASE_LINUX_BUILD_CONFIG_STRING - -// Predeclarations. -#ifdef INTERNAL_EXPERIMENTAL -namespace internal { -class FunctionRegistry; -} // namespace internal -#endif // INTERNAL_EXPERIMENTAL - -#ifdef INTERNAL_EXPERIMENTAL -#if FIREBASE_PLATFORM_DESKTOP -namespace heartbeat { -class HeartbeatController; // forward declaration -} // namespace heartbeat -#endif // FIREBASE_PLATFORM_DESKTOP -#endif // INTERNAL_EXPERIMENTAL - -namespace internal { -class AppInternal; -} // namespace internal - -/// @brief Reports whether a Firebase module initialized successfully. -enum InitResult { - /// The given library was successfully initialized. - kInitResultSuccess = 0, - - /// The given library failed to initialize due to a missing dependency. - /// - /// On Android, this typically means that Google Play services is not - /// available and the library requires it. - /// @if cpp_examples - /// Use google_play_services::CheckAvailability() and - /// google_play_services::MakeAvailable() to resolve this issue. - /// @endif - /// - /// @if swig_examples - /// Use FirebaseApp.CheckDependencies() and - /// FirebaseApp.FixDependenciesAsync() to resolve this issue. - /// @endif - /// - /// - /// Also, on Android, this value can be returned if the Java dependencies of a - /// Firebase component are not included in the application, causing - /// initialization to fail. This means that the application's build - /// environment is not configured correctly. To resolve the problem, - /// see the SDK setup documentation for the set of Java dependencies (AARs) - /// required for the component that failed to initialize. - kInitResultFailedMissingDependency -}; - -/// @brief Default name for firebase::App() objects. -extern const char* const kDefaultAppName; - -/// @brief Options that control the creation of a Firebase App. -/// @if cpp_examples -/// @see firebase::App -/// @endif -/// -/// @if swig_examples -/// @see FirebaseApp -/// @endif -/// -class AppOptions { - friend class App; - - public: - /// @brief Create AppOptions. - /// - /// @if cpp_examples - /// To create a firebase::App object, the Firebase application identifier - /// and API key should be set using set_app_id() and set_api_key() - /// respectively. - /// - /// @see firebase::App::Create(). - /// @endif - /// - /// @if swig_examples - /// To create a FirebaseApp object, the Firebase application identifier - /// and API key should be set using AppId and ApiKey respectively. - /// - /// @see FirebaseApp.Create(). - /// @endif - /// - AppOptions() {} - - /// Set the Firebase app ID used to uniquely identify an instance of an app. - /// - /// This is the mobilesdk_app_id in the Android google-services.json config - /// file or GOOGLE_APP_ID in the GoogleService-Info.plist. - /// - /// This only needs to be specified if your application does not include - /// google-services.json or GoogleService-Info.plist in its resources. - void set_app_id(const char* id) { app_id_ = id; } - - /// Retrieves the app ID. - /// - /// @if cpp_examples - /// @see set_app_id(). - /// @endif - /// - /// - /// @xmlonly - /// - /// Gets or sets the App Id. - /// - /// This is the mobilesdk_app_id in the Android google-services.json config - /// file or GOOGLE_APP_ID in the GoogleService-Info.plist. - /// - /// This only needs to be specified if your application does not include - /// google-services.json or GoogleService-Info.plist in its resources. - /// - /// @endxmlonly - /// - const char* app_id() const { return app_id_.c_str(); } - - /// API key used to authenticate requests from your app. - /// - /// For example, "AIzaSyDdVgKwhZl0sTTTLZ7iTmt1r3N2cJLnaDk" used to identify - /// your app to Google servers. - /// - /// This only needs to be specified if your application does not include - /// google-services.json or GoogleService-Info.plist in its resources. - void set_api_key(const char* key) { api_key_ = key; } - - /// Get the API key. - /// - /// @if cpp_examples - /// @see set_api_key(). - /// @endif - /// - /// - /// @xmlonly - /// - /// Gets or sets the API key used to authenticate requests from your app. - /// - /// For example, \"AIzaSyDdVgKwhZl0sTTTLZ7iTmt1r3N2cJLnaDk\" used to identify - /// your app to Google servers. - /// - /// This only needs to be specified if your application does not include - /// google-services.json or GoogleService-Info.plist in its resources. - /// - /// @endxmlonly - /// - const char* api_key() const { return api_key_.c_str(); } - - /// Set the Firebase Cloud Messaging sender ID. - /// - /// For example "012345678901", used to configure Firebase Cloud Messaging. - /// - /// This only needs to be specified if your application does not include - /// google-services.json or GoogleService-Info.plist in its resources. - void set_messaging_sender_id(const char* sender_id) { - fcm_sender_id_ = sender_id; - } - - /// Get the Firebase Cloud Messaging sender ID. - /// - /// @if cpp_examples - /// @see set_messaging_sender_id(). - /// @endif - /// - /// - /// @xmlonly - /// - /// Gets or sets the messaging sender Id. - /// - /// This only needs to be specified if your application does not include - /// google-services.json or GoogleService-Info.plist in its resources. - /// - /// @endxmlonly - /// - const char* messaging_sender_id() const { return fcm_sender_id_.c_str(); } - - /// Set the database root URL, e.g. @"http://abc-xyz-123.firebaseio.com". - void set_database_url(const char* url) { database_url_ = url; } - - /// Get database root URL, e.g. @"http://abc-xyz-123.firebaseio.com". - /// - /// - /// @xmlonly - /// - /// Gets or sets the database root URL, e.g. - /// @\"http://abc-xyz-123.firebaseio.com\". - /// - /// @endxmlonly - /// - const char* database_url() const { return database_url_.c_str(); } - - /// @cond FIREBASE_APP_INTERNAL - - /// Set the tracking ID for Google Analytics, e.g. @"UA-12345678-1". - void set_ga_tracking_id(const char* id) { ga_tracking_id_ = id; } - - /// Get the tracking ID for Google Analytics, - /// - /// @if cpp_examples - /// @see set_ga_tracking_id(). - /// @endif - /// - const char* ga_tracking_id() const { return ga_tracking_id_.c_str(); } - - /// @endcond - - /// Set the Google Cloud Storage bucket name, - /// e.g. @\"abc-xyz-123.storage.firebase.com\". - void set_storage_bucket(const char* bucket) { storage_bucket_ = bucket; } - - /// Get the Google Cloud Storage bucket name, - /// @see set_storage_bucket(). - /// - /// @xmlonly - /// - /// Gets or sets the Google Cloud Storage bucket name, e.g. - /// @\"abc-xyz-123.storage.firebase.com\". - /// - /// @endxmlonly - /// - const char* storage_bucket() const { return storage_bucket_.c_str(); } - - /// Set the Google Cloud project ID. - void set_project_id(const char* project) { project_id_ = project; } - - /// Get the Google Cloud project ID. - /// - /// This is the project_id in the Android google-services.json config - /// file or PROJECT_ID in the GoogleService-Info.plist. - /// - /// @xmlonly - /// - /// Gets the Google Cloud project ID. - /// - /// This is the project_id in the Android google-services.json config - /// file or PROJECT_ID in the GoogleService-Info.plist. - /// - /// @endxmlonly - /// - const char* project_id() const { return project_id_.c_str(); } - -#ifdef INTERNAL_EXPERIMENTAL - /// @brief set the iOS client ID. - /// - /// This is the clientID in the GoogleService-Info.plist. - void set_client_id(const char* client_id) { client_id_ = client_id; } - - /// @brief Get the iOS client ID. - /// - /// This is the client_id in the GoogleService-Info.plist. - const char* client_id() const { return client_id_.c_str(); } -#endif // INTERNAL_EXPERIMENTAL - -#ifdef INTERNAL_EXPERIMENTAL - /// @brief Set the Android or iOS client project name. - /// - /// This is the project_name in the Android google-services.json config - /// file or BUNDLE_ID in the GoogleService-Info.plist. - void set_package_name(const char* package_name) { - package_name_ = package_name; - } - - /// @brief Get the Android or iOS client project name. - /// - /// This is the project_name in the Android google-services.json config - /// file or BUNDLE_ID in the GoogleService-Info.plist. - const char* package_name() const { return package_name_.c_str(); } -#endif // INTERNAL_EXPERIMENTAL - - /// @brief Load options from a config string. - /// - /// @param[in] config A JSON string that contains Firebase configuration i.e. - /// the content of the downloaded google-services.json file. - /// @param[out] options Optional: If provided, load options into it. - /// - /// @returns An instance containing the loaded options if successful. - /// If the options argument to this function is null, this method returns an - /// AppOptions instance allocated from the heap. - static AppOptions* LoadFromJsonConfig(const char* config, - AppOptions* options = nullptr); - -#if INTERNAL_EXPERIMENTAL - /// @brief Determine whether the specified options match this set of options. - /// - /// Fields of this object that are empty are ignored in the comparison. - /// - /// @param[in] options Options to compare with. - bool operator==(const AppOptions& options) const { - return (package_name_.empty() || package_name_ == options.package_name_) && - (api_key_.empty() || api_key_ == options.api_key_) && - (app_id_.empty() || app_id_ == options.app_id_) && - (database_url_.empty() || database_url_ == options.database_url_) && - (ga_tracking_id_.empty() || - ga_tracking_id_ == options.ga_tracking_id_) && - (fcm_sender_id_.empty() || - fcm_sender_id_ == options.fcm_sender_id_) && - (storage_bucket_.empty() || - storage_bucket_ == options.storage_bucket_) && - (project_id_.empty() || project_id_ == options.project_id_); - } -#endif // INTERNAL_EXPERIMENTAL - -#if INTERNAL_EXPERIMENTAL - /// @brief Determine whether the specified options don't match this set of - /// options. - /// - /// Fields of this object that are empty are ignored in the comparison. - /// - /// @param[in] options Options to compare with. - bool operator!=(const AppOptions& options) const { - return !operator==(options); - } -#endif // INTERNAL_EXPERIMENTAL - -#if INTERNAL_EXPERIMENTAL -#if FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) - /// @brief Load default options from the resource file. - /// - /// @param[in] jni_env JNI environment required to allow Firebase services - /// to interact with the Android framework. - /// @param[in] activity JNI reference to the Android activity, required to - /// allow Firebase services to interact with the Android application. - /// @param options Options to populate from a resource file. - /// - /// @return An instance containing the loaded options if successful. - /// If the options argument to this function is null, this method returns an - /// AppOptions instance allocated from the heap.. - static AppOptions* LoadDefault(AppOptions* options, JNIEnv* jni_env, - jobject activity); -#endif // FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) - -#if !FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) - /// @brief Load default options from the resource file. - /// - /// @param options Options to populate from a resource file. - /// - /// @return An instance containing the loaded options if successful. - /// If the options argument to this function is null, this method returns an - /// AppOptions instance allocated from the heap. - static AppOptions* LoadDefault(AppOptions* options); -#endif // !FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) -#endif // INTERNAL_EXPERIMENTAL - -#if INTERNAL_EXPERIMENTAL -#if FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) - /// @brief Attempt to populate required options with default values if not - /// specified. - /// - /// @param[in] jni_env JNI environment required to allow Firebase services - /// to interact with the Android framework. - /// @param[in] activity JNI reference to the Android activity, required to - /// allow Firebase services to interact with the Android application. - /// - /// @return true if successful, false otherwise. - bool PopulateRequiredWithDefaults(JNIEnv* jni_env, jobject activity); -#endif // FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) - -#if !FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) - /// @brief Attempt to populate required options with default values if not - /// specified. - /// - /// @return true if successful, false otherwise. - bool PopulateRequiredWithDefaults(); -#endif // !FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) -#endif // INTERNAL_EXPERIMENTAL - - /// @cond FIREBASE_APP_INTERNAL - private: - /// Application package name (e.g Android package name or iOS bundle ID). - std::string package_name_; - /// API key used to communicate with Google Servers. - std::string api_key_; - /// ID of the app. - std::string app_id_; - /// ClientID of the app. - std::string client_id_; - /// Database root URL. - std::string database_url_; - /// Google analytics tracking ID. - std::string ga_tracking_id_; - /// FCM sender ID. - std::string fcm_sender_id_; - /// Google Cloud Storage bucket name. - std::string storage_bucket_; - /// Google Cloud project ID. - std::string project_id_; - /// @endcond -}; - -/// @brief Firebase application object. -/// -/// @if cpp_examples -/// firebase::App acts as a conduit for communication between all Firebase -/// services used by an application. -/// -/// For example: -/// @code -/// #if defined(__ANDROID__) -/// firebase::App::Create(firebase::AppOptions(), jni_env, activity); -/// #else -/// firebase::App::Create(firebase::AppOptions()); -/// #endif // defined(__ANDROID__) -/// @endcode -/// @endif -/// -/// @if swig_examples -/// FirebaseApp acts as a conduit for communication between all Firebase -/// services used by an application. A default instance is created -/// automatically, based on settings in your Firebase configuration file, -/// and all of the Firebase APIs connect with it automatically. -/// @endif -class App { - public: - ~App(); - -#if !FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) - /// @brief Initializes the default firebase::App with default options. - /// - /// @note This method is specific to non-Android implementations. - /// - /// @return New App instance, the App should not be destroyed for the - /// lifetime of the application. If default options can't be loaded this - /// will return null. - static App* Create(); -#endif // !FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) - -#ifndef SWIG -// -// For Unity, we actually use the simpler, iOS version for both platforms -// -#if FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) - /// @brief Initializes the default firebase::App with default options. - /// - /// @note This method is specific to the Android implementation. - /// - /// @param[in] jni_env JNI environment required to allow Firebase services - /// to interact with the Android framework. - /// @param[in] activity JNI reference to the Android activity, required to - /// allow Firebase services to interact with the Android application. - /// - /// @return New App instance. The App should not be destroyed for the - /// lifetime of the application. If default options can't be loaded this - /// will return null. - static App* Create(JNIEnv* jni_env, jobject activity); -#endif // FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) -#endif // SWIG - -#if !FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) - /// @brief Initializes the default firebase::App with the given options. - /// - /// @note This method is specific to non-Android implementations. - /// - /// Options are copied at initialization time, so changes to the object are - /// ignored. - /// @param[in] options Options that control the creation of the App. - /// - /// @return New App instance, the App should not be destroyed for the - /// lifetime of the application. - static App* Create(const AppOptions& options); -#endif // !FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) - -#ifndef SWIG -// -// For Unity, we actually use the simpler, iOS version for both platforms -// -#if FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) - /// @brief Initializes the default firebase::App with the given options. - /// - /// @note This method is specific to the Android implementation. - /// - /// Options are copied at initialization time, so changes to the object are - /// ignored. - /// @param[in] options Options that control the creation of the App. - /// @param[in] jni_env JNI environment required to allow Firebase services - /// to interact with the Android framework. - /// @param[in] activity JNI reference to the Android activity, required to - /// allow Firebase services to interact with the Android application. - /// - /// @return New App instance. The App should not be destroyed for the - /// lifetime of the application. - static App* Create(const AppOptions& options, JNIEnv* jni_env, - jobject activity); -#endif // FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) -#endif // SWIG - -#if !FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) - /// @brief Initializes a firebase::App with the given options that operates - /// on the named app. - /// - /// @note This method is specific to non-Android implementations. - /// - /// Options are copied at initialization time, so changes to the object are - /// ignored. - /// @param[in] options Options that control the creation of the App. - /// @param[in] name Name of this App instance. This is only required when - /// one application uses multiple App instances. - /// - /// @return New App instance, the App should not be destroyed for the - /// lifetime of the application. - static App* Create(const AppOptions& options, const char* name); -#endif // !FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) - -#ifndef SWIG -// -// For Unity, we actually use the simpler iOS version for both platforms -// -#if FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) - /// @brief Initializes a firebase::App with the given options that operates - /// on the named app. - /// - /// @note This method is specific to the Android implementation. - /// - /// Options are copied at initialization time, so changes to the object are - /// ignored. - /// @param[in] options Options that control the creation of the App. - /// @param[in] name Name of this App instance. This is only required when - /// one application uses multiple App instances. - /// @param[in] jni_env JNI environment required to allow Firebase services - /// to interact with the Android framework. - /// @param[in] activity JNI reference to the Android activity, required to - /// allow Firebase services to interact with the Android application. - /// - /// @return New App instance. The App should not be destroyed for the - /// lifetime of the application. - static App* Create(const AppOptions& options, const char* name, - JNIEnv* jni_env, jobject activity); -#endif // FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) -#endif // SWIG - - /// Get the default App, or nullptr if none has been created. - static App* GetInstance(); - - /// Get the App with the given name, or nullptr if none have been created. - static App* GetInstance(const char* name); - -#ifndef SWIG -// -// Unity doesn't need the JNI from here, it has its method to access JNI. -// -#if FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) - /// Get Java virtual machine, retrieved from the initial JNI environment. - /// @note This method is specific to the Android implementation. - /// - /// @return JNI Java virtual machine object. - JavaVM* java_vm() const; - /// Get JNI environment, needed for performing JNI calls, set on creation. - /// This is not trivial as the correct environment needs to retrieved per - /// thread. - /// @note This method is specific to the Android implementation. - /// - /// @return JNI environment object. - JNIEnv* GetJNIEnv() const; - /// Get a global reference to the Android activity provided to the App on - /// creation. Also serves as the Context needed for Firebase calls. - /// @note This method is specific to the Android implementation. - /// - /// @return Global JNI reference to the Android activity used to create - /// the App. The reference count of the returned object is not increased. - jobject activity() const { return activity_; } -#endif // FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) -#endif // SWIG - - /// Get the name of this App instance. - /// - /// @return The name of this App instance. If a name wasn't provided via - /// Create(), this returns @ref kDefaultAppName. - /// - /// @xmlonly - /// - /// Get the name of this FirebaseApp instance. - /// If a name wasn't provided via Create(), this will match @ref DefaultName. - /// - /// @endxmlonly - /// - const char* name() const { return name_.c_str(); } - - /// Get options the App was created with. - /// - /// @return Options used to create the App. - /// - /// @xmlonly - /// - /// @brief Get the AppOptions the FirebaseApp was created with. - /// @return AppOptions used to create the FirebaseApp. - /// - /// @endxmlonly - /// - const AppOptions& options() const { return options_; } - -#ifdef INTERNAL_EXPERIMENTAL - /// Sets whether automatic data collection is enabled for all products. - /// - /// By default, automatic data collection is enabled. To disable automatic - /// data collection in your mobile app, add to your Android application's - /// manifest: - /// - /// @if NOT_DOXYGEN - /// - /// @else - /// @code - /// <meta-data android:name="firebase_data_collection_default_enabled" - /// android:value="false" /> - /// @endcode - /// @endif - /// - /// or on iOS to your Info.plist: - /// - /// @if NOT_DOXYGEN - /// FirebaseDataCollectionDefaultEnabled - /// - /// @else - /// @code - /// <key>FirebaseDataCollectionDefaultEnabled</key> - /// <false/> - /// @endcode - /// @endif - /// - /// Once your mobile app is set to disable automatic data collection, you can - /// ask users to consent to data collection, and then enable it after their - /// approval by calling this method. - /// - /// This value is persisted across runs of the app so that it can be set once - /// when users have consented to collection. - /// - /// @param enabled Whether or not to enable automatic data collection. - void SetDataCollectionDefaultEnabled(bool enabled); - - /// Gets whether automatic data collection is enabled for all - /// products. Defaults to true unless - /// "firebase_data_collection_default_enabled" is set to false in your - /// Android manifest and FirebaseDataCollectionDefaultEnabled is set to NO - /// in your iOS app's Info.plist. - /// - /// @return Whether or not automatic data collection is enabled for all - /// products. - bool IsDataCollectionDefaultEnabled() const; -#endif // INTERNAL_EXPERIMENTAL -#ifdef SWIG - void SetDataCollectionDefaultEnabled(bool enabled); - bool IsDataCollectionDefaultEnabled() const; -#endif // SWIG - -#ifdef INTERNAL_EXPERIMENTAL - // This is only visible to SWIG and internal users of firebase::App. - /// Get the initialization results of modules that were initialized when - /// creating this app. - /// - /// @return Initialization results of modules indexed by module name. - const std::map& init_results() const { - return init_results_; - } - - // Returns a pointer to the function registry, used by components to expose - // methods to one another without introducing linkage dependencies. - internal::FunctionRegistry* function_registry(); - - /// @brief Register a library which utilizes the Firebase C++ SDK. - /// - /// @param library Name of the library to register as a user of the Firebase - /// C++ SDK. - /// @param version Version of the library being registered. - static void RegisterLibrary(const char* library, const char* version); - - // Internal method to retrieve the combined string of registered libraries. - static const char* GetUserAgent(); - - // On desktop, when App.Create() is invoked without parameters, it looks for a - // file named 'google-services-desktop.json', to load parameters from. - // This function sets the location to search in. - // Note - when setting this, make sure to end the path with the appropriate - // path separator! - static void SetDefaultConfigPath(const char* path); -#endif // INTERNAL_EXPERIMENTAL - -#ifdef INTERNAL_EXPERIMENTAL -#if FIREBASE_PLATFORM_DESKTOP - // These methods are only visible to SWIG and internal users of firebase::App. - - /// Logs a heartbeat using the internal HeartbeatController. - void LogHeartbeat() const; - - /// Get a pointer to the HeartbeatController associated with this app. - std::shared_ptr GetHeartbeatController() - const; -#endif // FIREBASE_PLATFORM_DESKTOP -#endif // INTERNAL_EXPERIMENTAL - -#ifdef INTERNAL_EXPERIMENTAL -#if FIREBASE_PLATFORM_ANDROID - /// Get the platform specific app implementation referenced by this object. - /// - /// @return Global reference to the FirebaseApp. The returned reference - /// most be deleted after use. - jobject GetPlatformApp() const; -#elif FIREBASE_PLATFORM_IOS || FIREBASE_PLATFORM_TVOS -#ifdef __OBJC__ - /// Get the platform specific app implementation referenced by this object. - /// - /// @return Reference to the FIRApp object owned by this app. - FIRApp* GetPlatformApp() const; -#endif // __OBJC__ -#endif // FIREBASE_PLATFORM_ANDROID, FIREBASE_PLATFORM_IOS, - // FIREBASE_PLATFORM_TVOS -#endif // INTERNAL_EXPERIMENTAL - - private: - /// Construct the object. - App() - : -#if FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) - activity_(nullptr), -#endif - internal_(nullptr) { - Initialize(); - -#ifdef FIREBASE_LINUX_BUILD_CONFIG_STRING - CheckCompilerString(FIREBASE_LINUX_BUILD_CONFIG_STRING); -#endif // FIREBASE_LINUX_BUILD_CONFIG_STRING - } - - /// Initialize internal implementation - void Initialize(); - -#ifndef SWIG -// -// Unity doesn't need the JNI from here, it has its method to access JNI. -// -#if FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) - /// Android activity. - /// @note This is specific to Android. - jobject activity_; -#endif // FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) -#endif // SWIG - - /// Name of the App instance. - std::string name_; - /// Options used to create this App instance. - AppOptions options_; - /// Module initialization results. - std::map init_results_; - /// Pointer to other internal data used by this instance. - internal::AppInternal* internal_; - - /// @endcond -}; - -} // namespace firebase - -#endif // FIREBASE_APP_SRC_INCLUDE_FIREBASE_APP_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/auth.h b/packages/firebase_core/firebase_core/firebase_core/firebase/auth.h deleted file mode 100644 index 408c34ea9006..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/auth.h +++ /dev/null @@ -1,939 +0,0 @@ -/* - * Copyright 2016 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_AUTH_SRC_INCLUDE_FIREBASE_AUTH_H_ -#define FIREBASE_AUTH_SRC_INCLUDE_FIREBASE_AUTH_H_ - -#include - -#include "firebase/app.h" -#include "firebase/auth/user.h" -#include "firebase/future.h" -#include "firebase/internal/common.h" - -#if !defined(DOXYGEN) -#ifndef SWIG -FIREBASE_APP_REGISTER_CALLBACKS_REFERENCE(auth) -#endif // SWIG -#endif // !defined(DOXYGEN) - -namespace firebase { - -/// @brief Firebase Authentication API. -/// -/// Firebase Authentication provides backend services to securely authenticate -/// users. It can authenticate users using passwords and federated identity -/// provider credentials, and it can integrate with a custom auth backend. -namespace auth { - -// Predeclarations. -struct AuthData; -class AuthStateListener; -class IdTokenListener; -class PhoneAuthProvider; -struct AuthCompletionHandle; -class FederatedAuthProvider; -class FederatedOAuthProvider; -struct SignInResult; - -/// @brief Firebase authentication object. -/// -/// -/// @if swig_examples -/// Firebase.Auth.FirebaseAuth is the gateway to the Firebase authentication -/// API. With it, you can reference @ref Firebase.Auth.FirebaseAuth objects to -/// manage user accounts and credentials. -/// -/// Each @ref Firebase.FirebaseApp has up to one Firebase.Auth.FirebaseAuth -/// class. You acquire the Firebase.Auth.FirebaseAuth class through the static -/// function @ref Firebase.Auth.FirebaseAuth.GetAuth. -/// -/// For example: -/// @code{.cs} -/// // Get the Auth class for your App. -/// Firebase.Auth.FirebaseAuth auth = Firebase.Auth.FirebaseAuth.GetAuth(app); -/// -/// // Request anonymous sign-in and wait until asynchronous call completes. -/// auth.SignInAnonymouslyAsync().ContinueWith((authTask) => { -/// // Print sign in results. -/// if (authTask.IsCanceled) { -/// DebugLog("Sign-in canceled."); -/// } else if (authTask.IsFaulted) { -/// DebugLog("Sign-in encountered an error."); -/// DebugLog(authTask.Exception.ToString()); -/// } else if (authTask.IsCompleted) { -/// Firebase.Auth.User user = authTask.Result; -/// DebugLog(String.Format("Signed in as {0} user.", -/// user.Anonymous ? "an anonymous" : "a non-anonymous")); -/// DebugLog("Signing out."); -/// auth.SignOut(); -/// }); -/// @endcode -/// @endif -/// -/// @if cpp_examples -/// -/// firebase::auth::Auth is the gateway to the Firebase authentication API. -/// With it, you can reference @ref firebase::auth::User objects to manage user -/// accounts and credentials. -/// -/// Each @ref firebase::App has up to one firebase::auth::Auth class. You -/// acquire the firebase::auth::Auth class through the static function -/// @ref firebase::auth::Auth::GetAuth. -/// -/// For example: -/// @code{.cpp} -/// -/// // Get the Auth class for your App. -/// firebase::auth::Auth* auth = firebase::auth::Auth::GetAuth(app); -/// -/// // Request anonymous sign-in and wait until asynchronous call completes. -/// firebase::Future sign_in_future = -/// auth->SignInAnonymously(); -/// while(sign_in_future.status() == firebase::kFutureStatusPending) { -/// // when polling, like this, make sure you service your platform's -/// // message loop -/// // see https://github.com/firebase/quickstart-cpp for a sample -/// ProcessEvents(300); -/// std::cout << "Signing in...\n"; -/// } -/// -/// const firebase::auth::AuthError error = -/// static_cast(sign_in_future.error()); -/// if (error != firebase::auth::kAuthErrorNone) { -/// std::cout << "Sign in failed with error '" -/// << sign_in_future.error_message() << "'\n"; -/// } else { -/// firebase::auth::User* user = *sign_in_future.result(); -/// // is_anonymous from Anonymous -/// std::cout << "Signed in as " -/// << (user->is_anonymous() ? "an anonymous" : "a non-anonymous") -/// << " user\n"; -/// } -/// @endcode -/// @endif -class Auth { - public: - /// @brief Results of calls @ref FetchProvidersForEmail. - /// - /// - /// @if swig_examples - /// @see FirebaseAuth.FetchProvidersForEmailAsync(). - /// @endif - /// - struct FetchProvidersResult { - /// The IDPs (identity providers) that can be used for `email`. - /// An array of length `num_providers` of null-terminated strings. - /// - /// The C# doc string is in the SWIG file because nested structs are - /// causing problems b/35780150 - /// - std::vector providers; - }; - - ~Auth(); - - /// Synchronously gets the cached current user, or nullptr if there is none. - /// @note This function may block and wait until the Auth instance finishes - /// loading the saved user's state. This should only happen for a short - /// period of time after the Auth instance is created. - /// - /// @xmlonly - /// - /// Synchronously gets the cached current user, or null if there is none. - /// @note This function may block and wait until the Auth instance finishes - /// loading the saved user's state. This should only happen for a short - /// period of time after the Auth instance is created. - /// - /// @endxmlonly - /// - User* current_user(); - - /// The current user language code. This can be set to the app’s current - /// language by calling set_language_code. The string must be a language code - /// that follows BCP 47. This will return an empty string if the app default - /// language code is being used. - std::string language_code() const; - - /// Sets the user-facing language code for auth operations that can be - /// internationalized, such as FirebaseUser.sendEmailVerification(). This - /// language code should follow the conventions defined by the IETF in BCP 47. - void set_language_code(const char* language_code); - - /// Sets the user-facing language code to be the default app language. This - /// uses a language associated with the device's locale data. On desktop - /// this will set the language code to the Firebase service's default. You - /// may subsequently customize the language code again by invoking - /// set_language_code(). - void UseAppLanguage(); - - // ----- Providers ------------------------------------------------------- - /// Asynchronously requests the IDPs (identity providers) that can be used - /// for the given email address. - /// - /// Useful for an "identifier-first" login flow. - /// - /// @if cpp_examples - /// The following sample code illustrates a possible login screen - /// that allows the user to pick an identity provider. - /// @code{.cpp} - /// // This function is called every frame to display the login screen. - /// // Returns the identity provider name, or "" if none selected. - /// const char* DisplayIdentityProviders(firebase::auth::Auth& auth, - /// const char* email) { - /// // Get results of most recent call to FetchProvidersForEmail(). - /// firebase::Future future = - /// auth.FetchProvidersForEmailLastResult(); - /// const firebase::auth::Auth::FetchProvidersResult* result = - /// future.result(); - /// - /// // Header. - /// ShowTextBox("Sign in %s", email); - /// - /// // Fetch providers from the server if we need to. - /// const bool refetch = - /// future.status() == firebase::kFutureStatusInvalid || - /// (result != nullptr && strcmp(email, result->email.c_str()) != 0); - /// if (refetch) { - /// auth.FetchProvidersForEmail(email); - /// } - /// - /// // Show a waiting icon if we're waiting for the asynchronous call to - /// // complete. - /// if (future.status() != firebase::kFutureStatusComplete) { - /// ShowImage("waiting icon"); - /// return ""; - /// } - /// - /// // Show error code if the call failed. - /// if (future.error() != firebase::auth::kAuthErrorNone) { - /// ShowTextBox("Error fetching providers: %s", future.error_message()); - /// } - /// - /// // Show a button for each provider available to this email. - /// // Return the provider for the button that's pressed. - /// for (size_t i = 0; i < result->providers.size(); ++i) { - /// const bool selected = ShowTextButton(result->providers[i].c_str()); - /// if (selected) return result->providers[i].c_str(); - /// } - /// return ""; - /// } - /// @endcode - /// @endif - Future FetchProvidersForEmail(const char* email); - - /// Get results of the most recent call to @ref FetchProvidersForEmail. - Future FetchProvidersForEmailLastResult() const; - - // ----- Sign In --------------------------------------------------------- - /// Asynchronously logs into Firebase with the given Auth token. - /// - /// An error is returned, if the token is invalid, expired or otherwise - /// not accepted by the server. - Future SignInWithCustomToken(const char* token); - - /// Get results of the most recent call to @ref SignInWithCustomToken. - Future SignInWithCustomTokenLastResult() const; - - /// Convenience method for @ref SignInAndRetrieveDataWithCredential that - /// doesn't return additional identity provider data. - Future SignInWithCredential(const Credential& credential); - - /// Get results of the most recent call to @ref SignInWithCredential. - Future SignInWithCredentialLastResult() const; - - /// Sign-in a user authenticated via a federated auth provider. - /// - /// @param[in] provider Contains information on the provider to authenticate - /// with. - /// - /// @return A Future with the result of the sign-in request. - /// - /// @note: This operation is supported only on iOS, tvOS and Android - /// platforms. On other platforms this method will return a Future with a - /// preset error code: kAuthErrorUnimplemented. - Future SignInWithProvider(FederatedAuthProvider* provider); - - /// Asynchronously logs into Firebase with the given credentials. - /// - /// For example, the credential could wrap a Facebook login access token or - /// a Twitter token/token-secret pair. - /// - /// The SignInResult contains both a reference to the User (which can be null - /// if the sign in failed), and AdditionalUserInfo, which holds details - /// specific to the Identity Provider used to sign in. - /// - /// An error is returned if the token is invalid, expired, or otherwise not - /// accepted by the server. - Future SignInAndRetrieveDataWithCredential( - const Credential& credential); - - /// Get results of the most recent call to - /// @ref SignInAndRetrieveDataWithCredential. - Future SignInAndRetrieveDataWithCredentialLastResult() const; - - /// Asynchronously creates and becomes an anonymous user. - /// If there is already an anonymous user signed in, that user will be - /// returned instead. - /// If there is any other existing user, that user will be signed out. - /// - /// - /// @if swig_examples - /// @code{.cs} - /// bool SignIn(Firebase.Auth.FirebaseAuth auth) { - /// auth.SignInAnonymouslyAsync().ContinueWith((authTask) => { - /// if (authTask.IsCanceled) { - /// DebugLog("Anonymous sign in canceled."); - /// } else if (authTask.IsFaulted) { - /// DebugLog("Anonymous sign in encountered an error."); - /// DebugLog(authTask.Exception.ToString()); - /// } else if (authTask.IsCompleted) { - /// DebugLog("Anonymous sign in successful!"); - /// } - /// }); - /// } - /// @endcode - /// @endif - /// - /// @if cpp_examples - /// The following sample code illustrates the sign-in flow that might be - /// used by a game or some other program with a regular (for example, 30Hz) - /// update loop. - /// - /// The sample calls SignIn() every frame. We don’t maintain our own - /// Futures but instead call SignInAnonymouslyLastResult() to get the Future - /// of our most recent call. - /// - /// @code{.cpp} - /// // Try to ensure that we get logged in. - /// // This function is called every frame. - /// bool SignIn(firebase::auth::Auth& auth) { - /// // Grab the result of the latest sign-in attempt. - /// firebase::Future future = - /// auth.SignInAnonymouslyLastResult(); - /// - /// // If we're in a state where we can try to sign in, do so. - /// if (future.status() == firebase::kFutureStatusInvalid || - /// (future.status() == firebase::kFutureStatusComplete && - /// future.error() != firebase::auth::kAuthErrorNone)) { - /// auth.SignInAnonymously(); - /// } - /// - /// // We're signed in if the most recent result was successful. - /// return future.status() == firebase::kFutureStatusComplete && - /// future.error() == firebase::auth::kAuthErrorNone; - /// } - /// @endcode - /// @endif - Future SignInAnonymously(); - - /// Get results of the most recent call to @ref SignInAnonymously. - Future SignInAnonymouslyLastResult() const; - - /// Signs in using provided email address and password. - /// An error is returned if the password is wrong or otherwise not accepted - /// by the server. - Future SignInWithEmailAndPassword(const char* email, - const char* password); - - /// Get results of the most recent call to @ref SignInWithEmailAndPassword. - Future SignInWithEmailAndPasswordLastResult() const; - - /// Creates, and on success, logs in a user with the given email address - /// and password. - /// - /// An error is returned when account creation is unsuccessful - /// (due to another existing account, invalid password, etc.). - Future CreateUserWithEmailAndPassword(const char* email, - const char* password); - - /// Get results of the most recent call to - /// @ref CreateUserWithEmailAndPassword. - Future CreateUserWithEmailAndPasswordLastResult() const; - - /// Removes any existing authentication credentials from this client. - /// This function always succeeds. - void SignOut(); - - // ----- Password Reset ------------------------------------------------- - /// Initiates a password reset for the given email address. - /// - /// If the email address is not registered, then the returned task has a - /// status of IsFaulted. - /// - /// - /// @if swig_examples - /// @code{.cs} - /// void ResetPassword(string email) { - /// auth.SendPasswordResetEmail(email).ContinueWith((authTask) => { - /// if (authTask.IsCanceled) { - /// DebugLog("Password reset was canceled."); - /// } else if (authTask.IsFaulted) { - /// DebugLog("Password reset encountered an error."); - /// DebugLog(authTask.Exception.ToString()); - /// } else if (authTask.IsCompleted) { - /// DebugLog("Password reset successful!"); - /// } - /// }); - /// } - /// @endcode - /// @endif - /// - /// @if cpp_examples - /// The following sample code illustrating a possible password reset flow. - /// Like in the Anonymous Sign-In example above, the ResetPasswordScreen() - /// function is called once per frame (say 30 times per second). - /// - /// No state is persisted by the caller in this example. The state of the - /// most recent calls are instead accessed through calls to functions like - /// auth.SendPasswordResetEmailLastResult(). - /// @code{.cpp} - /// const char* ImageNameForStatus(const firebase::FutureBase& future) { - /// assert(future.status() != firebase::kFutureStatusInvalid); - /// return future.status() == firebase::kFutureStatusPending - /// ? "waiting icon" - /// : future.error() == firebase::auth::kAuthErrorNone - /// ? "checkmark icon" - /// : "x mark icon"; - /// } - /// - /// // This function is called once per frame. - /// void ResetPasswordScreen(firebase::auth::Auth& auth) { - /// // Gather email address. - /// // ShowInputBox() returns a value when `enter` is pressed. - /// const std::string email = ShowInputBox("Enter e-mail"); - /// if (email != "") { - /// auth.SendPasswordResetEmail(email.c_str()); - /// } - /// - /// // Show checkmark, X-mark, or waiting icon beside the - /// // email input box, to indicate if email has been sent. - /// firebase::Future send_future = - /// auth.SendPasswordResetEmailLastResult(); - /// ShowImage(ImageNameForStatus(send_future)); - /// - /// // Display error message if the e-mail could not be sent. - /// if (send_future.status() == firebase::kFutureStatusComplete && - /// send_future.error() != firebase::auth::kAuthErrorNone) { - /// ShowTextBox(send_future.error_message()); - /// } - /// } - /// @endcode - /// @endif - Future SendPasswordResetEmail(const char* email); - - /// Get results of the most recent call to @ref SendPasswordResetEmail. - Future SendPasswordResetEmailLastResult() const; - -#ifndef SWIG - /// @brief Registers a listener to changes in the authentication state. - /// - /// There can be more than one listener registered at the same time. - /// The listeners are called asynchronously, possibly on a different thread. - /// - /// Authentication state changes are: - /// - Right after the listener has been registered - /// - When a user signs in - /// - When the current user signs out - /// - When the current user changes - /// - /// It is a recommended practice to always listen to sign-out events, as you - /// may want to prompt the user to sign in again and maybe restrict the - /// information or actions they have access to. - /// - /// Use RemoveAuthStateListener to unregister a listener. - /// - /// @note The caller owns `listener` and is responsible for destroying it. - /// When `listener` is destroyed, or when @ref Auth is destroyed, - /// RemoveAuthStateListener is called automatically. - void AddAuthStateListener(AuthStateListener* listener); - - /// @brief Unregisters a listener of authentication changes. - /// - /// Listener must previously been added with AddAuthStateListener. - /// - /// Note that listeners unregister themselves automatically when they - /// are destroyed, and the Auth class unregisters its listeners when the - /// Auth class itself is destroyed, so this function does not normally need - /// to be called explicitly. - void RemoveAuthStateListener(AuthStateListener* listener); - - /// @brief Registers a listener to changes in the ID token state. - /// - /// There can be more than one listener registered at the same time. - /// The listeners are called asynchronously, possibly on a different thread. - /// - /// Authentication state changes are: - /// - Right after the listener has been registered - /// - When a user signs in - /// - When the current user signs out - /// - When the current user changes - /// - When there is a change in the current user's token - /// - /// Use RemoveIdTokenListener to unregister a listener. - /// - /// @note The caller owns `listener` and is responsible for destroying it. - /// When `listener` is destroyed, or when @ref Auth is destroyed, - /// RemoveIdTokenListener is called automatically. - void AddIdTokenListener(IdTokenListener* listener); - - /// @brief Unregisters a listener of ID token changes. - /// - /// Listener must previously been added with AddIdTokenListener. - /// - /// Note that listeners unregister themselves automatically when they - /// are destroyed, and the Auth class unregisters its listeners when the - /// Auth class itself is destroyed, so this function does not normally need - /// to be called explicitly. - void RemoveIdTokenListener(IdTokenListener* listener); -#endif // not SWIG - - /// Gets the App this auth object is connected to. - App& app(); - - /// Returns the Auth object for an App. Creates the Auth if required. - /// - /// To get the Auth object for the default app, use, - /// GetAuth(GetDefaultFirebaseApp()); - /// - /// If the library Auth fails to initialize, init_result_out will be - /// written with the result status (if a pointer is given). - /// - /// @param[in] app The App to use for the Auth object. - /// @param[out] init_result_out Optional: If provided, write the init result - /// here. Will be set to kInitResultSuccess if initialization succeeded, or - /// kInitResultFailedMissingDependency on Android if Google Play services is - /// not available on the current device. - static Auth* GetAuth(App* app, InitResult* init_result_out = nullptr); - - private: - /// @cond FIREBASE_APP_INTERNAL - friend class ::firebase::App; - friend class ::firebase::auth::PhoneAuthProvider; - friend class IdTokenRefreshListener; - friend class IdTokenRefreshThread; - friend class UserDataPersist; - friend class UserDesktopTest; - friend class AuthDesktopTest; - - friend void EnableTokenAutoRefresh(AuthData* authData); - friend void DisableTokenAutoRefresh(AuthData* authData); - friend void ResetTokenRefreshCounter(AuthData* authData); - friend void LogHeartbeat(Auth* auth); - /// @endcond - - // Find Auth instance using App. Return null if the instance does not exist. - static Auth* FindAuth(App* app); - - // Provides access to the auth token for the current user. Returns the - // current user's auth token, or an empty string, if there isn't one. - // Note that this can potentially return an expired token from the cache. - static bool GetAuthTokenForRegistry(App* app, void* /*unused*/, void* out); - - // Provides asynchronous access to the auth token for the current user. Allow - // the caller to force-refresh the token. Even without force-refresh, this - // ensure the future contain a fresh current user's auth token. This function - // returns invalid future if user data is not available. - static bool GetAuthTokenAsyncForRegistry(App* app, void* force_refresh, - void* out_future); - - // Provides access to the current user's uid, equivalent to calling - // this->current_user()->uid(). Returns the current user's uid or an empty - // string, if there isn't one. The out pointer is expected to point to an - // instance of std::string. - static bool GetCurrentUserUidForRegistry(App* app, void* /*unused*/, - void* out); - - // Starts and stops a thread to ensure that the cached auth token is never - // kept long enough for it to expire. Refcounted, so multiple classes can - // register this without causing problems. - static bool StartTokenRefreshThreadForRegistry(App* app, void* /*unused*/, - void* /*unused*/); - static bool StopTokenRefreshThreadForRegistry(App* app, void* /*unused*/, - void* /*unused*/); - - // Adds an indirect auth state listener implemented as a callback and a - // context object. - // - // @param callback a function pointer that takes a single void* argument and - // returns void (i.e. it has type void (*)(void*)). - // @param context a pointer to an arbitrary object that Auth will pass to - // the callback when the auth state changes. - static bool AddAuthStateListenerForRegistry(App* app, void* callback, - void* context); - - // Removes the indirect auth state listener that was added with the same - // arguments. - static bool RemoveAuthStateListenerForRegistry(App* app, void* callback, - void* context); - - // Init and Destroy the platform specific auth data. - void InitPlatformAuth(AuthData* const auth_data); - void DestroyPlatformAuth(AuthData* const auth_data); - - // Call GetAuth() to create an Auth object. - // Constructors and destructors don't make any external calls. - // They just initialize and deinitialize internal variables. - Auth(App* app, void* auth_impl); - - // Delete the internal AuthData object. - void DeleteInternal(); - - // This class uses the pimpl mechanism to avoid exposing platform-dependent - // implementation. - AuthData* auth_data_; -}; - -#ifndef SWIG -/// @brief Listener called when there is a change in the authentication state. -/// -/// Override base class method to handle authentication state changes. -/// Methods are invoked asynchronously and may be invoked on other threads. -class AuthStateListener { - public: - /// @note: Destruction of the listener automatically calls - /// RemoveAuthStateListener() from the Auths this listener is registered with, - /// if those Auths have not yet been destroyed. - virtual ~AuthStateListener(); - - /// Called when the authentication state of `auth` changes. - /// - Right after the listener has been registered - /// - When a user is signed in - /// - When the current user is signed out - /// - When the current user changes - /// - /// @param[in] auth Disambiguates which @ref Auth instance the event - /// corresponds to, in the case where you are using more than one at the same - /// time. - virtual void OnAuthStateChanged(Auth* auth) = 0; - - private: - /// @cond FIREBASE_APP_INTERNAL - friend class Auth; - /// @endcond - - /// The Auths with which this listener has been registered. - std::vector auths_; -}; -#endif // not SWIG - -#ifndef SWIG -/// @brief Listener called when there is a change in the ID token. -/// -/// Override base class method to handle ID token changes. -/// Methods are invoked asynchronously and may be invoked on other threads. -class IdTokenListener { - public: - /// @note: Destruction of the listener automatically calls - /// RemoveIdTokenListener() from the Auths this listener is registered with, - /// if those Auths have not yet been destroyed. - virtual ~IdTokenListener(); - - /// Called when there is a change in the current user's token. - /// - Right after the listener has been registered - /// - When a user signs in - /// - When the current user signs out - /// - When the current user changes - /// - When there is a change in the current user's token - /// - /// @param[in] auth Disambiguates which @ref Auth instance the event - /// corresponds to, in the case where you are using more than one at the same - /// time. - virtual void OnIdTokenChanged(Auth* auth) = 0; - - private: - /// @cond FIREBASE_APP_INTERNAL - friend class Auth; - /// @endcond - - /// The Auths with which this listener has been registered. - std::vector auths_; -}; - -#endif // not SWIG - -/// @brief Used to authenticate with Federated Auth Providers. -/// -/// The federated auth provider implementation may facilitate multiple provider -/// types in the future, with support for OAuth to start. -class FederatedAuthProvider { - public: -#ifdef INTERNAL_EXPERIMENTAL -#ifndef SWIG - /// @brief Contains resulting information of a user authenticated by a - /// Federated Auth Provider. This information will be used by the internal - /// implementation to construct a corresponding User object. - struct AuthenticatedUserData { - /// The unique ID identifies the IdP account. - const char* uid; - - /// [opt] The email of the account. - const char* email; - - /// Whether the sign-in email is verified. - bool is_email_verified; - - /// [opt] The display name for the account. - const char* display_name; - - /// [opt] The username for the account. - const char* user_name; - - /// [opt] The photo Url for the account, if one exists. - const char* photo_url; - - /// The linked provider ID (e.g. "google.com" for the Google provider). - const char* provider_id; - - /// A Firebase Auth ID token for the authenticated user. - const char* access_token; - - /// A Firebase Auth refresh token for the authenticated user. - const char* refresh_token; - - /// [opt] IdP user profile data corresponding to the provided credential. - std::map raw_user_info; - - /// The number of seconds in which the ID token expires. - uint64_t token_expires_in_seconds; - }; - - /// @brief Handlers for client applications to facilitate federated auth - /// requests on non-mobile systems. - template - class Handler { - public: - virtual ~Handler() {} - - /// @brief Application sign-in handler. - /// - /// The application must implement this method to handle federated auth user - /// sign-in requests on non-mobile systems. - /// - /// @param[in] provider_data Contains information on the provider to - /// authenticate with. - /// @param[in] completion_handle Internal data pertaining to this operation - /// which must be passed to SignInComplete once the handler has completed - /// the sign in operation. - /// - /// @see Auth#SignInWithProvider - /// @see SignInComplete - virtual void OnSignIn(const T& provider_data, - AuthCompletionHandle* completion_handle) = 0; - - /// Completion for OnSignIn events. - /// - /// Invoke this method once the corresponding OnSignIn has been fulfilled. - /// This method will trigger the associated Future previously - /// returned from the Auth::SignInWithProvider method. - /// - /// @param[in] completion_handle The handle provided to the application's - /// FederatedAuthProvider::Handler::OnSignIn method. - /// @param[in] user_data The application's resulting Firebase user - /// values following the authorization request. - /// @param[in] auth_error The enumerated status code of the authorization - /// request. - /// @param[in] error_message An optional error message to be set in the - /// Future. - /// - /// @see OnSignIn - /// @see Auth::SignInWithProvider - void SignInComplete(AuthCompletionHandle* completion_handle, - const AuthenticatedUserData& user_data, - AuthError auth_error, const char* error_message); - - /// @brief Application user account link handler. - /// - /// The application must implement this method to handle federated auth user - /// link requests on non-mobile systems. - /// - /// @param[in] provider_data Contains information on the provider to - /// authenticate with. - /// @param[in] completion_handle Internal data pertaining to this operation - /// which must be passed to LinkComplete once the handler has completed the - /// user link operation. - /// - /// @see User#LinkWithProvider - virtual void OnLink(const T& provider_data, - AuthCompletionHandle* completion_handle) = 0; - - /// Completion for non-mobile user authorization handlers. - /// - /// Invoke this method once the OnLine process has been fulfilled. This - /// method will trigger the associated Future previously - /// returned from an invocation of User::LinkWithProvider. - /// - /// @param[in] completion_handle The handle provided to the - /// application's FederatedAuthProvider::Handler::OnLink method. - /// @param[in] user_data The application's resulting Firebase user - /// values following the user link request. - /// @param[in] auth_error The enumerated status code of the user link - /// request. - /// @param[in] error_message An optional error message to be set in the - /// Future. - /// - /// @see OnLink - /// @see User#LinkWithProvider - void LinkComplete(AuthCompletionHandle* completion_handle, - const AuthenticatedUserData& user_data, - AuthError auth_error, const char* error_message); - - /// @brief Application user re-authentication handler. - /// - /// The application must implement this method to handle federated auth user - /// re-authentication requests on non-mobile systems. - /// - /// @param[in] provider_data Contains information on the provider to - /// authenticate with. - /// @param[in] completion_handle Internal data pertaining to this operation - /// which must be passed to ReauthenticateComplete once the handler has - /// completed the reauthentication operation. - /// - /// @see User#ReauthenticateWithProviderComplete - virtual void OnReauthenticate(const T& provider_data, - AuthCompletionHandle* completion_handle) = 0; - - /// Completion for non-mobile user authorization handlers. - /// - /// Invoke this method once the OnReauthenticate process has been - /// fulfilled. This method will trigger the associated Future - /// previously returned from an invocation of - /// User::ReauthenticateWithProvider. - /// - /// @param[in] completion_handle The handle provided to the application's - /// FederatedAuthProvider::Handler::OnReauthenticate method. - /// @param[in] user_data The application's resulting Firebase user - /// values following the user re-authentication request. - /// @param[in] auth_error The enumerated status code of the reauthentication - /// request. - /// @param[in] error_message An optional error message to be set in the - /// Future. - /// - /// @see OnReauthenticate - /// @see User#ReuthenticateWithProvider - void ReauthenticateComplete(AuthCompletionHandle* completion_handle, - const AuthenticatedUserData& user_data, - AuthError auth_error, - const char* error_message); - }; -#endif // not SWIG -#endif // INTERNAL_EXPERIMENTAL - - FederatedAuthProvider() {} - virtual ~FederatedAuthProvider() {} - - private: - friend class ::firebase::auth::Auth; - friend class ::firebase::auth::User; - virtual Future SignIn(AuthData* auth_data) = 0; - virtual Future Link(AuthData* auth_data) = 0; - virtual Future Reauthenticate(AuthData* auth_data) = 0; -}; - -/// @brief Authenticates with Federated OAuth Providers via the -/// firebase::auth::Auth and firebase::auth::User classes. -/// -/// Once configured with a provider id, and with OAuth scope and OAuth custom -/// parameters via an FedeartedOAuthProviderData structure, an object of -/// this class may be used via Auth::SignInWithProvider to sign-in users, or via -/// User::LinkWithProvider and User::ReauthenticateWithProvider for cross -/// account linking and user reauthentication, respectively. -class FederatedOAuthProvider : public FederatedAuthProvider { - public: -#ifdef INTERNAL_EXPERIMENTAL -#ifndef SWIG - /// @brief A FederatedAuthProvider typed specifically for OAuth Authentication - /// handling. - /// - /// To be used on non-mobile environments for custom OAuth implementations and - /// UI flows. - typedef FederatedAuthProvider::Handler - AuthHandler; -#endif // !SWIG -#endif // INTERNAL_EXPERIMENTAL - - /// Constructs an unconfigured provider. - FederatedOAuthProvider(); - - /// Constructs a FederatedOAuthProvider preconfigured with provider data. - /// - /// @param[in] provider_data Contains the federated provider id and OAuth - /// scopes and OAuth custom parameters required for user authentication and - /// user linking. - explicit FederatedOAuthProvider( - const FederatedOAuthProviderData& provider_data); - -#ifdef INTERNAL_EXPERIMENTAL -#ifndef SWIG - /// @brief Constructs a provider with the required information to authenticate - /// using an OAuth Provider. - /// - /// An AuthHandler is required on desktop platforms to facilitate custom - /// implementations of OAuth authentication. The AuthHandler must outlive the - /// instance of this OAuthProvider on desktop systems and is ignored on iOS, - /// tvOS, and Android platforms. - /// - /// @param[in] provider_data Contains information on the provider to - /// authenticate with. - /// @param[in] handler An FederatedOAuthProviderData typed - /// FederatedAuthProvider::Handler which be invoked on non-mobile systems - /// to handle authentication requests. - FederatedOAuthProvider(const FederatedOAuthProviderData& provider_data, - AuthHandler* handler); -#endif // !SWIG -#endif // INTERNAL_EXPERIMENTAL - - ~FederatedOAuthProvider() override; - - /// @brief Configures the provider with OAuth provider information. - /// - /// @param[in] provider_data Contains the federated provider id and OAuth - /// scopes and OAuth custom parameters required for user authentication and - /// user linking. - void SetProviderData(const FederatedOAuthProviderData& provider_data); - -#ifdef INTERNAL_EXPERIMENTAL -#ifndef SWIG - /// @brief Configures the use of an AuthHandler for non-mobile systems. - /// - /// The existence of a handler is required for non-mobile systems, and is - /// ignored on iOS, tvOS and Android platforms. - /// - /// @param[in] handler An FederatedOAuthProviderData typed - /// FederatedAuthProvider::Handler which be invoked on non-mobile systems - /// to handle authentication requests. The handler must outlive the instance - /// of this FederatedOAuthProvider. - void SetAuthHandler(AuthHandler* handler); -#endif // !SWIG -#endif // INTERNAL_EXPERIMENTAL - - private: - friend class ::firebase::auth::Auth; - - Future SignIn(AuthData* auth_data) override; - Future Link(AuthData* auth_data) override; - Future Reauthenticate(AuthData* auth_data) override; - - FederatedOAuthProviderData provider_data_; -#ifdef INTERNAL_EXPERIMENTAL - AuthHandler* handler_; -#endif // INTERNAL_EXPERIMENTAL -}; - -} // namespace auth -} // namespace firebase - -#endif // FIREBASE_AUTH_SRC_INCLUDE_FIREBASE_AUTH_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/auth/credential.h b/packages/firebase_core/firebase_core/firebase_core/firebase/auth/credential.h deleted file mode 100644 index a179d199b67a..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/auth/credential.h +++ /dev/null @@ -1,633 +0,0 @@ -/* - * Copyright 2016 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_AUTH_SRC_INCLUDE_FIREBASE_AUTH_CREDENTIAL_H_ -#define FIREBASE_AUTH_SRC_INCLUDE_FIREBASE_AUTH_CREDENTIAL_H_ - -#include - -#include - -#include "firebase/auth/types.h" -#include "firebase/internal/common.h" - -namespace firebase { - -// Predeclarations. -class App; - -/// @cond FIREBASE_APP_INTERNAL -template -class Future; -/// @endcond - -namespace auth { - -// Predeclarations. -class Auth; -class User; - -// Opaque internal types. -struct AuthData; -class ForceResendingTokenData; -struct PhoneAuthProviderData; -struct PhoneListenerData; - -/// @brief Authentication credentials for an authentication provider. -/// -/// An authentication provider is a service that allows you to authenticate -/// a user. Firebase provides email/password authentication, but there are also -/// external authentication providers such as Facebook. -class Credential { -#ifndef SWIG - /// @cond FIREBASE_APP_INTERNAL - friend class EmailAuthProvider; - friend class FacebookAuthProvider; - friend class GameCenterAuthProvider; - friend class GitHubAuthProvider; - friend class GoogleAuthProvider; - friend class JniAuthPhoneListener; - friend class MicrosoftAuthProvider; - friend class OAuthProvider; - friend class PhoneAuthProvider; - friend class PlayGamesAuthProvider; - friend class TwitterAuthProvider; - friend class YahooAuthProvider; - friend class ServiceUpdatedCredentialProvider; - /// @endcond -#endif // !SWIG - - private: - /// Should only be created by `Provider` classes. - /// - /// @see EmailAuthProvider::GetCredential() - /// @see FacebookAuthProvider::GetCredential() - /// @see GoogleAuthProvider::GetCredential() - explicit Credential(void* impl) : impl_(impl), error_code_(kAuthErrorNone) {} - - public: - Credential() : impl_(nullptr), error_code_(kAuthErrorNone) {} - ~Credential(); - - /// Copy constructor. - Credential(const Credential& rhs); - - /// Copy a Credential. - Credential& operator=(const Credential& rhs); - - /// Gets the name of the Identification Provider (IDP) for the credential. - /// - /// - /// @xmlonly - /// - /// Gets the name of the Identification Provider (IDP) for the credential. - /// - /// @endxmlonly - /// - std::string provider() const; - - /// Get whether this credential is valid. A credential can be - /// invalid in an error condition, e.g. empty username/password. - /// - /// @returns True if the credential is valid, false otherwise. - bool is_valid() const; - - protected: - /// @cond FIREBASE_APP_INTERNAL - friend class Auth; - friend class User; - - /// Platform-specific implementation. - /// For example, FIRAuthCredential* on iOS. - void* impl_; - - // If not kAuthErrorNone, then use this error code and string to override - // whatever error we would normally return when trying to sign-in with this - // credential. - AuthError error_code_; - std::string error_message_; - /// @endcond -}; - -/// @brief Use email and password to authenticate. -/// -/// Allows developers to use the email and password credentials as they could -/// other auth providers. For example, this can be used to change passwords, -/// log in, etc. -class EmailAuthProvider { - public: - /// Generate a credential from the given email and password. - /// - /// @param email E-mail to generate the credential from. - /// @param password Password to use for the new credential. - /// - /// @returns New Credential. - static Credential GetCredential(const char* email, const char* password); - - /// The string used to identify this provider. - static const char* const kProviderId; -}; - -/// @brief Use an access token provided by Facebook to authenticate. -class FacebookAuthProvider { - public: - /// Generate a credential from the given Facebook token. - /// - /// @param access_token Facebook token to generate the credential from. - /// - /// @returns New Credential. - static Credential GetCredential(const char* access_token); - - /// The string used to identify this provider. - static const char* const kProviderId; -}; - -/// @brief GameCenter (Apple) auth provider -class GameCenterAuthProvider { - public: - /// Generate a credential from GameCenter for the current user. - /// - /// @return a Future that will be fulfilled with the resulting credential. - static Future GetCredential(); - - /// Get the result of the most recent GetCredential() call. - /// - /// @return an object which can be used to retrieve the Credential. - static Future GetCredentialLastResult(); - - /// Tests to see if the current user is signed in to GameCenter. - /// - /// @return true if the user is signed in, false otherwise. - static bool IsPlayerAuthenticated(); - - /// The string used to identify this provider. - static const char* const kProviderId; -}; - -/// @brief Use an access token provided by GitHub to authenticate. -class GitHubAuthProvider { - public: - /// Generate a credential from the given GitHub token. - /// - /// @param token The GitHub OAuth access token. - /// - /// @returns New Credential. - static Credential GetCredential(const char* token); - - /// The string used to identify this provider. - static const char* const kProviderId; -}; - -/// @brief Use an ID token and access token provided by Google to authenticate. -class GoogleAuthProvider { - public: - /// Generate a credential from the given Google ID token and/or access token. - /// - /// @param id_token Google Sign-In ID token. - /// @param access_token Google Sign-In access token. - /// - /// @returns New Credential. - static Credential GetCredential(const char* id_token, - const char* access_token); - - /// The string used to identify this provider. - static const char* const kProviderId; -}; - -/// @brief Use an access token provided by Microsoft to authenticate. -class MicrosoftAuthProvider { - public: - /// The string used to identify this provider. - static const char* const kProviderId; -}; - -/// @brief OAuth2.0+UserInfo auth provider (OIDC compliant and non-compliant). -class OAuthProvider { - public: - /// Generate a credential for an OAuth2 provider. - /// - /// @param provider_id Name of the OAuth2 provider - /// TODO(jsanmiya) add examples. - /// @param id_token The authentication token (OIDC only). - /// @param access_token TODO(jsanmiya) add explanation (currently missing - /// from Android and iOS implementations). - static Credential GetCredential(const char* provider_id, const char* id_token, - const char* access_token); - - /// Generate a credential for an OAuth2 provider. - /// - /// @param provider_id Name of the OAuth2 provider. - /// @param id_token The authentication token (OIDC only). - /// @param raw_nonce The raw nonce associated with the Auth credential being - /// created. - /// @param access_token The access token associated with the Auth credential - /// to be created, if available. This value may be null. - static Credential GetCredential(const char* provider_id, const char* id_token, - const char* raw_nonce, - const char* access_token); -}; - -/// @brief Use phone number text messages to authenticate. -/// -/// Allows developers to use the phone number and SMS verification codes -/// to authenticate a user on a mobile device. -/// -/// This class is not supported on tvOS and Desktop platforms. -/// -/// The verification flow results in a Credential that can be used to, -/// * Sign in to an existing phone number account/sign up with a new -/// phone number -/// * Link a phone number to a current user. This provider will be added to -/// the user. -/// * Update a phone number on an existing user. -/// * Re-authenticate an existing user. This may be needed when a sensitive -/// operation requires the user to be recently logged in. -/// -/// Possible verification flows: -/// (1) User manually enters verification code. -/// @if cpp_examples -/// - App calls @ref VerifyPhoneNumber. -/// - Web verification page is displayed to user where they may need to -/// solve a CAPTCHA. [iOS only]. -/// - Auth server sends the verification code via SMS to the provided -/// phone number. App receives verification id via Listener::OnCodeSent(). -/// - User receives SMS and enters verification code in app's GUI. -/// - App uses user's verification code to call -/// @ref PhoneAuthProvider::GetCredential. -/// @endif -/// -/// @if swig_examples -/// - App calls @ref VerifyPhoneNumber. -/// - Web verification page is displayed to user where they may need to -/// solve a CAPTCHA. [iOS only]. -/// - Auth server sends the verification code via SMS to the provided -/// phone number. App receives verification id via @ref CodeSent. -/// - User receives SMS and enters verification code in app's GUI. -/// - App uses user's verification code to call -/// @ref PhoneAuthProvider::GetCredential. -/// @endif -/// -/// -/// (2) SMS is automatically retrieved (Android only). -/// - App calls @ref VerifyPhoneNumber with `timeout_ms` > 0. -/// - Auth server sends the verification code via SMS to the provided -/// phone number. -/// - SMS arrives and is automatically retrieved by the operating system. -/// Credential is automatically created and passed to the app via -/// @if cpp_examples -/// Listener::OnVerificationCompleted(). -/// @endif -/// -/// @if swig_examples -/// @ref VerificationCompleted. -/// @endif -/// -/// -/// (3) Phone number is instantly verified (Android only). -/// - App calls @ref VerifyPhoneNumber. -/// - The operating system validates the phone number without having to -/// send an SMS. Credential is automatically created and passed to -/// the app via -/// @if cpp_examples -/// Listener::OnVerificationCompleted(). -/// @endif -/// -/// @if swig_examples -/// @ref VerificationCompleted. -/// @endif -/// -/// -/// @if cpp_examples -/// All three flows can be handled with the example code below. -/// The flow is complete when PhoneVerifier::credential() returns non-NULL. -/// -/// @code{.cpp} -/// class PhoneVerifier : public PhoneAuthProvider::Listener { -/// public: -/// PhoneVerifier(const char* phone_number, -/// PhoneAuthProvider* phone_auth_provider) -/// : display_message_("Sending SMS with verification code"), -/// display_verification_code_input_box_(false), -/// display_resend_sms_button_(false), -/// phone_auth_provider_(phone_auth_provider), -/// phone_number_(phone_number) { -/// SendSms(); -/// } -/// -/// ~PhoneVerifier() override {} -/// -/// void OnVerificationCompleted(Credential credential) override { -/// // Grab `mutex_` for the scope of `lock`. Callbacks can be called on -/// // other threads, so this mutex ensures data access is atomic. -/// MutexLock lock(mutex_); -/// credential_ = credential; -/// } -/// -/// void OnVerificationFailed(const std::string& error) override { -/// MutexLock lock(mutex_); -/// display_message_ = "Verification failed with error: " + error; -/// } -/// -/// void OnCodeSent(const std::string& verification_id, -/// const PhoneAuthProvider::ForceResendingToken& -/// force_resending_token) override { -/// MutexLock lock(mutex_); -/// verification_id_ = verification_id; -/// force_resending_token_ = force_resending_token; -/// -/// display_verification_code_input_box_ = true; -/// display_message_ = "Waiting for SMS"; -/// } -/// -/// void OnCodeAutoRetrievalTimeOut( -/// const std::string& verification_id) override { -/// MutexLock lock(mutex_); -/// display_resend_sms_button_ = true; -/// } -/// -/// // Draw the verification GUI on screen and process input events. -/// void Draw() { -/// MutexLock lock(mutex_); -/// -/// // Draw an informative message describing what's currently happening. -/// ShowTextBox(display_message_.c_str()); -/// -/// // Once the time out expires, display a button to resend the SMS. -/// // If the button is pressed, call VerifyPhoneNumber again using the -/// // force_resending_token_. -/// if (display_resend_sms_button_ && !verification_id_.empty()) { -/// const bool resend_sms = ShowTextButton("Resend SMS"); -/// if (resend_sms) { -/// SendSms(); -/// } -/// } -/// -/// // Once the SMS has been sent, allow the user to enter the SMS -/// // verification code into a text box. When the user has completed -/// // entering it, call GetCredential() to complete the flow. -/// if (display_verification_code_input_box_) { -/// const std::string verification_code = -/// ShowInputBox("Verification code"); -/// if (!verification_code.empty()) { -/// credential_ = phone_auth_provider_->GetCredential( -/// verification_id_.c_str(), verification_code.c_str()); -/// } -/// } -/// } -/// -/// // The phone number verification flow is complete when this returns -/// // non-NULL. -/// Credential* credential() { -/// MutexLock lock(mutex_); -/// return credential_.is_valid() ? &credential_ : nullptr; -/// } -/// -/// private: -/// void SendSms() { -/// static const uint32_t kAutoVerifyTimeOut = 2000; -/// MutexLock lock(mutex_); -/// phone_auth_provider_->VerifyPhoneNumber( -/// phone_number_.c_str(), kAutoVerifyTimeOut, &force_resending_token_, -/// this); -/// display_resend_sms_button_ = false; -/// } -/// -/// // GUI-related variables. -/// std::string display_message_; -/// bool display_verification_code_input_box_; -/// bool display_resend_sms_button_; -/// -/// // Phone flow related variables. -/// PhoneAuthProvider* phone_auth_provider_; -/// std::string phone_number_; -/// std::string verification_id_; -/// PhoneAuthProvider::ForceResendingToken force_resending_token_; -/// Credential credential_; -/// -/// // Callbacks can be called on other threads, so guard them with a mutex. -/// Mutex mutex_; -/// }; -/// @endcode -/// @endif -class PhoneAuthProvider { - public: - /// @brief Token to maintain current phone number verification session. - /// Acquired via @ref Listener::OnCodeSent. Used in @ref VerifyPhoneNumber. - class ForceResendingToken { - public: - /// This token will be invalid until it is assigned a value sent via - /// @ref Listener::OnCodeSent. It can still be passed into - /// @ref VerifyPhoneNumber, but it will be ignored. - ForceResendingToken(); - - /// Make `this` token refer to the same phone session as `rhs`. - ForceResendingToken(const ForceResendingToken& rhs); - - /// Releases internal resources when destructing. - ~ForceResendingToken(); - - /// Make `this` token refer to the same phone session as `rhs`. - ForceResendingToken& operator=(const ForceResendingToken& rhs); - - /// Return true if `rhs` is refers to the same phone number session as - /// `this`. - bool operator==(const ForceResendingToken& rhs) const; - - /// Return true if `rhs` is refers to a different phone number session as - /// `this`. - bool operator!=(const ForceResendingToken& rhs) const; - - private: - friend class JniAuthPhoneListener; - friend class PhoneAuthProvider; - ForceResendingTokenData* data_; - }; - - /// @brief Receive callbacks from @ref VerifyPhoneNumber events. - /// - /// Please see @ref PhoneAuthProvider for a sample implementation. - class Listener { - public: - Listener(); - virtual ~Listener(); - - /// @brief Phone number auto-verification succeeded. - /// - /// Called when, - /// - auto-sms-retrieval has succeeded--flow (2) in @ref PhoneAuthProvider - /// - instant validation has succeeded--flow (3) in @ref PhoneAuthProvider - /// - /// @note This callback is never called on iOS, since iOS does not have - /// auto-validation. It is always called immediately in the stub desktop - /// implementation, however, since it fakes immediate success. - /// - /// @param[in] credential The completed credential from the phone number - /// verification flow. - virtual void OnVerificationCompleted(Credential credential) = 0; - - /// @brief Phone number verification failed with an error. - /// - /// Called when and error occurred doing phone number authentication. - /// For example, - /// - quota exceeded - /// - unknown phone number format - /// - /// @param[in] error A description of the failure. - virtual void OnVerificationFailed(const std::string& error) = 0; - - /// @brief SMS message with verification code sent to phone number. - /// - /// Called immediately after Auth server sends a verification SMS. - /// Once receiving this, you can allow users to manually input the - /// verification code (even if you're also performing auto-verification). - /// For user manual input case, get the SMS verification code from the user - /// and then call @ref GetCredential with the user's code. - /// - /// @param[in] verification_id Pass to @ref GetCredential along with the - /// user-input verification code to complete the phone number verification - /// flow. - /// @param[in] force_resending_token If the user requests that another SMS - /// message be sent, use this when you recall @ref VerifyPhoneNumber. - virtual void OnCodeSent(const std::string& verification_id, - const ForceResendingToken& force_resending_token); - - /// @brief The timeout specified in @ref VerifyPhoneNumber has expired. - /// - /// Called once `auto_verify_time_out_ms` has passed. - /// If using auto SMS retrieval, you can choose to block the UI (do not - /// allow manual input of the verification code) until timeout is hit. - /// - /// @note This callback is called immediately on iOS, since iOS does not - /// have auto-validation. - /// - /// @param[in] verification_id Identify the transaction that has timed out. - virtual void OnCodeAutoRetrievalTimeOut(const std::string& verification_id); - - private: - friend class PhoneAuthProvider; - - /// Back-pointer to the data of the PhoneAuthProvider that - /// @ref VerifyPhoneNumber was called with. Used internally. - PhoneListenerData* data_; - }; - - /// Maximum value of `auto_verify_time_out_ms` in @ref VerifyPhoneNumber. - /// Larger values will be clamped. - /// - /// @deprecated This value is no longer used to clamp - /// `auto_verify_time_out_ms` in VerifyPhoneNumber. The range is - /// determined by the underlying SDK, ex. PhoneAuthOptions.Build - /// in Android SDK - static const uint32_t kMaxTimeoutMs; - - /// Start the phone number authentication operation. - /// - /// @param[in] phone_number The phone number identifier supplied by the user. - /// Its format is normalized on the server, so it can be in any format - /// here. - /// @param[in] auto_verify_time_out_ms The time out for SMS auto retrieval, in - /// miliseconds. Currently SMS auto retrieval is only supported on Android. - /// If 0, do not do SMS auto retrieval. - /// If positive, try to auto-retrieve the SMS verification code. - /// When the time out is exceeded, listener->OnCodeAutoRetrievalTimeOut() - /// is called. - /// @param[in] force_resending_token If NULL, assume this is a new phone - /// number to verify. If not-NULL, bypass the verification session deduping - /// and force resending a new SMS. - /// This token is received in @ref Listener::OnCodeSent. - /// This should only be used when the user presses a Resend SMS button. - /// @param[in,out] listener Class that receives notification whenever an SMS - /// verification event occurs. See sample code at top of class. - void VerifyPhoneNumber(const char* phone_number, - uint32_t auto_verify_time_out_ms, - const ForceResendingToken* force_resending_token, - Listener* listener); - - /// Generate a credential for the given phone number. - /// - /// @param[in] verification_id The id returned when sending the verification - /// code. Sent to the caller via @ref Listener::OnCodeSent. - /// @param[in] verification_code The verification code supplied by the user, - /// most likely by a GUI where the user manually enters the code - /// received in the SMS sent by @ref VerifyPhoneNumber. - /// - /// @returns New Credential. - Credential GetCredential(const char* verification_id, - const char* verification_code); - - /// Return the PhoneAuthProvider for the specified `auth`. - /// - /// @param[in] auth The Auth session for which we want to get a - /// PhoneAuthProvider. - static PhoneAuthProvider& GetInstance(Auth* auth); - - /// The string used to identify this provider. - static const char* const kProviderId; - - private: - friend struct AuthData; - friend class JniAuthPhoneListener; - - // Use @ref GetInstance to access the PhoneAuthProvider. - PhoneAuthProvider(); - - // The PhoneAuthProvider is owned by the Auth class. - ~PhoneAuthProvider(); - - PhoneAuthProviderData* data_; -}; - -/// @brief Use a server auth code provided by Google Play Games to authenticate. -class PlayGamesAuthProvider { - public: - /// Generate a credential from the given Server Auth Code. - /// - /// @param server_auth_code Play Games Sign in Server Auth Code. - /// - /// @return New Credential. - static Credential GetCredential(const char* server_auth_code); - - /// The string used to identify this provider. - static const char* const kProviderId; -}; - -/// @brief Use a token and secret provided by Twitter to authenticate. -class TwitterAuthProvider { - public: - /// Generate a credential from the given Twitter token and password. - /// - /// @param token The Twitter OAuth token. - /// @param secret The Twitter OAuth secret. - /// - /// @return New Credential. - static Credential GetCredential(const char* token, const char* secret); - - /// The string used to identify this provider. - static const char* const kProviderId; -}; - -/// @brief Use an access token provided by Yahoo to authenticate. -class YahooAuthProvider { - public: - /// The string used to identify this provider. - static const char* const kProviderId; -}; - -} // namespace auth -} // namespace firebase - -#endif // FIREBASE_AUTH_SRC_INCLUDE_FIREBASE_AUTH_CREDENTIAL_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/auth/types.h b/packages/firebase_core/firebase_core/firebase_core/firebase/auth/types.h deleted file mode 100644 index 3f141ad3692c..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/auth/types.h +++ /dev/null @@ -1,473 +0,0 @@ -/* - * Copyright 2016 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_AUTH_SRC_INCLUDE_FIREBASE_AUTH_TYPES_H_ -#define FIREBASE_AUTH_SRC_INCLUDE_FIREBASE_AUTH_TYPES_H_ - -#include -#include -#include - -namespace firebase { -namespace auth { - -/// All possible error codes from asynchronous calls. -/// For error details, -/// @if cpp_examples -/// call Future::ErrorMessage(). -/// @endif -/// -/// @if swig_examples -/// use the FirebaseException.Message property. -/// @endif -/// -enum AuthError { - /// Success. - kAuthErrorNone = 0, - - /// Function will be implemented in a later revision of the API. - kAuthErrorUnimplemented = -1, - - /// This indicates an internal error. - /// Common error code for all API Methods. - kAuthErrorFailure = 1, - - /// Indicates a validation error with the custom token. - /// This error originates from "bring your own auth" methods. - kAuthErrorInvalidCustomToken, - - /// Indicates the service account and the API key belong to different - /// projects. - /// Caused by "Bring your own auth" methods. - kAuthErrorCustomTokenMismatch, - - /// Indicates the IDP token or requestUri is invalid. - /// Caused by "Sign in with credential" methods. - kAuthErrorInvalidCredential, - - /// Indicates the user’s account is disabled on the server. - /// Caused by "Sign in with credential" methods. - kAuthErrorUserDisabled, - - /// Indicates an account already exists with the same email address but using - /// different sign-in credentials. Account linking is required. - /// Caused by "Sign in with credential" methods. - kAuthErrorAccountExistsWithDifferentCredentials, - - /// Indicates the administrator disabled sign in with the specified identity - /// provider. - /// Caused by "Set account info" methods. - kAuthErrorOperationNotAllowed, - - /// Indicates the email used to attempt a sign up is already in use. - /// Caused by "Set account info" methods. - kAuthErrorEmailAlreadyInUse, - - /// Indicates the user has attemped to change email or password more than 5 - /// minutes after signing in, and will need to refresh the credentials. - /// Caused by "Set account info" methods. - kAuthErrorRequiresRecentLogin, - - /// Indicates an attempt to link with a credential that has already been - /// linked with a different Firebase account. - /// Caused by "Set account info" methods. - kAuthErrorCredentialAlreadyInUse, - - /// Indicates an invalid email address. - /// Caused by "Sign in with password" methods. - kAuthErrorInvalidEmail, - - /// Indicates the user attempted sign in with a wrong password. - /// Caused by "Sign in with password" methods. - kAuthErrorWrongPassword, - - /// Indicates that too many requests were made to a server method. - /// Common error code for all API methods. - kAuthErrorTooManyRequests, - - /// Indicates the user account was not found. - /// Send password request email error code. - /// Common error code for all API methods. - kAuthErrorUserNotFound, - - /// Indicates an attempt to link a provider to which the account is already - /// linked. - /// Caused by "Link credential" methods. - kAuthErrorProviderAlreadyLinked, - - /// Indicates an attempt to unlink a provider that is not linked. - /// Caused by "Link credential" methods. - kAuthErrorNoSuchProvider, - - /// Indicates user's saved auth credential is invalid, the user needs to sign - /// in again. - /// Caused by requests with an STS id token. - kAuthErrorInvalidUserToken, - - /// Indicates the saved token has expired. - /// For example, the user may have changed account password on another device. - /// The user needs to sign in again on the device that made this request. - /// Caused by requests with an STS id token. - kAuthErrorUserTokenExpired, - - /// Indicates a network error occurred (such as a timeout, interrupted - /// connection, or unreachable host). These types of errors are often - /// recoverable with a retry. - /// Common error code for all API Methods. - kAuthErrorNetworkRequestFailed, - - /// Indicates an invalid API key was supplied in the request. - /// For Android these should no longer occur (as of 2016 v3). - /// Common error code for all API Methods. - kAuthErrorInvalidApiKey, - - /// Indicates the App is not authorized to use Firebase Authentication with - /// the provided API Key. - /// Common error code for all API Methods. - /// On Android this error should no longer occur (as of 2016 v3). - /// Common error code for all API Methods. - kAuthErrorAppNotAuthorized, - - /// Indicates that an attempt was made to reauthenticate with a user which is - /// not the current user. - kAuthErrorUserMismatch, - - /// Indicates an attempt to set a password that is considered too weak. - kAuthErrorWeakPassword, - - /// Internal api usage error code when there is no signed-in user - /// and getAccessToken is called. - /// - /// @note This error is only reported on Android. - kAuthErrorNoSignedInUser, - - /// This can happen when certain methods on App are performed, when the auth - /// API is not loaded. - /// - /// @note This error is only reported on Android. - kAuthErrorApiNotAvailable, - - /// Indicates the out-of-band authentication code is expired. - kAuthErrorExpiredActionCode, - - /// Indicates the out-of-band authentication code is invalid. - kAuthErrorInvalidActionCode, - - /// Indicates that there are invalid parameters in the payload during a - /// "send password reset email" attempt. - kAuthErrorInvalidMessagePayload, - - /// Indicates that an invalid phone number was provided. - /// This is caused when the user is entering a phone number for verification. - kAuthErrorInvalidPhoneNumber, - - /// Indicates that a phone number was not provided during phone number - /// verification. - /// - /// @note This error is iOS-specific. - kAuthErrorMissingPhoneNumber, - - /// Indicates that the recipient email is invalid. - kAuthErrorInvalidRecipientEmail, - - /// Indicates that the sender email is invalid during a "send password reset - /// email" attempt. - kAuthErrorInvalidSender, - - /// Indicates that an invalid verification code was used in the - /// verifyPhoneNumber request. - kAuthErrorInvalidVerificationCode, - - /// Indicates that an invalid verification ID was used in the - /// verifyPhoneNumber request. - kAuthErrorInvalidVerificationId, - - /// Indicates that the phone auth credential was created with an empty - /// verification code. - kAuthErrorMissingVerificationCode, - - /// Indicates that the phone auth credential was created with an empty - /// verification ID. - kAuthErrorMissingVerificationId, - - /// Indicates that an email address was expected but one was not provided. - kAuthErrorMissingEmail, - - /// Represents the error code for when an application attempts to create an - /// email/password account with an empty/null password field. - /// - /// @note This error is only reported on Android. - kAuthErrorMissingPassword, - - /// Indicates that the project's quota for this operation (SMS messages, - /// sign-ins, account creation) has been exceeded. Try again later. - kAuthErrorQuotaExceeded, - - /// Thrown when one or more of the credentials passed to a method fail to - /// identify and/or authenticate the user subject of that operation. Inspect - /// the error message to find out the specific cause. - /// @note This error is only reported on Android. - kAuthErrorRetryPhoneAuth, - - /// Indicates that the SMS code has expired. - kAuthErrorSessionExpired, - - /// Indicates that the app could not be verified by Firebase during phone - /// number authentication. - /// - /// @note This error is iOS-specific. - kAuthErrorAppNotVerified, - - /// Indicates a general failure during the app verification flow. - /// - /// @note This error is iOS-specific. - kAuthErrorAppVerificationFailed, - - /// Indicates that the reCAPTCHA token is not valid. - /// - /// @note This error is iOS and tvOS-specific. - kAuthErrorCaptchaCheckFailed, - - /// Indicates that an invalid APNS device token was used in the verifyClient - /// request. - /// - /// @note This error is iOS and tvOS-specific. - kAuthErrorInvalidAppCredential, - - /// Indicates that the APNS device token is missing in the verifyClient - /// request. - /// - /// @note This error is iOS and tvOS-specific. - kAuthErrorMissingAppCredential, - - /// Indicates that the clientID used to invoke a web flow is invalid. - /// - /// @note This error is iOS and tvOS-specific. - kAuthErrorInvalidClientId, - - /// Indicates that the domain specified in the continue URI is not valid. - /// - /// @note This error is iOS and tvOS-specific. - kAuthErrorInvalidContinueUri, - - /// Indicates that a continue URI was not provided in a request to the backend - /// which requires one. - kAuthErrorMissingContinueUri, - - /// Indicates an error occurred while attempting to access the keychain. - /// Common error code for all API Methods. - /// - /// @note This error is iOS and tvOS-specific. - kAuthErrorKeychainError, - - /// Indicates that the APNs device token could not be obtained. The app may - /// not have set up remote notification correctly, or may have failed to - /// forward the APNs device token to FIRAuth if app delegate swizzling is - /// disabled. - /// - /// @note This error is iOS and tvOS-specific. - kAuthErrorMissingAppToken, - - /// Indicates that the iOS bundle ID is missing when an iOS App Store ID is - /// provided. - /// - /// @note This error is iOS and tvOS-specific. - kAuthErrorMissingIosBundleId, - - /// Indicates that the app fails to forward remote notification to FIRAuth. - /// - /// @note This error is iOS and tvOS-specific. - kAuthErrorNotificationNotForwarded, - - /// Indicates that the domain specified in the continue URL is not white- - /// listed in the Firebase console. - /// - /// @note This error is iOS and tvOS-specific. - kAuthErrorUnauthorizedDomain, - - /// Indicates that an attempt was made to present a new web context while one - /// was already being presented. - kAuthErrorWebContextAlreadyPresented, - - /// Indicates that the URL presentation was cancelled prematurely by the user. - kAuthErrorWebContextCancelled, - - /// Indicates that Dynamic Links in the Firebase Console is not activated. - kAuthErrorDynamicLinkNotActivated, - - /// Indicates that the operation was cancelled. - kAuthErrorCancelled, - - /// Indicates that the provider id given for the web operation is invalid. - kAuthErrorInvalidProviderId, - - /// Indicates that an internal error occurred during a web operation. - kAuthErrorWebInternalError, - - /// Indicates that 3rd party cookies or data are disabled, or that there was - /// a problem with the browser. - kAuthErrorWebStorateUnsupported, - - /// Indicates that the provided tenant ID does not match the Auth instance's - /// tenant ID. - kAuthErrorTenantIdMismatch, - - /// Indicates that a request was made to the backend with an associated tenant - /// ID for an operation that does not support multi-tenancy. - kAuthErrorUnsupportedTenantOperation, - - /// Indicates that an FDL domain used for an out of band code flow is either - /// not configured or is unauthorized for the current project. - kAuthErrorInvalidLinkDomain, - - /// Indicates that credential related request data is invalid. This can occur - /// when there is a project number mismatch (sessionInfo, spatula header, - /// temporary proof), - /// an incorrect temporary proof phone number, or during game center sign in - /// when the user is - /// already signed into a different game center account. - kAuthErrorRejectedCredential, - - /// Indicates that the phone number provided in the MFA sign in flow to be - /// verified does not correspond to a phone second factor for the user. - kAuthErrorPhoneNumberNotFound, - - /// Indicates that a request was made to the backend with an invalid tenant - /// ID. - kAuthErrorInvalidTenantId, - - /// Indicates that a request was made to the backend without a valid client - /// identifier. - kAuthErrorMissingClientIdentifier, - - /// Indicates that a second factor challenge request was made without proof of - /// a successful first factor sign-in. - kAuthErrorMissingMultiFactorSession, - - /// Indicates that a second factor challenge request was made where a second - /// factor identifier was not provided. - kAuthErrorMissingMultiFactorInfo, - - /// Indicates that a second factor challenge request was made containing an - /// invalid proof of first factor sign-in. - kAuthErrorInvalidMultiFactorSession, - - /// Indicates that the user does not have a second factor matching the - /// provided identifier. - kAuthErrorMultiFactorInfoNotFound, - - /// Indicates that a request was made that is restricted to administrators - /// only. - kAuthErrorAdminRestrictedOperation, - - /// Indicates that the user's email must be verified to perform that request. - kAuthErrorUnverifiedEmail, - - /// Indicates that the user is trying to enroll a second factor that already - /// exists on their account. - kAuthErrorSecondFactorAlreadyEnrolled, - - /// Indicates that the user has reached the maximum number of allowed second - /// factors and is attempting to enroll another one. - kAuthErrorMaximumSecondFactorCountExceeded, - - /// Indicates that a user either attempted to enroll in 2FA with an - /// unsupported first factor or is enrolled and attempts a first factor sign - /// in that is not supported for 2FA users. - kAuthErrorUnsupportedFirstFactor, - - /// Indicates that a second factor users attempted to change their email with - /// updateEmail instead of verifyBeforeUpdateEmail. - kAuthErrorEmailChangeNeedsVerification, - -#ifdef INTERNAL_EXPERIMENTAL - /// Indicates that the provided event handler is null or invalid. - kAuthErrorInvalidEventHandler, - - /// Indicates that the federated provider is busy with a previous - /// authorization request. Try again when the previous authorization request - /// completes. - kAuthErrorFederatedProviderAreadyInUse, - - /// Indicates that one or more fields of the provided AuthenticatedUserData - /// are invalid. - kAuthErrorInvalidAuthenticatedUserData, - - /// Indicates that an error occurred during a Federated Auth UI Flow when the - /// user was prompted to enter their credentials. - kAuthErrorFederatedSignInUserInteractionFailure, - - /// Indicates that a request was made with a missing or invalid nonce. - /// This can happen if the hash of the provided raw nonce did not match the - /// hashed nonce in the OIDC ID token payload. - kAuthErrorMissingOrInvalidNonce, - - /// Indicates that the user did not authorize the application during Generic - /// IDP sign-in. - kAuthErrorUserCancelled, - - /// Indicates that a request was made to an unsupported backend endpoint in - /// passthrough mode. - kAuthErrorUnsupportedPassthroughOperation, - - /// Indicates that a token refresh was requested, but neither a refresh token - /// nor a custom token provider is available. - kAuthErrorTokenRefreshUnavailable, - -#endif // INTERNAL_EXEPERIMENTAL -}; - -/// @brief Contains information required to authenticate with a third party -/// provider. -struct FederatedProviderData { - /// @brief contains the id of the provider to be used during sign-in, link, or - /// reauthentication requests. - std::string provider_id; -}; - -/// @brief Contains information to identify an OAuth povider. -struct FederatedOAuthProviderData : FederatedProviderData { - /// Initailizes an empty provider data structure. - FederatedOAuthProviderData() {} - - /// Initializes the provider data structure with a provider id. - explicit FederatedOAuthProviderData(const std::string& provider) { - this->provider_id = provider; - } - -#ifndef SWIG - /// @brief Initializes the provider data structure with the specified provider - /// id, scopes and custom parameters. - FederatedOAuthProviderData( - const std::string& provider, std::vector scopes, - std::map custom_parameters) { - this->provider_id = provider; - this->scopes = scopes; - this->custom_parameters = custom_parameters; - } -#endif - - /// OAuth parmeters which specify which rights of access are being requested. - std::vector scopes; - - /// OAuth parameters which are provided to the federated provider service. - std::map custom_parameters; -}; - -} // namespace auth -} // namespace firebase - -#endif // FIREBASE_AUTH_SRC_INCLUDE_FIREBASE_AUTH_TYPES_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/auth/user.h b/packages/firebase_core/firebase_core/firebase_core/firebase/auth/user.h deleted file mode 100644 index ddd1ba890687..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/auth/user.h +++ /dev/null @@ -1,501 +0,0 @@ -/* - * Copyright 2016 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_AUTH_SRC_INCLUDE_FIREBASE_AUTH_USER_H_ -#define FIREBASE_AUTH_SRC_INCLUDE_FIREBASE_AUTH_USER_H_ - -#include -#include - -#include "firebase/auth/credential.h" -#include "firebase/auth/types.h" -#include "firebase/future.h" -#include "firebase/internal/common.h" -#include "firebase/variant.h" - -namespace firebase { -namespace auth { - -// Predeclarations. -class Auth; -struct AuthData; - -class FederatedAuthProvider; - -/// @brief Interface implemented by each identity provider. -class UserInfoInterface { - public: - virtual ~UserInfoInterface(); - - /// Gets the unique Firebase user ID for the user. - /// - /// @note The user's ID, unique to the Firebase project. - /// Do NOT use this value to authenticate with your backend server, if you - /// have one. - /// @if cpp_examples - /// Use User::GetToken() instead. - /// @endif - /// - /// @if swig_examples - /// Use User.Token instead. - /// @endif - /// @xmlonly - /// - /// Gets the unique Firebase user ID for the user. - /// - /// @note The user's ID, unique to the Firebase project. - /// Do NOT use this value to authenticate with your backend server, if you - /// have one. Use User.Token instead. - /// - /// @endxmlonly - /// - virtual std::string uid() const = 0; - - /// Gets email associated with the user, if any. - /// - /// @xmlonly - /// - /// Gets email associated with the user, if any. - /// - /// @endxmlonly - /// - virtual std::string email() const = 0; - - /// Gets the display name associated with the user, if any. - /// - /// @xmlonly - /// - /// Gets the display name associated with the user, if any. - /// - /// @endxmlonly - /// - virtual std::string display_name() const = 0; - - /// Gets the photo url associated with the user, if any. - /// - /// @xmlonly - /// - /// Gets the photo url associated with the user, if any. - /// - /// @endxmlonly - /// - virtual std::string photo_url() const = 0; - - /// Gets the provider ID for the user (For example, "Facebook"). - /// - /// @xmlonly - /// - /// Gets the provider ID for the user (For example, \"Facebook\"). - /// - /// @endxmlonly - /// - virtual std::string provider_id() const = 0; - - /// Gets the phone number for the user, in E.164 format. - virtual std::string phone_number() const = 0; -}; - -/// @brief Additional user data returned from an identity provider. -struct AdditionalUserInfo { - /// The provider identifier. - std::string provider_id; - - /// The name of the user. - std::string user_name; - - /// Additional identity-provider specific information. - /// Most likely a hierarchical key-value mapping, like a parsed JSON file. - /// Note we use map instead of unordered_map to support older compilers. - std::map profile; - - /// On a nonce-based credential link failure where the user has already linked - /// to the provider, the Firebase auth service may provide an updated - /// Credential. If is_valid returns true on this credential, then it may be - /// passed to a new firebase::auth::Auth::SignInWithCredential request to sign - /// the user in with the provider. - Credential updated_credential; -}; - -/// @brief Metadata corresponding to a Firebase user. -struct UserMetadata { - UserMetadata() : last_sign_in_timestamp(0), creation_timestamp(0) {} - - /// The last sign in UTC timestamp in milliseconds. - /// See https://en.wikipedia.org/wiki/Unix_time for details of UTC. - uint64_t last_sign_in_timestamp; - - /// The Firebase user creation UTC timestamp in milliseconds. - uint64_t creation_timestamp; -}; - -/// @brief Result of operations that can affect authentication state. -struct SignInResult { - SignInResult() : user(NULL) {} - - /// The currently signed-in @ref User, or NULL if there isn't any (i.e. the - /// user is signed out). - User* user; - - /// Identity-provider specific information for the user, if the provider is - /// one of Facebook, GitHub, Google, or Twitter. - AdditionalUserInfo info; - - /// Metadata associated with the Firebase user. - UserMetadata meta; -}; - -/// @brief Firebase user account object. -/// -/// This class allows you to manipulate the profile of a user, link to and -/// unlink from authentication providers, and refresh authentication tokens. -class User : public UserInfoInterface { - public: - /// Parameters to the UpdateUserProfile() function. - /// - /// For fields you don't want to update, pass NULL. - /// For fields you want to reset, pass "". - struct UserProfile { - /// Construct a UserProfile with no display name or photo URL. - UserProfile() : display_name(NULL), photo_url(NULL) {} - - /// User display name. - const char* display_name; - - /// User photo URI. - const char* photo_url; - }; - - ~User(); - - /// The Java Web Token (JWT) that can be used to identify the user to - /// the backend. - /// - /// If a current ID token is still believed to be valid (i.e. it has not yet - /// expired), that token will be returned immediately. - /// A developer may set the optional force_refresh flag to get a new ID token, - /// whether or not the existing token has expired. For example, a developer - /// may use this when they have discovered that the token is invalid for some - /// other reason. - Future GetToken(bool force_refresh); - -#if defined(INTERNAL_EXPERIMENTAL) || defined(SWIG) - /// A "thread safer" version of GetToken. - /// If called by two threads simultaneously, GetToken can return the same - /// pending Future twice. This creates problems if both threads try to set - /// the OnCompletion callback, unaware that there's another copy. - /// GetTokenThreadSafe returns a proxy to the Future if it's still pending, - /// allowing each proxy to have their own callback. - Future GetTokenThreadSafe(bool force_refresh); -#endif // defined(INTERNAL_EXPERIMENTAL) || defined(SWIG) - - /// Get results of the most recent call to @ref GetToken. - Future GetTokenLastResult() const; - - /// Gets the third party profile data associated with this user returned by - /// the authentication server, if any. - /// - /// @xmlonly - /// - /// Gets the third party profile data associated with this user returned by - /// the authentication server, if any. - /// - /// @endxmlonly - /// - const std::vector& provider_data() const; - - /// Sets the email address for the user. - /// - /// May fail if there is already an email/password-based account for the same - /// email address. - Future UpdateEmail(const char* email); - - /// Get results of the most recent call to @ref UpdateEmail. - Future UpdateEmailLastResult() const; - - /// Attempts to change the password for the current user. - /// - /// For an account linked to an Identity Provider (IDP) with no password, - /// this will result in the account becoming an email/password-based account - /// while maintaining the IDP link. May fail if the password is invalid, - /// if there is a conflicting email/password-based account, or if the token - /// has expired. - /// To retrieve fresh tokens, - /// @if cpp_examples - /// call @ref Reauthenticate. - /// @endif - /// - /// @if swig_examples - /// call @ref ReauthenticateAsync. - /// @endif - /// - Future UpdatePassword(const char* password); - - /// Get results of the most recent call to @ref UpdatePassword. - Future UpdatePasswordLastResult() const; - - /// Convenience function for @ref ReauthenticateAndRetrieveData that discards - /// the returned AdditionalUserInfo data. - Future Reauthenticate(const Credential& credential); - - /// Get results of the most recent call to @ref Reauthenticate. - Future ReauthenticateLastResult() const; - - /// Reauthenticate using a credential. - /// - /// @if cpp_examples - /// Some APIs (for example, @ref UpdatePassword, @ref Delete) require that - /// the token used to invoke them be from a recent login attempt. - /// This API takes an existing credential for the user and retrieves fresh - /// tokens, ensuring that the operation can proceed. Developers can call - /// this method prior to calling @ref UpdatePassword() to ensure success. - /// @endif - /// - /// @if swig_examples - /// Some APIs (for example, @ref UpdatePasswordAsync, @ref DeleteAsync) - /// require that the token used to invoke them be from a recent login attempt. - /// This API takes an existing credential for the user and retrieves fresh - /// tokens, ensuring that the operation can proceed. Developers can call - /// this method prior to calling @ref UpdatePasswordAsync() to ensure success. - /// @endif - /// - /// - /// Data from the Identity Provider used to sign-in is returned in the - /// AdditionalUserInfo inside the returned SignInResult. - /// - /// Returns an error if the existing credential is not for this user - /// or if sign-in with that credential failed. - /// @note: The current user may be signed out if this operation fails on - /// Android and desktop platforms. - Future ReauthenticateAndRetrieveData( - const Credential& credential); - - /// Get results of the most recent call to @ref ReauthenticateAndRetrieveData. - Future ReauthenticateAndRetrieveDataLastResult() const; - - /// @brief Re-authenticates the user with a federated auth provider. - /// - /// @param[in] provider Contains information on the auth provider to - /// authenticate with. - /// @return A Future with the result of the re-authentication - /// request. - /// @note: This operation is supported only on iOS, tvOS and Android - /// platforms. On other platforms this method will return a Future with a - /// preset error code: kAuthErrorUnimplemented. - Future ReauthenticateWithProvider( - FederatedAuthProvider* provider) const; - - /// Initiates email verification for the user. - Future SendEmailVerification(); - - /// Get results of the most recent call to @ref SendEmailVerification. - Future SendEmailVerificationLastResult() const; - - /// Updates a subset of user profile information. - Future UpdateUserProfile(const UserProfile& profile); - - /// Get results of the most recent call to @ref UpdateUserProfile. - Future UpdateUserProfileLastResult() const; - - /// Convenience function for @ref ReauthenticateAndRetrieveData that discards - /// the returned @ref AdditionalUserInfo in @ref SignInResult. - Future LinkWithCredential(const Credential& credential); - - /// Get results of the most recent call to @ref LinkWithCredential. - Future LinkWithCredentialLastResult() const; - - /// Links the user with the given 3rd party credentials. - /// - /// For example, a Facebook login access token, a Twitter token/token-secret - /// pair. - /// Status will be an error if the token is invalid, expired, or otherwise - /// not accepted by the server as well as if the given 3rd party - /// user id is already linked with another user account or if the current user - /// is already linked with another id from the same provider. - /// - /// Data from the Identity Provider used to sign-in is returned in the - /// @ref AdditionalUserInfo inside @ref SignInResult. - Future LinkAndRetrieveDataWithCredential( - const Credential& credential); - - /// Get results of the most recent call to - /// @ref LinkAndRetrieveDataWithCredential. - Future LinkAndRetrieveDataWithCredentialLastResult() const; - - /// Links this user with a federated auth provider. - /// - /// @param[in] provider Contains information on the auth provider to link - /// with. - /// @return A Future with the user data result of the link - /// request. - /// - /// @note: This operation is supported only on iOS, tvOS and Android - /// platforms. On other platforms this method will return a Future with a - /// preset error code: kAuthErrorUnimplemented. - Future LinkWithProvider(FederatedAuthProvider* provider) const; - - /// Unlinks the current user from the provider specified. - /// Status will be an error if the user is not linked to the given provider. - Future Unlink(const char* provider); - - /// Get results of the most recent call to @ref Unlink. - Future UnlinkLastResult() const; - - /// Updates the currently linked phone number on the user. - /// This is useful when a user wants to change their phone number. It is a - /// shortcut to calling Unlink(phone_credential.provider().c_str()) and then - /// LinkWithCredential(phone_credential). - /// `credential` must have been created with @ref PhoneAuthProvider. - Future UpdatePhoneNumberCredential(const Credential& credential); - - /// Get results of the most recent call to @ref UpdatePhoneNumberCredential. - Future UpdatePhoneNumberCredentialLastResult() const; - - /// Refreshes the data for this user. - /// - /// For example, the attached providers, email address, display name, etc. - Future Reload(); - - /// Get results of the most recent call to @ref Reload. - Future ReloadLastResult() const; - - /// Deletes the user account. - Future Delete(); - - /// Get results of the most recent call to @ref Delete. - Future DeleteLastResult() const; - - /// Gets the metadata for this user account. - UserMetadata metadata() const; - - /// Returns true if the email address associated with this user has been - /// verified. - /// - /// @xmlonly - /// - /// True if the email address associated with this user has been verified. - /// - /// @endxmlonly - /// - bool is_email_verified() const; - - /// Returns true if user signed in anonymously. - /// - /// @xmlonly - /// - /// True if user signed in anonymously. - /// - /// @endxmlonly - /// - bool is_anonymous() const; - - /// Gets the unique Firebase user ID for the user. - /// - /// @note The user's ID, unique to the Firebase project. - /// Do NOT use this value to authenticate with your backend server, if you - /// have one. - /// @if cpp_examples - /// Use User::GetToken() instead. - /// @endif - /// - /// @if swig_examples - /// Use User.Token instead. - /// @endif - /// @xmlonly - /// - /// Gets the unique Firebase user ID for the user. - /// - /// @note The user's ID, unique to the Firebase project. - /// Do NOT use this value to authenticate with your backend server, if you - /// have one. Use User.Token instead. - /// - /// @endxmlonly - /// - virtual std::string uid() const; - - /// Gets email associated with the user, if any. - /// - /// @xmlonly - /// - /// Gets email associated with the user, if any. - /// - /// @endxmlonly - /// - virtual std::string email() const; - - /// Gets the display name associated with the user, if any. - /// - /// @xmlonly - /// - /// Gets the display name associated with the user, if any. - /// - /// @endxmlonly - /// - virtual std::string display_name() const; - - /// Gets the photo url associated with the user, if any. - /// - /// @xmlonly - /// - /// Gets the photo url associated with the user, if any. - /// - /// @endxmlonly - /// - virtual std::string photo_url() const; - - /// Gets the provider ID for the user (For example, "Facebook"). - /// - /// @xmlonly - /// - /// Gets the provider ID for the user (For example, \"Facebook\"). - /// - /// @endxmlonly - /// - virtual std::string provider_id() const; - - /// Gets the phone number for the user, in E.164 format. - virtual std::string phone_number() const; - - private: - /// @cond FIREBASE_APP_INTERNAL - friend struct AuthData; - // Only exists in AuthData. Access via @ref Auth::CurrentUser(). - explicit User(AuthData* auth_data) : auth_data_(auth_data) {} - - // Disable copy constructor. - User(const User&) = delete; - // Disable copy operator. - User& operator=(const User&) = delete; - /// @endcond - -#if defined(INTERNAL_EXPERIMENTAL) - // Doxygen should not make docs for this function. - /// @cond FIREBASE_APP_INTERNAL - friend class IdTokenRefreshThread; - friend class IdTokenRefreshListener; - friend class Auth; - Future GetTokenInternal(const bool force_refresh, - const int future_identifier); - /// @endcond -#endif // defined(INTERNAL_EXPERIMENTAL) - - // Use the pimpl mechanism to hide data details in the cpp files. - AuthData* auth_data_; -}; - -} // namespace auth -} // namespace firebase - -#endif // FIREBASE_AUTH_SRC_INCLUDE_FIREBASE_AUTH_USER_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/database.h b/packages/firebase_core/firebase_core/firebase_core/firebase/database.h deleted file mode 100644 index d0dc904c107b..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/database.h +++ /dev/null @@ -1,199 +0,0 @@ -// Copyright 2016 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_H_ -#define FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_H_ - -#include "firebase/app.h" -#include "firebase/database/common.h" -#include "firebase/database/data_snapshot.h" -#include "firebase/database/database_reference.h" -#include "firebase/database/disconnection.h" -#include "firebase/database/listener.h" -#include "firebase/database/mutable_data.h" -#include "firebase/database/query.h" -#include "firebase/database/transaction.h" -#include "firebase/internal/common.h" -#include "firebase/log.h" - -namespace firebase { - -/// Namespace for the Firebase Realtime Database C++ SDK. -namespace database { - -namespace internal { -class DatabaseInternal; -} // namespace internal - -class DatabaseReference; - -#ifndef SWIG -/// @brief Entry point for the Firebase Realtime Database C++ SDK. -/// -/// To use the SDK, call firebase::database::Database::GetInstance() to obtain -/// an instance of Database, then use GetReference() to obtain references to -/// child paths within the database. From there you can set data via -/// Query::SetValue(), get data via Query::GetValue(), attach listeners, and -/// more. -#endif // SWIG -class Database { - public: - /// @brief Get an instance of Database corresponding to the given App. - /// - /// Firebase Realtime Database uses firebase::App to communicate with Firebase - /// Authentication to authenticate users to the Database server backend. - /// - /// If you call GetInstance() multiple times with the same App, you will get - /// the same instance of Database. - /// - /// @param[in] app Your instance of firebase::App. Firebase Realtime Database - /// will use this to communicate with Firebase Authentication. - /// @param[out] init_result_out Optional: If provided, write the init result - /// here. Will be set to kInitResultSuccess if initialization succeeded, or - /// kInitResultFailedMissingDependency on Android if Google Play services is - /// not available on the current device. - /// - /// @returns An instance of Database corresponding to the given App. - static Database* GetInstance(::firebase::App* app, - InitResult* init_result_out = nullptr); - - /// @brief Gets an instance of FirebaseDatabase for the specified URL. - /// - /// If you call GetInstance() multiple times with the same App and URL, you - /// will get the same instance of Database. - /// - /// @param[in] app Your instance of firebase::App. Firebase Realtime Database - /// will use this to communicate with Firebase Authentication. - /// @param[in] url The URL of your Firebase Realtime Database. This overrides - /// any url specified in the App options. - /// @param[out] init_result_out Optional: If provided, write the init result - /// here. Will be set to kInitResultSuccess if initialization succeeded, or - /// kInitResultFailedMissingDependency on Android if Google Play services is - /// not available on the current device. - /// - /// @returns An instance of Database corresponding to the given App and URL. - static Database* GetInstance(::firebase::App* app, const char* url, - InitResult* init_result_out = nullptr); - - /// @brief Destructor for the Database object. - /// - /// When deleted, this instance will be removed from the cache of Database - /// objects. If you call GetInstance() in the future with the same App, a new - /// Database instance will be created. - ~Database(); - - /// @brief Get the firebase::App that this Database was created with. - /// - /// @returns The firebase::App this Database was created with. - App* app() const; - - /// @brief Get the URL that this Database was created with. - /// - /// @returns The URL this Database was created with, or an empty string if - /// this Database was created with default parameters. This string will remain - /// valid in memory for the lifetime of this Database. - const char* url() const; - - /// @brief Get a DatabaseReference to the root of the database. - /// - /// @returns A DatabaseReference to the root of the database. - DatabaseReference GetReference() const; - /// @brief Get a DatabaseReference for the specified path. - /// - /// @returns A DatabaseReference to the specified path in the database. - /// If you specified an invalid path, the reference's - /// DatabaseReference::IsValid() will return false. - DatabaseReference GetReference(const char* path) const; - /// @brief Get a DatabaseReference for the provided URL, which must belong to - /// the database URL this instance is already connected to. - /// - /// @returns A DatabaseReference to the specified path in the database. - /// If you specified an invalid path, the reference's - /// DatabaseReference::IsValid() will return false. - DatabaseReference GetReferenceFromUrl(const char* url) const; - - /// @brief Shuts down the connection to the Firebase Realtime Database - /// backend until GoOnline() is called. - void GoOffline(); - - /// @brief Resumes the connection to the Firebase Realtime Database backend - /// after a previous GoOffline() call. - void GoOnline(); - - /// @brief Purge all pending writes to the Firebase Realtime Database server. - /// - /// The Firebase Realtime Database client automatically queues writes and - /// sends them to the server at the earliest opportunity, depending on network - /// connectivity. In some cases (e.g. offline usage) there may be a large - /// number of writes waiting to be sent. Calling this method will purge all - /// outstanding writes so they are abandoned. All writes will be purged, - /// including transactions and onDisconnect() writes. The writes will be - /// rolled back locally, perhaps triggering events for affected event - /// listeners, and the client will not (re-)send them to the Firebase backend. - void PurgeOutstandingWrites(); - - /// @brief Sets whether pending write data will persist between application - /// exits. - /// - /// The Firebase Database client will cache synchronized data and keep track - /// of all writes you've initiated while your application is running. It - /// seamlessly handles intermittent network connections and re-sends write - /// operations when the network connection is restored. However by default - /// your write operations and cached data are only stored in-memory and will - /// be lost when your app restarts. By setting this value to `true`, the data - /// will be persisted to on-device (disk) storage and will thus be available - /// again when the app is restarted (even when there is no network - /// connectivity at that time). - /// - /// @note SetPersistenceEnabled should be called before creating any instances - /// of DatabaseReference, and only needs to be called once per application. - /// - /// @param[in] enabled Set this to true to persist write data to on-device - /// (disk) storage, or false to discard pending writes when the app exists. - void set_persistence_enabled(bool enabled); - - /// Set the log verbosity of this Database instance. - /// - /// The log filtering is cumulative with Firebase App. That is, this library's - /// log messages will only be displayed if they are not filtered out by this - /// library's log level setting and by Firebase App's log level setting. - /// - /// @note On Android this can only be set before any operations have been - /// performed with the object. - /// - /// @param[in] log_level Log level, by default this is set to kLogLevelInfo. - void set_log_level(LogLevel log_level); - - /// Get the log verbosity of this Database instance. - /// - /// @return Get the currently configured logging verbosity. - LogLevel log_level() const; - - private: - friend Database* GetDatabaseInstance(::firebase::App* app, const char* url, - InitResult* init_result_out); - Database(::firebase::App* app, internal::DatabaseInternal* internal); - Database(const Database& src); - Database& operator=(const Database& src); - - // Delete the internal_ data. - void DeleteInternal(); - - internal::DatabaseInternal* internal_; -}; - -} // namespace database -} // namespace firebase - -#endif // FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/database/common.h b/packages/firebase_core/firebase_core/firebase_core/firebase/database/common.h deleted file mode 100644 index 298972784631..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/database/common.h +++ /dev/null @@ -1,83 +0,0 @@ -// Copyright 2016 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_COMMON_H_ -#define FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_COMMON_H_ - -#include "firebase/variant.h" - -namespace firebase { -namespace database { - -/// Error code returned by Firebase Realtime Database C++ functions. -enum Error { - /// The operation was a success, no error occurred. - kErrorNone = 0, - /// The operation had to be aborted due to a network disconnect. - kErrorDisconnected, - /// The supplied auth token has expired. - kErrorExpiredToken, - /// The specified authentication token is invalid. - kErrorInvalidToken, - /// The transaction had too many retries. - kErrorMaxRetries, - /// The operation could not be performed due to a network error. - kErrorNetworkError, - /// The server indicated that this operation failed. - kErrorOperationFailed, - /// The transaction was overridden by a subsequent set. - kErrorOverriddenBySet, - /// This client does not have permission to perform this operation. - kErrorPermissionDenied, - /// The service is unavailable. - kErrorUnavailable, - /// An unknown error occurred. - kErrorUnknownError, - /// The write was canceled locally. - kErrorWriteCanceled, - /// You specified an invalid Variant type for a field. For example, - /// a DatabaseReference's Priority and the keys of a Map must be of - /// scalar type (MutableString, StaticString, Int64, Double). - kErrorInvalidVariantType, - /// An operation that conflicts with this one is already in progress. For - /// example, calling SetValue and SetValueAndPriority on a DatabaseReference - /// is not allowed. - kErrorConflictingOperationInProgress, - /// The transaction was aborted, because the user's DoTransaction function - /// returned kTransactionResultAbort instead of kTransactionResultSuccess. - kErrorTransactionAbortedByUser, -}; - -/// @brief Get the human-readable error message corresponding to an error code. -/// -/// @param[in] error Error code to get the error message for. -/// -/// @returns Statically-allocated string describing the error. -extern const char* GetErrorMessage(Error error); - -/// @brief Get a server-populated value corresponding to the current -/// timestamp. -/// -/// When inserting values into the database, you can use the special value -/// firebase::database::ServerTimestamp() to have the server auto-populate the -/// current timestamp, which is represented as millieconds since the Unix epoch, -/// into the field. -/// -/// @returns A special value that tells the server to use the current timestamp. -const Variant& ServerTimestamp(); - -} // namespace database -} // namespace firebase - -#endif // FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_COMMON_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/database/data_snapshot.h b/packages/firebase_core/firebase_core/firebase_core/firebase/database/data_snapshot.h deleted file mode 100644 index cb83292a792b..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/database/data_snapshot.h +++ /dev/null @@ -1,205 +0,0 @@ -// Copyright 2016 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_DATA_SNAPSHOT_H_ -#define FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_DATA_SNAPSHOT_H_ - -#include - -#include - -#include "firebase/internal/common.h" -#include "firebase/variant.h" - -namespace firebase { -namespace database { -namespace internal { -class Callbacks; -class ChildEventRegistration; -class DataSnapshotInternal; -class DatabaseInternal; -class DatabaseInternalTestMatcherTest; -class DatabaseReferenceInternal; -class QueryInternal; -class Repo; -class ValueEventRegistration; -} // namespace internal - -class Database; -class DatabaseReference; - -#ifndef SWIG -/// A DataSnapshot instance contains data from a Firebase Database location. Any -/// time you read Database data, you receive the data as a DataSnapshot. These -/// are efficiently-generated and cannot be changed. To modify data, -/// use DatabaseReference::SetValue() or DatabaseReference::RunTransaction(). -#endif // SWIG -class DataSnapshot { - public: - /// @brief Default constructor. - /// - /// This DataSnapshot contains nothing and is considered invalid (i.e. - /// is_valid() == false). Use this to construct an empty DataSnapshot that you - /// will later populate with data from a database callback. - DataSnapshot() : internal_(nullptr) {} - -#ifdef INTERNAL_EXPERIMENTAL - explicit DataSnapshot(internal::DataSnapshotInternal* internal); -#endif - - /// @brief Copy constructor. DataSnapshots are immutable, so they can be - /// efficiently copied. - /// - /// @param[in] snapshot DataSnapshot to copy. - DataSnapshot(const DataSnapshot& snapshot); - - /// @brief Copy assignment operator. DataSnapshots are immutable, so they can - /// be efficiently copied. - /// - /// @param[in] snapshot DataSnapshot to copy. - /// - /// @returns Reference to the destination DataSnapshot. - DataSnapshot& operator=(const DataSnapshot& snapshot); - -#if defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) - /// @brief Move constructor. DataSnapshots are immutable, so they can be - /// efficiently moved. - /// - /// @param[in] snapshot DataSnapshot to move into this one. - DataSnapshot(DataSnapshot&& snapshot); - - /// @brief Move assignment operator. DataSnapshots are immutable, so they can - /// be efficiently moved. - /// - /// @param[in] snapshot DataSnapshot to move into this one. - /// - /// @returns Reference to this destination DataSnapshot. - DataSnapshot& operator=(DataSnapshot&& snapshot); -#endif // defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) - - /// Destructor. - ~DataSnapshot(); - - /// @brief Returns true if the data is non-empty. - bool exists() const; - - /// @brief Get a DataSnapshot for the location at the specified relative path. - /// - /// @param[in] path Path relative to this snapshot's location. - /// It only needs to be valid during this call. - /// - /// @returns A DataSnapshot corresponding to specified child location. - DataSnapshot Child(const char* path) const; - - /// @brief Get a DataSnapshot for the location at the specified relative path. - /// - /// @param[in] path Path relative to this snapshot's location. - /// - /// @returns A DataSnapshot corresponding to specified child location. - DataSnapshot Child(const std::string& path) const; - - /// @brief Get all the immediate children of this location. - /// - /// @returns The immediate children of this snapshot. - std::vector children() const; - - /// @brief Get the number of children of this location. - /// - /// @returns The number of immediate children of this snapshot. - size_t children_count() const; - - /// @brief Does this DataSnapshot have any children at all? - /// - /// @returns True if the snapshot has any children, false otherwise. - bool has_children() const; - - /// @brief Get the key name of the source location of this snapshot. - /// - /// @note The returned pointer is only guaranteed to be valid while the - /// DataSnapshot is still in memory. - /// - /// @returns Key name of the source location of this snapshot. - const char* key() const; - - /// @brief Get the key name of the source location of this snapshot. - /// - /// @returns Key name of the source location of this snapshot. - std::string key_string() const; - - /// @brief Get the value of the data contained in this snapshot. - /// - /// @returns The value of the data contained in this location. - Variant value() const; - - /// @brief Get the priority of the data contained in this snapshot. - /// - /// @returns The value of this location's Priority relative to its siblings. - Variant priority() const; - - /// @brief Obtain a DatabaseReference to the source location for this - /// snapshot. - /// - /// @returns A DatabaseReference corresponding to same location as - /// this snapshot. - DatabaseReference GetReference() const; - - /// @brief Does this DataSnapshot have data at a particular location? - /// - /// @param[in] path Path relative to this snapshot's location. - /// The pointer only needs to be valid during this call. - /// - /// @returns True if the snapshot has data at the specified location, false if - /// not. - bool HasChild(const char* path) const; - - /// @brief Does this DataSnapshot have data at a particular location? - /// - /// @param[in] path Path relative to this snapshot's location. - /// - /// @returns True if the snapshot has data at the specified location, false if - /// not. - bool HasChild(const std::string& path) const; - - /// @brief Returns true if this snapshot is valid, false if it is not - /// valid. An invalid snapshot could be returned by a transaction where an - /// error has occurred. - /// - /// @returns true if this snapshot is valid, false if this snapshot is - /// invalid. - bool is_valid() const; - - private: - /// @cond FIREBASE_APP_INTERNAL - friend class internal::Callbacks; - friend class internal::ChildEventRegistration; - friend class internal::DataSnapshotInternal; - friend class internal::DatabaseInternal; - friend class internal::DatabaseInternalTestMatcherTest; - friend class internal::DatabaseReferenceInternal; - friend class internal::QueryInternal; - friend class internal::Repo; - friend class internal::ValueEventRegistration; - /// @endcond - -#ifndef INTERNAL_EXPERIMENTAL - explicit DataSnapshot(internal::DataSnapshotInternal* internal); -#endif - - internal::DataSnapshotInternal* internal_; -}; - -} // namespace database -} // namespace firebase - -#endif // FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_DATA_SNAPSHOT_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/database/database_reference.h b/packages/firebase_core/firebase_core/firebase_core/firebase/database/database_reference.h deleted file mode 100644 index 3e746541a1d5..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/database/database_reference.h +++ /dev/null @@ -1,477 +0,0 @@ -// Copyright 2016 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_DATABASE_REFERENCE_H_ -#define FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_DATABASE_REFERENCE_H_ - -#include -#include - -#include "firebase/database/disconnection.h" -#include "firebase/database/query.h" -#include "firebase/database/transaction.h" -#include "firebase/future.h" -#include "firebase/internal/common.h" -#include "firebase/variant.h" - -namespace firebase { -namespace database { -namespace internal { -class DatabaseInternal; -class DatabaseReferenceInternal; -class Repo; -} // namespace internal - -class DataSnapshot; - -#ifndef SWIG -/// DatabaseReference represents a particular location in your Database and can -/// be used for reading or writing data to that Database location. -/// -/// This class is the starting point for all Database operations. After you've -/// initialized it with a URL, you can use it to read data, write data, and to -/// create new DatabaseReference instances. -#endif // SWIG -class DatabaseReference : public Query { - public: - /// @brief Default constructor. This creates an invalid DatabaseReference. - /// Attempting to perform any operations on this reference will fail unless a - /// valid DatabaseReference has been assigned to it. - DatabaseReference() : Query(), internal_(nullptr) {} - - /// @brief Required virtual destructor. - virtual ~DatabaseReference(); - - /// @brief Copy constructor. It's totally okay (and efficient) to copy - /// DatabaseReference instances, as they simply point to the same location in - /// the database. - /// - /// @param[in] reference DatabaseReference to copy from. - DatabaseReference(const DatabaseReference& reference); - - /// @brief Copy assignment operator. It's totally okay (and efficient) to copy - /// DatabaseReference instances, as they simply point to the same location in - /// the database. - /// - /// @param[in] reference DatabaseReference to copy from. - /// - /// @returns Reference to the destination DatabaseReference. - DatabaseReference& operator=(const DatabaseReference& reference); - -#if defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) - /// @brief Move constructor. Moving is an efficient operation for - /// DatabaseReference instances. - /// - /// @param[in] reference DatabaseReference to move data from. - DatabaseReference(DatabaseReference&& reference); - - /// @brief Move assignment operator. Moving is an efficient operation for - /// DatabaseReference instances. - /// - /// @param[in] reference DatabaseReference to move data from. - /// - /// @returns Reference to the destination DatabaseReference. - DatabaseReference& operator=(DatabaseReference&& reference); -#endif // defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) - - /// @brief Gets the database to which we refer. - /// - /// The pointer will remain valid indefinitely. - /// - /// @returns Firebase Database instance that this DatabaseReference refers to. - Database* database() const; - - /// @brief Gets the string key of this database location. - /// - /// The pointer is only valid while the DatabaseReference remains in memory. - /// - /// @returns String key of this database location, which will remain valid in - /// memory until the DatabaseReference itself goes away. - const char* key() const; - - /// @brief Gets the string key of this database location. - /// - /// @returns String key of this database location. - std::string key_string() const; - - /// @brief Returns true if this reference refers to the root of the database. - /// - /// @returns true if this reference refers to the root of the database, false - /// otherwise. - bool is_root() const; - - /// @brief Returns true if this reference is valid, false if it is not - /// valid. DatabaseReferences constructed with the default constructor - /// are considered invalid. An invalid reference could be returned by - /// Database::GetReference() or Database::GetReferenceFromUrl() if you specify - /// an incorrect location, or calling Query::GetReference() on an invalid - /// query. - /// - /// @returns true if this reference is valid, false if this reference is - /// invalid. - bool is_valid() const override; - - /// @brief Gets the parent of this location, or get this location again if - /// IsRoot(). - /// - /// @returns Parent of this location in the database, unless this location is - /// the root, in which case it returns this same location again. - DatabaseReference GetParent() const; - - /// @brief Gets the root of the database. - /// - /// @returns Root of the database. - DatabaseReference GetRoot() const; - - /// @brief Gets a reference to a location relative to this one. - /// - /// @param[in] path Path relative to this snapshot's location. - /// The pointer only needs to be valid during this call. - /// - /// @returns Child relative to this location. - DatabaseReference Child(const char* path) const; - - /// @brief Gets a reference to a location relative to this one. - /// - /// @param[in] path Path relative to this snapshot's location. - /// - /// @returns Child relative to this location. - DatabaseReference Child(const std::string& path) const; - - /// @brief Automatically generates a child location, create a reference to it, - /// and returns that reference to it. - /// - /// @returns A newly created child, with a unique key. - DatabaseReference PushChild() const; - - /// @brief Removes the value at this location from the database. - /// - /// This is an asynchronous operation which takes time to execute, and uses - /// firebase::Future to return its result. - /// - /// @returns A Future result, which will complete when the operation either - /// succeeds or fails. When the Future is completed, if its Error is - /// kErrorNone, the operation succeeded. - /// - /// @note Only one RemoveValue() should be running on a given database - /// location at the same time. If you need to run multiple operations at once, - /// use RunTransaction(). - Future RemoveValue(); - - /// @brief Gets the result of the most recent call to RemoveValue(); - /// - /// @returns Result of the most recent call to RemoveValue(). - Future RemoveValueLastResult(); - - /// @brief Run a user-supplied callback function (passing in a context), - /// possibly multiple times, to perform an atomic transaction on the database. - /// - /// @see firebase::database::DoTransactionWithContext for more information. - /// - /// @param[in] transaction_function The user-supplied function that will be - /// called, possibly multiple times, to perform the database transaction. - /// @param[in] context User-supplied context that will be passed to the - /// transaction function. - /// @param[in] trigger_local_events If true, events will be triggered for - /// intermediate state changes during the transaction. If false, only the - /// final state will cause events to be triggered. - /// - /// @returns A Future result, which will complete when the transaction either - /// succeeds or fails. When the Future is completed, if its Error is - /// kErrorNone, the operation succeeded and the transaction was committed, and - /// the new value of the data will be returned in the DataSnapshot result. If - /// the Error is kErrorTransactionAbortedByUser, the transaction was aborted - /// because the transaction function returned kTransactionResultAbort, and the - /// old value will be returned in DataSnapshot. Otherwise, if some other error - /// occurred, Error and ErrorMessage will be set and DataSnapshot will be - /// invalid. - /// - /// @note Only one RunTransaction() should be running on a given database - /// location at the same time. - Future RunTransaction( - DoTransactionWithContext transaction_function, void* context, - bool trigger_local_events = true); - -#if defined(FIREBASE_USE_STD_FUNCTION) || defined(DOXYGEN) - /// @brief Run a user-supplied callback, possibly multiple times, to perform - /// an atomic transaction on the database. - /// - /// @see firebase::database::DoTransactionFunction for more information. - /// - /// @param[in] transaction_function The user-supplied function or lambda that - /// will be called, possibly multiple times, to perform the database - /// transaction. - /// @param[in] trigger_local_events If true, events will be triggered for - /// intermediate state changes during the transaction. If false, only the - /// final state will cause events to be triggered. - /// - /// @returns A Future result, which will complete when the transaction either - /// succeeds or fails. When the Future is completed, if its Error is - /// kErrorNone, the operation succeeded and the transaction was committed, and - /// the new value of the data will be returned in the DataSnapshot result. If - /// the Error is kErrorTransactionAbortedByUser, the transaction was aborted - /// because the transaction function returned kTransactionResultAbort, and the - /// old value will be returned in DataSnapshot. Otherwise, if some other error - /// occurred, Error and ErrorMessage will be set and DataSnapshot will be - /// invalid. - /// - /// @note Only one RunTransaction() should be running on a given database - /// location at the same time. - /// - /// @note This version (that accepts an std::function) is not available when - /// using stlport on Android. If you don't wish to use std::function, use the - /// overloaded method that accepts a simple function pointer with a context. - Future RunTransaction( - DoTransactionFunction transaction_function, - bool trigger_local_events = true); -#endif // defined(FIREBASE_USE_STD_FUNCTION) || defined(DOXYGEN) - -#if !defined(FIREBASE_USE_STD_FUNCTION) || defined(DOXYGEN) - /// @brief Run a user-supplied callback function, possibly multiple times, to - /// perform an atomic transaction on the database. - /// - /// @see firebase::database::DoTransaction for more information. - /// - /// @param[in] transaction_function The user-supplied function that will be - /// called, possibly multiple times, to perform the database transaction. - /// @param[in] trigger_local_events If true, events will be triggered for - /// intermediate state changes during the transaction. If false, only the - /// final state will cause events to be triggered. - /// - /// @returns A Future result, which will complete when the transaction either - /// succeeds or fails. When the Future is completed, if its Error is - /// kErrorNone, the operation succeeded and the transaction was committed, and - /// the new value of the data will be returned in the DataSnapshot result. If - /// the Error is kErrorTransactionAbortedByUser, the transaction was aborted - /// because the transaction function returned kTransactionResultAbort, and the - /// old value will be returned in DataSnapshot. Otherwise, if some other error - /// occurred, Error and ErrorMessage will be set and DataSnapshot will be - /// invalid. - /// - /// @note Only one RunTransaction() should be running on a given database - /// location at the same time. - /// - /// @note This version (that accepts a simple function pointer) is only - /// available when using stlport and std::function is not available. - Future RunTransaction(DoTransaction transaction_function, - bool trigger_local_events = true); -#endif // !defined(FIREBASE_USE_STD_FUNCTION) || defined(DOXYGEN) - - /// @brief Get the result of the most recent call to RunTransaction(). - /// - /// @returns Results of the most recent call to RunTransaction(). - Future RunTransactionLastResult(); - - /// @brief Sets the priority of this field, which controls its sort - /// order relative to its siblings. - /// - /// In Firebase, children are sorted in the following order: - /// 1. First, children with no priority. - /// 2. Then, children with numerical priority, sorted numerically in - /// ascending order. - /// 3. Then, remaining children, sorted lexicographically in ascending order - /// of their text priority. - /// - /// Children with the same priority (including no priority) are sorted by - /// key: - /// A. First, children with keys that can be parsed as 32-bit integers, - /// sorted in ascending numerical order of their keys. - /// B. Then, remaining children, sorted in ascending lexicographical order - /// of their keys. - /// - /// This is an asynchronous operation which takes time to execute, and uses - /// firebase::Future to return its result. - /// - /// @param[in] priority Sort priority for this child relative to its siblings. - /// The Variant types accepted are Null, Int64, Double, and String. Other - /// types will return kErrorInvalidVariantType. - /// - /// @returns A Future result, which will complete when the operation either - /// succeeds or fails. When the Future is completed, if its Error is - /// kErrorNone, the operation succeeded. - /// - /// @note Only one SetPriority() should be running on a given database - /// location - /// at the same time. If you need to run multiple operations at once, use - /// RunTransaction(). - Future SetPriority(Variant priority); - - /// @brief Gets the result of the most recent call to SetPriority(). - /// - /// @returns Result of the most recent call to SetPriority(). - Future SetPriorityLastResult(); - - /// @brief Sets the data at this location to the given value. - /// - /// This is an asynchronous operation which takes time to execute, and uses - /// firebase::Future to return its result. - /// - /// @param[in] value The value to set this location to. The Variant's type - /// corresponds to the types accepted by the database JSON: - /// Null: Deletes this location from the database. - /// Int64: Inserts an integer value into this location. - /// Double: Inserts a floating point value into this location. - /// String: Inserts a string into this location. - /// (Accepts both Mutable and Static strings) - /// Vector: Inserts a JSON array into this location. The elements can be any - /// Variant type, including Vector and Map. - /// Map: Inserts a JSON associative array into this location. The keys must - /// be of type String (or Int64/Double which are converted to String). - /// The values can be any Variant type, including Vector and Map. - /// - /// @returns A Future result, which will complete when the operation either - /// succeeds or fails. When the Future is completed, if its Error is - /// kErrorNone, the operation succeeded. - /// - /// @note Only one SetValue() should be running on a given database location - /// at the same time. If you need to run multiple operations at once, use - /// RunTransaction(). - Future SetValue(Variant value); - - /// @brief Gets the result of the most recent call to SetValue(). - /// - /// @returns Result of the most recent call to SetValue(). - Future SetValueLastResult(); - - /// @brief Sets both the data and priority of this location. See SetValue() - /// and SetPriority() for context on the parameters. - /// - /// This is an asynchronous operation which takes time to execute, and uses - /// firebase::Future to return its result. - /// - /// @param[in] value The value to set this location to. See SetValue() for - /// information on the types accepted. - /// @param[in] priority The priority to set this location to. See - /// SetPriority() for information on the types accepted. - /// - /// @returns A Future result, which will complete when the operation either - /// succeeds or fails. When the Future is completed, if its Error is - /// kErrorNone, the operation succeeded. - /// - /// @note Only one SetValueAndPriority() should be running on a given database - /// location at the same time. SetValueAndPriority() can't be used on the same - /// location at the same time as either SetValue() or SetPriority(), and will - /// return kErrorConflictingOperationInProgress if you try. If you need to run - /// multiple operations at once, use RunTransaction(). - Future SetValueAndPriority(Variant value, Variant priority); - - /// @brief Get the result of the most recent call to SetValueAndPriority(). - /// - /// @returns Result of the most recent call to SetValueAndPriority(). - Future SetValueAndPriorityLastResult(); - - /// @brief Updates the specified child keys to the given values. - /// - /// @param[in] values A variant of type Map. The keys are the paths to update - /// and must be of type String (or Int64/Double which are converted to - /// String). The values can be any Variant type. A value of Variant type Null - /// will delete the child. - /// - /// @returns A Future result, which will complete when the operation either - /// succeeds or fails. When the Future is completed, if its Error is - /// kErrorNone, the operation succeeded. - /// - /// @note This method will return kErrorConflictingOperationInProgress if it - /// is run at the same time as SetValue(), SetValueAndPriority(), or - /// RemoveValue() in the same location. - Future UpdateChildren(Variant values); - - /// @brief Updates the specified child keys to the given values. - /// - /// This is an asynchronous operation which takes time to execute, and uses - /// firebase::Future to return its result. - /// - /// @param[in] values The paths to update, and their new child values. A value - /// of type Null will delete that particular child. - /// - /// @returns A Future result, which will complete when the operation either - /// succeeds or fails. When the Future is completed, if its Error is - /// kErrorNone, the operation succeeded. - inline Future UpdateChildren( - const std::map& values) { - return UpdateChildren(Variant(values)); - } - - /// @brief Gets the result of the most recent call to either version of - /// UpdateChildren(). - /// - /// @returns Result of the most recent call to UpdateChildren(). - Future UpdateChildrenLastResult(); - - /// @brief Get the absolute URL of this reference. - /// - /// @returns The absolute URL of the location this reference refers to. - std::string url() const; - - /// @brief Get the disconnect handler, which controls what actions the server - /// will perform to this location's data when this client disconnects. - /// - /// @returns Disconnection handler for this location. You can use this to - /// queue up operations on the server to be performed when the client - /// disconnects. - DisconnectionHandler* OnDisconnect(); - - /// @brief Manually disconnect Firebase Realtime Database from the server, and - /// disable automatic reconnection. This will affect all other instances of - /// DatabaseReference as well. - void GoOffline(); - - /// @brief Manually reestablish connection to the Firebase Realtime Database - /// server and enable automatic reconnection. This will affect all other - /// instances of DatabaseReference as well. - void GoOnline(); - - protected: - /// @cond FIREBASE_APP_INTERNAL - explicit DatabaseReference(internal::DatabaseReferenceInternal* internal); - /// @endcond - - private: - /// @cond FIREBASE_APP_INTERNAL - - // Remove the "Query" cleanup registration (which the base class constructor - // already registered) and replace it with a "DatabaseReference" registration. - // - // This is necessary so that if the instance needs to be cleaned up, the - // correct pointer type will be used to access it. - void SwitchCleanupRegistrationToDatabaseReference(); - - // Remove the "DatabaseReference" cleanup registration and replace it with a - // "Query" one. ~Query() will unregister that one. - void SwitchCleanupRegistrationBackToQuery(); - - friend class DataSnapshot; - friend class Query; - friend class internal::DatabaseInternal; - friend class internal::Repo; - friend bool operator==(const DatabaseReference& lhs, - const DatabaseReference& rhs); - /// @endcond - - internal::DatabaseReferenceInternal* internal_; -}; - -/// @brief Compares two DatabaseReference instances. -/// -/// @param[in] lhs A DatabaseReference. -/// @param[in] rhs A DatabaseReference to compare against. -/// -/// @returns True if the DatabaseReference instances have the same URL. False -/// otherwise. -bool operator==(const DatabaseReference& lhs, const DatabaseReference& rhs); - -} // namespace database -} // namespace firebase - -#endif // FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_DATABASE_REFERENCE_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/database/disconnection.h b/packages/firebase_core/firebase_core/firebase_core/firebase/database/disconnection.h deleted file mode 100644 index b21fa472e629..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/database/disconnection.h +++ /dev/null @@ -1,156 +0,0 @@ -// Copyright 2016 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_DISCONNECTION_H_ -#define FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_DISCONNECTION_H_ - -#include "firebase/future.h" -#include "firebase/internal/common.h" -#include "firebase/variant.h" - -namespace firebase { -namespace database { -namespace internal { -class DatabaseReferenceInternal; -class DisconnectionHandlerInternal; -} // namespace internal - -/// Allows you to register server-side actions to occur when the client -/// disconnects. Each method you call (with the exception of Cancel) will queue -/// up an action on the data that will be performed by the server in the event -/// the client disconnects. To reset this queue, call Cancel(). -/// -/// A DisconnectionHandler is associated with a specific location in the -/// database, as they are obtained by calling DatabaseReference::OnDisconnect(). -class DisconnectionHandler { - public: - ~DisconnectionHandler(); - - /// @brief Cancel any Disconnection operations that are queued up by this - /// handler. When the Future returns, if its Error is kErrorNone, the queue - /// has been cleared on the server. - /// - /// @returns A Future result, which will complete when the operation either - /// succeeds or fails. When the Future is completed, if its Error is - /// kErrorNone, the operation succeeded. - Future Cancel(); - /// @brief Get the result of the most recent call to Cancel(). - /// - /// @returns Result of the most recent call to Cancel(). - Future CancelLastResult(); - - /// @brief Remove the value at the current location when the client - /// disconnects. When the Future returns, if its Error is kErrorNone, the - /// RemoveValue operation has been successfully queued up on the server. - /// - /// @returns A Future result, which will complete when the operation either - /// succeeds or fails. When the Future is completed, if its Error is - /// kErrorNone, the operation succeeded. - Future RemoveValue(); - /// @brief Get the result of the most recent call to RemoveValue(). - /// - /// @returns Result of the most recent call to RemoveValue(). - Future RemoveValueLastResult(); - - /// @brief Set the value of the data at the current location when the client - /// disconnects. When the Future returns, if its Error is kErrorNone, the - /// SetValue operation has been successfully queued up on the server. - /// - /// @param[in] value The value to set this location to when the client - /// disconnects. For information on how the Variant types are used, - /// see firebase::database::DatabaseReference::SetValue(). - /// - /// @returns A Future result, which will complete when the operation either - /// succeeds or fails. When the Future is completed, if its Error is - /// kErrorNone, the operation succeeded. - Future SetValue(Variant value); - /// Get the result of the most recent call to SetValue(). - /// - /// @returns Result of the most recent call to SetValue(). - Future SetValueLastResult(); - - /// @brief Set the value and priority of the data at the current location when - /// the client disconnects. When the Future returns, if its Error is - /// kErrorNone, the SetValue operation has been successfully queued up on the - /// server. - /// - /// @param[in] value The value to set this location to when the client - /// disconnects. For information on how the Variant types are used, - /// see firebase::database::DatabaseReference::SetValue(). - /// @param[in] priority The priority to set this location to when the client - /// disconnects. The Variant types accepted are Null, Int64, Double, and - /// String. For information about how priority is used, see - /// firebase::database::DatabaseReference::SetPriority(). - /// - /// @returns A Future result, which will complete when the operation either - /// succeeds or fails. When the Future is completed, if its Error is - /// kErrorNone, the operation succeeded. - Future SetValueAndPriority(Variant value, Variant priority); - /// @brief Get the result of the most recent call to SetValueAndPriority(). - /// - /// @returns Result of the most recent call to SetValueAndPriority(). - Future SetValueAndPriorityLastResult(); - - /// @brief Updates the specified child keys to the given values when the - /// client disconnects. When the Future returns, if its Error is kErrorNone, - /// the UpdateChildren operation has been successfully queued up by the - /// server. - /// - /// @param[in] values A variant of type Map. The keys are the paths to update - /// and must be of type String (or Int64/Double which are converted to - /// String). The values can be any Variant type. A value of Variant type Null - /// will delete the child. - /// - /// @returns A Future result, which will complete when the operation either - /// succeeds or fails. When the Future is completed, if its Error is - /// kErrorNone, the operation succeeded. - Future UpdateChildren(Variant values); - /// @brief Updates the specified child keys to the given values when the - /// client disconnects. When the Future returns, if its Error is kErrorNone, - /// the UpdateChildren operation has been successfully queued up by the - /// server. - /// - /// @param[in] values The paths to update, and their new child values. A value - /// of type Null will delete that particular child. - /// - /// @returns A Future result, which will complete when the operation either - /// succeeds or fails. When the Future is completed, if its Error is - /// kErrorNone, the operation succeeded. - Future UpdateChildren(const std::map& values) { - return UpdateChildren(Variant(values)); - } - /// @brief Gets the result of the most recent call to either version of - /// UpdateChildren(). - /// - /// @returns Result of the most recent call to UpdateChildren(). - Future UpdateChildrenLastResult(); - - private: - /// @cond FIREBASE_APP_INTERNAL - friend class internal::DatabaseReferenceInternal; - friend class internal::DisconnectionHandlerInternal; - /// @endcond - - /// Call DatabaseReference::OnDisconnect() to get an instance of this class. - explicit DisconnectionHandler( - internal::DisconnectionHandlerInternal* internal); - - /// You can only get the DisconnectHandler for a given reference. - internal::DisconnectionHandlerInternal* internal_; -}; - -} // namespace database -} // namespace firebase - -#endif // FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_DISCONNECTION_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/database/listener.h b/packages/firebase_core/firebase_core/firebase_core/firebase/database/listener.h deleted file mode 100644 index fe13d9299003..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/database/listener.h +++ /dev/null @@ -1,112 +0,0 @@ -// Copyright 2016 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_LISTENER_H_ -#define FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_LISTENER_H_ - -#include "firebase/database/common.h" - -namespace firebase { -namespace database { - -class DataSnapshot; - -/// Value listener interface. Subclasses of this listener class can be -/// used to receive events about data changes at a location. Attach -/// the listener to a location using -/// DatabaseReference::AddValueListener() or -/// Query::AddValueListener(), and OnValueChanged() will be called -/// once immediately, and again when the value changes. -class ValueListener { - public: - virtual ~ValueListener(); - - /// This method will be called with a snapshot of the data at this - /// location each time that data changes. - /// - /// @param[in] snapshot The current data at the location. - virtual void OnValueChanged(const DataSnapshot& snapshot) = 0; - - /// @brief This method will be triggered in the event that this listener - /// either failed at the server, or is removed as a result of the security and - /// Firebase rules. - /// - /// @param[in] error A code corresponding to the error that occurred. - /// @param[in] error_message A description of the error that occurred. - virtual void OnCancelled(const Error& error, const char* error_message) = 0; -}; - -/// Child listener interface. Subclasses of this listener class can be -/// used to receive events about changes in the child locations of a -/// firebase::database::Query or -/// firebase::database::DatabaseReference. Attach the listener to a -/// location with Query::AddChildListener() or -/// DatabaseReference::AddChildListener() and the appropriate method -/// will be triggered when changes occur. -class ChildListener { - public: - virtual ~ChildListener(); - - /// @brief This method is triggered when a new child is added to the location - /// to which this listener was added. - /// - /// @param[in] snapshot An immutable snapshot of the data at the new data at - /// the child location. - /// @param[in] previous_sibling_key The key name of sibling location ordered - /// before the child. This will be nullptr for the first child node of a - /// location. - virtual void OnChildAdded(const DataSnapshot& snapshot, - const char* previous_sibling_key) = 0; - /// @brief This method is triggered when the data at a child location has - /// changed. - /// - /// @param[in] snapshot An immutable snapshot of the data at the new data at - /// the child location. - /// @param[in] previous_sibling_key The key name of sibling location ordered - /// before the child. This will be nullptr for the first child node of a - /// location. - virtual void OnChildChanged(const DataSnapshot& snapshot, - const char* previous_sibling_key) = 0; - /// @brief This method is triggered when a child location's priority changes. - /// See DatabaseReference::SetPriority() for more information on priorities - /// and - /// ordering data. - /// - /// @param[in] snapshot An immutable snapshot of the data at the new data at - /// the child location. - /// @param[in] previous_sibling_key The key name of sibling location ordered - /// before the child. This will be nullptr for the first child node of a - /// location. - virtual void OnChildMoved(const DataSnapshot& snapshot, - const char* previous_sibling_key) = 0; - /// @brief This method is triggered when a child is removed from the location - /// to which this listener was added. - /// - /// @param[in] snapshot An immutable snapshot of the data at the new data at - /// the child location. - virtual void OnChildRemoved(const DataSnapshot& snapshot) = 0; - - /// @brief This method will be triggered in the event that this listener - /// either failed at the server, or is removed as a result of the security and - /// Firebase rules. - /// - /// @param[in] error A code corresponding to the error that occurred. - /// @param[in] error_message A description of the error that occurred. - virtual void OnCancelled(const Error& error, const char* error_message) = 0; -}; - -} // namespace database -} // namespace firebase - -#endif // FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_LISTENER_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/database/mutable_data.h b/packages/firebase_core/firebase_core/firebase_core/firebase/database/mutable_data.h deleted file mode 100644 index cedfa159cca6..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/database/mutable_data.h +++ /dev/null @@ -1,165 +0,0 @@ -// Copyright 2016 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_MUTABLE_DATA_H_ -#define FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_MUTABLE_DATA_H_ - -#include "firebase/internal/common.h" -#include "firebase/variant.h" - -namespace firebase { -namespace database { -namespace internal { -class DatabaseInternal; -class DatabaseReferenceInternal; -class MutableDataInternal; -class Repo; -} // namespace internal - -#ifndef SWIG -/// Instances of this class encapsulate the data and priority at a location. It -/// is used in transactions, and it is intended to be inspected and then updated -/// to the desired data at that location. -#endif // SWIG -class MutableData { - public: -#if defined(FIREBASE_USE_MOVE_OPERATORS) - /// Move constructor - /// Move is more efficient than copy and delete. - MutableData(MutableData&& rhs); - - // MutableData may be moved. - MutableData& operator=(MutableData&& rhs); -#endif // defined(FIREBASE_USE_MOVE_OPERATORS) - - /// Destructor. - ~MutableData(); - - /// @brief Used to obtain a MutableData instance that encapsulates - /// the data and priority at the given relative path. - /// - /// Note that changes made to a child MutableData instance will be visible - /// to the parent and vice versa. - /// - /// @param[in] path Path relative to this snapshot's location. - /// The pointer only needs to be valid during this call. - /// - /// @returns MutableData for the Child relative to this location. The memory - /// will be freed when the Transaction is finished. - MutableData Child(const char* path); - - /// @brief Used to obtain a MutableData instance that encapsulates - /// the data and priority at the given relative path. - /// - /// @param[in] path Path relative to this snapshot's location. - /// - /// @returns MutableData for the Child relative to this location. The memory - /// will be freed when the Transaction is finished. - MutableData Child(const std::string& path); - - /// @brief Get all the immediate children of this location. - /// - /// @returns The immediate children of this location. - std::vector children(); - - /// @brief Get the number of children of this location. - /// - /// @returns The number of immediate children of this location. - size_t children_count(); - - /// @brief Get the key name of the source location of this data. - /// - /// @note The returned pointer is only guaranteed to be valid during the - /// transaction. - /// - /// @returns Key name of the source location of this data. - const char* key() const; - - /// @brief Get the key name of the source location of this data. - /// - /// @returns Key name of the source location of this data. - std::string key_string() const; - - /// @brief Get the value of the data contained at this location. - /// - /// @returns The value of the data contained at this location. - Variant value() const; - - /// @brief Get the priority of the data contained at this snapshot. - /// - /// @returns The value of this location's Priority relative to its siblings. - Variant priority(); - - /// @brief Does this MutableData have data at a particular location? - /// - /// @param[in] path Path relative to this data's location. - /// The pointer only needs to be valid during this call. - /// - /// @returns True if there is data at the specified location, false if not. - bool HasChild(const char* path) const; - - /// @brief Does this MutableData have data at a particular location? - /// - /// @param[in] path Path relative to this data's location. - /// @returns True if there is data at the specified location, false if not. - bool HasChild(const std::string& path) const; - - /// @brief Sets the data at this location to the given value. - /// - /// @param[in] value The value to set this location to. The Variant's type - /// corresponds to the types accepted by the database JSON: - /// Null: Deletes this location from the database. - /// Int64: Inserts an integer value into this location. - /// Double: Inserts a floating point value into this location. - /// String: Inserts a string into this location. - /// (Accepts both Mutable and Static strings) - /// Vector: Inserts a JSON array into this location. The elements can be any - /// Variant type, including Vector and Map. - /// Map: Inserts a JSON associative array into this location. The keys must - /// be of type String (or Int64/Double which are converted to String). - /// The values can be any Variant type, including Vector and Map. - void set_value(const Variant& value); - - /// @brief Sets the priority of this field, which controls its sort - /// order relative to its siblings. - /// - /// @see firebase::database::DatabaseReference::SetPriority() for information - /// on how Priority affects the ordering of a node's children. - /// - /// @param[in] priority Sort priority for this child relative to its siblings. - /// The Variant types accepted are Null, Int64, Double, and String. Other - /// types will return kErrorInvalidVariantType. - void set_priority(const Variant& priority); - - private: - /// @cond FIREBASE_APP_INTERNAL - friend class internal::DatabaseReferenceInternal; - friend class internal::DatabaseInternal; - friend class internal::MutableDataInternal; - friend class internal::Repo; - friend MutableData GetInvalidMutableData(); - /// @endcond - - explicit MutableData(internal::MutableDataInternal* internal); - - MutableData(const MutableData& rhs) = delete; - MutableData& operator=(const MutableData& rhs) = delete; - - internal::MutableDataInternal* internal_; -}; - -} // namespace database -} // namespace firebase - -#endif // FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_MUTABLE_DATA_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/database/query.h b/packages/firebase_core/firebase_core/firebase_core/firebase/database/query.h deleted file mode 100644 index c60707a7ee65..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/database/query.h +++ /dev/null @@ -1,358 +0,0 @@ -// Copyright 2016 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_QUERY_H_ -#define FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_QUERY_H_ - -#include - -#include "firebase/database/listener.h" -#include "firebase/future.h" -#include "firebase/internal/common.h" - -namespace firebase { -namespace database { -namespace internal { -class QueryInternal; -} // namespace internal - -class DatabaseReference; - -#ifndef SWIG -/// The Query class is used for reading data. Listeners can be attached, which -/// will be triggered when the data changes. -#endif // SWIG -class Query { - public: - /// Default constructor. This creates an invalid Query. Attempting to perform - /// any operations on this reference will fail unless a valid Query has been - /// assigned to it. - Query() : internal_(nullptr) {} - - /// Copy constructor. Queries can be copied. Copies exist independently of - /// each other. - Query(const Query& query); - - /// Copy assignment operator. Queries can be copied. Copies exist - /// independently of each other. - Query& operator=(const Query& query); - -#if defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) - /// Move constructor. - Query(Query&& query); - /// Move assignment operator. - Query& operator=(Query&& query); -#endif // defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) - - /// @brief Required virtual destructor. - virtual ~Query(); - - /// @brief Gets the value of the query for the given location a single time. - /// - /// This is an asynchronous operation which takes time to execute, and uses - /// firebase::Future to return its result. - /// - /// @returns A Future result, which will complete when the operation either - /// succeeds or fails. On this Future's completion, if its Error is - /// kErrorNone, the operation succeeded, and the DataSnapshot contains the - /// data in this location. - Future GetValue(); - /// @brief Gets the result of the most recent call to GetValue(). - /// - /// @returns Result of the most recent call to GetValue(). - Future GetValueLastResult(); - - /// @brief Adds a listener that will be called immediately and then again any - /// time the data changes. - /// - /// @param[in] listener A ValueListener instance, which must remain in memory - /// until you remove the listener from the Query. - void AddValueListener(ValueListener* listener); - - /// @brief Removes a listener that was previously added with - /// AddValueListener(). - /// - /// @param[in] listener A ValueListener instance to remove from the - /// Query. After it is removed, you can delete it or attach it to a new - /// location. - /// - /// @note You can remove a ValueListener from a different Query than you added - /// it to, as long as the two Query instances are equivalent. - void RemoveValueListener(ValueListener* listener); - - /// @brief Removes all value listeners that were added with - /// AddValueListener(). - /// - /// @note You can remove ValueListeners from a different Query than you added - /// them to, as long as the two Query instances are equivalent. - void RemoveAllValueListeners(); - - /// @brief Adds a listener that will be called any time a child is added, - /// removed, modified, or reordered. - /// - /// @param[in] listener A ChildListener instance, which must remain in memory - /// until you remove the listener from the Query. - void AddChildListener(ChildListener* listener); - - /// @brief Removes a listener that was previously added with - /// AddChildListener(). - /// - /// @param[in] listener A ChildListener instance to remove from the - /// Query. After it is removed, you can delete it or attach it to a new - /// location. - /// - /// @note You can remove a ChildListener from a different Query than you added - /// it to, as long as the two Query instances are equivalent. - void RemoveChildListener(ChildListener* listener); - - /// @brief Removes all child listeners that were added by AddChildListener(). - /// - /// @note You can remove ChildListeners from a different Query than you added - /// them to, as long as the two Query instances are equivalent. - void RemoveAllChildListeners(); - - /// @brief Gets a DatabaseReference corresponding to the given location. - /// - /// @returns A DatabaseReference corresponding to the same location as the - /// Query, but without any of the ordering or filtering parameters. - DatabaseReference GetReference() const; - - /// @brief Sets whether this location's data should be kept in sync even if - /// there are no active Listeners. - /// - /// By calling SetKeepSynchronized(true) on a given database location, the - /// data for that location will automatically be downloaded and kept in sync, - /// even when no listeners are attached for that location. Additionally, while - /// a location is kept synced, it will not be evicted from the persistent disk - /// cache. - /// - /// @param[in] keep_sync If true, set this location to be synchronized. If - /// false, set it to not be synchronized. - void SetKeepSynchronized(bool keep_sync); - - // The OrderBy* functions are used for two purposes: - // 1. Order the data when getting the list of children. - // 2. When filtering the data using the StartAt* and EndAt* functions further - // below, use the specified ordering. - - /// @brief Gets a query in which child nodes are ordered by the values of the - /// specified path. Any previous OrderBy directive will be replaced in the - /// returned Query. - /// - /// @param[in] path Path to a child node. The value of this node will be used - /// for sorting this query. The pointer you pass in need not remain valid - /// after the call completes. - /// - /// @returns A Query in this same location, with the children are sorted by - /// the value of their own child specified here. - Query OrderByChild(const char* path); - /// @brief Gets a query in which child nodes are ordered by the values of the - /// specified path. Any previous OrderBy directive will be replaced in the - /// returned Query. - /// - /// @param[in] path Path to a child node. The value of this node will be used - /// for sorting this query. - /// - /// @returns A Query in this same location, with the children are sorted by - /// the value of their own child specified here. - Query OrderByChild(const std::string& path); - /// @brief Gets a query in which child nodes are ordered by their keys. Any - /// previous OrderBy directive will be replaced in the returned Query. - /// - /// @returns A Query in this same location, with the children are sorted by - /// their key. - Query OrderByKey(); - /// @brief Gets a query in which child nodes are ordered by their priority. - /// Any previous OrderBy directive will be replaced in the returned Query. - /// - /// @returns A Query in this same location, with the children are sorted by - /// their priority. - Query OrderByPriority(); - /// @brief Create a query in which nodes are ordered by their value. - /// - /// @returns A Query in this same location, with the children are sorted by - /// their value. - Query OrderByValue(); - - // The StartAt, EndAt, and EqualTo functions are used to limit which child - // nodes are returned when iterating through the current location. - - /// @brief Get a Query constrained to nodes with the given sort value or - /// higher. - /// - /// This method is used to generate a reference to a limited view of the data - /// at this location. The Query returned will only refer to child nodes with a - /// value greater than or equal to the given value, using the given OrderBy - /// directive (or priority as the default). - /// - /// @param[in] order_value The lowest sort value the Query should include. - /// - /// @returns A Query in this same location, filtering out child nodes that - /// have a lower sort value than the sort value specified. - Query StartAt(Variant order_value); - /// @brief Get a Query constrained to nodes with the given sort value or - /// higher, and the given key or higher. - /// - /// This method is used to generate a reference to a limited view of the data - /// at this location. The Query returned will only refer to child nodes with a - /// value greater than or equal to the given value, using the given OrderBy - /// directive (or priority as default), and additionally only child nodes with - /// a key greater than or equal to the given key. - /// - /// Known issue This currently does not work properly on all platforms. - /// Please use StartAt(Variant order_value) instead. - /// - /// @param[in] order_value The lowest sort value the Query should include. - /// @param[in] child_key The lowest key the Query should include. - /// - /// @returns A Query in this same location, filtering out child nodes that - /// have a lower sort value than the sort value specified, or a lower key than - /// the key specified. - Query StartAt(Variant order_value, const char* child_key); - - /// @brief Get a Query constrained to nodes with the given sort value or - /// lower. - /// - /// This method is used to generate a reference to a limited view of the data - /// at this location. The Query returned will only refer to child nodes with a - /// value less than or equal to the given value, using the given OrderBy - /// directive (or priority as default). - /// - /// @param[in] order_value The highest sort value the Query should refer - /// to. - /// - /// @returns A Query in this same location, filtering out child nodes that - /// have a higher sort value or key than the sort value or key specified. - Query EndAt(Variant order_value); - /// @brief Get a Query constrained to nodes with the given sort value or - /// lower, and the given key or lower. - /// - /// This method is used to generate a reference to a limited view of - /// the data at this location. The Query returned will only refer to child - /// nodes with a value less than or equal to the given value, using the given - /// OrderBy directive (or priority as default), and additionally only child - /// nodes with a key less than or equal to the given key. - /// - /// Known issue This currently does not work properly on all platforms. - /// Please use EndAt(Variant order_value) instead. - /// - /// @param[in] order_value The highest sort value the Query should include. - /// @param[in] child_key The highest key the Query should include. - /// - /// @returns A Query in this same location, filtering out child nodes that - /// have a higher sort value than the sort value specified, or a higher key - /// than the key specified. - Query EndAt(Variant order_value, const char* child_key); - - /// @brief Get a Query constrained to nodes with the exact given sort value. - /// - /// This method is used to create a query constrained to only return child - /// nodes with the given value, using the given OrderBy directive (or priority - /// as default). - /// - /// @param[in] order_value The exact sort value the Query should include. - /// - /// @returns A Query in this same location, filtering out child nodes that - /// have a different sort value than the sort value specified. - Query EqualTo(Variant order_value); - - /// @brief Get a Query constrained to nodes with the exact given sort value, - /// and the exact given key. - /// - /// This method is used to create a query constrained to only return the child - /// node with the given value, using the given OrderBy directive (or priority - /// as default), and the given key. Note that there is at most one such child - /// as child key names are unique. - /// - /// Known issue This currently does not work properly on iOS, tvOS and - /// desktop. Please use EqualTo(Variant order_value) instead. - /// - /// @param[in] order_value The exact sort value the Query should include. - /// @param[in] child_key The exact key the Query should include. - /// - /// @returns A Query in this same location, filtering out child nodes that - /// have a different sort value than the sort value specified, and containing - /// at most one child with the exact key specified. - Query EqualTo(Variant order_value, const char* child_key); - - // The LimitTo* functions are used to limit how many child nodes are returned - // when iterating through the current location. - - /// @brief Gets a Query limited to only the first results. - /// - /// Limits the query to reference only the first N child nodes, using the - /// given OrderBy directive (or priority as default). - /// - /// @param[in] limit Number of children to limit the Query to. - /// - /// @returns A Query in this same location, limited to the specified number of - /// children (taken from the beginning of the sorted list). - Query LimitToFirst(size_t limit); - /// @brief Gets a Query limited to only the last results. - /// - /// @param[in] limit Number of children to limit the Query to. - /// - /// @returns A Query in this same location, limited to the specified number of - /// children (taken from the end of the sorted list). - Query LimitToLast(size_t limit); - - /// @brief Returns true if this query is valid, false if it is not valid. An - /// invalid query could be returned by, say, attempting to OrderBy two - /// different items, or calling OrderByChild() with an empty path, or by - /// constructing a Query with the default constructor. If a Query - /// is invalid, attempting to add more constraints will also result in an - /// invalid Query. - /// - /// @returns true if this query is valid, false if this query is - /// invalid. - virtual bool is_valid() const; - - protected: - /// @cond FIREBASE_APP_INTERNAL - explicit Query(internal::QueryInternal* internal); - void SetInternal(internal::QueryInternal* internal); - void RegisterCleanup(); - void UnregisterCleanup(); - /// @endcond - - private: - /// @cond FIREBASE_APP_INTERNAL - friend bool operator==(const Query& lhs, const Query& rhs); - /// @endcond - - internal::QueryInternal* internal_; -}; - -/// @brief Compares two Query instances. -/// -/// Two Query instances on the same database, in the same location, with the -/// same parameters (OrderBy*, StartAt, EndAt, EqualTo, Limit*) are considered -/// equivalent. -/// -/// Equivalent Queries have a shared pool of ValueListeners and -/// ChildListeners. When listeners are added or removed from one Query -/// instance, it affects all equivalent Query instances. -/// -/// @param[in] lhs The Query to compare against. -/// @param[in] rhs The Query to compare against. -/// -/// @returns True if the Query instances have the same database, the same -/// path, and the same parameters, determined by StartAt(), EndAt(), -/// EqualTo(), and the OrderBy and LimitTo methods. False otherwise. -bool operator==(const Query& lhs, const Query& rhs); - -} // namespace database -} // namespace firebase - -#endif // FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_QUERY_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/database/transaction.h b/packages/firebase_core/firebase_core/firebase_core/firebase/database/transaction.h deleted file mode 100644 index cb2dd33c59e2..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/database/transaction.h +++ /dev/null @@ -1,102 +0,0 @@ -// Copyright 2016 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_TRANSACTION_H_ -#define FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_TRANSACTION_H_ - -#include "firebase/database/common.h" -#include "firebase/database/data_snapshot.h" -#include "firebase/database/mutable_data.h" -#include "firebase/internal/common.h" -#include "firebase/variant.h" - -#if defined(FIREBASE_USE_STD_FUNCTION) -#include -#endif // defined(FIREBASE_USE_STD_FUNCTION) - -namespace firebase { -namespace database { - -/// Specifies whether the transaction succeeded or not. -enum TransactionResult { - /// The transaction was successful, the MutableData was updated. - kTransactionResultSuccess, - /// The transaction did not succeed. Any changes to the MutableData - /// will be discarded. - kTransactionResultAbort, -}; - -/// Your own transaction handler, which the Firebase Realtime Database library -/// may call multiple times to apply changes to the data, and should return -/// success or failure depending on whether it succeeds. - -/// @note This version of the callback is no longer supported (unless you are -/// building for Android with stlport). You should use either one of -/// DoTransactionWithContext (a simple function pointer that accepts context -/// data) or DoTransactionFunction (based on std::function). -/// -/// @see DoTransactionWithContext for more information. -typedef TransactionResult (*DoTransaction)(MutableData* data); - -/// Your own transaction handler, which the Firebase Realtime Database library -/// may call multiple times to apply changes to the data, and should return -/// success or failure depending on whether it succeeds. The context you -/// specified to RunTransaction will be passed into this call. -/// -/// This function will be called, _possibly multiple times_, with the current -/// data at this location. The function is responsible for inspecting that data -/// and modifying it as desired, then returning a TransactionResult specifying -/// either that the MutableData was modified to a desired new state, or that the -/// transaction should be aborted. Whenever this function is called, the -/// MutableData passed in must be modified from scratch. -/// -/// Since this function may be called repeatedly for the same transaction, be -/// extremely careful of any side effects that may be triggered by this -/// function. In addition, this function is called from within the Firebase -/// Realtime Database library's run loop, so care is also required when -/// accessing data that may be in use by other threads in your application. -/// -/// Best practices for this function are to ONLY rely on the data passed in. -/// -/// @param[in] data Mutable data, which the callback can edit. -/// @param[in] context Context pointer, passed verbatim to the callback. -/// -/// @returns The callback should return kTransactionResultSuccess if the data -/// was modified, or kTransactionResultAbort if it was unable to modify the -/// data. If the callback returns kTransactionResultAbort, the RunTransaction() -/// call will return the kErrorTransactionAbortedByUser error code. -/// -/// @note If you want a callback to be triggered when the transaction is -/// finished, you can use the Future value returned by the method -/// running the transaction, and call Future::OnCompletion() to register a -/// callback to be called when the transaction either succeeds or fails. -/// -/// @see DoTransaction for more information. -typedef TransactionResult (*DoTransactionWithContext)(MutableData* data, - void* context); - -#if defined(FIREBASE_USE_STD_FUNCTION) || defined(DOXYGEN) -/// Your own transaction handler function or lambda, which the Firebase Realtime -/// Database library may call multiple times to apply changes to the data, and -/// should return success or failure depending on whether it succeeds. -/// -/// @see DoTransactionWithContext for more information. -typedef std::function - DoTransactionFunction; -#endif // defined(FIREBASE_USE_STD_FUNCTION) || defined(DOXYGEN) - -} // namespace database -} // namespace firebase - -#endif // FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_TRANSACTION_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/dynamic_links.h b/packages/firebase_core/firebase_core/firebase_core/firebase/dynamic_links.h deleted file mode 100644 index 7a96de679f62..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/dynamic_links.h +++ /dev/null @@ -1,117 +0,0 @@ -// Copyright 2017 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef FIREBASE_DYNAMIC_LINKS_SRC_INCLUDE_FIREBASE_DYNAMIC_LINKS_H_ -#define FIREBASE_DYNAMIC_LINKS_SRC_INCLUDE_FIREBASE_DYNAMIC_LINKS_H_ - -#include - -#include "firebase/app.h" -#include "firebase/internal/common.h" - -#if !defined(DOXYGEN) && !defined(SWIG) -FIREBASE_APP_REGISTER_CALLBACKS_REFERENCE(dynamic_links) -#endif // !defined(DOXYGEN) && !defined(SWIG) - -namespace firebase { - -/// @brief Firebase Dynamic Links API. -/// -/// Firebase Dynamic Links is a cross-platform solution for generating and -/// receiving links, whether or not the app is already installed. -namespace dynamic_links { - -#ifndef SWIG -/// @brief Error code used by Futures returned by this API. -enum ErrorCode { - kErrorCodeSuccess = 0, - kErrorCodeFailed, -}; -#endif // SWIG - -/// @brief Enum describing the strength of a dynamic links match. -/// -/// This version is local to dynamic links; there is a similar enum in invites -/// and another internal version in app. -enum LinkMatchStrength { - /// No match has been achieved - kLinkMatchStrengthNoMatch = 0, - - /// The match between the Dynamic Link and device is not perfect. You should - /// not reveal any personal information related to the Dynamic Link. - kLinkMatchStrengthWeakMatch, - - /// The match between the Dynamic Link and this device has a high confidence, - /// but there is a small possibility of error. - kLinkMatchStrengthStrongMatch, - - /// The match between the Dynamic Link and the device is exact. You may - /// safely reveal any personal information related to this Dynamic Link. - kLinkMatchStrengthPerfectMatch -}; - -/// @brief The received Dynamic Link. -struct DynamicLink { - /// The URL that was passed to the app. - std::string url; - /// The match strength of the dynamic link. - LinkMatchStrength match_strength; -}; - -/// @brief Base class used to receive Dynamic Links. -class Listener { - public: - virtual ~Listener(); - - /// Called on the client when a dynamic link arrives. - /// - /// @param[in] dynamic_link The data describing the Dynamic Link. - virtual void OnDynamicLinkReceived(const DynamicLink* dynamic_link) = 0; -}; - -/// @brief Initialize Firebase Dynamic Links. -/// -/// After Initialize is called, the implementation may call functions on the -/// Listener provided at any time. -/// -/// @param[in] app The Firebase App object for this application. -/// @param[in] listener A Listener object that receives Dynamic Links. -/// -/// @return kInitResultSuccess if initialization succeeded, or -/// kInitResultFailedMissingDependency on Android if Google Play services is -/// not available on the current device. -InitResult Initialize(const App& app, Listener* listener); - -/// @brief Terminate Firebase Dynamic Links. -void Terminate(); - -/// @brief Set the listener for receiving Dynamic Links. -/// -/// @param[in] listener A Listener object that receives Dynamic Links. -/// -/// @return Pointer to the previously set listener. -Listener* SetListener(Listener* listener); - -/// Fetch any pending dynamic links. Each pending link will trigger a call to -/// the registered Listener class. -/// -/// This function is implicitly called on initialization. On iOS this is called -/// automatically when the app gains focus, but on Android this needs to be -/// called manually. -void Fetch(); - -} // namespace dynamic_links -} // namespace firebase - -#endif // FIREBASE_DYNAMIC_LINKS_SRC_INCLUDE_FIREBASE_DYNAMIC_LINKS_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/dynamic_links/components.h b/packages/firebase_core/firebase_core/firebase_core/firebase/dynamic_links/components.h deleted file mode 100644 index 7a8e8fa1a44b..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/dynamic_links/components.h +++ /dev/null @@ -1,336 +0,0 @@ -// Copyright 2017 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef FIREBASE_DYNAMIC_LINKS_SRC_INCLUDE_FIREBASE_DYNAMIC_LINKS_COMPONENTS_H_ -#define FIREBASE_DYNAMIC_LINKS_SRC_INCLUDE_FIREBASE_DYNAMIC_LINKS_COMPONENTS_H_ - -#include -#include -#include - -#include "firebase/future.h" - -namespace firebase { - -namespace dynamic_links { - -/// @brief Google Analytics Parameters. -/// -/// Note that the strings used by the struct are not copied, as so must -/// either be statically allocated, or must persist in memory until the -/// DynamicLinkComponents that uses them goes out of scope. -struct GoogleAnalyticsParameters { - /// Constructs an empty set of Google Analytics parameters. - GoogleAnalyticsParameters() - : source(nullptr), - medium(nullptr), - campaign(nullptr), - term(nullptr), - content(nullptr) {} - - /// The campaign source; used to identify a search engine, newsletter, - /// or other source. - const char* source; - /// The campaign medium; used to identify a medium such as email or - /// cost-per-click (cpc). - const char* medium; - /// The campaign name; The individual campaign name, slogan, promo code, etc. - /// for a product. - const char* campaign; - /// The campaign term; used with paid search to supply the keywords for ads. - const char* term; - /// The campaign content; used for A/B testing and content-targeted ads to - /// differentiate ads or links that point to the same URL. - const char* content; -}; - -/// @brief iOS Parameters. -/// -/// Note that the strings used by the struct are not copied, as so must -/// either be statically allocated, or must persist in memory until the -/// DynamicLinkComponents that uses them goes out of scope. -struct IOSParameters { - /// Constructs a set of IOS parameters with the given bundle id. - /// - /// @param bundle_id_ The parameters ID of the iOS app to use to open the - /// link. - IOSParameters(const char* bundle_id_) - : bundle_id(bundle_id_), - fallback_url(nullptr), - custom_scheme(nullptr), - ipad_fallback_url(nullptr), - ipad_bundle_id(nullptr), - app_store_id(nullptr), - minimum_version(nullptr) {} - - /// Constructs an empty set of IOS parameters. - IOSParameters() - : bundle_id(nullptr), - fallback_url(nullptr), - custom_scheme(nullptr), - ipad_fallback_url(nullptr), - ipad_bundle_id(nullptr), - app_store_id(nullptr), - minimum_version(nullptr) {} - - /// The parameters ID of the iOS app to use to open the link. The app must be - /// connected to your project from the Overview page of the Firebase console. - /// Note this field is required. - const char* bundle_id; - /// The link to open on iOS if the app is not installed. - /// - /// Specify this to do something other than install your app from the - /// App Store when the app isn't installed, such as open the mobile - /// web version of the content, or display a promotional page for your app. - const char* fallback_url; - /// The app's custom URL scheme, if defined to be something other than your - /// app's parameters ID. - const char* custom_scheme; - /// The link to open on iPad if the app is not installed. - /// - /// Overrides fallback_url when on iPad. - const char* ipad_fallback_url; - /// The iPad parameters ID of the app. - const char* ipad_bundle_id; - /// The App Store ID, used to send users to the App Store when the app isn't - /// installed. - const char* app_store_id; - /// The minimum version of your app that can open the link. - const char* minimum_version; -}; - -/// @brief iTunes Connect App Analytics Parameters. -/// -/// Note that the strings used by the struct are not copied, as so must -/// either be statically allocated, or must persist in memory until the -/// DynamicLinkComponents that uses them goes out of scope. -struct ITunesConnectAnalyticsParameters { - /// Constructs an empty set of ITunes Connect Analytics parameters. - ITunesConnectAnalyticsParameters() - : provider_token(nullptr), - affiliate_token(nullptr), - campaign_token(nullptr) {} - - /// The provider token that enables analytics for Dynamic Links from - /// within iTunes Connect. - const char* provider_token; - /// The affiliate token used to create affiliate-coded links. - const char* affiliate_token; - /// The campaign token that developers can add to any link in order to - /// track sales from a specific marketing campaign. - const char* campaign_token; -}; - -/// @brief Android Parameters. -/// -/// Note that the strings used by the struct are not copied, as so must -/// either be statically allocated, or must persist in memory until the -/// DynamicLinkComponents that uses them goes out of scope. -struct AndroidParameters { - /// Constructs a set of Android parameters with the given package name. - /// - /// The package name of the Android app to use to open the link. - AndroidParameters(const char* package_name_) - : package_name(package_name_), - fallback_url(nullptr), - minimum_version(0) {} - - /// Constructs an empty set of Android parameters. - AndroidParameters() - : package_name(nullptr), fallback_url(nullptr), minimum_version(0) {} - - /// The package name of the Android app to use to open the link. The app - /// must be connected to your project from the Overview page of the Firebase - /// console. - /// Note this field is required. - const char* package_name; - /// The link to open when the app isn't installed. - /// - /// Specify this to do something other than install your app from the - /// Play Store when the app isn't installed, such as open the mobile web - /// version of the content, or display a promotional page for your app. - const char* fallback_url; - /// The versionCode of the minimum version of your app that can open the link. - int minimum_version; -}; - -/// @brief Social meta-tag Parameters. -/// -/// Note that the strings used by the struct are not copied, as so must -/// either be statically allocated, or must persist in memory until the -/// DynamicLinkComponents that uses them goes out of scope. -struct SocialMetaTagParameters { - /// Constructs an empty set of Social meta-tag parameters. - SocialMetaTagParameters() - : title(nullptr), description(nullptr), image_url(nullptr) {} - - /// The title to use when the Dynamic Link is shared in a social post. - const char* title; - /// The description to use when the Dynamic Link is shared in a social post. - const char* description; - /// The URL to an image related to this link. - const char* image_url; -}; - -/// @brief The desired path length for shortened Dynamic Link URLs. -enum PathLength { - /// Uses the server-default for the path length. - /// See https://goo.gl/8yDAqC for more information. - kPathLengthDefault = 0, - /// Typical short link for non-sensitive links. - kPathLengthShort, - /// Short link that uses a very long path to make it more difficult to - /// guess. Useful for sensitive links. - kPathLengthUnguessable, -}; - -/// @brief Additional options for Dynamic Link creation. -struct DynamicLinkOptions { - /// Constructs an empty set of Dynamic Link options. - DynamicLinkOptions() : path_length(kPathLengthDefault) {} - - /// The desired path length for shortened Dynamic Link URLs. - PathLength path_length; -}; - -/// @brief The returned value from creating a Dynamic Link. -struct GeneratedDynamicLink { - /// The Dynamic Link value. - std::string url; - /// Information about potential warnings on link creation. - /// - /// Usually presence of warnings means parameter format errors, parameter - /// value errors, or missing parameters. - std::vector warnings; - /// If non-empty, the cause of the Dynamic Link generation failure. - std::string error; -}; - -/// @brief The information needed to generate a Dynamic Link. -/// -/// Note that the strings used by the struct are not copied, as so must -/// either be statically allocated, or must persist in memory until this -/// struct goes out of scope. -struct DynamicLinkComponents { - /// The link your app will open. - /// You can specify any URL your app can handle, such as a link to your - /// app's content, or a URL that initiates some - /// app-specific logic such as crediting the user with a coupon, or - /// displaying a specific welcome screen. This link must be a well-formatted - /// URL, be properly URL-encoded, and use the HTTP or HTTPS scheme. - /// Note, this field is required. - const char* link; - /// The domain (of the form "https://xyz.app.goo.gl") to use for this Dynamic - /// Link. You can find this value in the Dynamic Links section of the Firebase - /// console. - /// - /// If you have set up custom domains on your project, set this to your - /// project's custom domain as listed in the Firebase console. - /// - /// Only https:// links are supported. - /// - /// Note, this field is required. - const char* domain_uri_prefix; - /// The Google Analytics parameters. - GoogleAnalyticsParameters* google_analytics_parameters; - /// The iOS parameters. - IOSParameters* ios_parameters; - /// The iTunes Connect App Analytics parameters. - ITunesConnectAnalyticsParameters* itunes_connect_analytics_parameters; - /// The Android parameters. - AndroidParameters* android_parameters; - /// The social meta-tag parameters. - SocialMetaTagParameters* social_meta_tag_parameters; - - /// Default constructor, initializes all fields to null. - DynamicLinkComponents() - : link(nullptr), - domain_uri_prefix(nullptr), - google_analytics_parameters(nullptr), - ios_parameters(nullptr), - itunes_connect_analytics_parameters(nullptr), - android_parameters(nullptr), - social_meta_tag_parameters(nullptr) {} - - /// Constructor that initializes with the given link and domain. - /// - /// @param link_ The link your app will open. - /// @param domain_uri_prefix_ The domain (of the form - /// "https://xyz.app.goo.gl") to use for this Dynamic Link. You can find this - /// value in the Dynamic Links section of the Firebase console. If you have - /// set up custom domains on your project, set this to your project's custom - /// domain as listed in the Firebase console. Note: If you do not specify - /// "https://" as the URI scheme, it will be added. - DynamicLinkComponents(const char* link_, const char* domain_uri_prefix_) - : link(link_), - domain_uri_prefix(domain_uri_prefix_), - google_analytics_parameters(nullptr), - ios_parameters(nullptr), - itunes_connect_analytics_parameters(nullptr), - android_parameters(nullptr), - social_meta_tag_parameters(nullptr) { - // For backwards compatibility with dynamic_link_domain, if - // domain_uri_prefix doesn't start with "https://", add it. - static const char kHttpsPrefix[] = "https://"; - static const size_t kHttpsPrefixLength = sizeof(kHttpsPrefix) - 1; - if (strncmp(domain_uri_prefix, kHttpsPrefix, kHttpsPrefixLength) != 0) { - domain_uri_prefix_with_scheme = - std::string(kHttpsPrefix) + domain_uri_prefix; - domain_uri_prefix = domain_uri_prefix_with_scheme.c_str(); - } - } - -#ifndef INTERNAL_EXPERIMENTAL - - private: -#endif // INTERNAL_EXPERIMENTAL - std::string domain_uri_prefix_with_scheme; -}; - -/// Creates a long Dynamic Link from the given parameters. -GeneratedDynamicLink GetLongLink(const DynamicLinkComponents& components); - -/// Creates a shortened Dynamic Link from the given parameters. -/// @param components: Settings used to configure the behavior for the link. -Future GetShortLink( - const DynamicLinkComponents& components); - -/// Creates a shortened Dynamic Link from the given parameters. -/// @param components: Settings used to configure the behavior for the link. -/// @param options: Additional options for Dynamic Link shortening, indicating -/// whether or not to produce an unguessable or shortest possible link. -/// No references to the options object will be retained after the call. -Future GetShortLink( - const DynamicLinkComponents& components, const DynamicLinkOptions& options); - -/// Creates a shortened Dynamic Link from a given long Dynamic Link. -/// @param long_dynamic_link A link previously generated from GetLongLink. -Future GetShortLink(const char* long_dynamic_link); - -/// Creates a shortened Dynamic Link from a given long Dynamic Link. -/// @param long_dynamic_link: A link previously generated from GetLongLink. -/// @param options: Additional options for Dynamic Link shortening, indicating -/// whether or not to produce an unguessable or shortest possible link. -/// No references to the options object will be retained after the call. -Future GetShortLink(const char* long_dynamic_link, - const DynamicLinkOptions& options); - -/// Get the (possibly still pending) results of the most recent GetShortUrl -/// call. -Future GetShortLinkLastResult(); - -} // namespace dynamic_links -} // namespace firebase - -#endif // FIREBASE_DYNAMIC_LINKS_SRC_INCLUDE_FIREBASE_DYNAMIC_LINKS_COMPONENTS_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore.h deleted file mode 100644 index c35de11b4d1a..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore.h +++ /dev/null @@ -1,458 +0,0 @@ -/* - * Copyright 2018 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_H_ -#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_H_ - -#include -#include - -#include "firebase/internal/common.h" - -#include "firebase/app.h" -#include "firebase/future.h" -#include "firebase/log.h" -// Include *all* the public headers to make sure including just "firestore.h" is -// sufficient for users. -#include "firebase/firestore/collection_reference.h" -#include "firebase/firestore/document_change.h" -#include "firebase/firestore/document_reference.h" -#include "firebase/firestore/document_snapshot.h" -#include "firebase/firestore/field_path.h" -#include "firebase/firestore/field_value.h" -#include "firebase/firestore/firestore_errors.h" -#include "firebase/firestore/geo_point.h" -#include "firebase/firestore/listener_registration.h" -#include "firebase/firestore/load_bundle_task_progress.h" -#include "firebase/firestore/map_field_value.h" -#include "firebase/firestore/metadata_changes.h" -#include "firebase/firestore/query.h" -#include "firebase/firestore/query_snapshot.h" -#include "firebase/firestore/set_options.h" -#include "firebase/firestore/settings.h" -#include "firebase/firestore/snapshot_metadata.h" -#include "firebase/firestore/source.h" -#include "firebase/firestore/timestamp.h" -#include "firebase/firestore/transaction.h" -#include "firebase/firestore/transaction_options.h" -#include "firebase/firestore/write_batch.h" - -namespace firebase { -/** - * @brief Cloud Firestore API. - * - * Cloud Firestore is a flexible, scalable database for mobile, web, and server - * development from Firebase and Google Cloud Platform. - */ -namespace firestore { - -class FirestoreInternal; - -namespace csharp { - -class ApiHeaders; -class TransactionManager; - -} // namespace csharp - -/** - * @brief Entry point for the Firebase Firestore C++ SDK. - * - * To use the SDK, call firebase::firestore::Firestore::GetInstance() to obtain - * an instance of Firestore, then use Collection() or Document() to obtain - * references to child paths within the database. From there, you can set data - * via CollectionReference::Add() and DocumentReference::Set(), or get data via - * CollectionReference::Get() and DocumentReference::Get(), attach listeners, - * and more. - * - * @note Firestore classes are not meant to be subclassed except for use in test - * mocks. Subclassing is not supported in production code and new SDK releases - * may break code that does so. - */ -class Firestore { - public: - /** - * @brief Returns an instance of Firestore corresponding to the given App. - * - * Firebase Firestore uses firebase::App to communicate with Firebase - * Authentication to authenticate users to the Firestore server backend. - * - * If you call GetInstance() multiple times with the same App, you will get - * the same instance of Firestore. - * - * @param[in] app Your instance of firebase::App. Firebase Firestore will use - * this to communicate with Firebase Authentication. - * @param[out] init_result_out If provided, the initialization result will be - * written here. Will be set to firebase::kInitResultSuccess if initialization - * succeeded, or firebase::kInitResultFailedMissingDependency on Android if - * Google Play services is not available on the current device. - * - * @return An instance of Firestore corresponding to the given App. - */ - static Firestore* GetInstance(::firebase::App* app, - InitResult* init_result_out = nullptr); - - /** - * @brief Returns an instance of Firestore corresponding to the default App. - * - * Firebase Firestore uses the default App to communicate with Firebase - * Authentication to authenticate users to the Firestore server backend. - * - * If you call GetInstance() multiple times, you will get the same instance. - * - * @param[out] init_result_out If provided, the initialization result will be - * written here. Will be set to firebase::kInitResultSuccess if initialization - * succeeded, or firebase::kInitResultFailedMissingDependency on Android if - * Google Play services is not available on the current device. - * - * @return An instance of Firestore corresponding to the default App. - */ - static Firestore* GetInstance(InitResult* init_result_out = nullptr); - - /** - * @brief Destructor for the Firestore object. - * - * When deleted, this instance will be removed from the cache of Firestore - * objects. If you call GetInstance() in the future with the same App, a new - * Firestore instance will be created. - */ - virtual ~Firestore(); - - /** - * Deleted copy constructor; Firestore must be created with - * Firestore::GetInstance(). - */ - Firestore(const Firestore& src) = delete; - - /** - * Deleted copy assignment operator; Firestore must be created with - * Firestore::GetInstance(). - */ - Firestore& operator=(const Firestore& src) = delete; - - /** - * @brief Returns the firebase::App that this Firestore was created with. - * - * @return The firebase::App this Firestore was created with. - */ - virtual const App* app() const; - - /** - * @brief Returns the firebase::App that this Firestore was created with. - * - * @return The firebase::App this Firestore was created with. - */ - virtual App* app(); - - /** - * @brief Returns a CollectionReference instance that refers to the - * collection at the specified path within the database. - * - * @param[in] collection_path A slash-separated path to a collection. - * - * @return The CollectionReference instance. - */ - virtual CollectionReference Collection(const char* collection_path) const; - - /** - * @brief Returns a CollectionReference instance that refers to the - * collection at the specified path within the database. - * - * @param[in] collection_path A slash-separated path to a collection. - * - * @return The CollectionReference instance. - */ - virtual CollectionReference Collection( - const std::string& collection_path) const; - - /** - * @brief Returns a DocumentReference instance that refers to the document at - * the specified path within the database. - * - * @param[in] document_path A slash-separated path to a document. - * @return The DocumentReference instance. - */ - virtual DocumentReference Document(const char* document_path) const; - - /** - * @brief Returns a DocumentReference instance that refers to the document at - * the specified path within the database. - * - * @param[in] document_path A slash-separated path to a document. - * - * @return The DocumentReference instance. - */ - virtual DocumentReference Document(const std::string& document_path) const; - - /** - * @brief Returns a Query instance that includes all documents in the - * database that are contained in a collection or subcollection with the - * given collection_id. - * - * @param[in] collection_id Identifies the collections to query over. Every - * collection or subcollection with this ID as the last segment of its path - * will be included. Cannot contain a slash. - * - * @return The Query instance. - */ - virtual Query CollectionGroup(const char* collection_id) const; - - /** - * @brief Returns a Query instance that includes all documents in the - * database that are contained in a collection or subcollection with the - * given collection_id. - * - * @param[in] collection_id Identifies the collections to query over. Every - * collection or subcollection with this ID as the last segment of its path - * will be included. Cannot contain a slash. - * - * @return The Query instance. - */ - virtual Query CollectionGroup(const std::string& collection_id) const; - - /** Returns the settings used by this Firestore object. */ - virtual Settings settings() const; - - /** Sets any custom settings used to configure this Firestore object. */ - virtual void set_settings(Settings settings); - - /** - * Creates a write batch, used for performing multiple writes as a single - * atomic operation. - * - * Unlike transactions, write batches are persisted offline and therefore are - * preferable when you don't need to condition your writes on read data. - * - * @return The created WriteBatch object. - */ - virtual WriteBatch batch() const; - - /** - * Executes the given update and then attempts to commit the changes applied - * within the transaction. If any document read within the transaction has - * changed, the update function will be retried. If it fails to commit after - * 5 attempts, the transaction will fail. - * - * @param update function or lambda to execute within the transaction context. - * The string reference parameter can be used to set the error message. - * - * @return A Future that will be resolved when the transaction finishes. - */ - virtual Future RunTransaction( - std::function update); - - /** - * Executes the given update and then attempts to commit the changes applied - * within the transaction. If any document read within the transaction has - * changed, the update function will be retried. If it fails to commit after - * the `max_attempts` specified in the given `TransactionOptions`, the - * transaction will fail. - * - * @param options The transaction options for controlling execution. - * @param update function or lambda to execute within the transaction context. - * The string reference parameter can be used to set the error message. - * - * @return A Future that will be resolved when the transaction finishes. - */ - virtual Future RunTransaction( - TransactionOptions options, - std::function update); - - /** - * Sets the log verbosity of all Firestore instances. - * - * The default verbosity level is `kLogLevelInfo`. - * - * @param[in] log_level The desired verbosity. - */ - static void set_log_level(LogLevel log_level); - - /** - * Disables network access for this instance. While the network is disabled, - * any snapshot listeners or Get() calls will return results from cache, and - * any write operations will be queued until network usage is re-enabled via a - * call to EnableNetwork(). - * - * If the network was already disabled, calling `DisableNetwork()` again is - * a no-op. - */ - virtual Future DisableNetwork(); - - /** - * Re-enables network usage for this instance after a prior call to - * DisableNetwork(). - * - * If the network is currently enabled, calling `EnableNetwork()` is a no-op. - */ - virtual Future EnableNetwork(); - - /** - * Terminates this `Firestore` instance. - * - * After calling `Terminate()`, only the `ClearPersistence()` method may be - * used. Calling any other methods will result in an error. - * - * To restart after termination, simply create a new instance of `Firestore` - * with `Firestore::GetInstance()`. - * - * `Terminate()` does not cancel any pending writes and any tasks that are - * awaiting a response from the server will not be resolved. The next time you - * start this instance, it will resume attempting to send these writes to the - * server. - * - * Note: under normal circumstances, calling `Terminate()` is not required. - * This method is useful only when you want to force this instance to release - * all of its resources or in combination with `ClearPersistence()` to ensure - * that all local state is destroyed between test runs. - * - * @return A `Future` that is resolved when the instance has been successfully - * terminated. - */ - virtual Future Terminate(); - - /** - * Waits until all currently pending writes for the active user have been - * acknowledged by the backend. - * - * The returned future is resolved immediately without error if there are no - * outstanding writes. Otherwise, the future is resolved when all previously - * issued writes (including those written in a previous app session) have been - * acknowledged by the backend. The future does not wait for writes that were - * added after the method is called. If you wish to wait for additional - * writes, you have to call `WaitForPendingWrites` again. - * - * Any outstanding `WaitForPendingWrites` futures are resolved with an - * error during user change. - */ - virtual Future WaitForPendingWrites(); - - /** - * Clears the persistent storage. This includes pending writes and cached - * documents. - * - * Must be called while the Firestore instance is not started (after the app - * is shut down or when the app is first initialized). On startup, this method - * must be called before other methods (other than `settings()` and - * `set_settings()`). If the Firestore instance is still running, the function - * will complete with an error code of `FailedPrecondition`. - * - * Note: `ClearPersistence()` is primarily intended to help write - * reliable tests that use Firestore. It uses the most efficient mechanism - * possible for dropping existing data but does not attempt to securely - * overwrite or otherwise make cached data unrecoverable. For applications - * that are sensitive to the disclosure of cache data in between user sessions - * we strongly recommend not to enable persistence in the first place. - */ - virtual Future ClearPersistence(); - - /** - * Attaches a listener for a snapshots-in-sync event. Server-generated - * updates and local changes can affect multiple snapshot listeners. - * The snapshots-in-sync event indicates that all listeners affected by - * a given change have fired. - * - * NOTE: The snapshots-in-sync event only indicates that listeners are - * in sync with each other, but does not relate to whether those - * snapshots are in sync with the server. Use `SnapshotMetadata` in the - * individual listeners to determine if a snapshot is from the cache or - * the server. - * - * @param callback A callback to be called every time all snapshot - * listeners are in sync with each other. - * @return A `ListenerRegistration` object that can be used to remove the - * listener. - */ - virtual ListenerRegistration AddSnapshotsInSyncListener( - std::function callback); - - /** - * Loads a Firestore bundle into the local cache. - * - * @param bundle A string containing the bundle to be loaded. - * @return A `Future` that is resolved when the loading is either completed - * or aborted due to an error. - */ - virtual Future LoadBundle(const std::string& bundle); - - /** - * Loads a Firestore bundle into the local cache, with the provided callback - * executed for progress updates. - * - * @param bundle A string containing the bundle to be loaded. - * @param progress_callback A callback that is called with progress - * updates, and completion or error updates. - * @return A `Future` that is resolved when the loading is either completed - * or aborted due to an error. - */ - virtual Future LoadBundle( - const std::string& bundle, - std::function progress_callback); - - /** - * Reads a Firestore `Query` from the local cache, identified by the given - * name. - * - * Named queries are packaged into bundles on the server side (along with the - * resulting documents) and loaded into local cache using `LoadBundle`. Once - * in the local cache, you can use this method to extract a query by name. - * - * If a query cannot be found, the returned future will complete with its - * `error()` set to a non-zero error code. - * - * @param query_name The name of the query to read from saved bundles. - */ - virtual Future NamedQuery(const std::string& query_name); - - protected: - /** - * Default constructor, to be used only for mocking `Firestore`. - */ - Firestore() = default; - - private: - friend class FieldValueInternal; - friend class FirestoreInternal; - friend class Wrapper; - friend struct ConverterImpl; - friend class FirestoreIntegrationTest; - friend class IncludesTest; - template - friend struct CleanupFn; - - friend class csharp::ApiHeaders; - friend class csharp::TransactionManager; - - explicit Firestore(::firebase::App* app); - explicit Firestore(FirestoreInternal* internal); - - static Firestore* CreateFirestore(::firebase::App* app, - FirestoreInternal* internal, - InitResult* init_result_out); - static Firestore* AddFirestoreToCache(Firestore* firestore, - InitResult* init_result_out); - - static void SetClientLanguage(const std::string& language_token); - - // Delete the internal_ data. - void DeleteInternal(); - - mutable FirestoreInternal* internal_ = nullptr; -}; - -} // namespace firestore -} // namespace firebase - -#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/collection_reference.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/collection_reference.h deleted file mode 100644 index 3d9d4de2ee7f..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/collection_reference.h +++ /dev/null @@ -1,183 +0,0 @@ -/* - * Copyright 2018 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_COLLECTION_REFERENCE_H_ -#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_COLLECTION_REFERENCE_H_ - -#include - -#include "firebase/firestore/map_field_value.h" -#include "firebase/firestore/query.h" - -namespace firebase { - -/// @cond FIREBASE_APP_INTERNAL -template -class Future; -/// @endcond - -namespace firestore { - -class CollectionReferenceInternal; -class DocumentReference; - -/** - * @brief A CollectionReference can be used for adding documents, getting - * document references, and querying for documents (using the methods inherited - * from `Query`). - * - * @note Firestore classes are not meant to be subclassed except for use in test - * mocks. Subclassing is not supported in production code and new SDK releases - * may break code that does so. - */ -class CollectionReference : public Query { - public: - /** - * @brief Creates an invalid CollectionReference that has to be reassigned - * before it can be used. - * - * Calling any member function on an invalid CollectionReference will be - * a no-op. If the function returns a value, it will return a zero, empty, or - * invalid value, depending on the type of the value. - */ - CollectionReference(); - - /** - * @brief Copy constructor. - * - * `CollectionReference` can be efficiently copied because it simply refers to - * a location in the database. - * - * @param[in] other `CollectionReference` to copy from. - */ - CollectionReference(const CollectionReference& other); - - /** - * @brief Move constructor. - * - * Moving is more efficient than copying for a `CollectionReference`. After - * being moved from, a `CollectionReference` is equivalent to its - * default-constructed state. - * - * @param[in] other `CollectionReference` to move data from. - */ - CollectionReference(CollectionReference&& other); - - /** - * @brief Copy assignment operator. - * - * `CollectionReference` can be efficiently copied because it simply refers to - * a location in the database. - * - * @param[in] other `CollectionReference` to copy from. - * - * @return Reference to the destination `CollectionReference`. - */ - CollectionReference& operator=(const CollectionReference& other); - - /** - * @brief Move assignment operator. - * - * Moving is more efficient than copying for a `CollectionReference`. After - * being moved from, a `CollectionReference` is equivalent to its - * default-constructed state. - * - * @param[in] other `CollectionReference` to move data from. - * - * @return Reference to the destination `CollectionReference`. - */ - CollectionReference& operator=(CollectionReference&& other); - - /** - * @brief Gets the ID of the referenced collection. - * - * @return The ID as a std::string. - */ - virtual const std::string& id() const; - - /** - * @brief Returns the path of this collection (relative to the root of the - * database) as a slash-separated string. - * - * @return The path as a std::string. - */ - virtual std::string path() const; - - /** - * @brief Gets a DocumentReference to the document that contains this - * collection. - * - * @return The DocumentReference that contains this collection if this is a - * subcollection. If this is a root collection, returns an invalid - * DocumentReference (`DocumentReference::is_valid()` will return false). - */ - virtual DocumentReference Parent() const; - - /** - * @brief Returns a DocumentReference that points to a new document with an - * auto-generated ID within this collection. - * - * @return A DocumentReference pointing to the new document. - */ - virtual DocumentReference Document() const; - - /** - * @brief Gets a DocumentReference instance that refers to the document at the - * specified path within this collection. - * - * @param[in] document_path A slash-separated relative path to a document. - * The pointer only needs to be valid during this call. - * - * @return The DocumentReference instance. - */ - virtual DocumentReference Document(const char* document_path) const; - - /** - * @brief Gets a DocumentReference instance that refers to the document at the - * specified path within this collection. - * - * @param[in] document_path A slash-separated relative path to a document. - * - * @return The DocumentReference instance. - */ - virtual DocumentReference Document(const std::string& document_path) const; - - /** - * @brief Adds a new document to this collection with the specified data, - * assigning it a document ID automatically. - * - * @param data A map containing the data for the new document. - * - * @return A Future that will be resolved with the DocumentReference of the - * newly created document. - */ - virtual Future Add(const MapFieldValue& data); - - private: - friend class DocumentReference; - friend class DocumentReferenceInternal; - friend class FirestoreInternal; - friend struct ConverterImpl; - - explicit CollectionReference(CollectionReferenceInternal* internal); - - CollectionReferenceInternal* internal() const; -}; - -} // namespace firestore -} // namespace firebase - -#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_COLLECTION_REFERENCE_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/document_change.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/document_change.h deleted file mode 100644 index fbef011d290f..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/document_change.h +++ /dev/null @@ -1,203 +0,0 @@ -/* - * Copyright 2018 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_DOCUMENT_CHANGE_H_ -#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_DOCUMENT_CHANGE_H_ - -#include - -namespace firebase { -namespace firestore { - -class DocumentChangeInternal; -class DocumentSnapshot; - -/** - * @brief A DocumentChange represents a change to the documents matching - * a query. - * - * DocumentChange contains the document affected and the type of change that - * occurred (added, modified, or removed). - * - * @note Firestore classes are not meant to be subclassed except for use in test - * mocks. Subclassing is not supported in production code and new SDK releases - * may break code that does so. - */ -class DocumentChange { - public: - /** - * An enumeration of snapshot diff types. - */ - enum class Type { - /** - * Indicates a new document was added to the set of documents matching the - * query. - */ - kAdded, - - /** - * Indicates a document within the query was modified. - */ - kModified, - - /** - * Indicates a document within the query was removed (either deleted or no - * longer matches the query). - */ - kRemoved, - }; - - /** - * The sentinel index used as a return value to indicate no matches. - */ -#if defined(ANDROID) - // Older NDK (r16b) fails to define this properly. Fix this when support for - // the older NDK is removed. - static const std::size_t npos; -#else - static constexpr std::size_t npos = static_cast(-1); -#endif // defined(ANDROID) - - /** - * @brief Creates an invalid DocumentChange that has to be reassigned before - * it can be used. - * - * Calling any member function on an invalid DocumentChange will be a no-op. - * If the function returns a value, it will return a zero, empty, or invalid - * value, depending on the type of the value. - */ - DocumentChange(); - - /** - * @brief Copy constructor. - * - * `DocumentChange` is immutable and can be efficiently copied (no deep copy - * is performed). - * - * @param[in] other `DocumentChange` to copy from. - */ - DocumentChange(const DocumentChange& other); - - /** - * @brief Move constructor. - * - * Moving is more efficient than copying for a `DocumentChange`. After being - * moved from, a `DocumentChange` is equivalent to its default-constructed - * state. - * - * @param[in] other `DocumentChange` to move data from. - */ - DocumentChange(DocumentChange&& other); - - virtual ~DocumentChange(); - - /** - * @brief Copy assignment operator. - * - * `DocumentChange` is immutable and can be efficiently copied (no deep copy - * is performed). - * - * @param[in] other `DocumentChange` to copy from. - * - * @return Reference to the destination `DocumentChange`. - */ - DocumentChange& operator=(const DocumentChange& other); - - /** - * @brief Move assignment operator. - * - * Moving is more efficient than copying for a `DocumentChange`. After being - * moved from, a `DocumentChange` is equivalent to its default-constructed - * state. - * - * @param[in] other `DocumentChange` to move data from. - * - * @return Reference to the destination `DocumentChange`. - */ - DocumentChange& operator=(DocumentChange&& other); - - /** - * Returns the type of change that occurred (added, modified, or removed). - */ - virtual Type type() const; - - /** - * @brief The document affected by this change. - * - * Returns the newly added or modified document if this DocumentChange is for - * an updated document. Returns the deleted document if this document change - * represents a removal. - */ - virtual DocumentSnapshot document() const; - - /** - * The index of the changed document in the result set immediately prior to - * this DocumentChange (that is, supposing that all prior DocumentChange - * objects have been applied). Returns DocumentChange::npos for 'added' - * events. - */ - virtual std::size_t old_index() const; - - /** - * The index of the changed document in the result set immediately after this - * DocumentChange (that is, supposing that all prior DocumentChange objects - * and the current DocumentChange object have been applied). Returns - * DocumentChange::npos for 'removed' events. - */ - virtual std::size_t new_index() const; - - /** - * @brief Returns true if this `DocumentChange` is valid, false if it is - * not valid. An invalid `DocumentChange` could be the result of: - * - Creating a `DocumentChange` using the default constructor. - * - Moving from the `DocumentChange`. - * - Deleting your Firestore instance, which will invalidate all the - * `DocumentChange` instances associated with it. - * - * @return true if this `DocumentChange` is valid, false if this - * `DocumentChange` is invalid. - */ - bool is_valid() const { return internal_ != nullptr; } - - private: - std::size_t Hash() const; - - friend bool operator==(const DocumentChange& lhs, const DocumentChange& rhs); - friend std::size_t DocumentChangeHash(const DocumentChange& change); - - friend class FirestoreInternal; - friend class Wrapper; - friend struct ConverterImpl; - template - friend struct CleanupFn; - - explicit DocumentChange(DocumentChangeInternal* internal); - - mutable DocumentChangeInternal* internal_ = nullptr; -}; - -/** Checks `lhs` and `rhs` for equality. */ -bool operator==(const DocumentChange& lhs, const DocumentChange& rhs); - -/** Checks `lhs` and `rhs` for inequality. */ -inline bool operator!=(const DocumentChange& lhs, const DocumentChange& rhs) { - return !(lhs == rhs); -} - -} // namespace firestore -} // namespace firebase - -#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_DOCUMENT_CHANGE_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/document_reference.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/document_reference.h deleted file mode 100644 index d0f82cf42d73..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/document_reference.h +++ /dev/null @@ -1,351 +0,0 @@ -/* - * Copyright 2018 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_DOCUMENT_REFERENCE_H_ -#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_DOCUMENT_REFERENCE_H_ - -#include -#include -#include - -#include "firebase/internal/common.h" - -#include "firebase/firestore/firestore_errors.h" -#include "firebase/firestore/map_field_value.h" -#include "firebase/firestore/metadata_changes.h" -#include "firebase/firestore/set_options.h" -#include "firebase/firestore/source.h" - -namespace firebase { - -/// @cond FIREBASE_APP_INTERNAL -template -class Future; -/// @endcond - -namespace firestore { - -class CollectionReference; -class DocumentReferenceInternal; -class DocumentSnapshot; -template -class EventListener; -class Firestore; -class ListenerRegistration; - -/** - * @brief A DocumentReference refers to a document location in a Firestore - * database and can be used to write, read, or listen to the location. - * - * There may or may not exist a document at the referenced location. - * A DocumentReference can also be used to create a CollectionReference to - * a subcollection. - * - * Create a DocumentReference via `Firestore::Document(const std::string& - * path)`. - * - * @note Firestore classes are not meant to be subclassed except for use in test - * mocks. Subclassing is not supported in production code and new SDK releases - * may break code that does so. - */ -class DocumentReference { - public: - /** - * @brief Creates an invalid DocumentReference that has to be reassigned - * before it can be used. - * - * Calling any member function on an invalid DocumentReference will be - * a no-op. If the function returns a value, it will return a zero, empty, or - * invalid value, depending on the type of the value. - */ - DocumentReference(); - - /** - * @brief Copy constructor. - * - * `DocumentReference` can be efficiently copied because it simply refers to - * a location in the database. - * - * @param[in] other `DocumentReference` to copy from. - */ - DocumentReference(const DocumentReference& other); - - /** - * @brief Move constructor. - * - * Moving is more efficient than copying for a `DocumentReference`. After - * being moved from, a `DocumentReference` is equivalent to its - * default-constructed state. - * - * @param[in] other `DocumentReference` to move data from. - */ - DocumentReference(DocumentReference&& other); - - virtual ~DocumentReference(); - - /** - * @brief Copy assignment operator. - * - * `DocumentReference` can be efficiently copied because it simply refers to - * a location in the database. - * - * @param[in] other `DocumentReference` to copy from. - * - * @return Reference to the destination `DocumentReference`. - */ - DocumentReference& operator=(const DocumentReference& other); - - /** - * @brief Move assignment operator. - * - * Moving is more efficient than copying for a `DocumentReference`. After - * being moved from, a `DocumentReference` is equivalent to its - * default-constructed state. - * - * @param[in] other `DocumentReference` to move data from. - * - * @return Reference to the destination `DocumentReference`. - */ - DocumentReference& operator=(DocumentReference&& other); - - /** - * @brief Returns the Firestore instance associated with this document - * reference. - * - * The pointer will remain valid indefinitely. - * - * @return Firebase Firestore instance that this DocumentReference refers to. - */ - virtual const Firestore* firestore() const; - - /** - * @brief Returns the Firestore instance associated with this document - * reference. - * - * The pointer will remain valid indefinitely. - * - * @return Firebase Firestore instance that this DocumentReference refers to. - */ - virtual Firestore* firestore(); - - /** - * @brief Returns the string ID of this document location. - * - * @return String ID of this document location. - */ - virtual const std::string& id() const; - - /** - * @brief Returns the path of this document (relative to the root of the - * database) as a slash-separated string. - * - * @return String path of this document location. - */ - virtual std::string path() const; - - /** - * @brief Returns a CollectionReference to the collection that contains this - * document. - */ - virtual CollectionReference Parent() const; - - /** - * @brief Returns a CollectionReference instance that refers to the - * subcollection at the specified path relative to this document. - * - * @param[in] collection_path A slash-separated relative path to a - * subcollection. The pointer only needs to be valid during this call. - * - * @return The CollectionReference instance. - */ - virtual CollectionReference Collection(const char* collection_path) const; - - /** - * @brief Returns a CollectionReference instance that refers to the - * subcollection at the specified path relative to this document. - * - * @param[in] collection_path A slash-separated relative path to a - * subcollection. - * - * @return The CollectionReference instance. - */ - virtual CollectionReference Collection( - const std::string& collection_path) const; - - /** - * @brief Reads the document referenced by this DocumentReference. - * - * By default, Get() attempts to provide up-to-date data when possible by - * waiting for data from the server, but it may return cached data or fail if - * you are offline and the server cannot be reached. This behavior can be - * altered via the Source parameter. - * - * @param[in] source A value to configure the get behavior (optional). - * - * @return A Future that will be resolved with the contents of the Document at - * this DocumentReference. - */ - virtual Future Get(Source source = Source::kDefault) const; - - /** - * @brief Writes to the document referred to by this DocumentReference. - * - * If the document does not yet exist, it will be created. If you pass - * SetOptions, the provided data can be merged into an existing document. - * - * @param[in] data A map of the fields and values to write to the document. - * @param[in] options An object to configure the Set() behavior (optional). - * - * @return A Future that will be resolved when the write finishes. - */ - virtual Future Set(const MapFieldValue& data, - const SetOptions& options = SetOptions()); - - /** - * @brief Updates fields in the document referred to by this - * DocumentReference. - * - * If no document exists yet, the update will fail. - * - * @param[in] data A map of field / value pairs to update. Fields can contain - * dots to reference nested fields within the document. - * - * @return A Future that will be resolved when the client is online and the - * commit has completed against the server. The future will not resolve when - * the device is offline, though local changes will be visible immediately. - */ - virtual Future Update(const MapFieldValue& data); - - /** - * @brief Updates fields in the document referred to by this - * DocumentReference. - * - * If no document exists yet, the update will fail. - * - * @param[in] data A map from FieldPath to FieldValue to update. - * - * @return A Future that will be resolved when the client is online and the - * commit has completed against the server. The future will not resolve when - * the device is offline, though local changes will be visible immediately. - */ - virtual Future Update(const MapFieldPathValue& data); - - /** - * @brief Removes the document referred to by this DocumentReference. - * - * @return A Future that will be resolved when the delete completes. - */ - virtual Future Delete(); - - /** - * @brief Starts listening to the document referenced by this - * DocumentReference. - * - * @param[in] callback The std::function to call. When this function is - * called, snapshot value is valid if and only if error is Error::kErrorOk. - * The std::string is an error message; the value may be empty if an error - * message is not available. - * - * @return A registration object that can be used to remove the listener. - */ - virtual ListenerRegistration AddSnapshotListener( - std::function - callback); - - /** - * @brief Starts listening to the document referenced by this - * DocumentReference. - * - * @param[in] metadata_changes Indicates whether metadata-only changes (that - * is, only DocumentSnapshot::metadata() changed) should trigger snapshot - * events. - * @param[in] callback The std::function to call. When this function is - * called, snapshot value is valid if and only if error is Error::kErrorOk. - * The std::string is an error message; the value may be empty if an error - * message is not available. - * - * @return A registration object that can be used to remove the listener. - */ - virtual ListenerRegistration AddSnapshotListener( - MetadataChanges metadata_changes, - std::function - callback); - - /** - * @brief Returns true if this `DocumentReference` is valid, false if it is - * not valid. An invalid `DocumentReference` could be the result of: - * - Creating a `DocumentReference` using the default constructor. - * - Moving from the `DocumentReference`. - * - Calling `CollectionReference::Parent()` on a `CollectionReference` that - * is not a subcollection. - * - Deleting your Firestore instance, which will invalidate all the - * `DocumentReference` instances associated with it. - * - * @return true if this `DocumentReference` is valid, false if this - * `DocumentReference` is invalid. - */ - bool is_valid() const { return internal_ != nullptr; } - - /** - * Returns a string representation of this `DocumentReference` for - * logging/debugging purposes. - * - * @note the exact string representation is unspecified and subject to - * change; don't rely on the format of the string. - */ - std::string ToString() const; - - /** - * Outputs the string representation of this `DocumentReference` to the given - * stream. - * - * @see `ToString()` for comments on the representation format. - */ - friend std::ostream& operator<<(std::ostream& out, - const DocumentReference& reference); - - private: - friend bool operator==(const DocumentReference& lhs, - const DocumentReference& rhs); - - friend class CollectionReferenceInternal; - friend class DocumentSnapshotInternal; - friend class FieldValueInternal; - friend class FirestoreInternal; - friend class TransactionInternal; - friend class WriteBatchInternal; - friend struct ConverterImpl; - template - friend struct CleanupFn; - - explicit DocumentReference(DocumentReferenceInternal* internal); - - mutable DocumentReferenceInternal* internal_ = nullptr; -}; - -/** Checks `lhs` and `rhs` for equality. */ -bool operator==(const DocumentReference& lhs, const DocumentReference& rhs); - -/** Checks `lhs` and `rhs` for inequality. */ -inline bool operator!=(const DocumentReference& lhs, - const DocumentReference& rhs) { - return !(lhs == rhs); -} - -} // namespace firestore -} // namespace firebase - -#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_DOCUMENT_REFERENCE_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/document_snapshot.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/document_snapshot.h deleted file mode 100644 index 7617eb5d1412..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/document_snapshot.h +++ /dev/null @@ -1,297 +0,0 @@ -/* - * Copyright 2018 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_DOCUMENT_SNAPSHOT_H_ -#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_DOCUMENT_SNAPSHOT_H_ - -#include -#include - -#include "firebase/firestore/map_field_value.h" -#include "firebase/firestore/snapshot_metadata.h" - -namespace firebase { -namespace firestore { - -class DocumentReference; -class DocumentSnapshotInternal; -class FieldPath; -class FieldValue; -class Firestore; - -/** - * @brief A DocumentSnapshot contains data read from a document in your - * Firestore database. - * - * The data can be extracted with the GetData() method, or by using - * Get() to access a specific field. For a DocumentSnapshot that points to - * a non-existing document, any data access will cause a failed assertion. You - * can use the exists() method to explicitly verify a document's existence. - * - * @note Firestore classes are not meant to be subclassed except for use in test - * mocks. Subclassing is not supported in production code and new SDK releases - * may break code that does so. - */ -class DocumentSnapshot { - public: - /** - * Controls the return value for server timestamps that have not yet been set - * to their final value. - */ - enum class ServerTimestampBehavior { - /** - * Return Null for server timestamps that have not yet been set to their - * final value. - */ - kNone = 0, - - /** - * Return local estimates for server timestamps that have not yet been set - * to their final value. This estimate will likely differ from the final - * value and may cause these pending values to change once the server result - * becomes available. - */ - kEstimate, - - /** - * Return the previous value for server timestamps that have not yet been - * set to their final value. - */ - kPrevious, - - /** The default behavior, which is equivalent to specifying kNone. */ - // - // Note, SWIG renaming mechanism doesn't properly handle initializing an - // enum constant with another enum constant (e.g., in expression `kFoo = - // kBar` only `kFoo` will be renamed, leaving `kBar` as is, leading to - // compilation errors). - // - kDefault = 0, - }; - - /** - * @brief Creates an invalid DocumentSnapshot that has to be reassigned before - * it can be used. - * - * Calling any member function on an invalid DocumentSnapshot will be a no-op. - * If the function returns a value, it will return a zero, empty, or invalid - * value, depending on the type of the value. - */ - DocumentSnapshot(); - - /** - * @brief Copy constructor. - * - * `DocumentSnapshot` is immutable and can be efficiently copied (no deep copy - * is performed). - * - * @param[in] other `DocumentSnapshot` to copy from. - */ - DocumentSnapshot(const DocumentSnapshot& other); - - /** - * @brief Move constructor. - * - * Moving is more efficient than copying for a `DocumentSnapshot`. After being - * moved from, a `DocumentSnapshot` is equivalent to its default-constructed - * state. - * - * @param[in] other `DocumentSnapshot` to move data from. - */ - DocumentSnapshot(DocumentSnapshot&& other); - - virtual ~DocumentSnapshot(); - - /** - * @brief Copy assignment operator. - * - * `DocumentSnapshot` is immutable and can be efficiently copied (no deep copy - * is performed). - * - * @param[in] other `DocumentSnapshot` to copy from. - * - * @return Reference to the destination `DocumentSnapshot`. - */ - DocumentSnapshot& operator=(const DocumentSnapshot& other); - - /** - * @brief Move assignment operator. - * - * Moving is more efficient than copying for a `DocumentSnapshot`. After being - * moved from, a `DocumentSnapshot` is equivalent to its default-constructed - * state. - * - * @param[in] other `DocumentSnapshot` to move data from. - * - * @return Reference to the destination `DocumentSnapshot`. - */ - DocumentSnapshot& operator=(DocumentSnapshot&& other); - - /** - * @brief Returns the string ID of the document for which this - * DocumentSnapshot contains data. - * - * @return String ID of this document location. - */ - virtual const std::string& id() const; - - /** - * @brief Returns the document location for which this DocumentSnapshot - * contains data. - * - * @return DocumentReference of this document location. - */ - virtual DocumentReference reference() const; - - /** - * @brief Returns the metadata about this snapshot concerning its source and - * if it has local modifications. - * - * @return SnapshotMetadata about this snapshot. - */ - virtual SnapshotMetadata metadata() const; - - /** - * @brief Explicitly verify a document's existence. - * - * @return True if the document exists in this snapshot. - */ - virtual bool exists() const; - - /** - * @brief Retrieves all fields in the document as a map of FieldValues. - * - * @param stb Configures how server timestamps that have not yet - * been set to their final value are returned from the snapshot (optional). - * - * @return A map containing all fields in the document, or an empty map if the - * document doesn't exist. - */ - virtual MapFieldValue GetData( - ServerTimestampBehavior stb = ServerTimestampBehavior::kDefault) const; - - /** - * @brief Retrieves a specific field from the document. - * - * @param field String ID of the field to retrieve. The pointer only needs to - * be valid during this call. - * @param stb Configures how server timestamps that have not yet been set to - * their final value are returned from the snapshot (optional). - * - * @return The value contained in the field. If the field does not exist in - * the document, then a `FieldValue` instance with `is_valid() == false` will - * be returned. - */ - virtual FieldValue Get( - const char* field, - ServerTimestampBehavior stb = ServerTimestampBehavior::kDefault) const; - - /** - * @brief Retrieves a specific field from the document. - * - * @param field String ID of the field to retrieve. - * @param stb Configures how server timestamps that have not yet been set to - * their final value are returned from the snapshot (optional). - * - * @return The value contained in the field. If the field does not exist in - * the document, then a `FieldValue` instance with `is_valid() == false` will - * be returned. - */ - virtual FieldValue Get( - const std::string& field, - ServerTimestampBehavior stb = ServerTimestampBehavior::kDefault) const; - - /** - * @brief Retrieves a specific field from the document. - * - * @param field Path of the field to retrieve. - * @param stb Configures how server timestamps that have not yet been set to - * their final value are returned from the snapshot (optional). - * - * @return The value contained in the field. If the field does not exist in - * the document, then a `FieldValue` instance with `is_valid() == false` will - * be returned. - */ - virtual FieldValue Get( - const FieldPath& field, - ServerTimestampBehavior stb = ServerTimestampBehavior::kDefault) const; - - /** - * @brief Returns true if this `DocumentSnapshot` is valid, false if it is - * not valid. An invalid `DocumentSnapshot` could be the result of: - * - Creating a `DocumentSnapshot` with the default constructor. - * - Moving from the `DocumentSnapshot`. - * - Deleting your Firestore instance, which will invalidate all the - * `DocumentSnapshot` instances associated with it. - * - * @return true if this `DocumentSnapshot` is valid, false if this - * `DocumentSnapshot` is invalid. - */ - bool is_valid() const { return internal_ != nullptr; } - - /** - * Returns a string representation of this `DocumentSnapshot` for - * logging/debugging purposes. - * - * @note the exact string representation is unspecified and subject to - * change; don't rely on the format of the string. - */ - std::string ToString() const; - - /** - * Outputs the string representation of this `DocumentSnapshot` to the given - * stream. - * - * @see `ToString()` for comments on the representation format. - */ - friend std::ostream& operator<<(std::ostream& out, - const DocumentSnapshot& document); - - private: - std::size_t Hash() const; - - friend bool operator==(const DocumentSnapshot& lhs, - const DocumentSnapshot& rhs); - friend std::size_t DocumentSnapshotHash(const DocumentSnapshot& snapshot); - - friend class DocumentChangeInternal; - friend class EventListenerInternal; - friend class FirestoreInternal; - friend class QueryInternal; - friend class TransactionInternal; - friend class Wrapper; - friend struct ConverterImpl; - template - friend struct CleanupFn; - - explicit DocumentSnapshot(DocumentSnapshotInternal* internal); - - mutable DocumentSnapshotInternal* internal_ = nullptr; -}; - -/** Checks `lhs` and `rhs` for equality. */ -bool operator==(const DocumentSnapshot& lhs, const DocumentSnapshot& rhs); - -/** Checks `lhs` and `rhs` for inequality. */ -inline bool operator!=(const DocumentSnapshot& lhs, - const DocumentSnapshot& rhs) { - return !(lhs == rhs); -} - -} // namespace firestore -} // namespace firebase - -#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_DOCUMENT_SNAPSHOT_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/field_path.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/field_path.h deleted file mode 100644 index d09dec641140..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/field_path.h +++ /dev/null @@ -1,205 +0,0 @@ -/* - * Copyright 2018 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_FIELD_PATH_H_ -#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_FIELD_PATH_H_ - -#include -#include -#include -#include - -namespace firebase { -namespace firestore { - -#if !defined(__ANDROID__) - -namespace model { -class FieldPath; -} // namespace model - -#else - -class FieldPathPortable; - -#endif // !defined(__ANDROID__) - -/** - * @brief A FieldPath refers to a field in a document. - * - * The path may consist of a single field name (referring to a top level field - * in the document) or a list of field names (referring to a nested field in the - * document). - */ -class FieldPath final { - public: - /** - * @brief Creates an invalid FieldPath that has to be reassigned before it can - * be used. - * - * Calling any member function on an invalid FieldPath will be a no-op. If the - * function returns a value, it will return a zero, empty, or invalid value, - * depending on the type of the value. - */ - FieldPath(); - - /** - * Creates a FieldPath from the provided field names. If more than one field - * name is provided, the path will point to a nested field in a document. - * - * @param field_names A list of field names. - */ - FieldPath(std::initializer_list field_names); - - /** - * Creates a FieldPath from the provided field names. If more than one field - * name is provided, the path will point to a nested field in a document. - * - * @param field_names A vector of field names. - */ - FieldPath(const std::vector& field_names); - - /** - * @brief Copy constructor. - * - * This performs a deep copy, creating an independent instance. - * - * @param[in] other `FieldPath` to copy from. - */ - FieldPath(const FieldPath& other); - - /** - * @brief Move constructor. - * - * Moving is more efficient than copying for `FieldPath`. After being moved - * from, `FieldPath` is in a valid but unspecified state. - * - * @param[in] other `FieldPath` to move data from. - */ - FieldPath(FieldPath&& other) noexcept; - - ~FieldPath(); - - /** - * @brief Copy assignment operator. - * - * This performs a deep copy, creating an independent instance. - * - * @param[in] other `FieldPath` to copy from. - * - * @return Reference to the destination `FieldPath`. - */ - FieldPath& operator=(const FieldPath& other); - - /** - * @brief Move assignment operator. - * - * Moving is more efficient than copying for `FieldPath`. After being moved - * from, `FieldPath` is in a valid but unspecified state. - * - * @param[in] other `FieldPath` to move data from. - * - * @return Reference to the destination `FieldPath`. - */ - FieldPath& operator=(FieldPath&& other) noexcept; - - /** - * A special sentinel FieldPath to refer to the ID of a document. It can be - * used in queries to sort or filter by the document ID. - */ - static FieldPath DocumentId(); - - /** - * @brief Returns true if this `FieldPath` is valid, false if it is not valid. - * An invalid `FieldPath` could be the result of: - * - Creating a `FieldPath` using the default constructor. - * - Moving from the `FieldPath`. - * - * @return true if this `FieldPath` is valid, false if this `FieldPath` is - * invalid. - */ - bool is_valid() const { return internal_ != nullptr; } - - /** - * Returns a string representation of this `FieldPath` for - * logging/debugging purposes. - * - * @note the exact string representation is unspecified and subject to - * change; don't rely on the format of the string. - */ - std::string ToString() const; - - /** - * Outputs the string representation of this `FieldPath` to the given - * stream. - * - * @see `ToString()` for comments on the representation format. - */ - friend std::ostream& operator<<(std::ostream& out, const FieldPath& path); - - private: - // The type of the internal object that implements the public interface. -#if !defined(SWIG) -#if !defined(__ANDROID__) - using FieldPathInternal = ::firebase::firestore::model::FieldPath; -#else - using FieldPathInternal = ::firebase::firestore::FieldPathPortable; -#endif // !defined(__ANDROID__) -#endif // !defined(SWIG) - - friend bool operator==(const FieldPath& lhs, const FieldPath& rhs); - friend bool operator!=(const FieldPath& lhs, const FieldPath& rhs); - friend struct std::hash; - - friend class DocumentSnapshot; // For access to `FromDotSeparatedString` - friend class Query; - friend class QueryInternal; - friend class SetOptions; // For access to `FromDotSeparatedString` - friend class FieldPathConverter; - friend struct ConverterImpl; - - explicit FieldPath(FieldPathInternal* internal); - - static FieldPathInternal* InternalFromSegments( - std::vector field_names); - - static FieldPath FromDotSeparatedString(const std::string& path); - - FieldPathInternal* internal_ = nullptr; -}; - -} // namespace firestore -} // namespace firebase - -#if !defined(SWIG) -namespace std { -/** - * A convenient specialization of std::hash for FieldPath. - */ -template <> -struct hash { - /** - * Calculates the hash of the argument. - * - * Note: specialization of `std::hash` is provided for convenience only. The - * implementation is subject to change. - */ - size_t operator()(const firebase::firestore::FieldPath& field_path) const; -}; -} // namespace std -#endif // !defined(SWIG) - -#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_FIELD_PATH_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/field_value.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/field_value.h deleted file mode 100644 index e66814104ed7..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/field_value.h +++ /dev/null @@ -1,436 +0,0 @@ -/* - * Copyright 2018 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_FIELD_VALUE_H_ -#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_FIELD_VALUE_H_ - -#include -#include -#include -#include -#include - -#include "firebase/firestore/map_field_value.h" -#include "firebase/internal/type_traits.h" - -namespace firebase { - -class Timestamp; - -namespace firestore { - -class DocumentReference; -class FieldValueInternal; -class GeoPoint; - -/** - * @brief A field value represents variant datatypes as stored by Firestore. - * - * FieldValue can be used when reading a particular field with - * DocumentSnapshot::Get() or fields with DocumentSnapshot::GetData(). When - * writing document fields with DocumentReference::Set() or - * DocumentReference::Update(), it can also represent sentinel values in - * addition to real data values. - * - * For a non-sentinel instance, you can check whether it is of a particular type - * with is_foo() and get the value with foo_value(), where foo can be one of - * null, boolean, integer, double, timestamp, string, blob, reference, - * geo_point, array or map. If the instance is not of type foo, the call to - * foo_value() will fail (and cause a crash). - */ -class FieldValue final { - // Helper aliases for `Increment` member functions. - // Qualifying `is_integer` is to prevent ambiguity with the - // `FieldValue::is_integer` member function. - // Note: normally, `enable_if::type` would be included in the alias, but such - // a declaration breaks SWIG (presumably, SWIG cannot handle `typename` within - // an alias template). - template - using EnableIfIntegral = enable_if<::firebase::is_integer::value, int>; - template - using EnableIfFloatingPoint = enable_if::value, int>; - - public: - /** - * The enumeration of all valid runtime types of FieldValue. - */ - enum class Type { - kNull, - kBoolean, - kInteger, - kDouble, - kTimestamp, - kString, - kBlob, - kReference, - kGeoPoint, - kArray, - kMap, - // Below are sentinel types. Sentinel types can be passed to Firestore - // methods as arguments, but are never returned from Firestore. - kDelete, - kServerTimestamp, - kArrayUnion, - kArrayRemove, - kIncrementInteger, - kIncrementDouble, - }; - - /** - * @brief Creates an invalid FieldValue that has to be reassigned before it - * can be used. - * - * Calling any member function on an invalid FieldValue will be a no-op. If - * the function returns a value, it will return a zero, empty, or invalid - * value, depending on the type of the value. - */ - FieldValue(); - - /** - * @brief Copy constructor. - * - * `FieldValue` is immutable and can be efficiently copied (no deep copy is - * performed). - * - * @param[in] other `FieldValue` to copy from. - */ - FieldValue(const FieldValue& other); - - /** - * @brief Move constructor. - * - * Moving is more efficient than copying for a `FieldValue`. After being moved - * from, a `FieldValue` is equivalent to its default-constructed state. - * - * @param[in] other `FieldValue` to move data from. - */ - FieldValue(FieldValue&& other) noexcept; - - ~FieldValue(); - - /** - * @brief Copy assignment operator. - * - * `FieldValue` is immutable and can be efficiently copied (no deep copy is - * performed). - * - * @param[in] other `FieldValue` to copy from. - * - * @return Reference to the destination `FieldValue`. - */ - FieldValue& operator=(const FieldValue& other); - - /** - * @brief Move assignment operator. - * - * Moving is more efficient than copying for a `FieldValue`. After being moved - * from, a `FieldValue` is equivalent to its default-constructed state. - * - * @param[in] other `FieldValue` to move data from. - * - * @return Reference to the destination `FieldValue`. - */ - FieldValue& operator=(FieldValue&& other) noexcept; - - /** - * @brief Constructs a FieldValue containing the given boolean value. - */ - static FieldValue Boolean(bool value); - - /** - * @brief Constructs a FieldValue containing the given 64-bit integer value. - */ - static FieldValue Integer(int64_t value); - - /** - * @brief Constructs a FieldValue containing the given double-precision - * floating point value. - */ - static FieldValue Double(double value); - - /** - * @brief Constructs a FieldValue containing the given Timestamp value. - */ - static FieldValue Timestamp(Timestamp value); - - /** - * @brief Constructs a FieldValue containing the given std::string value. - */ - static FieldValue String(std::string value); - - /** - * @brief Constructs a FieldValue containing the given blob value of given - * size. `value` is copied into the returned FieldValue. - */ - static FieldValue Blob(const uint8_t* value, size_t size); - - /** - * @brief Constructs a FieldValue containing the given reference value. - */ - static FieldValue Reference(DocumentReference value); - - /** - * @brief Constructs a FieldValue containing the given GeoPoint value. - */ - static FieldValue GeoPoint(GeoPoint value); - - /** - * @brief Constructs a FieldValue containing the given FieldValue vector - * value. - */ - static FieldValue Array(std::vector value); - - /** - * @brief Constructs a FieldValue containing the given FieldValue map value. - */ - static FieldValue Map(MapFieldValue value); - - /** @brief Gets the current type contained in this FieldValue. */ - Type type() const; - - /** @brief Gets whether this FieldValue is currently null. */ - bool is_null() const { return type() == Type::kNull; } - - /** @brief Gets whether this FieldValue contains a boolean value. */ - bool is_boolean() const { return type() == Type::kBoolean; } - - /** @brief Gets whether this FieldValue contains an integer value. */ - bool is_integer() const { return type() == Type::kInteger; } - - /** @brief Gets whether this FieldValue contains a double value. */ - bool is_double() const { return type() == Type::kDouble; } - - /** @brief Gets whether this FieldValue contains a timestamp. */ - bool is_timestamp() const { return type() == Type::kTimestamp; } - - /** @brief Gets whether this FieldValue contains a string. */ - bool is_string() const { return type() == Type::kString; } - - /** @brief Gets whether this FieldValue contains a blob. */ - bool is_blob() const { return type() == Type::kBlob; } - - /** - * @brief Gets whether this FieldValue contains a reference to a document in - * the same Firestore. - */ - bool is_reference() const { return type() == Type::kReference; } - - /** @brief Gets whether this FieldValue contains a GeoPoint. */ - bool is_geo_point() const { return type() == Type::kGeoPoint; } - - /** @brief Gets whether this FieldValue contains an array of FieldValues. */ - bool is_array() const { return type() == Type::kArray; } - - /** @brief Gets whether this FieldValue contains a map of std::string to - * FieldValue. */ - bool is_map() const { return type() == Type::kMap; } - - /** @brief Gets the boolean value contained in this FieldValue. */ - bool boolean_value() const; - - /** @brief Gets the integer value contained in this FieldValue. */ - int64_t integer_value() const; - - /** @brief Gets the double value contained in this FieldValue. */ - double double_value() const; - - /** @brief Gets the timestamp value contained in this FieldValue. */ - class Timestamp timestamp_value() const; - - /** @brief Gets the string value contained in this FieldValue. */ - std::string string_value() const; - - /** @brief Gets the blob value contained in this FieldValue. */ - const uint8_t* blob_value() const; - - /** @brief Gets the blob size contained in this FieldValue. */ - size_t blob_size() const; - - /** @brief Gets the DocumentReference contained in this FieldValue. */ - DocumentReference reference_value() const; - - /** @brief Gets the GeoPoint value contained in this FieldValue. */ - class GeoPoint geo_point_value() const; - - /** @brief Gets the vector of FieldValues contained in this FieldValue. */ - std::vector array_value() const; - - /** - * @brief Gets the map of string to FieldValue contained in this FieldValue. - */ - MapFieldValue map_value() const; - - /** - * @brief Returns `true` if this `FieldValue` is valid, `false` if it is not - * valid. An invalid `FieldValue` could be the result of: - * - Creating a `FieldValue` using the default constructor. - * - Moving from the `FieldValue`. - * - Calling `DocumentSnapshot::Get(field)` for a field that does not exist - * in the document. - * - * @return `true` if this `FieldValue` is valid, `false` if this `FieldValue` - * is invalid. - */ - bool is_valid() const { return internal_ != nullptr; } - - /** @brief Constructs a null. */ - static FieldValue Null(); - - /** - * @brief Returns a sentinel for use with Update() to mark a field for - * deletion. - */ - static FieldValue Delete(); - - /** - * Returns a sentinel that can be used with Set() or Update() to include - * a server-generated timestamp in the written data. - */ - static FieldValue ServerTimestamp(); - - /** - * Returns a special value that can be used with Set() or Update() that tells - * the server to union the given elements with any array value that already - * exists on the server. Each specified element that doesn't already exist in - * the array will be added to the end. If the field being modified is not - * already an array, it will be overwritten with an array containing exactly - * the specified elements. - * - * @param elements The elements to union into the array. - * @return The FieldValue sentinel for use in a call to Set() or Update(). - */ - static FieldValue ArrayUnion(std::vector elements); - - /** - * Returns a special value that can be used with Set() or Update() that tells - * the server to remove the given elements from any array value that already - * exists on the server. All instances of each element specified will be - * removed from the array. If the field being modified is not already an - * array, it will be overwritten with an empty array. - * - * @param elements The elements to remove from the array. - * @return The FieldValue sentinel for use in a call to Set() or Update(). - */ - static FieldValue ArrayRemove(std::vector elements); - - /** - * Returns a special value that can be used with `Set()` or `Update()` that - * tells the server to increment the field's current value by the given - * integer value. - * - * If the current field value is an integer, possible integer overflows are - * resolved to `LONG_MAX` or `LONG_MIN`. If the current field value is a - * double, both values will be interpreted as doubles and the arithmetic will - * follow IEEE 754 semantics. - * - * If field is not an integer or a double, or if the field does not yet exist, - * the transformation will set the field to the given value. - * - * @param by_value The integer value to increment by. Should be an integer - * type not larger than `int64_t`. - * @return The FieldValue sentinel for use in a call to `Set()` or `Update().` - */ - template ::type = 0> - static FieldValue Increment(T by_value) { - // Note: Doxygen will run into trouble if this function's definition is - // moved outside the class body. - static_assert( - (std::numeric_limits::max)() <= - (std::numeric_limits::max)(), - "The integer type you provided is larger than can fit in an int64_t. " - "If you are sure the value will not be truncated, please explicitly " - "cast to int64_t before passing it to FieldValue::Increment()."); - return IntegerIncrement(static_cast(by_value)); - } - - /** - * Returns a special value that can be used with `Set()` or `Update()` that - * tells the server to increment the field's current value by the given - * floating point value. - * - * If the current field value is an integer, possible integer overflows are - * resolved to `LONG_MAX` or `LONG_MIN`. If the current field value is a - * double, both values will be interpreted as doubles and the arithmetic will - * follow IEEE 754 semantics. - * - * If field is not an integer or a double, or if the field does not yet exist, - * the transformation will set the field to the given value. - * - * @param by_value The double value to increment by. Should be a floating - * point type no larger than `double`. - * @return The FieldValue sentinel for use in a call to `Set()` or `Update().` - */ - template ::type = 0> - static FieldValue Increment(T by_value) { - // Note: Doxygen will run into trouble if this function's definition is - // moved outside the class body. - static_assert( - (std::numeric_limits::max)() <= (std::numeric_limits::max)(), - "The floating point type you provided is larger than can fit in a " - "double. If you are sure the value will not be truncated, please " - "explicitly cast to double before passing it to " - "FieldValue::Increment()."); - return DoubleIncrement(static_cast(by_value)); - } - - /** - * Returns a string representation of this `FieldValue` for logging/debugging - * purposes. - * - * @note the exact string representation is unspecified and subject to - * change; don't rely on the format of the string. - */ - std::string ToString() const; - - /** - * Outputs the string representation of this `FieldValue` to the given stream. - * - * @see `ToString()` for comments on the representation format. - */ - friend std::ostream& operator<<(std::ostream& out, const FieldValue& value); - - private: - friend class DocumentReferenceInternal; - friend class DocumentSnapshotInternal; - friend class FieldValueInternal; - friend class FirestoreInternal; - friend class QueryInternal; - friend class TransactionInternal; - friend class Wrapper; - friend class WriteBatchInternal; - friend struct ConverterImpl; - friend bool operator==(const FieldValue& lhs, const FieldValue& rhs); - - explicit FieldValue(FieldValueInternal* internal); - - static FieldValue IntegerIncrement(int64_t by_value); - static FieldValue DoubleIncrement(double by_value); - - FieldValueInternal* internal_ = nullptr; -}; - -/** Checks `lhs` and `rhs` for equality. */ -bool operator==(const FieldValue& lhs, const FieldValue& rhs); - -/** Checks `lhs` and `rhs` for inequality. */ -inline bool operator!=(const FieldValue& lhs, const FieldValue& rhs) { - return !(lhs == rhs); -} - -} // namespace firestore -} // namespace firebase - -#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_FIELD_VALUE_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/firestore_errors.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/firestore_errors.h deleted file mode 100644 index 6af214a08df1..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/firestore_errors.h +++ /dev/null @@ -1,116 +0,0 @@ -/* - * Copyright 2018 Google - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIRESTORE_CORE_INCLUDE_FIREBASE_FIRESTORE_FIRESTORE_ERRORS_H_ -#define FIRESTORE_CORE_INCLUDE_FIREBASE_FIRESTORE_FIRESTORE_ERRORS_H_ - -namespace firebase { -namespace firestore { - -/** - * Error codes used by Cloud Firestore. - * - * The codes are in sync across Firestore SDKs on various platforms. - */ -enum Error { - /** The operation completed successfully. */ - // Note: NSError objects will never have a code with this value. - kErrorOk = 0, - - kErrorNone = 0, - - /** The operation was cancelled (typically by the caller). */ - kErrorCancelled = 1, - - /** Unknown error or an error from a different error domain. */ - kErrorUnknown = 2, - - /** - * Client specified an invalid argument. Note that this differs from - * FailedPrecondition. InvalidArgument indicates arguments that are - * problematic regardless of the state of the system (e.g., an invalid field - * name). - */ - kErrorInvalidArgument = 3, - - /** - * Deadline expired before operation could complete. For operations that - * change the state of the system, this error may be returned even if the - * operation has completed successfully. For example, a successful response - * from a server could have been delayed long enough for the deadline to - * expire. - */ - kErrorDeadlineExceeded = 4, - - /** Some requested document was not found. */ - kErrorNotFound = 5, - - /** Some document that we attempted to create already exists. */ - kErrorAlreadyExists = 6, - - /** The caller does not have permission to execute the specified operation. */ - kErrorPermissionDenied = 7, - - /** - * Some resource has been exhausted, perhaps a per-user quota, or perhaps the - * entire file system is out of space. - */ - kErrorResourceExhausted = 8, - - /** - * Operation was rejected because the system is not in a state required for - * the operation's execution. - */ - kErrorFailedPrecondition = 9, - - /** - * The operation was aborted, typically due to a concurrency issue like - * transaction aborts, etc. - */ - kErrorAborted = 10, - - /** Operation was attempted past the valid range. */ - kErrorOutOfRange = 11, - - /** Operation is not implemented or not supported/enabled. */ - kErrorUnimplemented = 12, - - /** - * Internal errors. Means some invariants expected by underlying system has - * been broken. If you see one of these errors, something is very broken. - */ - kErrorInternal = 13, - - /** - * The service is currently unavailable. This is a most likely a transient - * condition and may be corrected by retrying with a backoff. - */ - kErrorUnavailable = 14, - - /** Unrecoverable data loss or corruption. */ - kErrorDataLoss = 15, - - /** - * The request does not have valid authentication credentials for the - * operation. - */ - kErrorUnauthenticated = 16 -}; - -} // namespace firestore -} // namespace firebase - -#endif // FIRESTORE_CORE_INCLUDE_FIREBASE_FIRESTORE_FIRESTORE_ERRORS_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/firestore_version.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/firestore_version.h deleted file mode 100644 index 627ead9e3ae7..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/firestore_version.h +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright 2018 Google - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIRESTORE_CORE_INCLUDE_FIREBASE_FIRESTORE_FIRESTORE_VERSION_H_ -#define FIRESTORE_CORE_INCLUDE_FIREBASE_FIRESTORE_FIRESTORE_VERSION_H_ - -namespace firebase { -namespace firestore { - -/** Version string for the Firebase Firestore SDK. */ -extern const char* const kFirestoreVersionString; - -} // namespace firestore -} // namespace firebase - -#endif // FIRESTORE_CORE_INCLUDE_FIREBASE_FIRESTORE_FIRESTORE_VERSION_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/geo_point.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/geo_point.h deleted file mode 100644 index ac56e74a4515..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/geo_point.h +++ /dev/null @@ -1,120 +0,0 @@ -/* - * Copyright 2018 Google - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIRESTORE_CORE_INCLUDE_FIREBASE_FIRESTORE_GEO_POINT_H_ -#define FIRESTORE_CORE_INCLUDE_FIREBASE_FIRESTORE_GEO_POINT_H_ - -#include -#include - -namespace firebase { -namespace firestore { - -/** - * An immutable object representing a geographical point in Firestore. The point - * is represented as a latitude/longitude pair. - * - * Latitude values are in the range of [-90, 90]. - * Longitude values are in the range of [-180, 180]. - */ -class GeoPoint { - public: - /** Creates a `GeoPoint` with both latitude and longitude set to 0. */ - GeoPoint() = default; - - /** - * Creates a `GeoPoint` from the provided latitude and longitude values. - * - * @param latitude The latitude as number of degrees between -90 and 90. - * @param longitude The longitude as number of degrees between -180 and 180. - */ - GeoPoint(double latitude, double longitude); - - /** Copy constructor, `GeoPoint` is trivially copyable. */ - GeoPoint(const GeoPoint& other) = default; - - /** Move constructor, equivalent to copying. */ - GeoPoint(GeoPoint&& other) = default; - - /** Copy assignment operator, `GeoPoint` is trivially copyable. */ - GeoPoint& operator=(const GeoPoint& other) = default; - - /** Move assignment operator, equivalent to copying. */ - GeoPoint& operator=(GeoPoint&& other) = default; - - /** Returns the latitude value of this `GeoPoint`. */ - double latitude() const { - return latitude_; - } - - /** Returns the latitude value of this `GeoPoint`. */ - double longitude() const { - return longitude_; - } - - /** - * Returns a string representation of this `GeoPoint` for logging/debugging - * purposes. - * - * @note: the exact string representation is unspecified and subject to - * change; don't rely on the format of the string. - */ - std::string ToString() const; - - /** - * Outputs the string representation of this `GeoPoint` to the given stream. - * - * @see `ToString()` for comments on the representation format. - */ - friend std::ostream& operator<<(std::ostream& out, const GeoPoint& geo_point); - - private: - double latitude_ = 0.0; - double longitude_ = 0.0; -}; - -/** Checks whether `lhs` and `rhs` are in ascending order. */ -bool operator<(const GeoPoint& lhs, const GeoPoint& rhs); - -/** Checks whether `lhs` and `rhs` are in descending order. */ -inline bool operator>(const GeoPoint& lhs, const GeoPoint& rhs) { - return rhs < lhs; -} - -/** Checks whether `lhs` and `rhs` are in non-ascending order. */ -inline bool operator>=(const GeoPoint& lhs, const GeoPoint& rhs) { - return !(lhs < rhs); -} - -/** Checks whether `lhs` and `rhs` are in non-descending order. */ -inline bool operator<=(const GeoPoint& lhs, const GeoPoint& rhs) { - return !(lhs > rhs); -} - -/** Checks `lhs` and `rhs` for inequality. */ -inline bool operator!=(const GeoPoint& lhs, const GeoPoint& rhs) { - return lhs < rhs || lhs > rhs; -} - -/** Checks `lhs` and `rhs` for equality. */ -inline bool operator==(const GeoPoint& lhs, const GeoPoint& rhs) { - return !(lhs != rhs); -} - -} // namespace firestore -} // namespace firebase - -#endif // FIRESTORE_CORE_INCLUDE_FIREBASE_FIRESTORE_GEO_POINT_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/listener_registration.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/listener_registration.h deleted file mode 100644 index 20487943347f..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/listener_registration.h +++ /dev/null @@ -1,130 +0,0 @@ -/* - * Copyright 2018 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_LISTENER_REGISTRATION_H_ -#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_LISTENER_REGISTRATION_H_ - -namespace firebase { -namespace firestore { - -class FirestoreInternal; -class ListenerRegistrationInternal; - -/** Represents a listener that can be removed by calling Remove(). */ -class ListenerRegistration { - public: - /** - * @brief Creates an invalid ListenerRegistration that has to be reassigned - * before it can be used. - * - * Calling Remove() on an invalid ListenerRegistration is a no-op. - */ - ListenerRegistration(); - - /** - * @brief Copy constructor. - * - * `ListenerRegistration` can be efficiently copied because it simply refers - * to the same underlying listener. If there is more than one copy of - * a `ListenerRegistration`, after calling `Remove` on one of them, the - * listener is removed, and calling `Remove` on any other copies will be - * a no-op. - * - * @param[in] other `ListenerRegistration` to copy from. - */ - ListenerRegistration(const ListenerRegistration& other); - - /** - * @brief Move constructor. - * - * Moving is more efficient than copying for a `ListenerRegistration`. After - * being moved from, a `ListenerRegistration` is equivalent to its - * default-constructed state. - * - * @param[in] other `ListenerRegistration` to move data from. - */ - ListenerRegistration(ListenerRegistration&& other); - - virtual ~ListenerRegistration(); - - /** - * @brief Copy assignment operator. - * - * `ListenerRegistration` can be efficiently copied because it simply refers - * to the same underlying listener. If there is more than one copy of - * a `ListenerRegistration`, after calling `Remove` on one of them, the - * listener is removed, and calling `Remove` on any other copies will be - * a no-op. - * - * @param[in] other `ListenerRegistration` to copy from. - * - * @return Reference to the destination `ListenerRegistration`. - */ - ListenerRegistration& operator=(const ListenerRegistration& other); - - /** - * @brief Move assignment operator. - * - * Moving is more efficient than copying for a `ListenerRegistration`. After - * being moved from, a `ListenerRegistration` is equivalent to its - * default-constructed state. - * - * @param[in] other `ListenerRegistration` to move data from. - * - * @return Reference to the destination `ListenerRegistration`. - */ - ListenerRegistration& operator=(ListenerRegistration&& other); - - /** - * Removes the listener being tracked by this ListenerRegistration. After the - * initial call, subsequent calls have no effect. - */ - virtual void Remove(); - - /** - * @brief Returns true if this `ListenerRegistration` is valid, false if it is - * not valid. An invalid `ListenerRegistration` could be the result of: - * - Creating a `ListenerRegistration` using the default constructor. - * - Moving from the `ListenerRegistration`. - * - Deleting your Firestore instance, which will invalidate all the - * `ListenerRegistration` instances associated with it. - * - * @return true if this `ListenerRegistration` is valid, false if this - * `ListenerRegistration` is invalid. - */ - bool is_valid() const { return internal_ != nullptr; } - - private: - friend class DocumentReferenceInternal; - friend class FirestoreInternal; - friend class ListenerRegistrationInternal; - friend class QueryInternal; - friend struct ConverterImpl; - template - friend struct CleanupFn; - - explicit ListenerRegistration(ListenerRegistrationInternal* internal); - - void Cleanup(); - - FirestoreInternal* firestore_ = nullptr; - mutable ListenerRegistrationInternal* internal_ = nullptr; -}; - -} // namespace firestore -} // namespace firebase - -#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_LISTENER_REGISTRATION_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/load_bundle_task_progress.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/load_bundle_task_progress.h deleted file mode 100644 index be9b235f1205..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/load_bundle_task_progress.h +++ /dev/null @@ -1,101 +0,0 @@ -/* - * Copyright 2021 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_LOAD_BUNDLE_TASK_PROGRESS_H_ -#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_LOAD_BUNDLE_TASK_PROGRESS_H_ - -#include - -namespace firebase { -namespace firestore { - -class LoadBundleTaskProgressInternal; - -/** Represents a progress update or the final state from loading bundles. */ -class LoadBundleTaskProgress { - public: - /** - * Represents the state of bundle loading tasks. - * - * Both `kSuccess` and `kError` are final states: the task will abort - * or complete and there will be no more updates after they are reported. - */ - enum class State { kError, kInProgress, kSuccess }; - - LoadBundleTaskProgress() = default; - /** Construct a LoadBundleTaskProgress with specific state. **/ - LoadBundleTaskProgress(int32_t documents_loaded, - int32_t total_documents, - int64_t bytes_loaded, - int64_t total_bytes, - State state); - - /** Returns how many documents have been loaded. */ - int32_t documents_loaded() const { return documents_loaded_; } - - /** - * Returns the total number of documents in the bundle. Returns 0 if the - * bundle failed to parse. - */ - int32_t total_documents() const { return total_documents_; } - - /** Returns how many bytes have been loaded. */ - int64_t bytes_loaded() const { return bytes_loaded_; } - - /** - * Returns the total number of bytes in the bundle. Returns 0 if the bundle - * failed to parse. - */ - int64_t total_bytes() const { return total_bytes_; } - - /** Returns the current state of the loading progress. */ - State state() const { return state_; } - - private: - friend class EventListenerInternal; - friend class LoadBundleTaskProgressInternal; - friend struct ConverterImpl; - -#if defined(__ANDROID__) - explicit LoadBundleTaskProgress(LoadBundleTaskProgressInternal* internal); -#endif // defined(__ANDROID__) - - int32_t documents_loaded_ = 0; - int32_t total_documents_ = 0; - int64_t bytes_loaded_ = 0; - int64_t total_bytes_ = 0; - State state_ = State::kInProgress; -}; - -/** LoadBundleTaskProgress == comparison operator. **/ -inline bool operator==(const LoadBundleTaskProgress& lhs, - const LoadBundleTaskProgress& rhs) { - return lhs.state() == rhs.state() && - lhs.bytes_loaded() == rhs.bytes_loaded() && - lhs.documents_loaded() == rhs.documents_loaded() && - lhs.total_bytes() == rhs.total_bytes() && - lhs.total_documents() == rhs.total_documents(); -} - -/** LoadBundleTaskProgress != comparison operator. **/ -inline bool operator!=(const LoadBundleTaskProgress& lhs, - const LoadBundleTaskProgress& rhs) { - return !(lhs == rhs); -} - -} // namespace firestore -} // namespace firebase - -#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_LOAD_BUNDLE_TASK_PROGRESS_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/map_field_value.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/map_field_value.h deleted file mode 100644 index 8c67c05a1088..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/map_field_value.h +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright 2018 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_MAP_FIELD_VALUE_H_ -#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_MAP_FIELD_VALUE_H_ - -#include -#include - -namespace firebase { -namespace firestore { - -class FieldPath; -class FieldValue; - -/** @brief A map of `FieldValue`s indexed by stringified field paths. */ -using MapFieldValue = std::unordered_map; -/** @brief A map of `FieldValue`s indexed by field paths. */ -using MapFieldPathValue = std::unordered_map; - -} // namespace firestore -} // namespace firebase - -#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_MAP_FIELD_VALUE_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/metadata_changes.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/metadata_changes.h deleted file mode 100644 index 13f9abe48427..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/metadata_changes.h +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright 2018 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_METADATA_CHANGES_H_ -#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_METADATA_CHANGES_H_ - -namespace firebase { -namespace firestore { - -/** - * Indicates whether metadata-only changes (that is, - * DocumentSnapshot::metadata() or QuerySnapshot::metadata() changed) should - * trigger snapshot events. - */ -enum class MetadataChanges { - /** Snapshot events will not be triggered by metadata-only changes. */ - kExclude, - - /** - * Snapshot events will be triggered by any changes, including metadata-only - * changes. - */ - kInclude, -}; - -} // namespace firestore -} // namespace firebase -#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_METADATA_CHANGES_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/query.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/query.h deleted file mode 100644 index d2e73400cee6..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/query.h +++ /dev/null @@ -1,683 +0,0 @@ -/* - * Copyright 2018 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_QUERY_H_ -#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_QUERY_H_ - -#include -#include -#include -#include -#include - -#include "firebase/internal/common.h" - -#include "firebase/firestore/firestore_errors.h" -#include "firebase/firestore/metadata_changes.h" -#include "firebase/firestore/source.h" - -namespace firebase { -/// @cond FIREBASE_APP_INTERNAL -template -class Future; -/// @endcond - -namespace firestore { - -class DocumentSnapshot; -template -class EventListener; -class FieldPath; -class FieldValue; -class ListenerRegistration; -class Firestore; -class QueryInternal; -class QuerySnapshot; - -/** - * @brief A Query which you can read or listen to. - * - * You can also construct refined Query objects by adding filters and ordering. - * - * You cannot construct a valid Query directly; use CollectionReference - * methods that return a Query instead. - * - * @note Firestore classes are not meant to be subclassed except for use in test - * mocks. Subclassing is not supported in production code and new SDK releases - * may break code that does so. - */ -class Query { - public: - /** - * An enum for the direction of a sort. - */ - enum class Direction { - kAscending, - kDescending, - }; - - /** - * @brief Creates an invalid Query that has to be reassigned before it can be - * used. - * - * Calling any member function on an invalid Query will be a no-op. If the - * function returns a value, it will return a zero, empty, or invalid value, - * depending on the type of the value. - */ - Query(); - - /** - * @brief Copy constructor. - * - * `Query` is immutable and can be efficiently copied (no deep copy is - * performed). - * - * @param[in] other `Query` to copy from. - */ - Query(const Query& other); - - /** - * @brief Move constructor. - * - * Moving is more efficient than copying for a `Query`. After being moved - * from, a `Query` is equivalent to its default-constructed state. - * - * @param[in] other `Query` to move data from. - */ - Query(Query&& other); - - virtual ~Query(); - - /** - * @brief Copy assignment operator. - * - * `Query` is immutable and can be efficiently copied (no deep copy is - * performed). - * - * @param[in] other `Query` to copy from. - * - * @return Reference to the destination `Query`. - */ - Query& operator=(const Query& other); - - /** - * @brief Move assignment operator. - * - * Moving is more efficient than copying for a `Query`. After being moved - * from, a `Query` is equivalent to its default-constructed state. - * - * @param[in] other `Query` to move data from. - * - * @return Reference to the destination `Query`. - */ - Query& operator=(Query&& other); - - /** - * @brief Returns the Firestore instance associated with this query. - * - * The pointer will remain valid indefinitely. - * - * @return Firebase Firestore instance that this Query refers to. - */ - virtual const Firestore* firestore() const; - - /** - * @brief Returns the Firestore instance associated with this query. - * - * The pointer will remain valid indefinitely. - * - * @return Firebase Firestore instance that this Query refers to. - */ - virtual Firestore* firestore(); - - /** - * @brief Creates and returns a new Query with the additional filter that - * documents must contain the specified field and the value should be equal to - * the specified value. - * - * @param[in] field The name of the field to compare. - * @param[in] value The value for comparison. - * - * @return The created Query. - */ - virtual Query WhereEqualTo(const std::string& field, - const FieldValue& value) const; - - /** - * @brief Creates and returns a new Query with the additional filter that - * documents must contain the specified field and the value should be equal to - * the specified value. - * - * @param[in] field The path of the field to compare. - * @param[in] value The value for comparison. - * - * @return The created Query. - */ - virtual Query WhereEqualTo(const FieldPath& field, - const FieldValue& value) const; - - /** - * @brief Creates and returns a new Query with the additional filter that - * documents must contain the specified field and the value does not equal the - * specified value. - * - * A Query can have only one `WhereNotEqualTo()` filter, and it cannot be - * combined with `WhereNotIn()`. - * - * @param[in] field The name of the field to compare. - * @param[in] value The value for comparison. - * - * @return The created Query. - */ - virtual Query WhereNotEqualTo(const std::string& field, - const FieldValue& value) const; - - /** - * @brief Creates and returns a new Query with the additional filter that - * documents must contain the specified field and the value does not equal the - * specified value. - * - * A Query can have only one `WhereNotEqualTo()` filter, and it cannot be - * combined with `WhereNotIn()`. - * - * @param[in] field The path of the field to compare. - * @param[in] value The value for comparison. - * - * @return The created Query. - */ - virtual Query WhereNotEqualTo(const FieldPath& field, - const FieldValue& value) const; - - /** - * @brief Creates and returns a new Query with the additional filter that - * documents must contain the specified field and the value should be less - * than the specified value. - * - * @param[in] field The name of the field to compare. - * @param[in] value The value for comparison. - * - * @return The created Query. - */ - virtual Query WhereLessThan(const std::string& field, - const FieldValue& value) const; - - /** - * @brief Creates and returns a new Query with the additional filter that - * documents must contain the specified field and the value should be less - * than the specified value. - * - * @param[in] field The path of the field to compare. - * @param[in] value The value for comparison. - * - * @return The created Query. - */ - virtual Query WhereLessThan(const FieldPath& field, - const FieldValue& value) const; - - /** - * @brief Creates and returns a new Query with the additional filter that - * documents must contain the specified field and the value should be less - * than or equal to the specified value. - * - * @param[in] field The name of the field to compare. - * @param[in] value The value for comparison. - * - * @return The created Query. - */ - virtual Query WhereLessThanOrEqualTo(const std::string& field, - const FieldValue& value) const; - - /** - * @brief Creates and returns a new Query with the additional filter that - * documents must contain the specified field and the value should be less - * than or equal to the specified value. - * - * @param[in] field The path of the field to compare. - * @param[in] value The value for comparison. - * - * @return The created Query. - */ - virtual Query WhereLessThanOrEqualTo(const FieldPath& field, - const FieldValue& value) const; - - /** - * @brief Creates and returns a new Query with the additional filter that - * documents must contain the specified field and the value should be greater - * than the specified value. - * - * @param[in] field The name of the field to compare. - * @param[in] value The value for comparison. - * - * @return The created Query. - */ - virtual Query WhereGreaterThan(const std::string& field, - const FieldValue& value) const; - - /** - * @brief Creates and returns a new Query with the additional filter that - * documents must contain the specified field and the value should be greater - * than the specified value. - * - * @param[in] field The path of the field to compare. - * @param[in] value The value for comparison. - * - * @return The created Query. - */ - virtual Query WhereGreaterThan(const FieldPath& field, - const FieldValue& value) const; - - /** - * @brief Creates and returns a new Query with the additional filter that - * documents must contain the specified field and the value should be greater - * than or equal to the specified value. - * - * @param[in] field The name of the field to compare. - * @param[in] value The value for comparison. - * - * @return The created Query. - */ - virtual Query WhereGreaterThanOrEqualTo(const std::string& field, - const FieldValue& value) const; - - /** - * @brief Creates and returns a new Query with the additional filter that - * documents must contain the specified field and the value should be greater - * than or equal to the specified value. - * - * @param[in] field The path of the field to compare. - * @param[in] value The value for comparison. - * - * @return The created Query. - */ - virtual Query WhereGreaterThanOrEqualTo(const FieldPath& field, - const FieldValue& value) const; - - /** - * @brief Creates and returns a new Query with the additional filter that - * documents must contain the specified field, the value must be an array, and - * that the array must contain the provided value. - * - * A Query can have only one `WhereArrayContains()` filter and it cannot be - * combined with `WhereArrayContainsAny()` or `WhereIn()`. - * - * @param[in] field The name of the field containing an array to search. - * @param[in] value The value that must be contained in the array. - * - * @return The created Query. - */ - virtual Query WhereArrayContains(const std::string& field, - const FieldValue& value) const; - - /** - * @brief Creates and returns a new Query with the additional filter that - * documents must contain the specified field, the value must be an array, and - * that the array must contain the provided value. - * - * A Query can have only one `WhereArrayContains()` filter and it cannot be - * combined with `WhereArrayContainsAny()` or `WhereIn()`. - * - * @param[in] field The path of the field containing an array to search. - * @param[in] value The value that must be contained in the array. - * - * @return The created Query. - */ - virtual Query WhereArrayContains(const FieldPath& field, - const FieldValue& value) const; - - /** - * @brief Creates and returns a new Query with the additional filter that - * documents must contain the specified field, the value must be an array, and - * that the array must contain at least one value from the provided list. - * - * A Query can have only one `WhereArrayContainsAny()` filter and it cannot be - * combined with `WhereArrayContains()` or `WhereIn()`. - * - * @param[in] field The name of the field containing an array to search. - * @param[in] values The list that contains the values to match. - * - * @return The created Query. - */ - virtual Query WhereArrayContainsAny( - const std::string& field, const std::vector& values) const; - - /** - * @brief Creates and returns a new Query with the additional filter that - * documents must contain the specified field, the value must be an array, and - * that the array must contain at least one value from the provided list. - * - * A Query can have only one `WhereArrayContainsAny()` filter and it cannot be - * combined with` WhereArrayContains()` or `WhereIn()`. - * - * @param[in] field The path of the field containing an array to search. - * @param[in] values The list that contains the values to match. - * - * @return The created Query. - */ - virtual Query WhereArrayContainsAny( - const FieldPath& field, const std::vector& values) const; - - /** - * @brief Creates and returns a new Query with the additional filter that - * documents must contain the specified field and the value must equal one of - * the values from the provided list. - * - * A Query can have only one `WhereIn()` filter and it cannot be - * combined with `WhereArrayContainsAny()`. - * - * @param[in] field The name of the field containing an array to search. - * @param[in] values The list that contains the values to match. - * - * @return The created Query. - */ - virtual Query WhereIn(const std::string& field, - const std::vector& values) const; - - /** - * @brief Creates and returns a new Query with the additional filter that - * documents must contain the specified field and the value must equal one of - * the values from the provided list. - * - * A Query can have only one `WhereIn()` filter and it cannot be - * combined with `WhereArrayContainsAny()`. - * - * @param[in] field The path of the field containing an array to search. - * @param[in] values The list that contains the values to match. - * - * @return The created Query. - */ - virtual Query WhereIn(const FieldPath& field, - const std::vector& values) const; - - /** - * @brief Creates and returns a new Query with the additional filter that - * documents must contain the specified field and the value must not equal any - * of the values from the provided list. - * - * One special case is that `WhereNotIn` cannot match `FieldValue::Null()` - * values. To query for documents where a field exists and is - * `FieldValue::Null()`, use `WhereNotEqualTo`, which can handle this special - * case. - * - * A `Query` can have only one `WhereNotIn()` filter, and it cannot be - * combined with `WhereArrayContains()`, `WhereArrayContainsAny()`, - * `WhereIn()`, or `WhereNotEqualTo()`. - * - * @param[in] field The name of the field containing an array to search. - * @param[in] values The list that contains the values to match. - * - * @return The created Query. - */ - virtual Query WhereNotIn(const std::string& field, - const std::vector& values) const; - - /** - * @brief Creates and returns a new Query with the additional filter that - * documents must contain the specified field and the value must not equal any - * of the values from the provided list. - * - * One special case is that `WhereNotIn` cannot match `FieldValue::Null()` - * values. To query for documents where a field exists and is - * `FieldValue::Null()`, use `WhereNotEqualTo`, which can handle this special - * case. - * - * A `Query` can have only one `WhereNotIn()` filter, and it cannot be - * combined with `WhereArrayContains()`, `WhereArrayContainsAny()`, - * `WhereIn()`, or `WhereNotEqualTo()`. - * - * @param[in] field The path of the field containing an array to search. - * @param[in] values The list that contains the values to match. - * - * @return The created Query. - */ - virtual Query WhereNotIn(const FieldPath& field, - const std::vector& values) const; - - /** - * @brief Creates and returns a new Query that's additionally sorted by the - * specified field. - * - * @param[in] field The field to sort by. - * @param[in] direction The direction to sort (optional). If not specified, - * order will be ascending. - * - * @return The created Query. - */ - virtual Query OrderBy(const std::string& field, - Direction direction = Direction::kAscending) const; - - /** - * @brief Creates and returns a new Query that's additionally sorted by the - * specified field. - * - * @param[in] field The field to sort by. - * @param[in] direction The direction to sort (optional). If not specified, - * order will be ascending. - * - * @return The created Query. - */ - virtual Query OrderBy(const FieldPath& field, - Direction direction = Direction::kAscending) const; - - /** - * @brief Creates and returns a new Query that only returns the first matching - * documents up to the specified number. - * - * @param[in] limit A non-negative integer to specify the maximum number of - * items to return. - * - * @return The created Query. - */ - virtual Query Limit(int32_t limit) const; - - /** - * @brief Creates and returns a new Query that only returns the last matching - * documents up to the specified number. - * - * @param[in] limit A non-negative integer to specify the maximum number of - * items to return. - * - * @return The created Query. - */ - virtual Query LimitToLast(int32_t limit) const; - - /** - * @brief Creates and returns a new Query that starts at the provided document - * (inclusive). The starting position is relative to the order of the query. - * The document must contain all of the fields provided in the order by of - * this query. - * - * @param[in] snapshot The snapshot of the document to start at. - * - * @return The created Query. - */ - virtual Query StartAt(const DocumentSnapshot& snapshot) const; - - /** - * @brief Creates and returns a new Query that starts at the provided fields - * relative to the order of the query. The order of the field values must - * match the order of the order by clauses of the query. - * - * @param[in] values The field values to start this query at, in order of the - * query's order by. - * - * @return The created Query. - */ - virtual Query StartAt(const std::vector& values) const; - - /** - * @brief Creates and returns a new Query that starts after the provided - * document (inclusive). The starting position is relative to the order of the - * query. The document must contain all of the fields provided in the order by - * of this query. - * - * @param[in] snapshot The snapshot of the document to start after. - * - * @return The created Query. - */ - virtual Query StartAfter(const DocumentSnapshot& snapshot) const; - - /** - * @brief Creates and returns a new Query that starts after the provided - * fields relative to the order of the query. The order of the field values - * must match the order of the order by clauses of the query. - * - * @param[in] values The field values to start this query after, in order of - * the query's order by. - * - * @return The created Query. - */ - virtual Query StartAfter(const std::vector& values) const; - - /** - * @brief Creates and returns a new Query that ends before the provided - * document (inclusive). The end position is relative to the order of the - * query. The document must contain all of the fields provided in the order by - * of this query. - * - * @param[in] snapshot The snapshot of the document to end before. - * - * @return The created Query. - */ - virtual Query EndBefore(const DocumentSnapshot& snapshot) const; - - /** - * @brief Creates and returns a new Query that ends before the provided fields - * relative to the order of the query. The order of the field values must - * match the order of the order by clauses of the query. - * - * @param[in] values The field values to end this query before, in order of - * the query's order by. - * - * @return The created Query. - */ - virtual Query EndBefore(const std::vector& values) const; - - /** - * @brief Creates and returns a new Query that ends at the provided document - * (inclusive). The end position is relative to the order of the query. The - * document must contain all of the fields provided in the order by of this - * query. - * - * @param[in] snapshot The snapshot of the document to end at. - * - * @return The created Query. - */ - virtual Query EndAt(const DocumentSnapshot& snapshot) const; - - /** - * @brief Creates and returns a new Query that ends at the provided fields - * relative to the order of the query. The order of the field values must - * match the order of the order by clauses of the query. - * - * @param[in] values The field values to end this query at, in order of the - * query's order by. - * - * @return The created Query. - */ - virtual Query EndAt(const std::vector& values) const; - - /** - * @brief Executes the query and returns the results as a QuerySnapshot. - * - * By default, Get() attempts to provide up-to-date data when possible by - * waiting for data from the server, but it may return cached data or fail if - * you are offline and the server cannot be reached. This behavior can be - * altered via the Source parameter. - * - * @param[in] source A value to configure the get behavior (optional). - * - * @return A Future that will be resolved with the results of the Query. - */ - virtual Future Get(Source source = Source::kDefault) const; - - /** - * @brief Starts listening to the QuerySnapshot events referenced by this - * query. - * - * @param[in] callback The std::function to call. When this function is - * called, snapshot value is valid if and only if error is Error::kErrorOk. - * The std::string is an error message; the value may be empty if an error - * message is not available. - * - * @return A registration object that can be used to remove the listener. - */ - virtual ListenerRegistration AddSnapshotListener( - std::function - callback); - - /** - * @brief Starts listening to the QuerySnapshot events referenced by this - * query. - * - * @param[in] metadata_changes Indicates whether metadata-only changes (that - * is, only DocumentSnapshot::metadata() changed) should trigger snapshot - * events. - * @param[in] callback The std::function to call. When this function is - * called, snapshot value is valid if and only if error is Error::kErrorOk. - * The std::string is an error message; the value may be empty if an error - * message is not available. - * - * @return A registration object that can be used to remove the listener. - */ - virtual ListenerRegistration AddSnapshotListener( - MetadataChanges metadata_changes, - std::function - callback); - - /** - * @brief Returns true if this `Query` is valid, false if it is not valid. An - * invalid `Query` could be the result of: - * - Creating a `Query` using the default constructor. - * - Moving from the `Query`. - * - Deleting your Firestore instance, which will invalidate all the `Query` - * instances associated with it. - * - * @return true if this `Query` is valid, false if this `Query` is invalid. - */ - bool is_valid() const { return internal_ != nullptr; } - - private: - size_t Hash() const; - - friend bool operator==(const Query& lhs, const Query& rhs); - friend size_t QueryHash(const Query& query); - - friend class FirestoreInternal; - friend class QueryInternal; - friend class QuerySnapshotInternal; - friend struct ConverterImpl; - template - friend struct CleanupFn; - // For access to the constructor and to `internal_`. - friend class CollectionReference; - - explicit Query(QueryInternal* internal); - - mutable QueryInternal* internal_ = nullptr; -}; - -/** Checks `lhs` and `rhs` for equality. */ -bool operator==(const Query& lhs, const Query& rhs); - -/** Checks `lhs` and `rhs` for inequality. */ -inline bool operator!=(const Query& lhs, const Query& rhs) { - return !(lhs == rhs); -} - -} // namespace firestore -} // namespace firebase - -#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_QUERY_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/query_snapshot.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/query_snapshot.h deleted file mode 100644 index 2dcf7aaf5239..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/query_snapshot.h +++ /dev/null @@ -1,194 +0,0 @@ -/* - * Copyright 2018 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_QUERY_SNAPSHOT_H_ -#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_QUERY_SNAPSHOT_H_ - -#include -#include - -#include "firebase/firestore/metadata_changes.h" -#include "firebase/firestore/snapshot_metadata.h" - -namespace firebase { -namespace firestore { - -class DocumentChange; -class DocumentSnapshot; -class Query; -class QuerySnapshotInternal; - -/** - * @brief A QuerySnapshot contains zero or more DocumentSnapshot objects. - * - * QuerySnapshot can be iterated using a range-based for loop, and its size can - * be inspected with empty() and size(). - * - * @note Firestore classes are not meant to be subclassed except for use in test - * mocks. Subclassing is not supported in production code and new SDK releases - * may break code that does so. - */ -class QuerySnapshot { - public: - /** - * @brief Creates an invalid QuerySnapshot that has to be reassigned before it - * can be used. - * - * Calling any member function on an invalid QuerySnapshot will be a no-op. If - * the function returns a value, it will return a zero, empty, or invalid - * value, depending on the type of the value. - */ - QuerySnapshot(); - - /** - * @brief Copy constructor. - * - * `QuerySnapshot` is immutable and can be efficiently copied (no deep copy is - * performed). - * - * @param[in] other `QuerySnapshot` to copy from. - */ - QuerySnapshot(const QuerySnapshot& other); - - /** - * @brief Move constructor. - * - * Moving is more efficient than copying for a `QuerySnapshot`. After being - * moved from, a `QuerySnapshot` is equivalent to its default-constructed - * state. - * - * @param[in] other `QuerySnapshot` to move data from. - */ - QuerySnapshot(QuerySnapshot&& other); - - virtual ~QuerySnapshot(); - - /** - * @brief Copy assignment operator. - * - * `QuerySnapshot` is immutable and can be efficiently copied (no deep copy is - * performed). - * - * @param[in] other `QuerySnapshot` to copy from. - * - * @return Reference to the destination `QuerySnapshot`. - */ - QuerySnapshot& operator=(const QuerySnapshot& other); - - /** - * @brief Move assignment operator. - * - * Moving is more efficient than copying for a `QuerySnapshot`. After being - * moved from, a `QuerySnapshot` is equivalent to its default-constructed - * state. - * - * @param[in] other `QuerySnapshot` to move data from. - * - * @return Reference to the destination `QuerySnapshot`. - */ - QuerySnapshot& operator=(QuerySnapshot&& other); - - /** - * @brief The query from which you got this QuerySnapshot. - */ - virtual Query query() const; - - /** - * @brief Metadata about this snapshot, concerning its source and if it has - * local modifications. - * - * @return The metadata for this document snapshot. - */ - virtual SnapshotMetadata metadata() const; - - /** - * @brief The list of documents that changed since the last snapshot. - * - * If it's the first snapshot, all documents will be in the list as added - * changes. Documents with changes only to their metadata will not be - * included. - * - * @param[in] metadata_changes Indicates whether metadata-only changes (that - * is, only QuerySnapshot::metadata() changed) should be included. - * - * @return The list of document changes since the last snapshot. - */ - virtual std::vector DocumentChanges( - MetadataChanges metadata_changes = MetadataChanges::kExclude) const; - - /** - * @brief The list of documents in this QuerySnapshot in order of the query. - * - * @return The list of documents. - */ - virtual std::vector documents() const; - - /** - * @brief Checks the emptiness of the QuerySnapshot. - * - * @return True if there are no documents in the QuerySnapshot. - */ - bool empty() const { return size() == 0; } - - /** - * @brief Checks the size of the QuerySnapshot. - * - * @return The number of documents in the QuerySnapshot. - */ - virtual std::size_t size() const; - - /** - * @brief Returns true if this `QuerySnapshot` is valid, false if it is not - * valid. An invalid `QuerySnapshot` could be the result of: - * - Creating a `QuerySnapshot` using the default constructor. - * - Moving from the `QuerySnapshot`. - * - Deleting your Firestore instance, which will invalidate all the - * `QuerySnapshot` instances associated with it. - * - * @return true if this `QuerySnapshot` is valid, false if this - * `QuerySnapshot` is invalid. - */ - bool is_valid() const { return internal_ != nullptr; } - - private: - std::size_t Hash() const; - - friend bool operator==(const QuerySnapshot& lhs, const QuerySnapshot& rhs); - friend std::size_t QuerySnapshotHash(const QuerySnapshot& snapshot); - - friend class EventListenerInternal; - friend class FirestoreInternal; - friend struct ConverterImpl; - template - friend struct CleanupFn; - - explicit QuerySnapshot(QuerySnapshotInternal* internal); - - mutable QuerySnapshotInternal* internal_ = nullptr; -}; - -/** Checks `lhs` and `rhs` for equality. */ -bool operator==(const QuerySnapshot& lhs, const QuerySnapshot& rhs); - -/** Checks `lhs` and `rhs` for inequality. */ -inline bool operator!=(const QuerySnapshot& lhs, const QuerySnapshot& rhs) { - return !(lhs == rhs); -} - -} // namespace firestore -} // namespace firebase - -#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_QUERY_SNAPSHOT_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/set_options.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/set_options.h deleted file mode 100644 index bf21b07a0c45..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/set_options.h +++ /dev/null @@ -1,161 +0,0 @@ -/* - * Copyright 2018 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_SET_OPTIONS_H_ -#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_SET_OPTIONS_H_ - -#include -#include -#include - -#include "firebase/firestore/field_path.h" - -namespace firebase { -namespace firestore { - -/** - * @brief An options object that configures the behavior of Set() calls. - * - * By providing the SetOptions objects returned by Merge(), the Set() methods in - * DocumentReference, WriteBatch and Transaction can be configured to perform - * granular merges instead of overwriting the target documents in their - * entirety. - */ -class SetOptions final { - public: - /** The enumeration of all types of SetOptions. */ - enum class Type { - /** Overwrites the whole document. */ - kOverwrite, - - /** - * Replaces the values specified in the call parameter while leaves omitted - * fields untouched. - */ - kMergeAll, - - /** - * Replaces the values of the fields explicitly specified in the call - * parameter. - */ - kMergeSpecific, - }; - - /** - * Creates SetOptions with overwrite semantics. - */ - SetOptions() = default; - - /** - * @brief Copy constructor. - * - * This performs a deep copy, creating an independent instance. - * - * @param[in] other `SetOptions` to copy from. - */ - SetOptions(const SetOptions& other) = default; - - /** - * @brief Move constructor. - * - * Moving is more efficient than copying for `SetOptions`. After being moved - * from, `SetOptions` is in a valid but unspecified state. - * - * @param[in] other `SetOptions` to move data from. - */ - SetOptions(SetOptions&& other) = default; - - ~SetOptions(); - - /** - * @brief Copy assignment operator. - * - * This performs a deep copy, creating an independent instance. - * - * @param[in] other `SetOptions` to copy from. - * - * @return Reference to the destination `SetOptions`. - */ - SetOptions& operator=(const SetOptions& other) = default; - - /** - * @brief Move assignment operator. - * - * Moving is more efficient than copying for `SetOptions`. After being moved - * from, `SetOptions` is in a valid but unspecified state. - * - * @param[in] other `SetOptions` to move data from. - * - * @return Reference to the destination `SetOptions`. - */ - SetOptions& operator=(SetOptions&& other) = default; - - /** - * Returns an instance that can be used to change the behavior of Set() calls - * to only replace the values specified in its data argument. Fields omitted - * from the Set() call will remain untouched. - */ - static SetOptions Merge(); - - /** - * Returns an instance that can be used to change the behavior of Set() calls - * to only replace the given fields. Any field that is not specified in - * `fields` is ignored and remains untouched. - * - * It is an error to pass a SetOptions object to a Set() call that is missing - * a value for any of the fields specified here. - * - * @param fields The list of fields to merge. Fields can contain dots to - * reference nested fields within the document. - */ - static SetOptions MergeFields(const std::vector& fields); - - /** - * Returns an instance that can be used to change the behavior of Set() calls - * to only replace the given fields. Any field that is not specified in - * `fields` is ignored and remains untouched. - * - * It is an error to pass a SetOptions object to a Set() call that is missing - * a value for any of the fields specified here in its to data argument. - * - * @param fields The list of fields to merge. - */ - static SetOptions MergeFieldPaths(const std::vector& fields); - - private: - friend bool operator==(const SetOptions& lhs, const SetOptions& rhs); - friend class SetOptionsInternal; - - SetOptions(Type type, std::unordered_set fields); - - Type type_ = Type::kOverwrite; - std::unordered_set fields_; -}; - -/** Checks `lhs` and `rhs` for equality. */ -inline bool operator==(const SetOptions& lhs, const SetOptions& rhs) { - return lhs.type_ == rhs.type_ && lhs.fields_ == rhs.fields_; -} - -/** Checks `lhs` and `rhs` for inequality. */ -inline bool operator!=(const SetOptions& lhs, const SetOptions& rhs) { - return !(lhs == rhs); -} - -} // namespace firestore -} // namespace firebase - -#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_SET_OPTIONS_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/settings.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/settings.h deleted file mode 100644 index 8169d9f594e8..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/settings.h +++ /dev/null @@ -1,247 +0,0 @@ -/* - * Copyright 2018 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_SETTINGS_H_ -#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_SETTINGS_H_ - -#if defined(__OBJC__) -#include -#endif - -#include -#include -#include -#include - -namespace firebase { -namespace firestore { - -#if !defined(__ANDROID__) -// -// This declaration is guarded by a preprocessor macro because it causes -// problems with name lookup on Android. Android implementation of the public -// API extensively uses function calls of the form `util::Foo` which are -// expected to resolve to `::firebase::util::Foo`. As soon as namespace -// `::firebase::firestore::util` becomes visible, it shadows `::firebase::util` -// (within `::firebase::firestore`), so now all those calls fail to compile -// because they are interpreted as referring to -// `::firebase::firestore::util::Foo`, which doesn't exist. Changing existing -// code is impractical because such usages are numerous. -// -namespace util { -class Executor; -} -#endif - -class FirestoreInternal; - -/** Settings used to configure a Firestore instance. */ -class Settings final { - public: - /** - * Constant to use with `set_cache_size_bytes` to disable garbage collection. - */ - static constexpr int64_t kCacheSizeUnlimited = -1; - - /** - * @brief Creates the default settings. - */ - Settings(); - - /** - * @brief Copy constructor. - * - * This performs a deep copy, creating an independent instance. - * - * @param[in] other `Settings` to copy from. - */ - Settings(const Settings& other) = default; - - /** - * @brief Move constructor. - * - * Moving is more efficient than copying for `Settings`. After being moved - * from, `Settings` is in a valid but unspecified state. - * - * @param[in] other `Settings` to move data from. - */ - Settings(Settings&& other) = default; - - /** - * @brief Copy assignment operator. - * - * This performs a deep copy, creating an independent instance. - * - * @param[in] other `Settings` to copy from. - * - * @return Reference to the destination `Settings`. - */ - Settings& operator=(const Settings& other) = default; - - /** - * @brief Move assignment operator. - * - * Moving is more efficient than copying for `Settings`. After being moved - * from, `Settings` is in a valid but unspecified state. - * - * @param[in] other `Settings` to move data from. - * - * @return Reference to the destination `Settings`. - */ - Settings& operator=(Settings&& other) = default; - - /** - * Gets the host of the Firestore backend to connect to. - */ - const std::string& host() const { return host_; } - - /** - * Returns whether to use SSL when communicating. - */ - bool is_ssl_enabled() const { return ssl_enabled_; } - - /** - * Returns whether to enable local persistent storage. - */ - bool is_persistence_enabled() const { return persistence_enabled_; } - - /** Returns cache size for on-disk data. */ - int64_t cache_size_bytes() const { return cache_size_bytes_; } - - /** - * Sets the host of the Firestore backend. The default is - * "firestore.googleapis.com". - * - * @param host The host string. - */ - void set_host(std::string host); - - /** - * Enables or disables SSL for communication. - * - * @param enabled Set true to enable SSL for communication. - */ - void set_ssl_enabled(bool enabled); - - /** - * Enables or disables local persistent storage. - * - * @param enabled Set true to enable local persistent storage. - */ - void set_persistence_enabled(bool enabled); - - /** - * Sets an approximate cache size threshold for the on-disk data. If the cache - * grows beyond this size, Cloud Firestore will start removing data that - * hasn't been recently used. The size is not a guarantee that the cache will - * stay below that size, only that if the cache exceeds the given size, - * cleanup will be attempted. - * - * By default, collection is enabled with a cache size of 100 MB. The minimum - * value is 1 MB. - */ - void set_cache_size_bytes(int64_t value); - -#if defined(__OBJC__) || defined(DOXYGEN) - /** - * Returns a dispatch queue that Firestore will use to execute callbacks. - * - * The returned dispatch queue is used for all completion handlers and event - * handlers. - * - * If no dispatch queue is explictly set by calling `set_dispatch_queue()` - * then a dedicated "callback queue" will be used; namely, the main thread - * will not be used for callbacks unless expliclty set to do so by a call to - * `set_dispatch_queue()`. - * - * @note This method is only available when `__OBJC__` is defined, such as - * when compiling for iOS or tvOS. - * - * @see `set_dispatch_queue(dispatch_queue_t)` for information on how to - * explicitly set the dispatch queue to use. - */ - dispatch_queue_t dispatch_queue() const; - - /** - * Sets the dispatch queue that Firestore will use to execute callbacks. - * - * The specified dispatch queue will be used for all completion handlers and - * event handlers. - * - * @param queue The dispatch queue to use. - * - * @note This method is only available when `__OBJC__` is defined, such as - * when compiling for iOS or tvOS. - * - * @see `dispatch_queue()` for the "get" counterpart to this method. - */ - void set_dispatch_queue(dispatch_queue_t queue); -#endif // defined(__OBJC__) || defined(DOXYGEN) - - /** - * Returns a string representation of these `Settings` for - * logging/debugging purposes. - * - * @note the exact string representation is unspecified and subject to - * change; don't rely on the format of the string. - */ - std::string ToString() const; - - /** - * Outputs the string representation of these `Settings` to the given - * stream. - * - * @see `ToString()` for comments on the representation format. - */ - friend std::ostream& operator<<(std::ostream& out, const Settings& settings); - - private: - static constexpr int64_t kDefaultCacheSizeBytes = 100 * 1024 * 1024; - - std::string host_; - bool ssl_enabled_ = true; - bool persistence_enabled_ = true; - int64_t cache_size_bytes_ = kDefaultCacheSizeBytes; - - // - // TODO(varconst): fix Android problems and make these declarations - // unconditional. - // -#if !defined(__ANDROID__) - friend class FirestoreInternal; - std::unique_ptr CreateExecutor() const; - - std::shared_ptr executor_; -#endif -}; - -/** Checks `lhs` and `rhs` for equality. */ -inline bool operator==(const Settings& lhs, const Settings& rhs) { - return lhs.host() == rhs.host() && - lhs.is_ssl_enabled() == rhs.is_ssl_enabled() && - lhs.is_persistence_enabled() == rhs.is_persistence_enabled() && - lhs.cache_size_bytes() == rhs.cache_size_bytes(); -} - -/** Checks `lhs` and `rhs` for inequality. */ -inline bool operator!=(const Settings& lhs, const Settings& rhs) { - return !(lhs == rhs); -} - -} // namespace firestore -} // namespace firebase - -#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_SETTINGS_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/snapshot_metadata.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/snapshot_metadata.h deleted file mode 100644 index ce7f3f2b8607..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/snapshot_metadata.h +++ /dev/null @@ -1,159 +0,0 @@ -/* - * Copyright 2018 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_SNAPSHOT_METADATA_H_ -#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_SNAPSHOT_METADATA_H_ - -#include -#include - -namespace firebase { -namespace firestore { - -/** Metadata about a snapshot, describing the state of the snapshot. */ -class SnapshotMetadata final { - public: - /** - * Constructs a SnapshotMetadata that has all of its boolean members set to - * false. - */ - SnapshotMetadata() = default; - - /** - * Constructs a SnapshotMetadata by providing boolean parameters that describe - * the state of the snapshot. - * - * @param has_pending_writes Whether there is any pending write on the - * snapshot. - * @param is_from_cache Whether the snapshot is from cache instead of backend. - */ - SnapshotMetadata(bool has_pending_writes, bool is_from_cache) - : has_pending_writes_(has_pending_writes), - is_from_cache_(is_from_cache) {} - - /** - * @brief Copy constructor. - * - * This performs a deep copy, creating an independent instance. - * - * @note This class is currently trivially copyable, but it is not guaranteed - * to stay that way, and code relying on this might be broken by a future - * release. - * - * @param[in] other `SnapshotMetadata` to copy from. - */ - SnapshotMetadata(const SnapshotMetadata& other) = default; - - /** - * @brief Move constructor, equivalent to copying. - * - * After being moved from, `SnapshotMetadata` is in a valid but unspecified - * state. - * - * @param[in] other `SnapshotMetadata` to move data from. - */ - SnapshotMetadata(SnapshotMetadata&& other) = default; - - /** - * @brief Copy assignment operator. - * - * This performs a deep copy, creating an independent instance. - * - * @note This class is currently trivially copyable, but it is not guaranteed - * to stay that way, and code relying on this might be broken by a future - * release. - * - * @param[in] other `SnapshotMetadata` to copy from. - * - * @return Reference to the destination `SnapshotMetadata`. - */ - SnapshotMetadata& operator=(const SnapshotMetadata& other) = default; - - /** - * @brief Move assignment operator, equivalent to copying. - * - * After being moved from, `SnapshotMetadata` is in a valid but unspecified - * state. - * - * @param[in] other `SnapshotMetadata` to move data from. - * - * @return Reference to the destination `SnapshotMetadata`. - */ - SnapshotMetadata& operator=(SnapshotMetadata&& other) = default; - - /** - * Returns whether the snapshot contains the result of local writes. - * - * @return true if the snapshot contains the result of local writes (for - * example, Set() or Update() calls) that have not yet been committed to the - * backend. If your listener has opted into metadata updates (via - * MetadataChanges::kInclude) you will receive another snapshot with - * has_pending_writes() equal to false once the writes have been committed to - * the backend. - */ - bool has_pending_writes() const { return has_pending_writes_; } - - /** - * Returns whether the snapshot was created from cached data. - * - * @return true if the snapshot was created from cached data rather than - * guaranteed up-to-date server data. If your listener has opted into metadata - * updates (via MetadataChanges::kInclude) you will receive another snapshot - * with is_from_cache() equal to false once the client has received up-to-date - * data from the backend. - */ - bool is_from_cache() const { return is_from_cache_; } - - /** - * Returns a string representation of this `SnapshotMetadata` for - * logging/debugging purposes. - * - * @note the exact string representation is unspecified and subject to - * change; don't rely on the format of the string. - */ - std::string ToString() const; - - /** - * Outputs the string representation of this `SnapshotMetadata` to the given - * stream. - * - * @see `ToString()` for comments on the representation format. - */ - friend std::ostream& operator<<(std::ostream& out, - const SnapshotMetadata& metadata); - - private: - bool has_pending_writes_ = false; - bool is_from_cache_ = false; -}; - -/** Checks `lhs` and `rhs` for equality. */ -inline bool operator==(const SnapshotMetadata& lhs, - const SnapshotMetadata& rhs) { - return lhs.has_pending_writes() == rhs.has_pending_writes() && - lhs.is_from_cache() == rhs.is_from_cache(); -} - -/** Checks `lhs` and `rhs` for inequality. */ -inline bool operator!=(const SnapshotMetadata& lhs, - const SnapshotMetadata& rhs) { - return !(lhs == rhs); -} - -} // namespace firestore -} // namespace firebase - -#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_SNAPSHOT_METADATA_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/source.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/source.h deleted file mode 100644 index 743106d9e578..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/source.h +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright 2018 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_SOURCE_H_ -#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_SOURCE_H_ - -namespace firebase { -namespace firestore { - -/** - * @brief Configures the behavior of DocumentReference::Get() and Query::Get(). - * - * By providing a Source value, these methods can be configured to fetch results - * only from the server, only from the local cache, or attempt to fetch results - * from the server and fall back to the cache (which is the default). - */ -enum class Source { - /** - * Causes Firestore to try to retrieve an up-to-date (server-retrieved) - * snapshot, but fall back to returning cached data if the server can't be - * reached. - */ - kDefault, - - /** - * Causes Firestore to avoid the cache, generating an error if the server - * cannot be reached. Note that the cache will still be updated if the server - * request succeeds. Also note that latency-compensation still takes effect, - * so any pending write operations will be visible in the returned data - * (merged into the server-provided data). - */ - kServer, - - /** - * Causes Firestore to immediately return a value from the cache, ignoring the - * server completely (implying that the returned value may be stale with - * respect to the value on the server). If there is no data in the cache to - * satisfy the DocumentReference::Get() call will return an error and - * Query::Get() will return an empty QuerySnapshot with no documents. - */ - kCache, -}; - -} // namespace firestore -} // namespace firebase -#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_SOURCE_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/timestamp.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/timestamp.h deleted file mode 100644 index e806bb87c136..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/timestamp.h +++ /dev/null @@ -1,252 +0,0 @@ -/* - * Copyright 2018 Google - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIRESTORE_CORE_INCLUDE_FIREBASE_FIRESTORE_TIMESTAMP_H_ -#define FIRESTORE_CORE_INCLUDE_FIREBASE_FIRESTORE_TIMESTAMP_H_ - -#include -#include -#include -#include - -#if !defined(_STLPORT_VERSION) -#include // NOLINT(build/c++11) -#endif // !defined(_STLPORT_VERSION) - -namespace firebase { - -/** - * A Timestamp represents a point in time independent of any time zone or - * calendar, represented as seconds and fractions of seconds at nanosecond - * resolution in UTC Epoch time. It is encoded using the Proleptic Gregorian - * Calendar which extends the Gregorian calendar backwards to year one. It is - * encoded assuming all minutes are 60 seconds long, i.e. leap seconds are - * "smeared" so that no leap second table is needed for interpretation. Range is - * from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.999999999Z. - * - * @see - * https://github.com/google/protobuf/blob/master/src/google/protobuf/timestamp.proto - */ -class Timestamp { - public: - /** - * Creates a new timestamp representing the epoch (with seconds and - * nanoseconds set to 0). - */ - Timestamp() = default; - - /** - * Creates a new timestamp. - * - * @param seconds The number of seconds of UTC time since Unix epoch - * 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to - * 9999-12-31T23:59:59Z inclusive; otherwise, assertion failure will be - * triggered. - * @param nanoseconds The non-negative fractions of a second at nanosecond - * resolution. Negative second values with fractions must still have - * non-negative nanoseconds values that count forward in time. Must be - * from 0 to 999,999,999 inclusive; otherwise, assertion failure will be - * triggered. - */ - Timestamp(int64_t seconds, int32_t nanoseconds); - - /** Copy constructor, `Timestamp` is trivially copyable. */ - Timestamp(const Timestamp& other) = default; - - /** Move constructor, equivalent to copying. */ - Timestamp(Timestamp&& other) = default; - - /** Copy assignment operator, `Timestamp` is trivially copyable. */ - Timestamp& operator=(const Timestamp& other) = default; - - /** Move assignment operator, equivalent to copying. */ - Timestamp& operator=(Timestamp&& other) = default; - - /** - * Creates a new timestamp with the current date. - * - * The precision is up to nanoseconds, depending on the system clock. - * - * @return a new timestamp representing the current date. - */ - static Timestamp Now(); - - /** - * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z. - */ - int64_t seconds() const { - return seconds_; - } - - /** - * The non-negative fractions of a second at nanosecond resolution. Negative - * second values with fractions still have non-negative nanoseconds values - * that count forward in time. - */ - int32_t nanoseconds() const { - return nanoseconds_; - } - - /** - * Converts `time_t` to a `Timestamp`. - * - * @param seconds_since_unix_epoch - * @parblock - * The number of seconds of UTC time since Unix epoch - * 1970-01-01T00:00:00Z. Can be negative to represent dates before the - * epoch. Must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z - * inclusive; otherwise, assertion failure will be triggered. - * - * Note that while the epoch of `time_t` is unspecified, it's usually Unix - * epoch. If this assumption is broken, this function will produce - * incorrect results. - * @endparblock - * - * @return a new timestamp with the given number of seconds and zero - * nanoseconds. - */ - static Timestamp FromTimeT(time_t seconds_since_unix_epoch); - -#if !defined(_STLPORT_VERSION) - /** - * Converts `std::chrono::time_point` to a `Timestamp`. - * - * @param time_point - * @parblock - * The time point with system clock's epoch, which is - * presumed to be Unix epoch 1970-01-01T00:00:00Z. Can be negative to - * represent dates before the epoch. Must be from 0001-01-01T00:00:00Z to - * 9999-12-31T23:59:59Z inclusive; otherwise, assertion failure will be - * triggered. - * - * Note that while the epoch of `std::chrono::system_clock` is - * unspecified, it's usually Unix epoch. If this assumption is broken, - * this constructor will produce incorrect results. - * @endparblock - */ - static Timestamp FromTimePoint( - std::chrono::time_point time_point); - - /** - * Converts this `Timestamp` to a `time_point`. - * - * Important: if overflow would occur, the returned value will be the maximum - * or minimum value that `Duration` can hold. Note in particular that `long - * long` is insufficient to hold the full range of `Timestamp` values with - * nanosecond precision (which is why `Duration` defaults to `microseconds`). - */ - template - std::chrono::time_point ToTimePoint() const; -#endif // !defined(_STLPORT_VERSION) - - /** - * Returns a string representation of this `Timestamp` for logging/debugging - * purposes. - * - * @note: the exact string representation is unspecified and subject to - * change; don't rely on the format of the string. - */ - std::string ToString() const; - - /** - * Outputs the string representation of this `Timestamp` to the given stream. - * - * @see `ToString()` for comments on the representation format. - */ - friend std::ostream& operator<<(std::ostream& out, - const Timestamp& timestamp); - - private: - // Checks that the number of seconds is within the supported date range, and - // that nanoseconds satisfy 0 <= ns <= 1second. - void ValidateBounds() const; - - int64_t seconds_ = 0; - int32_t nanoseconds_ = 0; -}; - -/** Checks whether `lhs` and `rhs` are in ascending order. */ -inline bool operator<(const Timestamp& lhs, const Timestamp& rhs) { - return lhs.seconds() < rhs.seconds() || - (lhs.seconds() == rhs.seconds() && - lhs.nanoseconds() < rhs.nanoseconds()); -} - -/** Checks whether `lhs` and `rhs` are in descending order. */ -inline bool operator>(const Timestamp& lhs, const Timestamp& rhs) { - return rhs < lhs; -} - -/** Checks whether `lhs` and `rhs` are in non-ascending order. */ -inline bool operator>=(const Timestamp& lhs, const Timestamp& rhs) { - return !(lhs < rhs); -} - -/** Checks whether `lhs` and `rhs` are in non-descending order. */ -inline bool operator<=(const Timestamp& lhs, const Timestamp& rhs) { - return !(lhs > rhs); -} - -/** Checks `lhs` and `rhs` for inequality. */ -inline bool operator!=(const Timestamp& lhs, const Timestamp& rhs) { - return lhs < rhs || lhs > rhs; -} - -/** Checks `lhs` and `rhs` for equality. */ -inline bool operator==(const Timestamp& lhs, const Timestamp& rhs) { - return !(lhs != rhs); -} - -#if !defined(_STLPORT_VERSION) - -// Make sure the header compiles even when included after `` without -// `NOMINMAX` defined. `push/pop_macro` pragmas are supported by Visual Studio -// as well as Clang and GCC. -#pragma push_macro("min") -#pragma push_macro("max") -#undef min -#undef max - -template -std::chrono::time_point Timestamp::ToTimePoint() const { - namespace chr = std::chrono; - using TimePoint = chr::time_point; - - // Saturate on overflow - const auto max_seconds = chr::duration_cast(Duration::max()); - if (seconds_ > 0 && max_seconds.count() <= seconds_) { - return TimePoint{Duration::max()}; - } - const auto min_seconds = chr::duration_cast(Duration::min()); - if (seconds_ < 0 && min_seconds.count() >= seconds_) { - return TimePoint{Duration::min()}; - } - - const auto seconds = chr::duration_cast(chr::seconds(seconds_)); - const auto nanoseconds = - chr::duration_cast(chr::nanoseconds(nanoseconds_)); - return TimePoint{seconds + nanoseconds}; -} - -#pragma pop_macro("max") -#pragma pop_macro("min") - -#endif // !defined(_STLPORT_VERSION) - -} // namespace firebase - -#endif // FIRESTORE_CORE_INCLUDE_FIREBASE_FIRESTORE_TIMESTAMP_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/transaction.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/transaction.h deleted file mode 100644 index af78e0a2fb70..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/transaction.h +++ /dev/null @@ -1,143 +0,0 @@ -/* - * Copyright 2018 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_TRANSACTION_H_ -#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_TRANSACTION_H_ - -#include - -#include "firebase/firestore/firestore_errors.h" -#include "firebase/firestore/map_field_value.h" -#include "firebase/firestore/set_options.h" - -namespace firebase { -namespace firestore { - -class DocumentReference; -class DocumentSnapshot; -class TransactionInternal; - -/** - * @brief Transaction provides methods to read and write data within - * a transaction. - * - * You cannot create a `Transaction` directly; use `Firestore::RunTransaction()` - * function instead. - * - * @note Firestore classes are not meant to be subclassed except for use in test - * mocks. Subclassing is not supported in production code and new SDK releases - * may break code that does so. - */ -class Transaction { - public: - /** Destructor. */ - virtual ~Transaction(); - - /** - * @brief Deleted copy constructor. - * - * A `Transaction` object is only valid for the duration of the callback you - * pass to `Firestore::RunTransaction()` and cannot be copied. - */ - Transaction(const Transaction& other) = delete; - - /** - * @brief Deleted copy assignment operator. - * - * A `Transaction` object is only valid for the duration of the callback you - * pass to `Firestore::RunTransaction()` and cannot be copied. - */ - Transaction& operator=(const Transaction& other) = delete; - - /** - * @brief Writes to the document referred to by the provided reference. - * - * If the document does not yet exist, it will be created. If you pass - * SetOptions, the provided data can be merged into an existing document. - * - * @param[in] document The DocumentReference to overwrite. - * @param[in] data A map of the fields and values to write to the document. - * @param[in] options An object to configure the Set() behavior (optional). - */ - virtual void Set(const DocumentReference& document, - const MapFieldValue& data, - const SetOptions& options = SetOptions()); - - /** - * Updates fields in the document referred to by the provided reference. If no - * document exists yet, the update will fail. - * - * @param[in] document The DocumentReference to update. - * @param[in] data A map of field / value pairs to update. Fields can contain - * dots to reference nested fields within the document. - */ - virtual void Update(const DocumentReference& document, - const MapFieldValue& data); - - /** - * Updates fields in the document referred to by the provided reference. If no - * document exists yet, the update will fail. - * - * @param[in] document The DocumentReference to update. - * @param[in] data A map from FieldPath to FieldValue to update. - */ - virtual void Update(const DocumentReference& document, - const MapFieldPathValue& data); - - /** - * Deletes the document referred to by the provided reference. - * - * @param[in] document The DocumentReference to delete. - */ - virtual void Delete(const DocumentReference& document); - - /** - * Reads the document referred by the provided reference. - * - * @param[in] document The DocumentReference to read. - * @param[out] error_code An out parameter to capture an error, if one - * occurred. - * @param[out] error_message An out parameter to capture error message, if - * any. - * @return The contents of the document at this DocumentReference or invalid - * DocumentSnapshot if there is any error. - */ - virtual DocumentSnapshot Get(const DocumentReference& document, - Error* error_code, - std::string* error_message); - - protected: - /** - * Default constructor, to be used only for mocking a `Transaction`. - */ - Transaction() = default; - - private: - friend class FirestoreInternal; - friend class TransactionInternal; - friend struct ConverterImpl; - template - friend struct CleanupFn; - - explicit Transaction(TransactionInternal* internal); - - mutable TransactionInternal* internal_ = nullptr; -}; - -} // namespace firestore -} // namespace firebase - -#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_TRANSACTION_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/transaction_options.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/transaction_options.h deleted file mode 100644 index 9433578879b3..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/transaction_options.h +++ /dev/null @@ -1,137 +0,0 @@ -/* - * Copyright 2022 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_TRANSACTION_OPTIONS_H_ -#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_TRANSACTION_OPTIONS_H_ - -#include -#include -#include - -namespace firebase { -namespace firestore { - -/** - * Options to customize transaction behavior for `Firestore.runTransaction()`. - */ -class TransactionOptions final { - public: - /** - * @brief Creates the default `TransactionOptions`. - */ - TransactionOptions() = default; - - /** - * @brief Copy constructor. - * - * This performs a deep copy, creating an independent instance. - * - * @param[in] other `TransactionOptions` to copy from. - */ - TransactionOptions(const TransactionOptions& other) = default; - - /** - * @brief Move constructor. - * - * Moving is not any more efficient than copying for `TransactionOptions` - * because this class is trivially copyable; however, future additions to this - * class may make it not trivially copyable, at which point moving would be - * more efficient than copying. After being moved from, `TransactionOptions` - * is in a valid but unspecified state. - * - * @param[in] other `TransactionOptions` to move data from. - */ - TransactionOptions(TransactionOptions&& other) = default; - - /** - * @brief Copy assignment operator. - * - * This performs a deep copy, creating an independent instance. - * - * @param[in] other `TransactionOptions` to copy from. - * - * @return Reference to the destination `TransactionOptions`. - */ - TransactionOptions& operator=(const TransactionOptions& other) = default; - - /** - * @brief Move assignment operator. - * - * Moving is not any more efficient than copying for `TransactionOptions` - * because this class is trivially copyable; however, future additions to this - * class may make it not trivially copyable, at which point moving would be - * more efficient than copying. After being moved from, `TransactionOptions` - * is in a valid but unspecified state. - * - * @param[in] other `TransactionOptions` to move data from. - * - * @return Reference to the destination `TransactionOptions`. - */ - TransactionOptions& operator=(TransactionOptions&& other) = default; - - /** - * @brief Gets the maximum number of attempts to commit, after which the - * transaction fails. - * - * The default value is 5. - */ - int32_t max_attempts() const { return max_attempts_; } - - /** - * @brief Sets the maximum number of attempts to commit, after which the - * transaction fails. - * - * The default value is 5. - * - * @param[in] max_attempts The maximum number of attempts; must be greater - * than zero. - */ - void set_max_attempts(int32_t max_attempts); - - /** - * Returns a string representation of this `TransactionOptions` object for - * logging/debugging purposes. - * - * @note the exact string representation is unspecified and subject to - * change; don't rely on the format of the string. - */ - std::string ToString() const; - - /** - * Outputs the string representation of this `TransactionOptions` object to - * the given stream. - * - * @see `ToString()` for comments on the representation format. - */ - friend std::ostream& operator<<(std::ostream&, const TransactionOptions&); - - private: - int32_t max_attempts_ = 5; -}; - -/** Compares two `TransactionOptions` objects for equality. */ -bool operator==(const TransactionOptions&, const TransactionOptions&); - -/** Compares two `TransactionOptions` objects for inequality. */ -inline bool operator!=(const TransactionOptions& lhs, - const TransactionOptions& rhs) { - return !(lhs == rhs); -} - -} // namespace firestore -} // namespace firebase - -#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_TRANSACTION_OPTIONS_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/write_batch.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/write_batch.h deleted file mode 100644 index 1e92cd693516..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/write_batch.h +++ /dev/null @@ -1,188 +0,0 @@ -/* - * Copyright 2018 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_WRITE_BATCH_H_ -#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_WRITE_BATCH_H_ - -#include "firebase/firestore/map_field_value.h" -#include "firebase/firestore/set_options.h" - -namespace firebase { - -/// @cond FIREBASE_APP_INTERNAL -template -class Future; -/// @endcond - -namespace firestore { - -class DocumentReference; -class WriteBatchInternal; - -/** - * @brief A write batch is used to perform multiple writes as a single atomic - * unit. - * - * A WriteBatch object provides methods for adding writes to the write batch. - * None of the writes will be committed (or visible locally) until Commit() is - * called. - * - * Unlike transactions, write batches are persisted offline and therefore are - * preferable when you don't need to condition your writes on read data. - * - * @note Firestore classes are not meant to be subclassed except for use in test - * mocks. Subclassing is not supported in production code and new SDK releases - * may break code that does so. - */ -class WriteBatch { - public: - /** - * @brief Creates an invalid WriteBatch that has to be reassigned before it - * can be used. - * - * Calling any member function on an invalid WriteBatch will be a no-op. If - * the function returns a value, it will return a zero, empty, or invalid - * value, depending on the type of the value. - */ - WriteBatch(); - - /** - * @brief Copy constructor. - * - * This performs a deep copy, creating an independent instance. - * - * @param[in] other `WriteBatch` to copy from. - */ - WriteBatch(const WriteBatch& other); - - /** - * @brief Move constructor. - * - * Moving is more efficient than copying for a `WriteBatch`. After being moved - * from, a `WriteBatch` is equivalent to its default-constructed state. - * - * @param[in] other `WriteBatch` to move data from. - */ - WriteBatch(WriteBatch&& other); - - virtual ~WriteBatch(); - - /** - * @brief Copy assignment operator. - * - * This performs a deep copy, creating an independent instance. - * - * @param[in] other `WriteBatch` to copy from. - * - * @return Reference to the destination `WriteBatch`. - */ - WriteBatch& operator=(const WriteBatch& other); - - /** - * @brief Move assignment operator. - * - * Moving is more efficient than copying for a `WriteBatch`. After being moved - * from, a `WriteBatch` is equivalent to its default-constructed state. - * - * @param[in] other `WriteBatch` to move data from. - * - * @return Reference to the destination `WriteBatch`. - */ - WriteBatch& operator=(WriteBatch&& other); - - /** - * @brief Writes to the document referred to by the provided reference. - * - * If the document does not yet exist, it will be created. If you pass - * SetOptions, the provided data can be merged into an existing document. - * - * @param document The DocumentReference to write to. - * @param data A map of the fields and values to write to the document. - * @param[in] options An object to configure the Set() behavior (optional). - * - * @return This WriteBatch instance. Used for chaining method calls. - */ - virtual WriteBatch& Set(const DocumentReference& document, - const MapFieldValue& data, - const SetOptions& options = SetOptions()); - - /** - * Updates fields in the document referred to by the provided reference. If no - * document exists yet, the update will fail. - * - * @param document The DocumentReference to update. - * @param data A map of field / value pairs to update. Fields can contain dots - * to reference nested fields within the document. - * @return This WriteBatch instance. Used for chaining method calls. - */ - virtual WriteBatch& Update(const DocumentReference& document, - const MapFieldValue& data); - - /** - * Updates fields in the document referred to by the provided reference. If no - * document exists yet, the update will fail. - * - * @param document The DocumentReference to update. - * @param data A map from FieldPath to FieldValue to update. - * @return This WriteBatch instance. Used for chaining method calls. - */ - virtual WriteBatch& Update(const DocumentReference& document, - const MapFieldPathValue& data); - - /** - * Deletes the document referred to by the provided reference. - * - * @param document The DocumentReference to delete. - * @return This WriteBatch instance. Used for chaining method calls. - */ - virtual WriteBatch& Delete(const DocumentReference& document); - - /** - * Commits all of the writes in this write batch as a single atomic unit. - * - * @return A Future that will be resolved when the write finishes. - */ - virtual Future Commit(); - - /** - * @brief Returns true if this `WriteBatch` is valid, false if it is not - * valid. An invalid `WriteBatch` could be the result of: - * - Creating a `WriteBatch` using the default constructor. - * - Moving from the `WriteBatch`. - * - Deleting your Firestore instance, which will invalidate all the - * `WriteBatch` instances associated with it. - * - * @return true if this `WriteBatch` is valid, false if this `WriteBatch` is - * invalid. - */ - bool is_valid() const { return internal_ != nullptr; } - - private: - friend class FirestoreInternal; - friend class WriteBatchInternal; - friend struct ConverterImpl; - template - friend struct CleanupFn; - - explicit WriteBatch(WriteBatchInternal* internal); - - mutable WriteBatchInternal* internal_ = nullptr; -}; - -} // namespace firestore -} // namespace firebase - -#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_WRITE_BATCH_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/functions.h b/packages/firebase_core/firebase_core/firebase_core/firebase/functions.h deleted file mode 100644 index 500a05cc7ae9..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/functions.h +++ /dev/null @@ -1,115 +0,0 @@ -// Copyright 2017 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef FIREBASE_FUNCTIONS_SRC_INCLUDE_FIREBASE_FUNCTIONS_H_ -#define FIREBASE_FUNCTIONS_SRC_INCLUDE_FIREBASE_FUNCTIONS_H_ - -#include - -#include "firebase/app.h" -#include "firebase/functions/callable_reference.h" -#include "firebase/functions/callable_result.h" -#include "firebase/functions/common.h" - -namespace firebase { - -/// Namespace for the Firebase C++ SDK for Cloud Functions. -namespace functions { - -/// @cond FIREBASE_APP_INTERNAL -namespace internal { -class FunctionsInternal; -} // namespace internal -/// @endcond - -class FunctionsReference; - -#ifndef SWIG -/// @brief Entry point for the Firebase C++ SDK for Cloud Functions. -/// -/// To use the SDK, call firebase::functions::Functions::GetInstance() to -/// obtain an instance of Functions, then use GetHttpsCallable() to obtain -/// references to callable functions. From there you can call them with -/// CallableReference::Call(). -#endif // SWIG -class Functions { - public: - /// @brief Destructor. You may delete an instance of Functions when - /// you are finished using it, to shut down the Functions library. - ~Functions(); - - /// @brief Get an instance of Functions corresponding to the given App. - /// - /// Cloud Functions uses firebase::App to communicate with Firebase - /// Authentication to authenticate users to the server backend. - /// - /// @param[in] app An instance of firebase::App. Cloud Functions will use - /// this to communicate with Firebase Authentication. - /// @param[out] init_result_out Optional: If provided, write the init result - /// here. Will be set to kInitResultSuccess if initialization succeeded, or - /// kInitResultFailedMissingDependency on Android if Google Play services is - /// not available on the current device. - /// - /// @returns An instance of Functions corresponding to the given App. - static Functions* GetInstance(::firebase::App* app, - InitResult* init_result_out = nullptr); - - /// @brief Get an instance of Functions corresponding to the given App. - /// - /// Cloud Functions uses firebase::App to communicate with Firebase - /// Authentication to authenticate users to the server backend. - /// - /// @param[in] app An instance of firebase::App. Cloud Functions will use - /// this to communicate with Firebase Authentication. - /// @param[in] region The region to call functions in. - /// @param[out] init_result_out Optional: If provided, write the init result - /// here. Will be set to kInitResultSuccess if initialization succeeded, or - /// kInitResultFailedMissingDependency on Android if Google Play services is - /// not available on the current device. - /// - /// @returns An instance of Functions corresponding to the given App. - static Functions* GetInstance(::firebase::App* app, const char* region, - InitResult* init_result_out = nullptr); - - /// @brief Get the firebase::App that this Functions was created with. - /// - /// @returns The firebase::App this Functions was created with. - ::firebase::App* app(); - - /// @brief Get a FunctionsReference for the specified path. - HttpsCallableReference GetHttpsCallable(const char* name) const; - - /// @brief Get a FunctionsReference for the specified URL. - HttpsCallableReference GetHttpsCallableFromURL(const char* url) const; - - /// @brief Sets an origin for a Cloud Functions emulator to use. - void UseFunctionsEmulator(const char* origin); - - private: - /// @cond FIREBASE_APP_INTERNAL - Functions(::firebase::App* app, const char* region); - Functions(const Functions& src); - Functions& operator=(const Functions& src); - - // Delete the internal_ data. - void DeleteInternal(); - - internal::FunctionsInternal* internal_; - /// @endcond -}; - -} // namespace functions -} // namespace firebase - -#endif // FIREBASE_FUNCTIONS_SRC_INCLUDE_FIREBASE_FUNCTIONS_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/functions/callable_reference.h b/packages/firebase_core/firebase_core/firebase_core/firebase/functions/callable_reference.h deleted file mode 100644 index 9641c23564df..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/functions/callable_reference.h +++ /dev/null @@ -1,124 +0,0 @@ -// Copyright 2017 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef FIREBASE_FUNCTIONS_SRC_INCLUDE_FIREBASE_FUNCTIONS_CALLABLE_REFERENCE_H_ -#define FIREBASE_FUNCTIONS_SRC_INCLUDE_FIREBASE_FUNCTIONS_CALLABLE_REFERENCE_H_ - -#include -#include - -#include "firebase/future.h" -#include "firebase/internal/common.h" - -namespace firebase { -class Variant; - -namespace functions { -class Functions; -class HttpsCallableResult; - -/// @cond FIREBASE_APP_INTERNAL -namespace internal { -class HttpsCallableReferenceInternal; -} // namespace internal -/// @endcond - -#ifndef SWIG -/// Represents a reference to a Cloud Functions object. -/// Developers can call HTTPS Callable Functions. -#endif // SWIG -class HttpsCallableReference { - public: - /// @brief Default constructor. This creates an invalid - /// HttpsCallableReference. Attempting to perform any operations on this - /// reference will fail unless a valid HttpsCallableReference has been - /// assigned to it. - HttpsCallableReference() : internal_(nullptr) {} - - ~HttpsCallableReference(); - - /// @brief Copy constructor. It's totally okay (and efficient) to copy - /// HttpsCallableReference instances, as they simply point to the same - /// location. - /// - /// @param[in] reference HttpsCallableReference to copy from. - HttpsCallableReference(const HttpsCallableReference& reference); - - /// @brief Copy assignment operator. It's totally okay (and efficient) to copy - /// HttpsCallableReference instances, as they simply point to the same - /// location. - /// - /// @param[in] reference HttpsCallableReference to copy from. - /// - /// @returns Reference to the destination HttpsCallableReference. - HttpsCallableReference& operator=(const HttpsCallableReference& reference); - -#if defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) - /// @brief Move constructor. Moving is an efficient operation for - /// HttpsCallableReference instances. - /// - /// @param[in] other HttpsCallableReference to move data from. - HttpsCallableReference(HttpsCallableReference&& other); - - /// @brief Move assignment operator. Moving is an efficient operation for - /// HttpsCallableReference instances. - /// - /// @param[in] other HttpsCallableReference to move data from. - /// - /// @returns Reference to the destination HttpsCallableReference. - HttpsCallableReference& operator=(HttpsCallableReference&& other); -#endif // defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) - - /// @brief Gets the firebase::functions::Functions instance to which we refer. - /// - /// The pointer will remain valid indefinitely. - /// - /// @returns The firebase::functions::Functions instance that this - /// HttpsCallableReference refers to. - Functions* functions(); - - /// @brief Calls the function. - /// - /// @returns The result of the call; - Future Call(); - - /// @brief Calls the function. - /// - /// @param[in] data The params to pass to the function. - /// @returns The result of the call; - Future Call(const Variant& data); - - /// @brief Returns true if this HttpsCallableReference is valid, false if it - /// is not valid. An invalid HttpsCallableReference indicates that the - /// reference is uninitialized (created with the default constructor) or that - /// there was an error retrieving the reference. - /// - /// @returns true if this HttpsCallableReference is valid, false if this - /// HttpsCallableReference is invalid. - bool is_valid() const; - - private: - /// @cond FIREBASE_APP_INTERNAL - friend class Functions; - - HttpsCallableReference(internal::HttpsCallableReferenceInternal* internal); - - internal::HttpsCallableReferenceInternal* internal_; - /// @endcond -}; - -} // namespace functions -} // namespace firebase - -#endif // FIREBASE_FUNCTIONS_SRC_INCLUDE_FIREBASE_FUNCTIONS_CALLABLE_REFERENCE_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/functions/callable_result.h b/packages/firebase_core/firebase_core/firebase_core/firebase/functions/callable_result.h deleted file mode 100644 index 5186377ae828..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/functions/callable_result.h +++ /dev/null @@ -1,96 +0,0 @@ -// Copyright 2018 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef FIREBASE_FUNCTIONS_SRC_INCLUDE_FIREBASE_FUNCTIONS_CALLABLE_RESULT_H_ -#define FIREBASE_FUNCTIONS_SRC_INCLUDE_FIREBASE_FUNCTIONS_CALLABLE_RESULT_H_ - -#include "firebase/functions/common.h" -#include "firebase/variant.h" - -namespace firebase { -namespace functions { - -/// @cond FIREBASE_APP_INTERNAL -namespace internal { -class HttpsCallableReferenceInternal; -} -/// @endcond - -/// An HttpsCallableResult contains the result of calling an HttpsCallable. -class HttpsCallableResult { - public: - /// @brief Creates an HttpsCallableResult with null data. - HttpsCallableResult() {} - - ~HttpsCallableResult() {} - - /// @brief Copy constructor. Copying is as efficient as copying a Variant. - /// - /// @param[in] other HttpsCallableResult to copy data from. - HttpsCallableResult(const HttpsCallableResult& other) : data_(other.data_) {} - - /// @brief Assignment operator. Copying is as efficient as copying a Variant. - /// - /// @param[in] other HttpsCallableResult to copy data from. - /// - /// @returns Reference to the destination HttpsCallableResult. - HttpsCallableResult& operator=(const HttpsCallableResult& other) { - data_ = other.data_; - return *this; - } - -#if defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) - /// @brief Move constructor. Moving is an efficient operation for - /// HttpsCallableResult instances. - /// - /// @param[in] other HttpsCallableResult to move data from. - HttpsCallableResult(HttpsCallableResult&& other) { - data_ = std::move(other.data_); - } - - /// @brief Move assignment operator. Moving is an efficient operation for - /// HttpsCallableResult instances. - /// - /// @param[in] other HttpsCallableResult to move data from. - /// - /// @returns Reference to the destination HttpsCallableResult. - HttpsCallableResult& operator=(HttpsCallableResult&& other) { - data_ = std::move(other.data_); - return *this; - } - -#endif // defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) - - /// @brief Returns the data that is the result of a Call. - /// - /// @returns The variant containing the data. - const Variant& data() const { return data_; } - - private: - /// @cond FIREBASE_APP_INTERNAL - // Only functions are allowed to construct results. - friend class ::firebase::functions::internal::HttpsCallableReferenceInternal; - HttpsCallableResult(const Variant& data) : data_(data) {} -#if defined(FIREBASE_USE_MOVE_OPERATORS) - HttpsCallableResult(Variant&& data) : data_(std::move(data)) {} -#endif // defined(FIREBASE_USE_MOVE_OPERATORS) - - Variant data_; - /// @endcond -}; - -} // namespace functions -} // namespace firebase - -#endif // FIREBASE_FUNCTIONS_SRC_INCLUDE_FIREBASE_FUNCTIONS_CALLABLE_RESULT_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/functions/common.h b/packages/firebase_core/firebase_core/firebase_core/firebase/functions/common.h deleted file mode 100644 index 143dc8257618..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/functions/common.h +++ /dev/null @@ -1,202 +0,0 @@ -// Copyright 2017 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef FIREBASE_FUNCTIONS_SRC_INCLUDE_FIREBASE_FUNCTIONS_COMMON_H_ -#define FIREBASE_FUNCTIONS_SRC_INCLUDE_FIREBASE_FUNCTIONS_COMMON_H_ - -#include "firebase/variant.h" - -namespace firebase { -namespace functions { - -/// Error code returned by Cloud Functions C++ functions. -/// Standard gRPC error codes, as defined in: -/// https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto -enum Error { -#ifdef INTERNAL_EXPERIMENTAL -// LINT.IfChange -#endif // INTERNAL_EXPERIMENTAL - - // Not an error; returned on success - // - // HTTP Mapping: 200 OK - kErrorNone = 0, - - // The operation was cancelled, typically by the caller. - // - // HTTP Mapping: 499 Client Closed Request - kErrorCancelled = 1, - - // Unknown error. For example, this error may be returned when - // a `Status` value received from another address space belongs to - // an error space that is not known in this address space. Also - // errors raised by APIs that do not return enough error information - // may be converted to this error. - // - // HTTP Mapping: 500 Internal Server Error - kErrorUnknown = 2, - - // The client specified an invalid argument. Note that this differs - // from `FAILED_PRECONDITION`. `INVALID_ARGUMENT` indicates arguments - // that are problematic regardless of the state of the system - // (e.g., a malformed file name). - // - // HTTP Mapping: 400 Bad Request - kErrorInvalidArgument = 3, - - // The deadline expired before the operation could complete. For operations - // that change the state of the system, this error may be returned - // even if the operation has completed successfully. For example, a - // successful response from a server could have been delayed long - // enough for the deadline to expire. - // - // HTTP Mapping: 504 Gateway Timeout - kErrorDeadlineExceeded = 4, - - // Some requested entity (e.g., file or directory) was not found. - // - // Note to server developers: if a request is denied for an entire class - // of users, such as gradual feature rollout or undocumented whitelist, - // `NOT_FOUND` may be used. If a request is denied for some users within - // a class of users, such as user-based access control, `PERMISSION_DENIED` - // must be used. - // - // HTTP Mapping: 404 Not Found - kErrorNotFound = 5, - - // The entity that a client attempted to create (e.g., file or directory) - // already exists. - // - // HTTP Mapping: 409 Conflict - kErrorAlreadyExists = 6, - - // The caller does not have permission to execute the specified - // operation. `PERMISSION_DENIED` must not be used for rejections - // caused by exhausting some resource (use `RESOURCE_EXHAUSTED` - // instead for those errors). `PERMISSION_DENIED` must not be - // used if the caller can not be identified (use `UNAUTHENTICATED` - // instead for those errors). This error code does not imply the - // request is valid or the requested entity exists or satisfies - // other pre-conditions. - // - // HTTP Mapping: 403 Forbidden - kErrorPermissionDenied = 7, - - // The request does not have valid authentication credentials for the - // operation. - // - // HTTP Mapping: 401 Unauthorized - kErrorUnauthenticated = 16, - - // Some resource has been exhausted, perhaps a per-user quota, or - // perhaps the entire file system is out of space. - // - // HTTP Mapping: 429 Too Many Requests - kErrorResourceExhausted = 8, - - // The operation was rejected because the system is not in a state - // required for the operation's execution. For example, the directory - // to be deleted is non-empty, an rmdir operation is applied to - // a non-directory, etc. - // - // Service implementors can use the following guidelines to decide - // between `FAILED_PRECONDITION`, `ABORTED`, and `UNAVAILABLE`: - // (a) Use `UNAVAILABLE` if the client can retry just the failing call. - // (b) Use `ABORTED` if the client should retry at a higher level - // (e.g., when a client-specified test-and-set fails, indicating the - // client should restart a read-modify-write sequence). - // (c) Use `FAILED_PRECONDITION` if the client should not retry until - // the system state has been explicitly fixed. E.g., if an "rmdir" - // fails because the directory is non-empty, `FAILED_PRECONDITION` - // should be returned since the client should not retry unless - // the files are deleted from the directory. - // - // HTTP Mapping: 400 Bad Request - kErrorFailedPrecondition = 9, - - // The operation was aborted, typically due to a concurrency issue such as - // a sequencer check failure or transaction abort. - // - // See the guidelines above for deciding between `FAILED_PRECONDITION`, - // `ABORTED`, and `UNAVAILABLE`. - // - // HTTP Mapping: 409 Conflict - kErrorAborted = 10, - - // The operation was attempted past the valid range. E.g., seeking or - // reading past end-of-file. - // - // Unlike `INVALID_ARGUMENT`, this error indicates a problem that may - // be fixed if the system state changes. For example, a 32-bit file - // system will generate `INVALID_ARGUMENT` if asked to read at an - // offset that is not in the range [0,2^32-1], but it will generate - // `OUT_OF_RANGE` if asked to read from an offset past the current - // file size. - // - // There is a fair bit of overlap between `FAILED_PRECONDITION` and - // `OUT_OF_RANGE`. We recommend using `OUT_OF_RANGE` (the more specific - // error) when it applies so that callers who are iterating through - // a space can easily look for an `OUT_OF_RANGE` error to detect when - // they are done. - // - // HTTP Mapping: 400 Bad Request - kErrorOutOfRange = 11, - - // The operation is not implemented or is not supported/enabled in this - // service. - // - // HTTP Mapping: 501 Not Implemented - kErrorUnimplemented = 12, - - // Internal errors. This means that some invariants expected by the - // underlying system have been broken. This error code is reserved - // for serious errors. - // - // HTTP Mapping: 500 Internal Server Error - kErrorInternal = 13, - - // The service is currently unavailable. This is most likely a - // transient condition, which can be corrected by retrying with - // a backoff. - // - // See the guidelines above for deciding between `FAILED_PRECONDITION`, - // `ABORTED`, and `UNAVAILABLE`. - // - // HTTP Mapping: 503 Service Unavailable - kErrorUnavailable = 14, - - // Unrecoverable data loss or corruption. - // - // HTTP Mapping: 500 Internal Server Error - kErrorDataLoss = 15, - -}; - -#ifdef INTERNAL_EXPERIMENTAL -/// @cond FIREBASE_APP_INTERNAL -namespace internal { - -// Get the human-readable error message corresponding to an error code. -// -// Returns a statically-allocated string describing the error code you pass in. -const char* GetErrorMessage(Error error); - -} // namespace internal -/// @endcond -#endif // INTERNAL_EXPERIMENTAL - -} // namespace functions -} // namespace firebase - -#endif // FIREBASE_FUNCTIONS_SRC_INCLUDE_FIREBASE_FUNCTIONS_COMMON_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/future.h b/packages/firebase_core/firebase_core/firebase_core/firebase/future.h deleted file mode 100644 index 0d09fc079a32..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/future.h +++ /dev/null @@ -1,533 +0,0 @@ -/* - * Copyright 2016 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_APP_SRC_INCLUDE_FIREBASE_FUTURE_H_ -#define FIREBASE_APP_SRC_INCLUDE_FIREBASE_FUTURE_H_ - -#include -#include - -#include - -#include "firebase/internal/common.h" -#include "firebase/internal/mutex.h" - -#ifdef FIREBASE_USE_STD_FUNCTION -#include -#endif - -namespace firebase { - -// Predeclarations. -/// @cond FIREBASE_APP_INTERNAL -namespace detail { -class FutureApiInterface; -class CompletionCallbackHandle; -} // namespace detail -/// @endcond - -/// Asynchronous call status. -enum FutureStatus { - /// Results are ready. - kFutureStatusComplete, - - /// Result is still being processed. - kFutureStatusPending, - - /// No result is pending. - /// FutureBase::Release() or move operator was called. - kFutureStatusInvalid -}; - -/// Handle that the API uses to identify an asynchronous call. -/// The exact interpretation of the handle is up to the API. -typedef uintptr_t FutureHandleId; - -/// Class that provides more context to FutureHandleId, which allows the -/// underlying API to track handles, perform reference counting, etc. -class FutureHandle { - public: - /// @cond FIREBASE_APP_INTERNAL - FutureHandle(); - explicit FutureHandle(FutureHandleId id) : FutureHandle(id, nullptr) {} - FutureHandle(FutureHandleId id, detail::FutureApiInterface* api); - ~FutureHandle(); - - // Copy constructor and assignment operator. - FutureHandle(const FutureHandle& rhs); - FutureHandle& operator=(const FutureHandle& rhs); - -#if defined(FIREBASE_USE_MOVE_OPERATORS) - // Move constructor and assignment operator. - FutureHandle(FutureHandle&& rhs) noexcept; - FutureHandle& operator=(FutureHandle&& rhs) noexcept; -#endif // defined(FIREBASE_USE_MOVE_OPERATORS) - - // Comparison operators. - bool operator!=(const FutureHandle& rhs) const { return !(*this == rhs); } - bool operator==(const FutureHandle& rhs) const { - // Only compare IDs, since the API is irrelevant (comparison will only occur - // within the context of a single API anyway). - return id() == rhs.id(); - } - - FutureHandleId id() const { return id_; } - detail::FutureApiInterface* api() const { return api_; } - - // Detach from the FutureApi. This handle will no longer increment the - // Future's reference count. This is mainly used for testing, so that you can - // still look up the Future based on its handle's ID without affecting the - // reference count yourself. - void Detach(); - - // Called by CleanupNotifier when the API is being deleted. At this point we - // can ignore all of the reference counts since all Future data is about to be - // deleted anyway. - void Cleanup() { api_ = nullptr; } - - private: - FutureHandleId id_; - detail::FutureApiInterface* api_; - /// @endcond -}; - -/// @brief Type-independent return type of asynchronous calls. -/// -/// @see Future for code samples. -/// -/// @cond FIREBASE_APP_INTERNAL -/// Notes: -/// - Futures have pointers back to the API, but the API does not maintain -/// pointers to its Futures. Therefore, all Futures must be destroyed -/// *before* the API is destroyed. -/// - Futures can be moved or copied. Call results are reference counted, -/// and are destroyed when they are no longer referenced by any Futures. -/// - The actual `Status`, `Error`, and `Result` values are kept inside the -/// API. This makes synchronization and data management easier. -/// -/// WARNING: This class should remain POD (plain old data). It should not have -/// virtual methods. Nor should the derived Future class add any -/// data. Internally, we static_cast FutureBase to Future, -/// so the underlying data should remain the same. -/// @endcond -class FutureBase { - public: - /// Function pointer for a completion callback. When we call this, we will - /// send the completed future, along with the user data that you specified - /// when you set up the callback. - typedef void (*CompletionCallback)(const FutureBase& result_data, - void* user_data); - -#if defined(INTERNAL_EXPERIMENTAL) - /// Handle, representing a completion callback, that can be passed to - /// RemoveOnCompletion. - using CompletionCallbackHandle = detail::CompletionCallbackHandle; -#endif - - /// Construct an untyped future. - FutureBase(); - - /// @cond FIREBASE_APP_INTERNAL - - /// Construct an untyped future using the specified API and handle. - /// - /// @param api API class used to provide the future implementation. - /// @param handle Handle to the future. - FutureBase(detail::FutureApiInterface* api, const FutureHandle& handle); - - /// @endcond - - ~FutureBase(); - - /// Copy constructor and operator. - /// Increment the reference count when creating a copy of the future. - FutureBase(const FutureBase& rhs); - - /// Copy an untyped future. - FutureBase& operator=(const FutureBase& rhs); - -#if defined(FIREBASE_USE_MOVE_OPERATORS) - /// Move constructor and operator. - /// Move is more efficient than copy and delete because we don't touch the - /// reference counting in the API. - FutureBase(FutureBase&& rhs) noexcept; - - /// Copy an untyped future. - FutureBase& operator=(FutureBase&& rhs) noexcept; -#endif // defined(FIREBASE_USE_MOVE_OPERATORS) - - /// Explicitly release the internal resources for a future. - /// Future will become invalid. - void Release(); - - /// Completion status of the asynchronous call. - FutureStatus status() const; - - /// When status() is firebase::kFutureStatusComplete, returns the API-defined - /// error code. Otherwise, return value is undefined. - int error() const; - - /// When status() is firebase::kFutureStatusComplete, returns the API-defined - /// error message, as human-readable text, or an empty string if the API does - /// not provide a human readable description of the error. - /// - /// @note The returned pointer is only valid for the lifetime of the Future - /// or its copies. - const char* error_message() const; - - /// Result of the asynchronous call, or nullptr if the result is still - /// pending. Cast is required since GetFutureResult() returns void*. - const void* result_void() const; - -#if defined(INTERNAL_EXPERIMENTAL) - /// Special timeout value indicating an infinite timeout. - /// - /// Passing this value to FutureBase::Wait() or Future::Await() will cause - /// those methods to wait until the future is complete. - /// - /// @Warning It is inadvisable to use this from code that could be called - /// from an event loop. - static const int kWaitTimeoutInfinite; - - /// Block (i.e. suspend the current thread) until either the future is - /// completed or the specified timeout period (in milliseconds) has elapsed. - /// If `timeout_milliseconds` is `kWaitTimeoutInfinite`, then the timeout - /// period is treated as being infinite, i.e. this will block until the - /// future is completed. - /// - /// @return True if the future completed, or - /// false if the timeout period elapsed before the future completed. - bool Wait(int timeout_milliseconds) const; -#endif // defined(INTERNAL_EXPERIMENTAL) - - /// Register a single callback that will be called at most once, when the - /// future is completed. - /// - /// If you call any OnCompletion() method more than once on the same future, - /// only the most recent callback you registered with OnCompletion() will be - /// called. -#if defined(INTERNAL_EXPERIMENTAL) - /// However completions registered with AddCompletion() will still be - /// called even if there is a subsequent call to OnCompletion(). - /// - /// When the future completes, first the most recent callback registered with - /// OnCompletion(), if any, will be called; then all callbacks registered with - /// AddCompletion() will be called, in the order that they were registered. -#endif - /// - /// When your callback is called, the user_data that you supplied here will be - /// passed back as the second parameter. - /// - /// @param[in] callback Function pointer to your callback. - /// @param[in] user_data Optional user data. We will pass this back to your - /// callback. - void OnCompletion(CompletionCallback callback, void* user_data) const; - -#if defined(FIREBASE_USE_STD_FUNCTION) || defined(DOXYGEN) - /// Register a single callback that will be called at most once, when the - /// future is completed. - /// - /// If you call any OnCompletion() method more than once on the same future, - /// only the most recent callback you registered with OnCompletion() will be - /// called. -#if defined(INTERNAL_EXPERIMENTAL) - /// However completions registered with AddCompletion() will still be - /// called even if there is a subsequent call to OnCompletion(). - /// - /// When the future completes, first the most recent callback registered with - /// OnCompletion(), if any, will be called; then all callbacks registered with - /// AddCompletion() will be called, in the order that they were registered. -#endif - /// - /// @param[in] callback Function or lambda to call. - /// - /// @note This method is not available when using STLPort on Android, as - /// `std::function` is not supported on STLPort. - void OnCompletion(std::function callback) const; -#endif // defined(FIREBASE_USE_STD_FUNCTION) || defined(DOXYGEN) - -#if defined(INTERNAL_EXPERIMENTAL) - /// Like OnCompletion, but allows adding multiple callbacks. - /// - /// If you call AddCompletion() more than once, all of the completions that - /// you register will be called, when the future is completed. However, any - /// callbacks which were subsequently removed by calling RemoveOnCompletion - /// will not be called. - /// - /// When the future completes, first the most recent callback registered with - /// OnCompletion(), if any, will be called; then all callbacks registered with - /// AddCompletion() will be called, in the order that they were registered. - /// - /// @param[in] callback Function pointer to your callback. - /// @param[in] user_data Optional user data. We will pass this back to your - /// callback. - /// @return A handle that can be passed to RemoveOnCompletion. - CompletionCallbackHandle AddOnCompletion(CompletionCallback callback, - void* user_data) const; - -#if defined(FIREBASE_USE_STD_FUNCTION) || defined(DOXYGEN) - /// Like OnCompletion, but allows adding multiple callbacks. - /// - /// If you call AddCompletion() more than once, all of the completions that - /// you register will be called, when the future is completed. However, any - /// callbacks which were subsequently removed by calling RemoveOnCompletion - /// will not be called. - /// - /// When the future completes, first the most recent callback registered with - /// OnCompletion(), if any, will be called; then all callbacks registered with - /// AddCompletion() will be called, in the order that they were registered. - /// - /// @param[in] callback Function or lambda to call. - /// @return A handle that can be passed to RemoveOnCompletion. - /// - /// @note This method is not available when using STLPort on Android, as - /// `std::function` is not supported on STLPort. - CompletionCallbackHandle AddOnCompletion( - std::function callback) const; - -#endif // defined(FIREBASE_USE_STD_FUNCTION) || defined(DOXYGEN) - - /// Unregisters a callback that was previously registered with - /// AddOnCompletion. - /// - /// @param[in] completion_handle The return value of a previous call to - /// AddOnCompletion. - void RemoveOnCompletion(CompletionCallbackHandle completion_handle) const; -#endif // defined(INTERNAL_EXPERIMENTAL) - - /// Returns true if the two Futures reference the same result. - bool operator==(const FutureBase& rhs) const { - MutexLock lock(mutex_); - return api_ == rhs.api_ && handle_ == rhs.handle_; - } - - /// Returns true if the two Futures reference different results. - bool operator!=(const FutureBase& rhs) const { return !operator==(rhs); } - -#if defined(INTERNAL_EXPERIMENTAL) - /// Returns the API-specific handle. Should only be called by the API. - FutureHandle GetHandle() const { - MutexLock lock(mutex_); - return handle_; - } -#endif // defined(INTERNAL_EXPERIMENTAL) - - protected: - /// @cond FIREBASE_APP_INTERNAL - - mutable Mutex mutex_; - - /// Backpointer to the issuing API class. - /// Set to nullptr when Future is invalidated. - detail::FutureApiInterface* api_; - - /// API-specified handle type. - FutureHandle handle_; - - /// @endcond -}; - -/// @brief Type-specific version of FutureBase. -/// -/// The Firebase C++ SDK uses this class to return results from asynchronous -/// operations. All Firebase C++ functions and method calls that operate -/// asynchronously return a Future, and provide a "LastResult" function to -/// retrieve the most recent Future result. -/// -/// @code -/// // You can retrieve the Future from the function call directly, like this: -/// Future< SampleResultType > future = firebase::SampleAsyncOperation(); -/// -/// // Or you can retrieve it later, like this: -/// firebase::SampleAsyncOperation(); -/// // [...] -/// Future< SampleResultType > future = -/// firebase::SampleAsyncOperationLastResult(); -/// @endcode -/// -/// When you have a Future from an asynchronous operation, it will eventually -/// complete. Once it is complete, you can check for errors (a nonzero error() -/// means an error occurred) and get the result data if no error occurred by -/// calling result(). -/// -/// There are two ways to find out that a Future has completed. You can poll -/// its status(), or set an OnCompletion() callback: -/// -/// @code -/// // Check whether the status is kFutureStatusComplete. -/// if (future.status() == firebase::kFutureStatusComplete) { -/// if (future.error() == 0) { -/// DoSomethingWithResultData(future.result()); -/// } -/// else { -/// LogMessage("Error %d: %s", future.error(), future.error_message()); -/// } -/// } -/// -/// // Or, set an OnCompletion callback, which accepts a C++11 lambda or -/// // function pointer. You can pass your own user data to the callback. In -/// // most cases, the callback will be running in a different thread, so take -/// // care to make sure your code is thread-safe. -/// future.OnCompletion([](const Future< SampleResultType >& completed_future, -/// void* user_data) { -/// // We are probably in a different thread right now. -/// if (completed_future.error() == 0) { -/// DoSomethingWithResultData(completed_future.result()); -/// } -/// else { -/// LogMessage("Error %d: %s", -/// completed_future.error(), -/// completed_future.error_message()); -/// } -/// }, user_data); -/// @endcode -/// -/// @tparam ResultType The type of this Future's result. -// -// WARNING: This class should not have virtual methods or data members. -// See the warning in FutureBase for further details. -template -class Future : public FutureBase { - public: - /// Function pointer for a completion callback. When we call this, we will - /// send the completed future, along with the user data that you specified - /// when you set up the callback. - typedef void (*TypedCompletionCallback)(const Future& result_data, - void* user_data); - - /// Construct a future. - Future() {} - - /// @cond FIREBASE_APP_INTERNAL - - /// Construct a future using the specified API and handle. - /// - /// @param api API class used to provide the future implementation. - /// @param handle Handle to the future. - Future(detail::FutureApiInterface* api, const FutureHandle& handle) - : FutureBase(api, handle) {} - - /// @endcond - - /// Result of the asynchronous call, or nullptr if the result is still - /// pending. Allows the API to provide a type-specific interface. - /// - const ResultType* result() const { - return static_cast(result_void()); - } - -#if defined(INTERNAL_EXPERIMENTAL) - /// Waits (blocks) until either the future is completed, or the specified - /// timeout period (in milliseconds) has elapsed, then returns the result of - /// the asynchronous call. - /// - /// This is a convenience method that calls Wait() and then returns result(). - /// - /// If `timeout_milliseconds` is `kWaitTimeoutInfinite`, then the timeout - /// period is treated as being infinite, i.e. this will block until the - /// future is completed. - const ResultType* Await(int timeout_milliseconds) const { - Wait(timeout_milliseconds); - return result(); - } -#endif // defined(INTERNAL_EXPERIMENTAL) - - /// Register a single callback that will be called at most once, when the - /// future is completed. - /// - /// If you call any OnCompletion() method more than once on the same future, - /// only the most recent callback you registered will be called. - /// - /// When your callback is called, the user_data that you supplied here will be - /// passed back as the second parameter. - /// - /// @param[in] callback Function pointer to your callback. - /// @param[in] user_data Optional user data. We will pass this back to your - /// callback. - /// - /// @note This is the same callback as FutureBase::OnCompletion(), so you - /// can't expect to set both and have both run; again, only the most recently - /// registered one will run. - inline void OnCompletion(TypedCompletionCallback callback, - void* user_data) const; - -#if defined(FIREBASE_USE_STD_FUNCTION) || defined(DOXYGEN) - /// Register a single callback that will be called at most once, when the - /// future is completed. - /// - /// If you call any OnCompletion() method more than once on the same future, - /// only the most recent callback you registered will be called. - /// - /// @param[in] callback Function or lambda to call. - /// - /// @note This method is not available when using STLPort on Android, as - /// `std::function` is not supported on STLPort. - /// - /// @note This is the same callback as FutureBase::OnCompletion(), so you - /// can't expect to set both and have both run; again, only the most recently - /// registered one will run. - inline void OnCompletion( - std::function&)> callback) const; -#endif // defined(FIREBASE_USE_STD_FUNCTION) || defined(DOXYGEN) - -#if defined(INTERNAL_EXPERIMENTAL) - /// Like OnCompletion, but allows adding multiple callbacks. - /// - /// If you call AddCompletion() more than once, all of the completions that - /// you register will be called, when the future is completed. However, any - /// callbacks which were subsequently removed by calling RemoveOnCompletion - /// will not be called. - /// - /// When the future completes, first the most recent callback registered with - /// OnCompletion(), if any, will be called; then all callbacks registered with - /// AddCompletion() will be called, in the order that they were registered. - /// - /// @param[in] callback Function pointer to your callback. - /// @param[in] user_data Optional user data. We will pass this back to your - /// callback. - /// @return A handle that can be passed to RemoveOnCompletion. - inline CompletionCallbackHandle AddOnCompletion( - TypedCompletionCallback callback, void* user_data) const; - -#if defined(FIREBASE_USE_STD_FUNCTION) || defined(DOXYGEN) - /// Like OnCompletion, but allows adding multiple callbacks. - /// - /// If you call AddCompletion() more than once, all of the completions that - /// you register will be called, when the future is completed. However, any - /// callbacks which were subsequently removed by calling RemoveOnCompletion - /// will not be called. - /// - /// When the future completes, first the most recent callback registered with - /// OnCompletion(), if any, will be called; then all callbacks registered with - /// AddCompletion() will be called, in the order that they were registered. - /// - /// @param[in] callback Function or lambda to call. - /// @return A handle that can be passed to RemoveOnCompletion. - /// - /// @note This method is not available when using STLPort on Android, as - /// `std::function` is not supported on STLPort. - inline CompletionCallbackHandle AddOnCompletion( - std::function&)> callback) const; -#endif // defined(FIREBASE_USE_STD_FUNCTION) || defined(DOXYGEN) -#endif // defined(INTERNAL_EXPERIMENTAL) -}; - -} // namespace firebase - -// Include the inline implementation. -#include "firebase/internal/future_impl.h" - -#endif // FIREBASE_APP_SRC_INCLUDE_FIREBASE_FUTURE_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/gma.h b/packages/firebase_core/firebase_core/firebase_core/firebase/gma.h deleted file mode 100644 index b7da2cf569b9..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/gma.h +++ /dev/null @@ -1,207 +0,0 @@ -/* - * Copyright 2021 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_GMA_SRC_INCLUDE_FIREBASE_GMA_H_ -#define FIREBASE_GMA_SRC_INCLUDE_FIREBASE_GMA_H_ - -#include "firebase/internal/platform.h" - -#if FIREBASE_PLATFORM_ANDROID -#include -#endif // FIREBASE_PLATFORM_ANDROID - -#include - -#include "firebase/app.h" -#include "firebase/gma/ad_view.h" -#include "firebase/gma/interstitial_ad.h" -#include "firebase/gma/rewarded_ad.h" -#include "firebase/gma/types.h" -#include "firebase/internal/common.h" - -#if !defined(DOXYGEN) && !defined(SWIG) -FIREBASE_APP_REGISTER_CALLBACKS_REFERENCE(gma) -#endif // !defined(DOXYGEN) && !defined(SWIG) - -namespace firebase { -// In the GMA docs, link to firebase::Future in the Firebase C++ docs. -#if defined(DOXYGEN_ADMOB) -/// @brief The Google Mobile Ads C++ SDK uses this class to return results from -/// asynchronous operations. All C++ functions and method calls that operate -/// asynchronously return a %Future, and provide a "LastResult" -/// function to retrieve the most recent %Future result. -/// -/// The Google Mobile Ads C++ SDK uses this class from the Firebase C++ SDK to -/// return results from asynchronous operations. For more information, see the -/// Firebase -/// C++ SDK documentation. -template -class Future { - // Empty class (used for documentation only). -}; -#endif // defined(DOXYGEN_ADMOB) - -/// @brief API for Google Mobile Ads with Firebase. -/// -/// The GMA API allows you to load and display mobile ads using the Google -/// Mobile Ads SDK. Each ad format has its own header file. -namespace gma { - -/// Initializes Google Mobile Ads (GMA) via Firebase. -/// -/// @param[in] app The Firebase app for which to initialize mobile ads. -/// -/// @param[out] init_result_out Optional: If provided, write the basic init -/// result here. kInitResultSuccess if initialization succeeded, or -/// kInitResultFailedMissingDependency on Android if Google Play services is not -/// available on the current device and the Google Mobile Ads SDK requires -/// Google Play services (for example, when using 'play-services-ads-lite'). -/// Note that this does not include the adapter initialization status, which is -/// returned in the Future. -/// -/// @return If init_result_out is kInitResultSuccess, this Future will contain -/// the initialization status of each adapter once initialization is complete. -/// Otherwise, the returned Future will have kFutureStatusInvalid. -Future Initialize( - const ::firebase::App& app, InitResult* init_result_out = nullptr); - -#if FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) -/// Initializes Google Mobile Ads (GMA) without Firebase for Android. -/// -/// The arguments to @ref Initialize are platform-specific so the caller must do -/// something like this: -/// @code -/// #if defined(__ANDROID__) -/// firebase::gma::Initialize(jni_env, activity); -/// #else -/// firebase::gma::Initialize(); -/// #endif -/// @endcode -/// -/// @param[in] jni_env JNIEnv pointer. -/// @param[in] activity Activity used to start the application. -/// @param[out] init_result_out Optional: If provided, write the basic init -/// result here. kInitResultSuccess if initialization succeeded, or -/// kInitResultFailedMissingDependency on Android if Google Play services is not -/// available on the current device and the Google Mobile Ads SDK requires -/// Google Play services (for example, when using 'play-services-ads-lite'). -/// Note that this does not include the adapter initialization status, which is -/// returned in the Future. -/// -/// @return If init_result_out is kInitResultSuccess, this Future will contain -/// the initialization status of each adapter once initialization is complete. -/// Otherwise, the returned Future will have kFutureStatusInvalid. -Future Initialize( - JNIEnv* jni_env, jobject activity, InitResult* init_result_out = nullptr); - -#endif // defined(__ANDROID__) || defined(DOXYGEN) -#if !FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) -/// Initializes Google Mobile Ads (GMA) without Firebase for iOS. -/// -/// @param[out] init_result_out Optional: If provided, write the basic init -/// result here. kInitResultSuccess if initialization succeeded, or -/// kInitResultFailedMissingDependency on Android if Google Play services is not -/// available on the current device and the Google Mobile Ads SDK requires -/// Google Play services (for example, when using 'play-services-ads-lite'). -/// Note that this does not include the adapter initialization status, which is -/// returned in the Future. -/// -/// @return If init_result_out is kInitResultSuccess, this Future -/// will contain the initialization status of each adapter once initialization -/// is complete. Otherwise, the returned Future will have -/// kFutureStatusInvalid. -Future Initialize( - InitResult* init_result_out = nullptr); -#endif // !defined(__ANDROID__) || defined(DOXYGEN) - -/// Get the Future returned by a previous call to -/// @ref firebase::gma::Initialize(). -Future InitializeLastResult(); - -/// Get the current adapter initialization status. You can poll this method to -/// check which adapters have been initialized. -AdapterInitializationStatus GetInitializationStatus(); - -/// Disables automated SDK crash reporting on iOS. If not called, the SDK -/// records the original exception handler if available and registers a new -/// exception handler. The new exception handler only reports SDK related -/// exceptions and calls the recorded original exception handler. -/// -/// This method has no effect on Android. -void DisableSDKCrashReporting(); - -/// Disables mediation adapter initialization on iOS during initialization of -/// the GMA SDK. Calling this method may negatively impact your ad -/// performance and should only be called if you will not use GMA SDK -/// controlled mediation during this app session. This method must be called -/// before initializing the GMA SDK or loading ads and has no effect once the -/// SDK has been initialized. -/// -/// This method has no effect on Android. -void DisableMediationInitialization(); - -/// Sets the global @ref RequestConfiguration that will be used for -/// every @ref AdRequest during the app's session. -/// -/// @param[in] request_configuration The request configuration that should be -/// applied to all ad requests. -void SetRequestConfiguration(const RequestConfiguration& request_configuration); - -/// Gets the global RequestConfiguration. -/// -/// @return the currently active @ref RequestConfiguration that's being -/// used for every ad request. -/// @note: on iOS, the -/// @ref RequestConfiguration::tag_for_child_directed_treatment and -/// @ref RequestConfiguration::tag_for_under_age_of_consent fields will be set -/// to RequestConfiguration.kChildDirectedTreatmentUnspecified, and -/// RequestConfiguration.kUnderAgeOfConsentUnspecified, respectfully. -RequestConfiguration GetRequestConfiguration(); - -/// Opens the ad inspector UI. -/// -/// @param[in] parent The platform-specific UI element that will host the -/// ad inspector. For iOS this should be the window's -/// UIViewController. For Android this is the -/// Activity Context which the GMA SDK is running in. -/// @param[in] listener The listener will be invoked when the user closes -/// the ad inspector UI. @ref firebase::gma::Initialize(). must be called -/// prior to this function. -void OpenAdInspector(AdParent parent, AdInspectorClosedListener* listener); - -/// Controls whether the Google Mobile Ads SDK Same App Key is enabled. -/// -/// This function must be invoked after GMA has been initialized. The value set -/// persists across app sessions. The key is enabled by default. -/// -/// This operation is supported on iOS only. This is a no-op on Android -/// systems. -/// -/// @param[in] is_enabled whether the Google Mobile Ads SDK Same App Key is -/// enabled. -void SetIsSameAppKeyEnabled(bool is_enabled); - -/// @brief Terminate GMA. -/// -/// Frees resources associated with GMA that were allocated during -/// @ref firebase::gma::Initialize(). -void Terminate(); - -} // namespace gma -} // namespace firebase - -#endif // FIREBASE_GMA_SRC_INCLUDE_FIREBASE_GMA_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/gma/ad_view.h b/packages/firebase_core/firebase_core/firebase_core/firebase/gma/ad_view.h deleted file mode 100644 index 16916a21665f..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/gma/ad_view.h +++ /dev/null @@ -1,267 +0,0 @@ -/* - * Copyright 2021 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_GMA_SRC_INCLUDE_FIREBASE_GMA_AD_VIEW_H_ -#define FIREBASE_GMA_SRC_INCLUDE_FIREBASE_GMA_AD_VIEW_H_ - -#include "firebase/future.h" -#include "firebase/gma/types.h" -#include "firebase/internal/common.h" - -namespace firebase { -namespace gma { - -namespace internal { -// Forward declaration for platform-specific data, implemented in each library. -class AdViewInternal; -} // namespace internal - -class AdViewBoundingBoxListener; -struct BoundingBox; - -/// @brief Loads and displays Google Mobile Ads AdView ads. -/// -/// Each AdView object corresponds to a single GMA ad placement of a specified -/// size. There are methods to load an ad, move it, show it and hide it, and -/// retrieve the bounds of the ad onscreen. -/// -/// AdView objects provide information about their current state through -/// Futures. Methods like @ref Initialize, @ref LoadAd, and @ref Hide each have -/// a corresponding @ref Future from which the result of the last call can be -/// determined. The two variants of @ref SetPosition share a single result -/// @ref Future, since they're essentially the same action. -/// -/// For example, you could initialize, load, and show an AdView while -/// checking the result of the previous action at each step as follows: -/// -/// @code -/// namespace gma = ::firebase::gma; -/// gma::AdView* ad_view = new gma::AdView(); -/// ad_view->Initialize(ad_parent, "YOUR_AD_UNIT_ID", desired_ad_size) -/// @endcode -/// -/// Then, later: -/// -/// @code -/// if (ad_view->InitializeLastResult().status() == -/// ::firebase::kFutureStatusComplete && -/// ad_view->InitializeLastResult().error() == -/// firebase::gma::kAdErrorCodeNone) { -/// ad_view->LoadAd(your_ad_request); -/// } -/// @endcode -class AdView { - public: - /// The possible screen positions for a @ref AdView, configured via - /// @ref SetPosition. - enum Position { - /// The position isn't one of the predefined screen locations. - kPositionUndefined = -1, - /// Top of the screen, horizontally centered. - kPositionTop = 0, - /// Bottom of the screen, horizontally centered. - kPositionBottom, - /// Top-left corner of the screen. - kPositionTopLeft, - /// Top-right corner of the screen. - kPositionTopRight, - /// Bottom-left corner of the screen. - kPositionBottomLeft, - /// Bottom-right corner of the screen. - kPositionBottomRight, - }; - - /// Creates an uninitialized @ref AdView object. - /// @ref Initialize must be called before the object is used. - AdView(); - - ~AdView(); - - /// Initializes the @ref AdView object. - /// @param[in] parent The platform-specific UI element that will host the ad. - /// @param[in] ad_unit_id The ad unit ID to use when requesting ads. - /// @param[in] size The desired ad size for the ad. - Future Initialize(AdParent parent, const char* ad_unit_id, - const AdSize& size); - - /// Returns a @ref Future that has the status of the last call to - /// @ref Initialize. - Future InitializeLastResult() const; - - /// Begins an asynchronous request for an ad. If successful, the ad will - /// automatically be displayed in the AdView. - /// @param[in] request An AdRequest struct with information about the request - /// to be made (such as targeting info). - Future LoadAd(const AdRequest& request); - - /// Returns a @ref Future containing the status of the last call to - /// @ref LoadAd. - Future LoadAdLastResult() const; - - /// Retrieves the @ref AdView's current onscreen size and location. - /// - /// @return The current size and location. Values are in pixels, and location - /// coordinates originate from the top-left corner of the screen. - BoundingBox bounding_box() const; - - /// Sets an AdListener for this ad view. - /// - /// @param[in] listener An AdListener object which will be invoked - /// when lifecycle events occur on this AdView. - void SetAdListener(AdListener* listener); - - /// Sets a listener to be invoked when the Ad's bounding box - /// changes size or location. - /// - /// @param[in] listener A AdViewBoundingBoxListener object which will be - /// invoked when the ad changes size, shape, or position. - void SetBoundingBoxListener(AdViewBoundingBoxListener* listener); - - /// Sets a listener to be invoked when this ad is estimated to have earned - /// money. - /// - /// @param[in] listener A PaidEventListener object to be invoked when a - /// paid event occurs on the ad. - void SetPaidEventListener(PaidEventListener* listener); - - /// Moves the @ref AdView so that its top-left corner is located at - /// (x, y). Coordinates are in pixels from the top-left corner of the screen. - /// - /// When built for Android, the library will not display an ad on top of or - /// beneath an Activity's status bar. If a call to SetPostion - /// would result in an overlap, the @ref AdView is placed just below the - /// status bar, so no overlap occurs. - /// @param[in] x The desired horizontal coordinate. - /// @param[in] y The desired vertical coordinate. - /// - /// @return a @ref Future which will be completed when this move operation - /// completes. - Future SetPosition(int x, int y); - - /// Moves the @ref AdView so that it's located at the given predefined - /// position. - /// - /// @param[in] position The predefined position to which to move the - /// @ref AdView. - /// - /// @return a @ref Future which will be completed when this move operation - /// completes. - Future SetPosition(Position position); - - /// Returns a @ref Future containing the status of the last call to either - /// version of @ref SetPosition. - Future SetPositionLastResult() const; - - /// Hides the AdView. - Future Hide(); - - /// Returns a @ref Future containing the status of the last call to - /// @ref Hide. - Future HideLastResult() const; - - /// Shows the @ref AdView. - Future Show(); - - /// Returns a @ref Future containing the status of the last call to - /// @ref Show. - Future ShowLastResult() const; - - /// Pauses the @ref AdView. Should be called whenever the C++ engine - /// pauses or the application loses focus. - Future Pause(); - - /// Returns a @ref Future containing the status of the last call to - /// @ref Pause. - Future PauseLastResult() const; - - /// Resumes the @ref AdView after pausing. - Future Resume(); - - /// Returns a @ref Future containing the status of the last call to - /// @ref Resume. - Future ResumeLastResult() const; - - /// Cleans up and deallocates any resources used by the @ref AdView. - /// You must call this asynchronous operation before this object's destructor - /// is invoked or risk leaking device resources. - Future Destroy(); - - /// Returns a @ref Future containing the status of the last call to - /// @ref Destroy. - Future DestroyLastResult() const; - - /// Returns the AdSize of the AdView. - /// - /// @return An @ref AdSize object representing the size of the ad. If this - /// view has not been initialized then the AdSize will be 0,0. - AdSize ad_size() const; - - protected: - /// Pointer to a listener for AdListener events. - AdListener* ad_listener_; - - /// Pointer to a listener for BoundingBox events. - AdViewBoundingBoxListener* ad_view_bounding_box_listener_; - - /// Pointer to a listener for paid events. - PaidEventListener* paid_event_listener_; - - private: - // An internal, platform-specific implementation object that this class uses - // to interact with the Google Mobile Ads SDKs for iOS and Android. - internal::AdViewInternal* internal_; -}; - -/// A listener class that developers can extend and pass to an @ref AdView -/// object's @ref AdView::SetBoundingBoxListener method to be notified of -/// changes to the size of the Ad's bounding box. -class AdViewBoundingBoxListener { - public: - virtual ~AdViewBoundingBoxListener(); - - /// This method is called when the @ref AdView object's bounding box - /// changes. - /// - /// @param[in] ad_view The view whose bounding box changed. - /// @param[in] box The new bounding box. - virtual void OnBoundingBoxChanged(AdView* ad_view, BoundingBox box) = 0; -}; - -/// @brief The screen location and dimensions of an AdView once it has been -/// initialized. -struct BoundingBox { - /// Default constructor which initializes all member variables to 0. - BoundingBox() - : height(0), width(0), x(0), y(0), position(AdView::kPositionUndefined) {} - - /// Height of the ad in pixels. - int height; - /// Width of the ad in pixels. - int width; - /// Horizontal position of the ad in pixels from the left. - int x; - /// Vertical position of the ad in pixels from the top. - int y; - - /// The position of the AdView if one has been set as the target position, or - /// kPositionUndefined otherwise. - AdView::Position position; -}; - -} // namespace gma -} // namespace firebase - -#endif // FIREBASE_GMA_SRC_INCLUDE_FIREBASE_GMA_AD_VIEW_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/gma/interstitial_ad.h b/packages/firebase_core/firebase_core/firebase_core/firebase/gma/interstitial_ad.h deleted file mode 100644 index 4680537178c8..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/gma/interstitial_ad.h +++ /dev/null @@ -1,128 +0,0 @@ -/* - * Copyright 2021 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_GMA_SRC_INCLUDE_FIREBASE_GMA_INTERSTITIAL_AD_H_ -#define FIREBASE_GMA_SRC_INCLUDE_FIREBASE_GMA_INTERSTITIAL_AD_H_ - -#include "firebase/future.h" -#include "firebase/gma/types.h" -#include "firebase/internal/common.h" - -namespace firebase { -namespace gma { - -namespace internal { -// Forward declaration for platform-specific data, implemented in each library. -class InterstitialAdInternal; -} // namespace internal - -/// @brief Loads and displays Google Mobile Ads interstitial ads. -/// -/// @ref InterstitialAd is a single-use object that can load and show a -/// single GMA interstitial ad. -/// -/// InterstitialAd objects provide information about their current state -/// through Futures. @ref Initialize, @ref LoadAd, and @ref Show each have a -/// corresponding @ref Future from which you can determine result of the -/// previous call. -/// -/// Here's how one might initialize, load, and show an interstitial ad while -/// checking against the result of the previous action at each step: -/// -/// @code -/// namespace gma = ::firebase::gma; -/// gma::InterstitialAd* interstitial = new gma::InterstitialAd(); -/// interstitial->Initialize(ad_parent); -/// @endcode -/// -/// Then, later: -/// -/// @code -/// if (interstitial->InitializeLastResult().status() == -/// ::firebase::kFutureStatusComplete && -/// interstitial->InitializeLastResult().error() == -/// firebase::gma::kAdErrorCodeNone) { -/// interstitial->LoadAd( "YOUR_AD_UNIT_ID", my_ad_request); -/// } -/// @endcode -/// -/// And after that: -/// -/// @code -/// if (interstitial->LoadAdLastResult().status() == -/// ::firebase::kFutureStatusComplete && -/// interstitial->LoadAdLastResult().error() == -/// firebase::gma::kAdErrorCodeNone)) { -/// interstitial->Show(); -/// } -/// @endcode -class InterstitialAd { - public: - /// Creates an uninitialized @ref InterstitialAd object. - /// @ref Initialize must be called before the object is used. - InterstitialAd(); - - ~InterstitialAd(); - - /// Initialize the @ref InterstitialAd object. - /// @param[in] parent The platform-specific UI element that will host the ad. - Future Initialize(AdParent parent); - - /// Returns a @ref Future containing the status of the last call to - /// @ref Initialize. - Future InitializeLastResult() const; - - /// Begins an asynchronous request for an ad. - /// - /// @param[in] ad_unit_id The ad unit ID to use in loading the ad. - /// @param[in] request An AdRequest struct with information about the request - /// to be made (such as targeting info). - Future LoadAd(const char* ad_unit_id, const AdRequest& request); - - /// Returns a @ref Future containing the status of the last call to - /// @ref LoadAd. - Future LoadAdLastResult() const; - - /// Shows the @ref InterstitialAd. This should not be called unless an ad has - /// already been loaded. - Future Show(); - - /// Returns a @ref Future containing the status of the last call to - /// @ref Show. - Future ShowLastResult() const; - - /// Sets the @ref FullScreenContentListener for this @ref InterstitialAd. - /// - /// @param[in] listener A valid @ref FullScreenContentListener to receive - /// callbacks. - void SetFullScreenContentListener(FullScreenContentListener* listener); - - /// Registers a callback to be invoked when this ad is estimated to have - /// earned money - /// - /// @param[in] listener A valid @ref PaidEventListener to receive callbacks. - void SetPaidEventListener(PaidEventListener* listener); - - private: - // An internal, platform-specific implementation object that this class uses - // to interact with the Google Mobile Ads SDKs for iOS and Android. - internal::InterstitialAdInternal* internal_; -}; - -} // namespace gma -} // namespace firebase - -#endif // FIREBASE_GMA_SRC_INCLUDE_FIREBASE_GMA_INTERSTITIAL_AD_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/gma/rewarded_ad.h b/packages/firebase_core/firebase_core/firebase_core/firebase/gma/rewarded_ad.h deleted file mode 100644 index a3c5431486d4..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/gma/rewarded_ad.h +++ /dev/null @@ -1,152 +0,0 @@ -/* - * Copyright 2021 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_GMA_SRC_INCLUDE_FIREBASE_GMA_REWARDED_AD_H_ -#define FIREBASE_GMA_SRC_INCLUDE_FIREBASE_GMA_REWARDED_AD_H_ - -#include - -#include "firebase/future.h" -#include "firebase/gma/types.h" -#include "firebase/internal/common.h" - -namespace firebase { -namespace gma { - -namespace internal { -// Forward declaration for platform-specific data, implemented in each library. -class RewardedAdInternal; -} // namespace internal - -/// @brief Loads and displays Google Mobile Ads rewarded ads. -/// -/// @ref RewardedAd is a single-use object that can load and show a -/// single GMA rewarded ad. -/// -/// RewardedAd objects provide information about their current state -/// through Futures. @ref Initialize, @ref LoadAd, and @ref Show each have a -/// corresponding @ref Future from which you can determine result of the -/// previous call. -/// -/// Here's how one might initialize, load, and show an rewarded ad while -/// checking against the result of the previous action at each step: -/// -/// @code -/// namespace gma = ::firebase::gma; -/// gma::RewardedAd* rewarded = new gma::RewardedAd(); -/// rewarded->Initialize(ad_parent); -/// @endcode -/// -/// Then, later: -/// -/// @code -/// if (rewarded->InitializeLastResult().status() == -/// ::firebase::kFutureStatusComplete && -/// rewarded->InitializeLastResult().error() == -/// firebase::gma::kAdErrorCodeNone) { -/// rewarded->LoadAd( "YOUR_AD_UNIT_ID", my_ad_request); -/// } -/// @endcode -/// -/// And after that: -/// -/// @code -/// if (rewarded->LoadAdLastResult().status() == -/// ::firebase::kFutureStatusComplete && -/// rewarded->LoadAdLastResult().error() == -/// firebase::gma::kAdErrorCodeNone)) { -/// rewarded->Show(&my_user_earned_reward_listener); -/// } -/// @endcode -class RewardedAd { - public: - /// Options for RewardedAd server-side verification callbacks. Set options on - /// a RewardedAd object using the @ref SetServerSideVerificationOptions - /// method. - struct ServerSideVerificationOptions { - /// Custom data to be included in server-side verification callbacks. - std::string custom_data; - - /// User id to be used in server-to-server reward callbacks. - std::string user_id; - }; - - /// Creates an uninitialized @ref RewardedAd object. - /// @ref Initialize must be called before the object is used. - RewardedAd(); - - ~RewardedAd(); - - /// Initialize the @ref RewardedAd object. - /// @param[in] parent The platform-specific UI element that will host the ad. - Future Initialize(AdParent parent); - - /// Returns a @ref Future containing the status of the last call to - /// @ref Initialize. - Future InitializeLastResult() const; - - /// Begins an asynchronous request for an ad. - /// - /// @param[in] ad_unit_id The ad unit ID to use in loading the ad. - /// @param[in] request An AdRequest struct with information about the request - /// to be made (such as targeting info). - Future LoadAd(const char* ad_unit_id, const AdRequest& request); - - /// Returns a @ref Future containing the status of the last call to - /// @ref LoadAd. - Future LoadAdLastResult() const; - - /// Shows the @ref RewardedAd. This should not be called unless an ad has - /// already been loaded. - /// - /// @param[in] listener The @ref UserEarnedRewardListener to be notified when - /// user earns a reward. - Future Show(UserEarnedRewardListener* listener); - - /// Returns a @ref Future containing the status of the last call to - /// @ref Show. - Future ShowLastResult() const; - - /// Sets the @ref FullScreenContentListener for this @ref RewardedAd. - /// - /// @param[in] listener A valid @ref FullScreenContentListener to receive - /// callbacks. - void SetFullScreenContentListener(FullScreenContentListener* listener); - - /// Registers a callback to be invoked when this ad is estimated to have - /// earned money - /// - /// @param[in] listener A valid @ref PaidEventListener to receive callbacks. - void SetPaidEventListener(PaidEventListener* listener); - - /// Sets the server side verification options. - /// - /// @param[in] serverSideVerificationOptions A @ref - /// ServerSideVerificationOptions object containing custom data and a user - /// Id. - void SetServerSideVerificationOptions( - const ServerSideVerificationOptions& serverSideVerificationOptions); - - private: - // An internal, platform-specific implementation object that this class uses - // to interact with the Google Mobile Ads SDKs for iOS and Android. - internal::RewardedAdInternal* internal_; -}; - -} // namespace gma -} // namespace firebase - -#endif // FIREBASE_GMA_SRC_INCLUDE_FIREBASE_GMA_REWARDED_AD_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/gma/types.h b/packages/firebase_core/firebase_core/firebase_core/firebase/gma/types.h deleted file mode 100644 index 292ee4138a68..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/gma/types.h +++ /dev/null @@ -1,939 +0,0 @@ -/* - * Copyright 2021 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_GMA_SRC_INCLUDE_FIREBASE_GMA_TYPES_H_ -#define FIREBASE_GMA_SRC_INCLUDE_FIREBASE_GMA_TYPES_H_ - -#include -#include -#include -#include -#include - -#include "firebase/future.h" -#include "firebase/internal/platform.h" - -#if FIREBASE_PLATFORM_ANDROID -#include -#elif FIREBASE_PLATFORM_IOS || FIREBASE_PLATFORM_TVOS -extern "C" { -#include -} // extern "C" -#endif // FIREBASE_PLATFORM_ANDROID, FIREBASE_PLATFORM_IOS, - // FIREBASE_PLATFORM_TVOS - -namespace firebase { -namespace gma { - -struct AdErrorInternal; -struct AdapterResponseInfoInternal; -struct BoundingBox; -struct ResponseInfoInternal; - -class AdapterResponseInfo; -class AdViewBoundingBoxListener; -class GmaInternal; -class AdView; -class InterstitialAd; -class PaidEventListener; -class ResponseInfo; - -namespace internal { -class AdViewInternal; -} - -/// This is a platform specific datatype that is required to create -/// a Google Mobile Ads ad. -/// -/// The following defines the datatype on each platform: -///
    -///
  • Android: A `jobject` which references an Android Activity.
  • -///
  • iOS: An `id` which references an iOS UIView.
  • -///
-#if FIREBASE_PLATFORM_ANDROID -/// An Android Activity from Java. -typedef jobject AdParent; -#elif FIREBASE_PLATFORM_IOS || FIREBASE_PLATFORM_TVOS -/// A pointer to an iOS UIView. -typedef id AdParent; -#else -/// A void pointer for stub classes. -typedef void* AdParent; -#endif // FIREBASE_PLATFORM_ANDROID, FIREBASE_PLATFORM_IOS, - // FIREBASE_PLATFORM_TVOS - -/// Error codes returned by Future::error(). -enum AdErrorCode { - /// Call completed successfully. - kAdErrorCodeNone, - /// The ad has not been fully initialized. - kAdErrorCodeUninitialized, - /// The ad is already initialized (repeat call). - kAdErrorCodeAlreadyInitialized, - /// A call has failed because an ad is currently loading. - kAdErrorCodeLoadInProgress, - /// A call to load an ad has failed due to an internal SDK error. - kAdErrorCodeInternalError, - /// A call to load an ad has failed due to an invalid request. - kAdErrorCodeInvalidRequest, - /// A call to load an ad has failed due to a network error. - kAdErrorCodeNetworkError, - /// A call to load an ad has failed because no ad was available to serve. - kAdErrorCodeNoFill, - /// An attempt has been made to show an ad on an Android Activity that has - /// no window token (such as one that's not done initializing). - kAdErrorCodeNoWindowToken, - /// An attempt to load an Ad Network extras class for an ad request has - /// failed. - kAdErrorCodeAdNetworkClassLoadError, - /// The ad server experienced a failure processing the request. - kAdErrorCodeServerError, - /// The current device’s OS is below the minimum required version. - kAdErrorCodeOSVersionTooLow, - /// The request was unable to be loaded before being timed out. - kAdErrorCodeTimeout, - /// Will not send request because the interstitial object has already been - /// used. - kAdErrorCodeInterstitialAlreadyUsed, - /// The mediation response was invalid. - kAdErrorCodeMediationDataError, - /// Error finding or creating a mediation ad network adapter. - kAdErrorCodeMediationAdapterError, - /// Attempting to pass an invalid ad size to an adapter. - kAdErrorCodeMediationInvalidAdSize, - /// Invalid argument error. - kAdErrorCodeInvalidArgument, - /// Received invalid response. - kAdErrorCodeReceivedInvalidResponse, - /// Will not send a request because the rewarded ad object has already been - /// used. - kAdErrorCodeRewardedAdAlreadyUsed, - /// A mediation ad network adapter received an ad request, but did not fill. - /// The adapter’s error is included as an underlyingError. - kAdErrorCodeMediationNoFill, - /// Will not send request because the ad object has already been used. - kAdErrorCodeAdAlreadyUsed, - /// Will not send request because the application identifier is missing. - kAdErrorCodeApplicationIdentifierMissing, - /// Android Ad String is invalid. - kAdErrorCodeInvalidAdString, - /// The ad can not be shown when app is not in the foreground. - kAdErrorCodeAppNotInForeground, - /// A mediation adapter failed to show the ad. - kAdErrorCodeMediationShowError, - /// The ad is not ready to be shown. - kAdErrorCodeAdNotReady, - /// Ad is too large for the scene. - kAdErrorCodeAdTooLarge, - /// Attempted to present ad from a non-main thread. This is an internal - /// error which should be reported to support if encountered. - kAdErrorCodeNotMainThread, - /// A debug operation failed because the device is not in test mode. - kAdErrorCodeNotInTestMode, - /// An attempt to load the Ad Inspector failed. - kAdErrorCodeInspectorFailedToLoad, - /// The request to show the Ad Inspector failed because it's already open. - kAdErrorCodeInsepctorAlreadyOpen, - /// Fallback error for any unidentified cases. - kAdErrorCodeUnknown, -}; - -/// A listener for receiving notifications during the lifecycle of a BannerAd. -class AdListener { - public: - virtual ~AdListener(); - - /// Called when a click is recorded for an ad. - virtual void OnAdClicked() {} - - /// Called when the user is about to return to the application after clicking - /// on an ad. - virtual void OnAdClosed() {} - - /// Called when an impression is recorded for an ad. - virtual void OnAdImpression() {} - - /// Called when an ad opens an overlay that covers the screen. - virtual void OnAdOpened() {} -}; - -/// Information about why an ad operation failed. -class AdError { - public: - /// Default Constructor. - AdError(); - - /// Copy Constructor. - AdError(const AdError& ad_error); - - /// Destructor. - virtual ~AdError(); - - /// Assignment operator. - AdError& operator=(const AdError& obj); - - /// Retrieves an AdError which represents the cause of this error. - /// - /// @return a pointer to an adError which represents the cause of this - /// AdError. If there was no cause then nullptr is returned. - std::unique_ptr GetCause() const; - - /// Gets the error's code. - AdErrorCode code() const; - - /// Gets the domain of the error. - const std::string& domain() const; - - /// Gets the message describing the error. - const std::string& message() const; - - /// Gets the ResponseInfo if an error occurred during a loadAd operation. - /// The ResponseInfo will have empty fields if this AdError does not - /// represent an error stemming from a load ad operation. - const ResponseInfo& response_info() const; - - /// Returns a log friendly string version of this object. - virtual const std::string& ToString() const; - - /// A domain string which represents an undefined error domain. - /// - /// The GMA SDK returns this domain for domain() method invocations when - /// converting error information from legacy mediation adapter callbacks. - static const char* const kUndefinedDomain; - - private: - friend class AdapterResponseInfo; - friend class GmaInternal; - friend class AdView; - friend class InterstitialAd; - - /// Constructor used when building results in Ad event callbacks. - explicit AdError(const AdErrorInternal& ad_error_internal); - - // Collection of response from adapters if this Result is due to a loadAd - // operation. - ResponseInfo* response_info_; - - // An internal, platform-specific implementation object that this class uses - // to interact with the Google Mobile Ads SDKs for iOS and Android. - AdErrorInternal* internal_; -}; - -/// Information about an ad response. -class ResponseInfo { - public: - /// Constructor creates an uninitialized ResponseInfo. - ResponseInfo(); - - /// Gets the AdapterResponseInfo objects for the ad response. - /// - /// @return a vector of AdapterResponseInfo objects containing metadata for - /// each adapter included in the ad response. - const std::vector& adapter_responses() const { - return adapter_responses_; - } - - /// A class name that identifies the ad network that returned the ad. - /// Returns an empty string if the ad failed to load. - const std::string& mediation_adapter_class_name() const { - return mediation_adapter_class_name_; - } - - /// Gets the response ID string for the loaded ad. Returns an empty - /// string if the ad fails to load. - const std::string& response_id() const { return response_id_; } - - /// Gets a log friendly string version of this object. - const std::string& ToString() const { return to_string_; } - - private: - friend class AdError; - friend class GmaInternal; - - explicit ResponseInfo(const ResponseInfoInternal& internal); - - std::vector adapter_responses_; - std::string mediation_adapter_class_name_; - std::string response_id_; - std::string to_string_; -}; - -/// Information about the result of an ad operation. -class AdResult { - public: - /// Default Constructor. - AdResult(); - - /// Constructor. - explicit AdResult(const AdError& ad_error); - - /// Destructor. - virtual ~AdResult(); - - /// Returns true if the operation was successful. - bool is_successful() const; - - /// An object representing an error which occurred during an ad operation. - /// If the @ref AdResult::is_successful() returned true, then the - /// @ref AdError object returned via this method will contain no contextual - /// information. - const AdError& ad_error() const; - - /// For debugging and logging purposes, successfully loaded ads provide a - /// ResponseInfo object which contains information about the adapter which - /// loaded the ad. If the ad failed to load then the object returned from - /// this method will have default values. Information about the error - /// should be retrieved via @ref AdResult::ad_error() instead. - const ResponseInfo& response_info() const; - - private: - friend class GmaInternal; - - /// Constructor invoked upon successful ad load. This contains response - /// information from the adapter which loaded the ad. - explicit AdResult(const ResponseInfo& response_info); - - /// Denotes if the @ref AdResult represents a success or an error. - bool is_successful_; - - /// Information about the error. Will be a default-constructed @ref AdError - /// if this result represents a success. - AdError ad_error_; - - /// Information from the adapter which loaded the ad. - ResponseInfo response_info_; -}; - -/// A snapshot of a mediation adapter's initialization status. -class AdapterStatus { - public: - AdapterStatus() : is_initialized_(false), latency_(0) {} - - /// Detailed description of the status. - /// - /// This method should only be used for informational purposes, such as - /// logging. Use @ref is_initialized to make logical decisions regarding an - /// adapter's status. - const std::string& description() const { return description_; } - - /// Returns the adapter's initialization state. - bool is_initialized() const { return is_initialized_; } - - /// The adapter's initialization latency in milliseconds. - /// 0 if initialization has not yet ended. - int latency() const { return latency_; } - -#if !defined(DOXYGEN) - // Equality operator for testing. - bool operator==(const AdapterStatus& rhs) const { - return (description() == rhs.description() && - is_initialized() == rhs.is_initialized() && - latency() == rhs.latency()); - } -#endif // !defined(DOXYGEN) - - private: - friend class GmaInternal; - std::string description_; - bool is_initialized_; - int latency_; -}; - -/// An immutable snapshot of the GMA SDK’s initialization status, categorized -/// by mediation adapter. -class AdapterInitializationStatus { - public: - /// Initialization status of each known ad network, keyed by its adapter's - /// class name. - std::map GetAdapterStatusMap() const { - return adapter_status_map_; - } -#if !defined(DOXYGEN) - // Equality operator for testing. - bool operator==(const AdapterInitializationStatus& rhs) const { - return (GetAdapterStatusMap() == rhs.GetAdapterStatusMap()); - } -#endif // !defined(DOXYGEN) - - private: - friend class GmaInternal; - std::map adapter_status_map_; -}; - -/// Listener to be invoked when the Ad Inspector has been closed. -class AdInspectorClosedListener { - public: - virtual ~AdInspectorClosedListener(); - - /// Called when the user clicked the ad. The AdResult contains the status of - /// the operation, including details of the error if one occurred. - virtual void OnAdInspectorClosed(const AdResult& ad_result) = 0; -}; - -/// @brief Response information for an individual ad network contained within -/// a @ref ResponseInfo object. -class AdapterResponseInfo { - public: - /// Destructor - ~AdapterResponseInfo(); - - /// @brief Information about the result including whether an error - /// occurred, and any contextual information about that error. - /// - /// @return the error that occurred while rendering the ad. If no error - /// occurred then the AdResult's successful method will return true. - AdResult ad_result() const { return ad_result_; } - - /// Returns a string representation of a class name that identifies the ad - /// network adapter. - const std::string& adapter_class_name() const { return adapter_class_name_; } - - /// Amount of time the ad network spent loading an ad. - /// - /// @return number of milliseconds the network spent loading an ad. This value - /// is 0 if the network did not make a load attempt. - int64_t latency_in_millis() const { return latency_; } - - /// A log friendly string version of this object. - const std::string& ToString() const { return to_string_; } - - private: - friend class ResponseInfo; - - /// Constructs an Adapter Response Info Object. - explicit AdapterResponseInfo(const AdapterResponseInfoInternal& internal); - - AdResult ad_result_; - std::string adapter_class_name_; - int64_t latency_; - std::string to_string_; -}; - -/// The size of a banner ad. -class AdSize { - public: - /// Denotes the orientation of the AdSize. - enum Orientation { - /// AdSize should reflect the current orientation of the device. - kOrientationCurrent = 0, - - /// AdSize will be adaptively formatted in Landscape mode. - kOrientationLandscape, - - /// AdSize will be adaptively formatted in Portrait mode. - kOrientationPortrait - }; - - /// Denotes the type size object that the @ref AdSize represents. - enum Type { - /// The standard AdSize type of a set height and width. - kTypeStandard = 0, - - /// An adaptive size anchored to a portion of the screen. - kTypeAnchoredAdaptive, - - /// An adaptive size intended to be embedded in scrollable content. - kTypeInlineAdaptive, - }; - - /// Mobile Marketing Association (MMA) banner ad size (320x50 - /// density-independent pixels). - static const AdSize kBanner; - - /// Interactive Advertising Bureau (IAB) full banner ad size - /// (468x60 density-independent pixels). - static const AdSize kFullBanner; - - /// Taller version of kBanner. Typically 320x100. - static const AdSize kLargeBanner; - - /// Interactive Advertising Bureau (IAB) leaderboard ad size - /// (728x90 density-independent pixels). - static const AdSize kLeaderboard; - - /// Interactive Advertising Bureau (IAB) medium rectangle ad size - /// (300x250 density-independent pixels). - static const AdSize kMediumRectangle; - - /// Creates a new AdSize. - /// - /// @param[in] width The width of the ad in density-independent pixels. - /// @param[in] height The height of the ad in density-independent pixels. - AdSize(uint32_t width, uint32_t height); - - /// @brief Creates an AdSize with the given width and a Google-optimized - /// height to create a banner ad in landscape mode. - /// - /// @param[in] width The width of the ad in density-independent pixels. - /// - /// @return an AdSize with the given width and a Google-optimized height - /// to create a banner ad. The size returned will have an aspect ratio - /// similar to BANNER, suitable for anchoring near the top or bottom of - /// your app. The exact size of the ad returned can be retrieved by calling - /// @ref AdView::ad_size once the ad has been loaded. - static AdSize GetLandscapeAnchoredAdaptiveBannerAdSize(uint32_t width); - - /// @brief Creates an AdSize with the given width and a Google-optimized - /// height to create a banner ad in portrait mode. - /// - /// @param[in] width The width of the ad in density-independent pixels. - /// - /// @return an AdSize with the given width and a Google-optimized height - /// to create a banner ad. The size returned will have an aspect ratio - /// similar to BANNER, suitable for anchoring near the top or bottom - /// of your app. The exact size of the ad returned can be retrieved by - /// calling @ref AdView::ad_size once the ad has been loaded. - static AdSize GetPortraitAnchoredAdaptiveBannerAdSize(uint32_t width); - - /// @brief Creates an AdSize with the given width and a Google-optimized - /// height to create a banner ad given the current orientation. - /// - /// @param[in] width The width of the ad in density-independent pixels. - /// - /// @return an AdSize with the given width and a Google-optimized height - /// to create a banner ad. The size returned will have an aspect ratio - /// similar to AdSize, suitable for anchoring near the top or bottom of - /// your app. The exact size of the ad returned can be retrieved by calling - /// @ref AdView::ad_size once the ad has been loaded. - static AdSize GetCurrentOrientationAnchoredAdaptiveBannerAdSize( - uint32_t width); - - /// @brief This ad size is most suitable for banner ads given a maximum - /// height. - /// - /// This AdSize allows Google servers to choose an optimal ad size with - /// a height less than or equal to the max height given in - /// - /// @param[in] width The width of the ad in density-independent pixels. - /// @param[in] max_height The maximum height that a loaded ad will have. Must - /// be - /// at least 32 dp, but a maxHeight of 50 dp or higher is recommended. - /// - /// @return an AdSize with the given width and a height that is always 0. - /// The exact size of the ad returned can be retrieved by calling - /// @ref AdView::ad_size once the ad has been loaded. - static AdSize GetInlineAdaptiveBannerAdSize(int width, int max_height); - - /// @brief Creates an AdSize with the given width and the device’s - /// landscape height. - /// - /// This ad size allows Google servers to choose an optimal ad size with - /// a height less than or equal to the height of the screen in landscape - /// orientation. - /// - /// @param[in] width The width of the ad in density-independent pixels. - /// - /// @return an AdSize with the given width and a height that is always 0. - /// The exact size of the ad returned can be retrieved by calling - /// @ref AdView::ad_size once the ad has been loaded. - static AdSize GetLandscapeInlineAdaptiveBannerAdSize(int width); - - /// @brief Creates an AdSize with the given width and the device’s - /// portrait height. - /// - /// This ad size allows Google servers to choose an optimal ad size with - /// a height less than or equal to the height of the screen in portrait - /// orientation. - /// - /// @param[in] width The width of the ad in density-independent pixels. - /// - /// @return an AdSize with the given width and a height that is always 0. - /// The exact size of the ad returned can be retrieved by calling - /// @ref AdView::ad_size once the ad has been loaded. - static AdSize GetPortraitInlineAdaptiveBannerAdSize(int width); - - /// @brief A convenience method to return an inline adaptive banner ad size - /// given the current interface orientation. - /// - /// This AdSize allows Google servers to choose an optimal ad size with a - /// height less than or equal to the height of the screen in the requested - /// orientation. - /// - /// @param[in] width The width of the ad in density-independent pixels. - /// - /// @return an AdSize with the given width and a height that is always 0. - /// The exact size of the ad returned can be retrieved by calling - /// @ref AdView::ad_size once the ad has been loaded. - static AdSize GetCurrentOrientationInlineAdaptiveBannerAdSize(int width); - - /// Comparison operator. - /// - /// @return true if `rhs` refers to the same AdSize as `this`. - bool operator==(const AdSize& rhs) const; - - /// Comparison operator. - /// - /// @returns true if `rhs` refers to a different AdSize as `this`. - bool operator!=(const AdSize& rhs) const; - - /// The width of the region represented by this AdSize. Value is in - /// density-independent pixels. - uint32_t width() const { return width_; } - - /// The height of the region represented by this AdSize. Value is in - /// density-independent pixels. - uint32_t height() const { return height_; } - - /// The AdSize orientation. - Orientation orientation() const { return orientation_; } - - /// The AdSize type, either standard size or adaptive. - Type type() const { return type_; } - - private: - friend class firebase::gma::internal::AdViewInternal; - - /// Returns an Anchor Adpative AdSize Object given a width and orientation. - static AdSize GetAnchoredAdaptiveBannerAdSize(uint32_t width, - Orientation orientation); - - /// Returns true if the AdSize parameter is equivalient to this AdSize object. - bool is_equal(const AdSize& ad_size) const; - - /// Denotes the orientation for anchored adaptive AdSize objects. - Orientation orientation_; - - /// Advertisement width in platform-indepenent pixels. - uint32_t width_; - - /// Advertisement width in platform-indepenent pixels. - uint32_t height_; - - /// The type of AdSize (standard or adaptive) - Type type_; -}; - -/// Contains targeting information used to fetch an ad. -class AdRequest { - public: - /// Creates an @ref AdRequest with no custom configuration. - AdRequest(); - - /// Creates an @ref AdRequest with the optional content URL. - /// - /// When requesting an ad, apps may pass the URL of the content they are - /// serving. This enables keyword targeting to match the ad with the content. - /// - /// The URL is ignored if null or the number of characters exceeds 512. - /// - /// @param[in] content_url the url of the content being viewed. - explicit AdRequest(const char* content_url); - - ~AdRequest(); - - /// The content URL targeting information. - /// - /// @return the content URL for the @ref AdRequest. The string will be empty - /// if no content URL has been configured. - const std::string& content_url() const { return content_url_; } - - /// A Map of adapter class names to their collection of extra parameters, as - /// configured via @ref add_extra. - const std::map >& extras() - const { - return extras_; - } - - /// Keywords which will help GMA to provide targeted ads, as added by - /// @ref add_keyword. - const std::unordered_set& keywords() const { return keywords_; } - - /// Returns the set of neighboring content URLs or an empty set if no URLs - /// were set via @ref add_neighboring_content_urls(). - const std::unordered_set& neighboring_content_urls() const { - return neighboring_content_urls_; - } - - /// Add a network extra for the associated ad mediation adapter. - /// - /// Appends an extra to the corresponding list of extras for the ad mediation - /// adapter. Each ad mediation adapter can have multiple extra strings. - /// - /// @param[in] adapter_class_name the class name of the ad mediation adapter - /// for which to add the extra. - /// @param[in] extra_key a key which will be passed to the corresponding ad - /// mediation adapter. - /// @param[in] extra_value the value associated with extra_key. - void add_extra(const char* adapter_class_name, const char* extra_key, - const char* extra_value); - - /// Adds a keyword for targeting purposes. - /// - /// Multiple keywords may be added via repeated invocations of this method. - /// - /// @param[in] keyword a string that GMA will use to aid in targeting ads. - void add_keyword(const char* keyword); - - /// When requesting an ad, apps may pass the URL of the content they are - /// serving. This enables keyword targeting to match the ad with the content. - /// - /// The URL is ignored if null or the number of characters exceeds 512. - /// - /// @param[in] content_url the url of the content being viewed. - void set_content_url(const char* content_url); - - /// Adds to the list of URLs which represent web content near an ad. - /// - /// Promotes brand safety and allows displayed ads to have an app level - /// rating (MA, T, PG, etc) that is more appropriate to neighboring content. - /// - /// Subsequent invocations append to the existing list. - /// - /// @param[in] neighboring_content_urls neighboring content URLs to be - /// attached to the existing neighboring content URLs. - void add_neighboring_content_urls( - const std::vector& neighboring_content_urls); - - private: - std::string content_url_; - std::map > extras_; - std::unordered_set keywords_; - std::unordered_set neighboring_content_urls_; -}; - -/// Describes a reward credited to a user for interacting with a RewardedAd. -class AdReward { - public: - /// Creates an @ref AdReward. - AdReward(const std::string& type, int64_t amount) - : type_(type), amount_(amount) {} - - /// Returns the reward amount. - int64_t amount() const { return amount_; } - - /// Returns the type of the reward. - const std::string& type() const { return type_; } - - private: - const int64_t amount_; - const std::string type_; -}; - -/// The monetary value earned from an ad. -class AdValue { - public: - /// Allowed constants for @ref precision_type(). - enum PrecisionType { - /// An ad value with unknown precision. - kdValuePrecisionUnknown = 0, - /// An ad value estimated from aggregated data. - kAdValuePrecisionEstimated, - /// A publisher-provided ad value, such as manual CPMs in a mediation group. - kAdValuePrecisionPublisherProvided = 2, - /// The precise value paid for this ad. - kAdValuePrecisionPrecise = 3 - }; - - /// Constructor - AdValue(const char* currency_code, PrecisionType precision_type, - int64_t value_micros) - : currency_code_(currency_code), - precision_type_(precision_type), - value_micros_(value_micros) {} - - /// The value's ISO 4217 currency code. - const std::string& currency_code() const { return currency_code_; } - - /// The precision of the reported ad value. - PrecisionType precision_type() const { return precision_type_; } - - /// The ad's value in micro-units, where 1,000,000 micro-units equal one - /// unit of the currency. - int64_t value_micros() const { return value_micros_; } - - private: - const std::string currency_code_; - const PrecisionType precision_type_; - const int64_t value_micros_; -}; - -/// @brief Listener to be invoked when ads show and dismiss full screen content, -/// such as a fullscreen ad experience or an in-app browser. -class FullScreenContentListener { - public: - virtual ~FullScreenContentListener(); - - /// Called when the user clicked the ad. - virtual void OnAdClicked() {} - - /// Called when the ad dismissed full screen content. - virtual void OnAdDismissedFullScreenContent() {} - - /// Called when the ad failed to show full screen content. - /// - /// @param[in] ad_error An object containing detailed information - /// about the error. - virtual void OnAdFailedToShowFullScreenContent(const AdError& ad_error) {} - - /// Called when an impression is recorded for an ad. - virtual void OnAdImpression() {} - - /// Called when the ad showed the full screen content. - virtual void OnAdShowedFullScreenContent() {} -}; - -/// Listener to be invoked when ads have been estimated to earn money. -class PaidEventListener { - public: - virtual ~PaidEventListener(); - - /// Called when an ad is estimated to have earned money. - virtual void OnPaidEvent(const AdValue& value) {} -}; - -/// @brief Global configuration that will be used for every @ref AdRequest. -/// Set the configuration via @ref SetRequestConfiguration. -struct RequestConfiguration { - /// A maximum ad content rating, which may be configured via - /// @ref max_ad_content_rating. - enum MaxAdContentRating { - /// No content rating has been specified. - kMaxAdContentRatingUnspecified = -1, - - /// Content suitable for general audiences, including families. - kMaxAdContentRatingG, - - /// Content suitable only for mature audiences. - kMaxAdContentRatingMA, - - /// Content suitable for most audiences with parental guidance. - kMaxAdContentRatingPG, - - /// Content suitable for teen and older audiences. - kMaxAdContentRatingT - }; - - /// Specify whether you would like your app to be treated as child-directed - /// for purposes of the Children’s Online Privacy Protection Act (COPPA). - /// Values defined here may be configured via - /// @ref tag_for_child_directed_treatment. - enum TagForChildDirectedTreatment { - /// Indicates that ad requests will include no indication of how you would - /// like your app treated with respect to COPPA. - kChildDirectedTreatmentUnspecified = -1, - - /// Indicates that your app should not be treated as child-directed for - /// purposes of the Children’s Online Privacy Protection Act (COPPA). - kChildDirectedTreatmentFalse, - - /// Indicates that your app should be treated as child-directed for purposes - /// of the Children’s Online Privacy Protection Act (COPPA). - kChildDirectedTreatmentTrue - }; - - /// Configuration values to mark your app to receive treatment for users in - /// the European Economic Area (EEA) under the age of consent. Values defined - /// here should be configured via @ref tag_for_under_age_of_consent. - enum TagForUnderAgeOfConsent { - /// Indicates that the publisher has not specified whether the ad request - /// should receive treatment for users in the European Economic Area (EEA) - /// under the age of consent. - kUnderAgeOfConsentUnspecified = -1, - - /// Indicates the publisher specified that the ad request should not receive - /// treatment for users in the European Economic Area (EEA) under the age of - /// consent. - kUnderAgeOfConsentFalse, - - /// Indicates the publisher specified that the ad request should receive - /// treatment for users in the European Economic Area (EEA) under the age of - /// consent. - kUnderAgeOfConsentTrue - }; - - /// Sets a maximum ad content rating. GMA ads returned for your app will - /// have a content rating at or below that level. - MaxAdContentRating max_ad_content_rating; - - /// @brief Allows you to specify whether you would like your app - /// to be treated as child-directed for purposes of the Children’s Online - /// Privacy Protection Act (COPPA) - - /// http://business.ftc.gov/privacy-and-security/childrens-privacy. - /// - /// If you set this value to - /// RequestConfiguration.kChildDirectedTreatmentTrue, you will indicate - /// that your app should be treated as child-directed for purposes of the - /// Children’s Online Privacy Protection Act (COPPA). - /// - /// If you set this value to - /// RequestConfiguration.kChildDirectedTreatmentFalse, you will indicate - /// that your app should not be treated as child-directed for purposes of the - /// Children’s Online Privacy Protection Act (COPPA). - /// - /// If you do not set this value, or set this value to - /// RequestConfiguration.kChildDirectedTreatmentUnspecified, ad requests will - /// include no indication of how you would like your app treated with respect - /// to COPPA. - /// - /// By setting this value, you certify that this notification is accurate and - /// you are authorized to act on behalf of the owner of the app. You - /// understand that abuse of this setting may result in termination of your - /// Google account. - /// - /// @note: it may take some time for this designation to be fully implemented - /// in applicable Google services. - /// - TagForChildDirectedTreatment tag_for_child_directed_treatment; - - /// This value allows you to mark your app to receive treatment for users in - /// the European Economic Area (EEA) under the age of consent. This feature is - /// designed to help facilitate compliance with the General Data Protection - /// Regulation (GDPR). Note that you may have other legal obligations under - /// GDPR. Please review the European Union's guidance and consult with your - /// own legal counsel. Please remember that Google's tools are designed to - /// facilitate compliance and do not relieve any particular publisher of its - /// obligations under the law. - /// - /// When using this feature, a Tag For Users under the Age of Consent in - /// Europe (TFUA) parameter will be included in all ad requests. This - /// parameter disables personalized advertising, including remarketing, for - /// that specific ad request. It also disables requests to third-party ad - /// vendors, such as ad measurement pixels and third-party ad servers. - /// - /// If you set this value to RequestConfiguration.kUnderAgeOfConsentTrue, you - /// will indicate that you want your app to be handled in a manner suitable - /// for users under the age of consent. - /// - /// If you set this value to RequestConfiguration.kUnderAgeOfConsentFalse, - /// you will indicate that you don't want your app to be handled in a manner - /// suitable for users under the age of consent. - /// - /// If you do not set this value, or set this value to - /// kUnderAgeOfConsentUnspecified, your app will include no indication of how - /// you would like your app to be handled in a manner suitable for users under - /// the age of consent. - TagForUnderAgeOfConsent tag_for_under_age_of_consent; - - /// Sets a list of test device IDs corresponding to test devices which will - /// always request test ads. - std::vector test_device_ids; -}; - -/// Listener to be invoked when the user earned a reward. -class UserEarnedRewardListener { - public: - virtual ~UserEarnedRewardListener(); - /// Called when the user earned a reward. The app is responsible for - /// crediting the user with the reward. - /// - /// @param[in] reward the @ref AdReward that should be granted to the user. - virtual void OnUserEarnedReward(const AdReward& reward) {} -}; - -} // namespace gma -} // namespace firebase - -#endif // FIREBASE_GMA_SRC_INCLUDE_FIREBASE_GMA_TYPES_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/installations.h b/packages/firebase_core/firebase_core/firebase_core/firebase/installations.h deleted file mode 100644 index c9774bc37e73..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/installations.h +++ /dev/null @@ -1,123 +0,0 @@ -// Copyright 2020 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef FIREBASE_INSTALLATIONS_SRC_INCLUDE_FIREBASE_INSTALLATIONS_H_ -#define FIREBASE_INSTALLATIONS_SRC_INCLUDE_FIREBASE_INSTALLATIONS_H_ - -#include -#include - -#include "firebase/app.h" -#include "firebase/future.h" -#include "firebase/internal/common.h" - -/// @brief Namespace that encompasses all Firebase APIs. -namespace firebase { - -namespace installations { - -/// Installations error codes. -enum Error { - kErrorNone = 0, - /// An unknown error occurred. - kErrorUnknown, - /// Installations service cannot be accessed. - kErrorNoAccess, - /// Some of the parameters of the request were invalid. - kErrorInvalidConfiguration, -}; - -namespace internal { -// Implementation specific data for an Installation. -class InstallationsInternal; -} // namespace internal - -/// @brief Installations provides a unique identifier for each app instance and -/// a mechanism to authenticate and authorize actions (for example, sending an -/// FCM message). -/// -/// Provides a unique identifier for a Firebase installation. -/// Provides an auth token for a Firebase installation. -/// Provides a API to perform data deletion for a Firebase -/// installation. -class Installations { - public: - ~Installations(); - - /// @brief Get the App this object is connected to. - /// - /// @return App this object is connected to. - App* app() const { return app_; } - - /// @brief Returns the Installations object for an App creating the - /// Installations if required. - /// - /// @param[in] app The App to create an Installations object from. - /// - /// @return Installations object if successful, nullptr otherwise. - static Installations* GetInstance(App* app); - - /// @brief Returns a stable identifier that uniquely identifies the app - /// installation. - /// - /// @return Unique identifier for the app installation. - Future GetId(); - - /// @brief Get the results of the most recent call to @ref GetId. - Future GetIdLastResult(); - - /// @brief Call to delete this Firebase app installation from the Firebase - /// backend. - Future Delete(); - - /// @brief Get the results of the most recent call to @ref Delete. - Future DeleteLastResult(); - - /// @brief Returns a token that authorizes an Entity to perform an action on - /// behalf of the application identified by installations. - /// - /// This is similar to an OAuth2 token except it applies to the - /// application instance instead of a user. - /// - /// For example, to get a token that can be used to send messages to an - /// application via Firebase Cloud Messaging, set entity to the - /// sender ID, and set scope to "FCM". - /// - /// @param forceRefresh If set true, will always return a new token. - /// - /// @return Returns a valid authentication token for the Firebase - /// installation. - Future GetToken(bool forceRefresh); - - /// @brief Get the results of the most recent call to @ref GetToken. - Future GetTokenLastResult(); - - private: - explicit Installations(App* app); - - static Installations* FindInstallations(App* app); - // Installations internal initialize. - bool InitInternal(); - // Clean up Installations instance. - void DeleteInternal(); - - App* app_; - internal::InstallationsInternal* installations_internal_; -}; - -} // namespace installations - -} // namespace firebase - -#endif // FIREBASE_INSTALLATIONS_SRC_INCLUDE_FIREBASE_INSTALLATIONS_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/internal/common.h b/packages/firebase_core/firebase_core/firebase_core/firebase/internal/common.h deleted file mode 100644 index 2e2878a0bd97..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/internal/common.h +++ /dev/null @@ -1,128 +0,0 @@ -/* - * Copyright 2016 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_APP_SRC_INCLUDE_FIREBASE_INTERNAL_COMMON_H_ -#define FIREBASE_APP_SRC_INCLUDE_FIREBASE_INTERNAL_COMMON_H_ - -// This file contains definitions that configure the SDK. - -// Include a STL header file, othewise _STLPORT_VERSION won't be set. -#include - -// Move operators use rvalue references, which are a C++11 extension. -// Also, Visual Studio 2010 and later actually support move operators despite -// reporting __cplusplus to be 199711L, so explicitly check for that. -// Also, stlport doesn't implement std::move(). -#if (__cplusplus >= 201103L || _MSC_VER >= 1600) && !defined(_STLPORT_VERSION) -#define FIREBASE_USE_MOVE_OPERATORS -#endif - -// stlport doesn't implement std::function. -#if !defined(_STLPORT_VERSION) -#define FIREBASE_USE_STD_FUNCTION -#endif // !defined(_STLPORT_VERSION) - -// stlport doesn't implement std::aligned_storage. -#if defined(_STLPORT_VERSION) -#include - -namespace firebase { -template -struct AlignedStorage { - struct type { - alignas(Alignment) unsigned char data[Length]; - }; -}; -} // namespace firebase -#define FIREBASE_ALIGNED_STORAGE ::firebase::AlignedStorage -#else -#include -#define FIREBASE_ALIGNED_STORAGE std::aligned_storage -#endif // defined(_STLPORT_VERSION) - -// Visual Studio 2013 does not support snprintf, so use streams instead. -#if !(defined(_MSC_VER) && _MSC_VER <= 1800) -#define FIREBASE_USE_SNPRINTF -#endif // !(defined(_MSC_VER) && _MSC_VER <= 1800) - -#if !(defined(_MSC_VER) && _MSC_VER <= 1800) -#define FIREBASE_USE_EXPLICIT_DEFAULT_METHODS -#endif // !(defined(_MSC_VER) && _MSC_VER <= 1800) - -#if !defined(DOXYGEN) && !defined(SWIG) -#if !defined(_WIN32) && !defined(__CYGWIN__) -// Prevent GCC & Clang from stripping a symbol. -#define FIREBASE_APP_KEEP_SYMBOL __attribute__((used)) -#else -// MSVC needs to reference a symbol directly in the application for it to be -// kept in the final executable. In this case, the end user's application -// must include the appropriate Firebase header (e.g firebase/analytics.h) to -// initialize the module. -#define FIREBASE_APP_KEEP_SYMBOL -#endif // !defined(_WIN32) && !defined(__CYGWIN__) - -// Module initializer's name. -// -// This can be used to explicitly include a module initializer in an application -// to prevent the object from being stripped by the linker. The symbol is -// located in the "firebase" namespace so can be referenced using: -// -// ::firebase::FIREBASE_APP_REGISTER_CALLBACKS_REFERENCE_NAME(name) -// -// Where "name" is the module name, for example "analytics". -#define FIREBASE_APP_REGISTER_CALLBACKS_INITIALIZER_NAME(module_name) \ - g_##module_name##_initializer - -// Declare a module initializer variable as a global. -#define FIREBASE_APP_REGISTER_CALLBACKS_INITIALIZER_VARIABLE(module_name) \ - namespace firebase { \ - extern void* FIREBASE_APP_REGISTER_CALLBACKS_INITIALIZER_NAME(module_name); \ - } /* namespace firebase */ - -// Generates code which references a module initializer. -// For example, FIREBASE_APP_REGISTER_REFERENCE(analytics) will register the -// module initializer for the analytics module. -#define FIREBASE_APP_REGISTER_CALLBACKS_REFERENCE(module_name) \ - FIREBASE_APP_REGISTER_CALLBACKS_INITIALIZER_VARIABLE(module_name) \ - namespace firebase { \ - static void* module_name##_ref FIREBASE_APP_KEEP_SYMBOL = \ - &FIREBASE_APP_REGISTER_CALLBACKS_INITIALIZER_NAME(module_name); \ - } /* namespace firebase */ -#endif // !defined(DOXYGEN) && !defined(SWIG) - -#if defined(SWIG) || defined(DOXYGEN) -// SWIG needs to ignore the FIREBASE_DEPRECATED tag. -#define FIREBASE_DEPRECATED -#endif // defined(SWIG) || defined(DOXYGEN) - -#ifndef FIREBASE_DEPRECATED -#ifdef __GNUC__ -#define FIREBASE_DEPRECATED __attribute__((deprecated)) -#elif defined(_MSC_VER) -#define FIREBASE_DEPRECATED __declspec(deprecated) -#else -// We don't know how to mark functions as "deprecated" with this compiler. -#define FIREBASE_DEPRECATED -#endif -#endif // FIREBASE_DEPRECATED - -// Calculates the number of elements in an array. -#define FIREBASE_ARRAYSIZE(x) (sizeof(x) / sizeof((x)[0])) - -// Guaranteed compile time strlen. -#define FIREBASE_STRLEN(s) (FIREBASE_ARRAYSIZE(s) - sizeof((s)[0])) - -#endif // FIREBASE_APP_SRC_INCLUDE_FIREBASE_INTERNAL_COMMON_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/internal/future_impl.h b/packages/firebase_core/firebase_core/firebase_core/firebase/internal/future_impl.h deleted file mode 100644 index 59e7771d010b..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/internal/future_impl.h +++ /dev/null @@ -1,359 +0,0 @@ -/* - * Copyright 2016 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_APP_SRC_INCLUDE_FIREBASE_INTERNAL_FUTURE_IMPL_H_ -#define FIREBASE_APP_SRC_INCLUDE_FIREBASE_INTERNAL_FUTURE_IMPL_H_ - -/// @cond FIREBASE_APP_INTERNAL - -// You shouldn't include future_impl.h directly, since its just the inline -// implementation of the functions in future.h. Include future.h instead. -#include "firebase/future.h" - -#if defined(FIREBASE_USE_MOVE_OPERATORS) -#include -#endif // defined(FIREBASE_USE_MOVE_OPERATORS) - -namespace firebase { - -class ReferenceCountedFutureImpl; - -namespace detail { - -class CompletionCallbackHandle; - -/// Pure-virtual interface that APIs must implement to use Futures. -class FutureApiInterface { - public: - // typedef void FutureCallbackFn(const FutureBase* future); - virtual ~FutureApiInterface(); - - /// Increment the reference count on handle's asynchronous call. - /// Called when the Future is copied. - virtual void ReferenceFuture(const FutureHandle& handle) = 0; - - /// Decrement the reference count on handle's asynchronous call. - /// Called when the Future is destroyed or moved. - /// If the reference count drops to zero, the asynchronous call can be - /// forgotten. - virtual void ReleaseFuture(const FutureHandle& handle) = 0; - - /// Return the status of the asynchronous call. - virtual FutureStatus GetFutureStatus(const FutureHandle& handle) const = 0; - - /// Return the API-specific error. - /// Valid when GetFutureStatus() is kFutureStatusComplete, and undefined - /// otherwise. - virtual int GetFutureError(const FutureHandle& handle) const = 0; - - /// Return the API-specific error, in human-readable form, or "" if no message - /// has been provided. - /// Valid when GetFutureStatus() is kFutureStatusComplete, and undefined - /// otherwise. - virtual const char* GetFutureErrorMessage( - const FutureHandle& handle) const = 0; - - /// Return a pointer to the completed asynchronous result, or NULL if - /// result is still pending. - /// After an asynchronous call is marked complete, the API should not - /// modify the result (especially on a callback thread), since the threads - /// owning the Future can reference the result memory via this function. - virtual const void* GetFutureResult(const FutureHandle& handle) const = 0; - - /// Register a callback that will be called when this future's status is set - /// to Complete. If clear_existing_callbacks is true, then the new callback - /// will replace any existing callbacks, otherwise it will be added to the - /// list of callbacks. - /// - /// The future's result data will be passed back when the callback is - /// called, along with the user_data supplied here. - /// - /// After the callback has been called, if `user_data_delete_fn_ptr` is - /// non-null, then `(*user_data_delete_fn_ptr)(user_data)` will be called. - virtual CompletionCallbackHandle AddCompletionCallback( - const FutureHandle& handle, FutureBase::CompletionCallback callback, - void* user_data, void (*user_data_delete_fn)(void*), - bool clear_existing_callbacks) = 0; - - /// Unregister a callback that was previously registered with - /// `AddCompletionCallback`. - virtual void RemoveCompletionCallback( - const FutureHandle& handle, CompletionCallbackHandle callback_handle) = 0; - -#if defined(FIREBASE_USE_STD_FUNCTION) - /// Register a callback that will be called when this future's status is set - /// to Complete. - /// - /// If `clear_existing_callbacks` is true, then the new callback - /// will replace any existing callbacks, otherwise it will be added to the - /// list of callbacks. - /// - /// The future's result data will be passed back when the callback is - /// called. - /// - /// @return A handle that can be passed to `FutureBase::RemoveCompletion`. - virtual CompletionCallbackHandle AddCompletionCallbackLambda( - const FutureHandle& handle, - std::function callback, - bool clear_existing_callbacks) = 0; -#endif // defined(FIREBASE_USE_STD_FUNCTION) - - /// Register this Future instance to be cleaned up. - virtual void RegisterFutureForCleanup(FutureBase* future) = 0; - - /// Unregister this Future instance from the cleanup list. - virtual void UnregisterFutureForCleanup(FutureBase* future) = 0; -}; - -inline void RegisterForCleanup(FutureApiInterface* api, FutureBase* future) { - if (api != NULL) { // NOLINT - api->RegisterFutureForCleanup(future); - } -} - -inline void UnregisterForCleanup(FutureApiInterface* api, FutureBase* future) { - if (api != NULL) { // NOLINT - api->UnregisterFutureForCleanup(future); - } -} - -class CompletionCallbackHandle { - public: - // Construct a null CompletionCallbackHandle. - CompletionCallbackHandle() - : callback_(nullptr), - user_data_(nullptr), - user_data_delete_fn_(nullptr) {} - - private: - friend class ::firebase::FutureBase; - friend class ::firebase::ReferenceCountedFutureImpl; - CompletionCallbackHandle(FutureBase::CompletionCallback callback, - void* user_data, void (*user_data_delete_fn)(void*)) - : callback_(callback), - user_data_(user_data), - user_data_delete_fn_(user_data_delete_fn) {} - - FutureBase::CompletionCallback callback_; - void* user_data_; - void (*user_data_delete_fn_)(void*); -}; - -} // namespace detail - -template -void Future::OnCompletion(TypedCompletionCallback callback, - void* user_data) const { - FutureBase::OnCompletion(reinterpret_cast(callback), - user_data); -} - -#if defined(FIREBASE_USE_STD_FUNCTION) -template -inline void Future::OnCompletion( - std::function&)> callback) const { - FutureBase::OnCompletion( - *reinterpret_cast*>(&callback)); -} -#endif // defined(FIREBASE_USE_STD_FUNCTION) - -#if defined(INTERNAL_EXPERIMENTAL) -template -FutureBase::CompletionCallbackHandle Future::AddOnCompletion( - TypedCompletionCallback callback, void* user_data) const { - return FutureBase::AddOnCompletion( - reinterpret_cast(callback), user_data); -} - -#if defined(FIREBASE_USE_STD_FUNCTION) -template -inline FutureBase::CompletionCallbackHandle Future::AddOnCompletion( - std::function&)> callback) const { - return FutureBase::AddOnCompletion( - *reinterpret_cast*>(&callback)); -} -#endif // defined(FIREBASE_USE_STD_FUNCTION) - -#endif // defined(INTERNAL_EXPERIMENTAL) - -inline FutureBase::FutureBase() - : mutex_(Mutex::Mode::kModeNonRecursive), - api_(NULL), - handle_(0) {} // NOLINT - -inline FutureBase::FutureBase(detail::FutureApiInterface* api, - const FutureHandle& handle) - : mutex_(Mutex::Mode::kModeNonRecursive), api_(api), handle_(handle) { - api_->ReferenceFuture(handle_); - // Once the FutureBase has reference, we don't need extra handle reference. - handle_.Detach(); - detail::RegisterForCleanup(api_, this); -} - -inline FutureBase::~FutureBase() { Release(); } - -inline FutureBase::FutureBase(const FutureBase& rhs) - : mutex_(Mutex::Mode::kModeNonRecursive), - api_(NULL) // NOLINT -{ // NOLINT - *this = rhs; -} - -inline FutureBase& FutureBase::operator=(const FutureBase& rhs) { - Release(); - - detail::FutureApiInterface* new_api; - FutureHandle new_handle; - { - MutexLock lock(rhs.mutex_); - new_api = rhs.api_; - new_handle = rhs.handle_; - } - - { - MutexLock lock(mutex_); - api_ = new_api; - handle_ = new_handle; - - if (api_ != NULL) { // NOLINT - api_->ReferenceFuture(handle_); - } - detail::RegisterForCleanup(api_, this); - } - - return *this; -} - -#if defined(FIREBASE_USE_MOVE_OPERATORS) -inline FutureBase::FutureBase(FutureBase&& rhs) noexcept - : mutex_(Mutex::Mode::kModeNonRecursive), - api_(NULL) // NOLINT -{ - *this = std::move(rhs); -} - -inline FutureBase& FutureBase::operator=(FutureBase&& rhs) noexcept { - Release(); - - detail::FutureApiInterface* new_api; - FutureHandle new_handle; - { - MutexLock lock(rhs.mutex_); - detail::UnregisterForCleanup(rhs.api_, &rhs); - new_api = rhs.api_; - new_handle = rhs.handle_; - rhs.api_ = NULL; // NOLINT - } - - MutexLock lock(mutex_); - api_ = new_api; - handle_ = new_handle; - detail::RegisterForCleanup(api_, this); - return *this; -} -#endif // defined(FIREBASE_USE_MOVE_OPERATORS) - -inline void FutureBase::Release() { - MutexLock lock(mutex_); - if (api_ != NULL) { // NOLINT - detail::UnregisterForCleanup(api_, this); - api_->ReleaseFuture(handle_); - api_ = NULL; // NOLINT - } -} - -inline FutureStatus FutureBase::status() const { - MutexLock lock(mutex_); - return api_ == NULL ? // NOLINT - kFutureStatusInvalid - : api_->GetFutureStatus(handle_); -} - -inline int FutureBase::error() const { - MutexLock lock(mutex_); - return api_ == NULL ? -1 : api_->GetFutureError(handle_); // NOLINT -} - -inline const char* FutureBase::error_message() const { - MutexLock lock(mutex_); - return api_ == NULL ? NULL : api_->GetFutureErrorMessage(handle_); // NOLINT -} - -inline const void* FutureBase::result_void() const { - MutexLock lock(mutex_); - return api_ == NULL ? NULL : api_->GetFutureResult(handle_); // NOLINT -} - -inline void FutureBase::OnCompletion(CompletionCallback callback, - void* user_data) const { - MutexLock lock(mutex_); - if (api_ != NULL) { // NOLINT - api_->AddCompletionCallback(handle_, callback, user_data, nullptr, - /*clear_existing_callbacks=*/true); - } -} - -#if defined(INTERNAL_EXPERIMENTAL) -inline FutureBase::CompletionCallbackHandle FutureBase::AddOnCompletion( - CompletionCallback callback, void* user_data) const { - MutexLock lock(mutex_); - if (api_ != NULL) { // NOLINT - return api_->AddCompletionCallback(handle_, callback, user_data, nullptr, - /*clear_existing_callbacks=*/false); - } - return CompletionCallbackHandle(); -} - -inline void FutureBase::RemoveOnCompletion( - CompletionCallbackHandle completion_handle) const { - MutexLock lock(mutex_); - if (api_ != NULL) { // NOLINT - api_->RemoveCompletionCallback(handle_, completion_handle); - } -} -#endif // defined(INTERNAL_EXPERIMENTAL) - -#if defined(FIREBASE_USE_STD_FUNCTION) -inline void FutureBase::OnCompletion( - std::function callback) const { - MutexLock lock(mutex_); - if (api_ != NULL) { // NOLINT - api_->AddCompletionCallbackLambda(handle_, callback, - /*clear_existing_callbacks=*/true); - } -} - -#if defined(INTERNAL_EXPERIMENTAL) -inline FutureBase::CompletionCallbackHandle FutureBase::AddOnCompletion( - std::function callback) const { - MutexLock lock(mutex_); - if (api_ != NULL) { // NOLINT - return api_->AddCompletionCallbackLambda( - handle_, callback, - /*clear_existing_callbacks=*/false); - } - return CompletionCallbackHandle(); -} -#endif // defined(INTERNAL__EXPERIMENTAL) - -#endif // defined(FIREBASE_USE_STD_FUNCTION) - -// NOLINTNEXTLINE - allow namespace overridden -} // namespace firebase - -/// @endcond - -#endif // FIREBASE_APP_SRC_INCLUDE_FIREBASE_INTERNAL_FUTURE_IMPL_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/internal/mutex.h b/packages/firebase_core/firebase_core/firebase_core/firebase/internal/mutex.h deleted file mode 100644 index 86f6a45d1b38..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/internal/mutex.h +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Copyright 2016 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_APP_SRC_INCLUDE_FIREBASE_INTERNAL_MUTEX_H_ -#define FIREBASE_APP_SRC_INCLUDE_FIREBASE_INTERNAL_MUTEX_H_ - -#include "firebase/internal/platform.h" - -#if FIREBASE_PLATFORM_WINDOWS -#include -#else -#include -#endif // FIREBASE_PLATFORM_WINDOWS - -namespace firebase { - -#if !defined(DOXYGEN) - -/// @brief A simple synchronization lock. Only one thread at a time can Acquire. -class Mutex { - public: - // Bitfield that describes the mutex configuration. - enum Mode { - kModeNonRecursive = (0 << 0), - kModeRecursive = (1 << 0), - }; - - Mutex() : Mutex(kModeRecursive) {} - - explicit Mutex(Mode mode); - - ~Mutex(); - - // Acquires the lock for this mutex, blocking until it is available. - void Acquire(); - - // Releases the lock for this mutex acquired by a previous `Acquire()` call. - void Release(); - -// Returns the implementation-defined native mutex handle. -// Used by firebase::Thread implementation. -#if FIREBASE_PLATFORM_WINDOWS - HANDLE* native_handle() { return &synchronization_object_; } -#else - pthread_mutex_t* native_handle() { return &mutex_; } -#endif // FIREBASE_PLATFORM_WINDOWS - - private: - Mutex(const Mutex&) = delete; - Mutex& operator=(const Mutex&) = delete; - -#if FIREBASE_PLATFORM_WINDOWS - HANDLE synchronization_object_; - Mode mode_; -#else - pthread_mutex_t mutex_; -#endif // FIREBASE_PLATFORM_WINDOWS -}; - -/// @brief Acquire and hold a /ref Mutex, while in scope. -/// -/// Example usage: -/// \code{.cpp} -/// Mutex syncronization_mutex; -/// void MyFunctionThatRequiresSynchronization() { -/// MutexLock lock(syncronization_mutex); -/// // ... logic ... -/// } -/// \endcode -class MutexLock { - public: - explicit MutexLock(Mutex& mutex) : mutex_(&mutex) { mutex_->Acquire(); } - ~MutexLock() { mutex_->Release(); } - - private: - // Copy is disallowed. - MutexLock(const MutexLock& rhs); // NOLINT - MutexLock& operator=(const MutexLock& rhs); - - Mutex* mutex_; -}; - -#endif // !defined(DOXYGEN) - -} // namespace firebase - -#endif // FIREBASE_APP_SRC_INCLUDE_FIREBASE_INTERNAL_MUTEX_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/internal/platform.h b/packages/firebase_core/firebase_core/firebase_core/firebase/internal/platform.h deleted file mode 100644 index 17d64e32d022..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/internal/platform.h +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Copyright 2019 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_APP_SRC_INCLUDE_FIREBASE_INTERNAL_PLATFORM_H_ -#define FIREBASE_APP_SRC_INCLUDE_FIREBASE_INTERNAL_PLATFORM_H_ - -// This header serts exactly one of these FIREBASE_PLATFORM macros to 1, and the -// rest to 0: -// -// FIREBASE_PLATFORM_ANDROID -// FIREBASE_PLATFORM_IOS -// FIREBASE_PLATFORM_TVOS -// FIREBASE_PLATFORM_OSX -// FIREBASE_PLATFORM_WINDOWS -// FIREBASE_PLATFORM_LINUX -// FIREBASE_PLATFORM_UNKNOWN -// -// You can use e.g. #if FIREBASE_PLATFORM_OSX to conditionally compile code -// after including this header. -// -// It also defines some convenience macros: -// FIREBASE_PLATFORM_DESKTOP (1 on OSX, WINDOWS, and LINUX, 0 otherwise) -// FIREBASE_PLATFORM_MOBILE (1 on IOS and ANDROID, 0 otherwise) - -#define FIREBASE_PLATFORM_ANDROID 0 -#define FIREBASE_PLATFORM_IOS 0 -#define FIREBASE_PLATFORM_TVOS 0 -#define FIREBASE_PLATFORM_OSX 0 -#define FIREBASE_PLATFORM_WINDOWS 0 -#define FIREBASE_PLATFORM_LINUX 0 -#define FIREBASE_PLATFORM_UNKNOWN 0 - -#ifdef __APPLE__ -#include "TargetConditionals.h" -#endif // __APPLE__ - -#if defined(__ANDROID__) -#undef FIREBASE_PLATFORM_ANDROID -#define FIREBASE_PLATFORM_ANDROID 1 -#elif defined(TARGET_OS_IOS) && TARGET_OS_IOS -#undef FIREBASE_PLATFORM_IOS -#define FIREBASE_PLATFORM_IOS 1 -#elif defined(TARGET_OS_TV) && TARGET_OS_TV -#undef FIREBASE_PLATFORM_TVOS -#define FIREBASE_PLATFORM_TVOS 1 -#elif defined(TARGET_OS_OSX) && TARGET_OS_OSX -#undef FIREBASE_PLATFORM_OSX -#define FIREBASE_PLATFORM_OSX 1 -#elif defined(_WIN32) -#undef FIREBASE_PLATFORM_WINDOWS -#define FIREBASE_PLATFORM_WINDOWS 1 -#elif defined(__linux__) -#undef FIREBASE_PLATFORM_LINUX -#define FIREBASE_PLATFORM_LINUX 1 -#else -#undef FIREBASE_PLATFORM_UNKNOWN -#define FIREBASE_PLATFORM_UNKNOWN 1 -#endif - -#if FIREBASE_PLATFORM_LINUX - -// Include std library header to get version defines -#include - -#if defined(__clang__) -#define FIREBASE_COMPILER_CLANG 1 -#elif defined(__GNUC__) -#define FIREBASE_COMPILER_GCC 1 -#endif - -#if defined(_LIBCPP_VERSION) -#define FIREBASE_STANDARD_LIBCPP 1 -#elif defined(__GLIBCXX__) -#define FIREBASE_STANDARD_LIBSTDCPP 1 -#endif - -#if (FIREBASE_COMPILER_CLANG && FIREBASE_STANDARD_LIBCPP) -#define FIREBASE_LINUX_BUILD_CONFIG_STRING "clang_libstdcpp" -#elif (FIREBASE_COMPILER_CLANG && FIREBASE_STANDARD_LIBSTDCPP) -#define FIREBASE_LINUX_BUILD_CONFIG_STRING "clang_libcpp" -#elif (FIREBASE_COMPILER_GCC && FIREBASE_STANDARD_LIBCPP) -#define FIREBASE_LINUX_BUILD_CONFIG_STRING "gcc_libstdcpp" -#elif (FIREBASE_COMPILER_GCC && FIREBASE_STANDARD_LIBSTDCPP) -#define FIREBASE_LINUX_BUILD_CONFIG_STRING "gcc_libcpp" -#else -#error "Unsupported compiler or standard library" -#endif - -#endif // FIREBASE_PLATFORM_LINUX - -#define FIREBASE_PLATFORM_MOBILE \ - (FIREBASE_PLATFORM_IOS || FIREBASE_PLATFORM_ANDROID) -#define FIREBASE_PLATFORM_DESKTOP \ - (FIREBASE_PLATFORM_LINUX || FIREBASE_PLATFORM_WINDOWS || \ - FIREBASE_PLATFORM_OSX) - -#endif // FIREBASE_APP_SRC_INCLUDE_FIREBASE_INTERNAL_PLATFORM_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/internal/type_traits.h b/packages/firebase_core/firebase_core/firebase_core/firebase/internal/type_traits.h deleted file mode 100644 index 7c465ea27c1e..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/internal/type_traits.h +++ /dev/null @@ -1,134 +0,0 @@ -/* - * Copyright 2017 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_APP_SRC_INCLUDE_FIREBASE_INTERNAL_TYPE_TRAITS_H_ -#define FIREBASE_APP_SRC_INCLUDE_FIREBASE_INTERNAL_TYPE_TRAITS_H_ - -#include -#include - -// Doxygen breaks trying to parse this file, and since it is internal logic, -// it doesn't need to be included in the generated documentation. -#ifndef DOXYGEN - -namespace firebase { - -template -struct remove_reference { - typedef T type; -}; - -template -struct remove_reference { - typedef T type; -}; - -template -struct remove_reference { - typedef T type; -}; - -template -struct is_array { - static constexpr bool value = false; -}; - -template -struct is_array { - static constexpr bool value = true; -}; - -template -struct is_array { - static constexpr bool value = true; -}; - -template -struct is_lvalue_reference { - static constexpr bool value = false; -}; - -template -struct is_lvalue_reference { - static constexpr bool value = true; -}; - -// STLPort does include header, but its contents are in `std::tr1` -// namespace. To work around this, use aliases. -// TODO(varconst): all of the reimplementations of traits above can be replaced -// with appropriate aliases. -// TODO(varconst): the traits in this file would be more conformant if they -// inherited from `std::integral_constant`. -#ifdef STLPORT -#define FIREBASE_TYPE_TRAITS_NS std::tr1 -#else -#define FIREBASE_TYPE_TRAITS_NS std -#endif - -template -using decay = FIREBASE_TYPE_TRAITS_NS::decay; - -template -using decay_t = typename decay::type; - -template -using enable_if = FIREBASE_TYPE_TRAITS_NS::enable_if; - -template -using is_floating_point = FIREBASE_TYPE_TRAITS_NS::is_floating_point; - -template -using is_integral = FIREBASE_TYPE_TRAITS_NS::is_integral; - -template -using is_same = FIREBASE_TYPE_TRAITS_NS::is_same; - -template -using integral_constant = FIREBASE_TYPE_TRAITS_NS::integral_constant; - -using true_type = FIREBASE_TYPE_TRAITS_NS::true_type; -using false_type = FIREBASE_TYPE_TRAITS_NS::false_type; - -#undef FIREBASE_TYPE_TRAITS_NS - -// `is_char::value` is true iff `T` is a character type (including `wchar_t` -// and C++11 fixed-width character types). -template -struct is_char { - static constexpr bool value = -#if __cplusplus >= 202002L - is_same::value || -#endif -#if __cplusplus >= 201103L - is_same::value || is_same::value || -#endif - is_same::value || is_same::value || - is_same::value || is_same::value; -}; - -// A subset of `std::is_integral`: excludes `bool` and character types. -template -struct is_integer { - static constexpr bool value = - is_integral::value && !is_same::value && !is_char::value; -}; - -// NOLINTNEXTLINE - allow namespace overridden -} // namespace firebase - -#endif // DOXYGEN - -#endif // FIREBASE_APP_SRC_INCLUDE_FIREBASE_INTERNAL_TYPE_TRAITS_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/log.h b/packages/firebase_core/firebase_core/firebase_core/firebase/log.h deleted file mode 100644 index 3d36ce37dcb3..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/log.h +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright 2016 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_APP_SRC_INCLUDE_FIREBASE_LOG_H_ -#define FIREBASE_APP_SRC_INCLUDE_FIREBASE_LOG_H_ - -/// @brief Namespace that encompasses all Firebase APIs. -namespace firebase { - -/// @brief Levels used when logging messages. -enum LogLevel { - /// Verbose Log Level - kLogLevelVerbose = 0, - /// Debug Log Level - kLogLevelDebug, - /// Info Log Level - kLogLevelInfo, - /// Warning Log Level - kLogLevelWarning, - /// Error Log Level - kLogLevelError, - /// Assert Log Level - kLogLevelAssert, -}; - -/// @brief Sets the logging verbosity. -/// All log messages at or above the specific log level. -/// -/// @param[in] level Log level to display, by default this is set to -/// kLogLevelInfo. -void SetLogLevel(LogLevel level); - -/// @brief Gets the logging verbosity. -/// -/// @return Get the currently configured logging verbosity. -LogLevel GetLogLevel(); - -// NOLINTNEXTLINE - allow namespace overridden -} // namespace firebase - -#endif // FIREBASE_APP_SRC_INCLUDE_FIREBASE_LOG_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/messaging.h b/packages/firebase_core/firebase_core/firebase_core/firebase/messaging.h deleted file mode 100644 index e7c7f5776868..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/messaging.h +++ /dev/null @@ -1,728 +0,0 @@ -// Copyright 2016 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef FIREBASE_MESSAGING_SRC_INCLUDE_FIREBASE_MESSAGING_H_ -#define FIREBASE_MESSAGING_SRC_INCLUDE_FIREBASE_MESSAGING_H_ - -#include - -#include -#include -#include - -#include "firebase/app.h" -#include "firebase/future.h" -#include "firebase/internal/common.h" - -#if !defined(DOXYGEN) && !defined(SWIG) -FIREBASE_APP_REGISTER_CALLBACKS_REFERENCE(messaging) -#endif // !defined(DOXYGEN) && !defined(SWIG) - -namespace firebase { - -/// @brief Firebase Cloud Messaging API. -/// -/// Firebase Cloud Messaging allows you to send data from your server to your -/// users' devices, and receive messages from devices on the same connection -/// if you're using a XMPP server. -/// -/// The FCM service handles all aspects of queueing of messages and delivery -/// to client applications running on target devices. -namespace messaging { - -/// @brief A class to configure the behavior of Firebase Cloud Messaging. -/// -/// This class contains various configuration options that control some of -/// Firebase Cloud Messaging's behavior. -struct MessagingOptions { - /// Default constructor. - MessagingOptions() : suppress_notification_permission_prompt(false) {} - - /// If true, do not display the prompt to the user requesting permission to - /// allow notifications to this app. If the prompt is suppressed in this way, - /// the developer must manually prompt the user for permission at some point - /// in the future using `RequestPermission()`. - /// - /// If this prompt has already been accepted once in the past the prompt will - /// not be displayed again. - /// - /// This option currently only applies to iOS and tvOS. - bool suppress_notification_permission_prompt; -}; - -/// @brief Data structure for parameters that are unique to the Android -/// implementation. -struct AndroidNotificationParams { - /// The channel id that was provided when the message was sent. - std::string channel_id; -}; - -/// Used for messages that display a notification. -/// -/// On android, this requires that the app is using the Play Services client -/// library. -struct Notification { - Notification() : android(nullptr) {} - -#ifndef SWIG - /// Copy constructor. Makes a deep copy of this Message. - Notification(const Notification& other) : android(nullptr) { *this = other; } -#endif // !SWIG - -#ifndef SWIG - /// Copy assignment operator. Makes a deep copy of this Message. - Notification& operator=(const Notification& other) { - this->title = other.title; - this->body = other.body; - this->icon = other.icon; - this->sound = other.sound; - this->tag = other.tag; - this->color = other.color; - this->click_action = other.click_action; - this->body_loc_key = other.body_loc_key; - this->body_loc_args = other.body_loc_args; - this->title_loc_key = other.title_loc_key; - this->title_loc_args = other.title_loc_args; - delete this->android; - if (other.android) { - this->android = new AndroidNotificationParams(*other.android); - } else { - this->android = nullptr; - } - return *this; - } -#endif // !SWIG - - /// Destructor. - ~Notification() { delete android; } - - /// Indicates notification title. This field is not visible on tvOS, iOS - /// phones and tablets. - std::string title; - - /// Indicates notification body text. - std::string body; - - /// Indicates notification icon. Sets value to myicon for drawable resource - /// myicon. - std::string icon; - - /// Indicates a sound to play when the device receives the notification. - /// Supports default, or the filename of a sound resource bundled in the - /// app. - /// - /// Android sound files must reside in /res/raw/, while iOS and tvOS sound - /// files can be in the main bundle of the client app or in the - /// Library/Sounds folder of the app’s data container. - std::string sound; - - /// Indicates the badge on the client app home icon. iOS and tvOS only. - std::string badge; - - /// Indicates whether each notification results in a new entry in the - /// notification drawer on Android. If not set, each request creates a new - /// notification. If set, and a notification with the same tag is already - /// being shown, the new notification replaces the existing one in the - /// notification drawer. - std::string tag; - - /// Indicates color of the icon, expressed in \#rrggbb format. Android only. - std::string color; - - /// The action associated with a user click on the notification. - /// - /// On Android, if this is set, an activity with a matching intent filter is - /// launched when user clicks the notification. - /// - /// If set on iOS or tvOS, corresponds to category in APNS payload. - std::string click_action; - - /// Indicates the key to the body string for localization. - /// - /// On iOS and tvOS, this corresponds to "loc-key" in APNS payload. - /// - /// On Android, use the key in the app's string resources when populating this - /// value. - std::string body_loc_key; - - /// Indicates the string value to replace format specifiers in body string - /// for localization. - /// - /// On iOS and tvOS, this corresponds to "loc-args" in APNS payload. - /// - /// On Android, these are the format arguments for the string resource. For - /// more information, see [Formatting strings][1]. - /// - /// [1]: - /// https://developer.android.com/guide/topics/resources/string-resource.html#FormattingAndStyling - std::vector body_loc_args; - - /// Indicates the key to the title string for localization. - /// - /// On iOS and tvOS, this corresponds to "title-loc-key" in APNS payload. - /// - /// On Android, use the key in the app's string resources when populating this - /// value. - std::string title_loc_key; - - /// Indicates the string value to replace format specifiers in title string - /// for localization. - /// - /// On iOS and tvOS, this corresponds to "title-loc-args" in APNS payload. - /// - /// On Android, these are the format arguments for the string resource. For - /// more information, see [Formatting strings][1]. - /// - /// [1]: - /// https://developer.android.com/guide/topics/resources/string-resource.html#FormattingAndStyling - std::vector title_loc_args; - - /// Parameters that are unique to the Android implementation. - AndroidNotificationParams* android; -}; - -/// @brief Data structure used to send messages to, and receive messages from, -/// cloud messaging. -struct Message { - /// Initialize the message. - Message() - : time_to_live(0), - notification(nullptr), - notification_opened(false), - sent_time(0) {} - - /// Destructor. - ~Message() { delete notification; } - -#ifndef SWIG - /// Copy constructor. Makes a deep copy of this Message. - Message(const Message& other) : notification(nullptr) { *this = other; } -#endif // !SWIG - -#ifndef SWIG - /// Copy assignment operator. Makes a deep copy of this Message. - Message& operator=(const Message& other) { - this->from = other.from; - this->to = other.to; - this->collapse_key = other.collapse_key; - this->data = other.data; - this->raw_data = other.raw_data; - this->message_id = other.message_id; - this->message_type = other.message_type; - this->priority = other.priority; - this->original_priority = other.original_priority; - this->sent_time = other.sent_time; - this->time_to_live = other.time_to_live; - this->error = other.error; - this->error_description = other.error_description; - delete this->notification; - if (other.notification) { - this->notification = new Notification(*other.notification); - } else { - this->notification = nullptr; - } - this->notification_opened = other.notification_opened; - this->link = other.link; - return *this; - } -#endif // !SWIG - - /// Authenticated ID of the sender. This is a project number in most cases. - /// - /// Any value starting with google.com, goog. or gcm. are reserved. - /// - /// This field is only used for downstream messages received through - /// Listener::OnMessage(). - std::string from; - - /// This parameter specifies the recipient of a message. - /// - /// For example it can be a registration token, a topic name, an Instance ID - /// or project ID. - /// - /// PROJECT_ID@gcm.googleapis.com or Instance ID are accepted. - std::string to; - - /// This parameter identifies a group of messages (e.g., with collapse_key: - /// "Updates Available") that can be collapsed, so that only the last message - /// gets sent when delivery can be resumed. This is intended to avoid sending - /// too many of the same messages when the device comes back online or becomes - /// active. - /// - /// Note that there is no guarantee of the order in which messages get sent. - /// - /// Note: A maximum of 4 different collapse keys is allowed at any given time. - /// This means a FCM connection server can simultaneously store 4 different - /// send-to-sync messages per client app. If you exceed this number, there is - /// no guarantee which 4 collapse keys the FCM connection server will keep. - /// - /// This field is only used for downstream messages received through - /// Listener::OnMessage(). - std::string collapse_key; - - /// The metadata, including all original key/value pairs. Includes some of the - /// HTTP headers used when sending the message. `gcm`, `google` and `goog` - /// prefixes are reserved for internal use. - std::map data; - - /// Binary payload. - std::vector raw_data; - - /// Message ID. This can be specified by sender. Internally a hash of the - /// message ID and other elements will be used for storage. The ID must be - /// unique for each topic subscription - using the same ID may result in - /// overriding the original message or duplicate delivery. - std::string message_id; - - /// Equivalent with a content-type. - /// - /// Defined values: - /// - "deleted_messages" - indicates the server had too many messages and - /// dropped some, and the client should sync with his own server. - /// Current limit is 100 messages stored. - /// - "send_event" - indicates an upstream message has been pushed to the - /// FCM server. It does not guarantee the upstream destination received - /// it. - /// Parameters: "message_id" - /// - "send_error" - indicates an upstream message expired, without being - /// sent to the FCM server. - /// Parameters: "message_id" and "error" - /// - /// If this field is missing, the message is a regular message. - /// - /// This field is only used for downstream messages received through - /// Listener::OnMessage(). - std::string message_type; - - /// Sets the priority of the message. Valid values are "normal" and "high." On - /// iOS and tvOS, these correspond to APNs priority 5 and 10. - /// - /// By default, messages are sent with normal priority. Normal priority - /// optimizes the client app's battery consumption, and should be used unless - /// immediate delivery is required. For messages with normal priority, the app - /// may receive the message with unspecified delay. - /// - /// When a message is sent with high priority, it is sent immediately, and the - /// app can wake a sleeping device and open a network connection to your - /// server. - /// - /// For more information, see [Setting the priority of a message][1]. - /// - /// This field is only used for downstream messages received through - /// Listener::OnMessage(). - /// - /// [1]: - /// https://firebase.google.com/docs/cloud-messaging/concept-options#setting-the-priority-of-a-message - std::string priority; - - /// This parameter specifies 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. For more - /// information, see [Setting the lifespan of a message][1]. - /// - /// This field is only used for downstream messages received through - /// Listener::OnMessage(). - /// - /// [1]: https://firebase.google.com/docs/cloud-messaging/concept-options#ttl - int32_t time_to_live; - - /// Error code. Used in "nack" messages for CCS, and in responses from the - /// server. - /// See the CCS specification for the externally-supported list. - /// - /// This field is only used for downstream messages received through - /// Listener::OnMessage(). - std::string error; - - /// Human readable details about the error. - /// - /// This field is only used for downstream messages received through - /// Listener::OnMessage(). - std::string error_description; - - /// Optional notification to show. This only set if a notification was - /// received with this message, otherwise it is null. - /// - /// The notification is only guaranteed to be valid during the call to - /// Listener::OnMessage(). If you need to keep it around longer you will need - /// to make a copy of either the Message or Notification. Copying the Message - /// object implicitly makes a deep copy of the notification (allocated with - /// new) which is owned by the Message. - /// - /// This field is only used for downstream messages received through - /// Listener::OnMessage(). - Notification* notification; - - /// A flag indicating whether this message was opened by tapping a - /// notification in the OS system tray. If the message was received this way - /// this flag is set to true. - bool notification_opened; - - /// The link into the app from the message. - /// - /// This field is only used for downstream messages received through - /// Listener::OnMessage(). - std::string link; - - /// @cond FIREBASE_APP_INTERNAL - /// Original priority of the message. - std::string original_priority; - - /// UTC timestamp in milliseconds when the message was sent. - /// See https://en.wikipedia.org/wiki/Unix_time for details of UTC. - int64_t sent_time; - /// @endcond -}; - -/// @brief Base class used to receive messages from Firebase Cloud Messaging. -/// -/// You need to override base class methods to handle any events required by the -/// application. Methods are invoked asynchronously and may be invoked on other -/// threads. -class Listener { - public: - virtual ~Listener(); - - /// Called on the client when a message arrives. - /// - /// @param[in] message The data describing this message. - virtual void OnMessage(const Message& message) = 0; - - /// Called on the client when a registration token arrives. This function - /// will eventually be called in response to a call to - /// firebase::messaging::Initialize(...). - /// - /// @param[in] token The registration token. - virtual void OnTokenReceived(const char* token) = 0; -}; - -/// @brief Initialize Firebase Cloud Messaging. -/// -/// After Initialize is called, the implementation may call functions on the -/// Listener provided at any time. -/// -/// @param[in] app The Firebase App object for this application. -/// @param[in] listener A Listener object that listens for events from the -/// Firebase Cloud Messaging servers. -/// -/// @return kInitResultSuccess if initialization succeeded, or -/// kInitResultFailedMissingDependency on Android if Google Play services is -/// not available on the current device. -InitResult Initialize(const App& app, Listener* listener); - -/// @brief Initialize Firebase Cloud Messaging. -/// -/// After Initialize is called, the implementation may call functions on the -/// Listener provided at any time. -/// -/// @param[in] app The Firebase App object for this application. -/// @param[in] listener A Listener object that listens for events from the -/// Firebase Cloud Messaging servers. -/// @param[in] options A set of options that configure the -/// initialzation behavior of Firebase Cloud Messaging. -/// -/// @return kInitResultSuccess if initialization succeeded, or -/// kInitResultFailedMissingDependency on Android if Google Play services is -/// not available on the current device. -InitResult Initialize(const App& app, Listener* listener, - const MessagingOptions& options); - -/// @brief Terminate Firebase Cloud Messaging. -/// -/// Frees resources associated with Firebase Cloud Messaging. -/// -/// @note On Android, the services will not be shut down by this method. -void Terminate(); - -/// Determines if automatic token registration during initalization is enabled. -/// -/// @return true if auto token registration is enabled and false if disabled. -bool IsTokenRegistrationOnInitEnabled(); - -/// Enable or disable token registration during initialization of Firebase Cloud -/// Messaging. -/// -/// This token is what identifies the user to Firebase, so disabling this avoids -/// creating any new identity and automatically sending it to Firebase, unless -/// consent has been granted. -/// -/// If this setting is enabled, it triggers the token registration refresh -/// immediately. This setting is persisted across app restarts and overrides the -/// setting "firebase_messaging_auto_init_enabled" specified in your Android -/// manifest (on Android) or Info.plist (on iOS and tvOS). -/// -///

By default, token registration during initialization is enabled. -/// -/// The registration happens before you can programmatically disable it, so -/// if you need to change the default, (for example, because you want to prompt -/// the user before FCM generates/refreshes a registration token on app -/// startup), add to your application’s manifest: -/// -/// -/// @if NOT_DOXYGEN -/// -/// @else -/// @code -/// <meta-data android:name="firebase_messaging_auto_init_enabled" -/// android:value="false" /> -/// @endcode -/// @endif -/// -/// or on iOS or tvOS to your Info.plist: -/// -/// @if NOT_DOXYGEN -/// FirebaseMessagingAutoInitEnabled -/// -/// @else -/// @code -/// <key>FirebaseMessagingAutoInitEnabled</key> -/// <false/> -/// @endcode -/// @endif -/// -/// @param enable sets if a registration token should be requested on -/// initialization. -void SetTokenRegistrationOnInitEnabled(bool enable); - -#ifndef SWIG -/// @brief Set the listener for events from the Firebase Cloud Messaging -/// servers. -/// -/// A listener must be set for the application to receive messages from -/// the Firebase Cloud Messaging servers. The implementation may call functions -/// on the Listener provided at any time. -/// -/// @param[in] listener A Listener object that listens for events from the -/// Firebase Cloud Messaging servers. -/// -/// @return Pointer to the previously set listener. -Listener* SetListener(Listener* listener); -#endif // !SWIG - -/// Error code returned by Firebase Cloud Messaging C++ functions. -enum Error { - /// The operation was a success, no error occurred. - kErrorNone = 0, - /// Permission to receive notifications was not granted. - kErrorFailedToRegisterForRemoteNotifications, - /// Topic name is invalid for subscription/unsubscription. - kErrorInvalidTopicName, - /// Could not subscribe/unsubscribe because there is no registration token. - kErrorNoRegistrationToken, - /// Unknown error. - kErrorUnknown, -}; - -/// @brief Displays a prompt to the user requesting permission to display -/// notifications. -/// -/// The permission prompt only appears on iOS and tvOS. If the user has -/// already agreed to allow notifications, no prompt is displayed and the -/// returned future is completed immediately. -/// -/// @return A future that completes when the notification prompt has been -/// dismissed. -Future RequestPermission(); - -/// @brief Gets the result of the most recent call to RequestPermission(); -/// -/// @return Result of the most recent call to RequestPermission(). -Future RequestPermissionLastResult(); - -/// @brief Subscribe to receive all messages to the specified topic. -/// -/// Subscribes an app instance to a topic, enabling it to receive messages -/// sent to that topic. -/// -/// Call this function from the main thread. FCM is not thread safe. -/// -/// @param[in] topic The name of the topic to subscribe. Must match the -/// following regular expression: `[a-zA-Z0-9-_.~%]{1,900}`. -Future Subscribe(const char* topic); - -/// @brief Gets the result of the most recent call to Unsubscribe(); -/// -/// @return Result of the most recent call to Unsubscribe(). -Future SubscribeLastResult(); - -/// @brief Unsubscribe from a topic. -/// -/// Unsubscribes an app instance from a topic, stopping it from receiving -/// any further messages sent to that topic. -/// -/// Call this function from the main thread. FCM is not thread safe. -/// -/// @param[in] topic The name of the topic to unsubscribe from. Must match the -/// following regular expression: `[a-zA-Z0-9-_.~%]{1,900}`. -Future Unsubscribe(const char* topic); - -/// @brief Gets the result of the most recent call to Unsubscribe(); -/// -/// @return Result of the most recent call to Unsubscribe(). -Future UnsubscribeLastResult(); - -/// Determines whether Firebase Cloud Messaging exports message delivery metrics -/// to BigQuery. -/// -/// This function is currently only implemented on Android, and returns false -/// with no other behavior on other platforms. -/// -/// @return true if Firebase Cloud Messaging exports message delivery metrics to -/// BigQuery. -bool DeliveryMetricsExportToBigQueryEnabled(); - -/// Enables or disables Firebase Cloud Messaging message delivery metrics export -/// to BigQuery. -/// -/// By default, message delivery metrics are not exported to BigQuery. Use this -/// method to enable or disable the export at runtime. In addition, you can -/// enable the export by adding to your manifest. Note that the run-time method -/// call will override the manifest value. -/// -/// -/// -/// This function is currently only implemented on Android, and has no behavior -/// on other platforms. -/// -/// @param[in] enable Whether Firebase Cloud Messaging should export message -/// delivery metrics to BigQuery. -void SetDeliveryMetricsExportToBigQuery(bool enable); - -/// @brief This creates a Firebase Installations ID, if one does not exist, and -/// sends information about the application and the device where it's running to -/// the Firebase backend. -/// -/// @return A future with the token. -Future GetToken(); - -/// @brief Gets the result of the most recent call to GetToken(); -/// -/// @return Result of the most recent call to GetToken(). -Future GetTokenLastResult(); - -/// @brief Deletes the default token for this Firebase project. -/// -/// Note that this does not delete the Firebase Installations ID that may have -/// been created when generating the token. See Installations.Delete() for -/// deleting that. -/// -/// @return A future that completes when the token is deleted. -Future DeleteToken(); - -/// @brief Gets the result of the most recent call to DeleteToken(); -/// -/// @return Result of the most recent call to DeleteToken(). -Future DeleteTokenLastResult(); - -class PollableListenerImpl; - -/// @brief A listener that can be polled to consume pending `Message`s. -/// -/// This class is intended to be used with applications that have a main loop -/// that frequently updates, such as in the case of a game that has a main -/// loop that updates 30 to 60 times a second. Rather than respond to incoming -/// messages and tokens via the `OnMessage` virtual function, this class will -/// queue up the message internally in a thread-safe manner so that it can be -/// consumed with `PollMessage`. For example: -/// -/// ::firebase::messaging::PollableListener listener; -/// ::firebase::messaging::Initialize(app, &listener); -/// -/// while (true) { -/// std::string token; -/// if (listener.PollRegistrationToken(&token)) { -/// LogMessage("Received a registration token"); -/// } -/// -/// ::firebase::messaging::Message message; -/// while (listener.PollMessage(&message)) { -/// LogMessage("Received a new message"); -/// } -/// -/// // Remainder of application logic... -/// } -class PollableListener : public Listener { - public: - /// @brief The default constructor. - PollableListener(); - - /// @brief The required virtual destructor. - virtual ~PollableListener(); - - /// @brief An implementation of `OnMessage` which adds the incoming messages - /// to a queue, which can be consumed by calling `PollMessage`. - virtual void OnMessage(const Message& message); - - /// @brief An implementation of `OnTokenReceived` which stores the incoming - /// token so that it can be consumed by calling `PollRegistrationToken`. - virtual void OnTokenReceived(const char* token); - - /// @brief Returns the first message queued up, if any. - /// - /// If one or more messages has been received, the first message in the - /// queue will be popped and used to populate the `message` argument and the - /// function will return `true`. If there are no pending messages, `false` is - /// returned. This function should be called in a loop until all messages have - /// been consumed, like so: - /// - /// ::firebase::messaging::Message message; - /// while (listener.PollMessage(&message)) { - /// LogMessage("Received a new message"); - /// } - /// - /// @param[out] message The `Message` struct to be populated. If there were no - /// pending messages, `message` is not modified. - /// - /// @return Returns `true` if there was a pending message, `false` otherwise. - bool PollMessage(Message* message); - - /// @brief Returns the registration key, if a new one has been received. - /// - /// When a new registration token is received, it is cached internally and can - /// be retrieved by calling `PollRegistrationToken`. The cached registration - /// token will be used to populate the `token` argument, then the cache will - /// be cleared and the function will return `true`. If there is no cached - /// registration token this function retuns `false`. - /// - /// std::string token; - /// if (listener.PollRegistrationToken(&token)) { - /// LogMessage("Received a registration token"); - /// } - /// - /// @param[out] token A string to be populated with the new token if one has - /// been received. If there were no new token, the string is left unmodified. - /// - /// @return Returns `true` if there was a new token, `false` otherwise. - bool PollRegistrationToken(std::string* token) { - bool got_token; - std::string token_received = PollRegistrationToken(&got_token); - if (got_token) { - *token = token_received; - } - return got_token; - } - - private: - std::string PollRegistrationToken(bool* got_token); - - // The implementation of the `PollableListener`. - PollableListenerImpl* impl_; -}; - -} // namespace messaging -} // namespace firebase - -#endif // FIREBASE_MESSAGING_SRC_INCLUDE_FIREBASE_MESSAGING_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/remote_config.h b/packages/firebase_core/firebase_core/firebase_core/firebase/remote_config.h deleted file mode 100644 index a2bd41775775..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/remote_config.h +++ /dev/null @@ -1,526 +0,0 @@ -// Copyright 2016 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef FIREBASE_REMOTE_CONFIG_SRC_INCLUDE_FIREBASE_REMOTE_CONFIG_H_ -#define FIREBASE_REMOTE_CONFIG_SRC_INCLUDE_FIREBASE_REMOTE_CONFIG_H_ - -#include -#include -#include - -#include "firebase/app.h" -#include "firebase/future.h" -#include "firebase/internal/common.h" -#include "firebase/internal/platform.h" -#ifndef SWIG -#include "firebase/variant.h" -#endif // SWIG - -#if !defined(DOXYGEN) && !defined(SWIG) -FIREBASE_APP_REGISTER_CALLBACKS_REFERENCE(remote_config) -#endif // !defined(DOXYGEN) && !defined(SWIG) - -/// @brief Namespace that encompasses all Firebase APIs. -namespace firebase { - -#ifndef SWIG -/// @brief Firebase Remote Config API. -/// -/// Firebase Remote Config is a cloud service that lets you change the -/// appearance and behavior of your app without requiring users to download an -/// app update. -#endif // SWIG -namespace remote_config { - -/// @brief Describes the most recent fetch request status. -enum LastFetchStatus { - /// The most recent fetch was a success, and its data is ready to be - /// applied, if you have not already done so. - kLastFetchStatusSuccess, - /// The most recent fetch request failed. - kLastFetchStatusFailure, - /// The most recent fetch is still in progress. - kLastFetchStatusPending, -}; - -/// @brief Describes the most recent fetch failure. -enum FetchFailureReason { - /// The fetch has not yet failed. - kFetchFailureReasonInvalid, - /// The most recent fetch failed because it was throttled by the server. - /// (You are sending too many fetch requests in too short a time.) - kFetchFailureReasonThrottled, - /// The most recent fetch failed for an unknown reason. - kFetchFailureReasonError, -}; - -/// @brief Describes the state of the most recent Fetch() call. -/// Normally returned as a result of the GetInfo() function. -struct ConfigInfo { - /// @brief The time (in milliseconds since the epoch) that the last fetch - /// operation completed. - uint64_t fetch_time; - - /// @brief The status of the last fetch request. - LastFetchStatus last_fetch_status; - - /// @brief The reason the most recent fetch failed. - FetchFailureReason last_fetch_failure_reason; - - /// @brief The time (in milliseconds since the epoch) when the refreshing of - /// Remote Config data is throttled. - uint64_t throttled_end_time; -}; - -/// @brief Describes the source a config value was retrieved from. -enum ValueSource { - /// The value was not specified and no default was specified, so a static - /// value (0 for numeric values, an empty string for strings) was returned. - kValueSourceStaticValue, - /// The value was found in the remote data store, and returned. - kValueSourceRemoteValue, - /// The value was not specified, so the specified default value was - /// returned instead. - kValueSourceDefaultValue, -}; - -/// @brief Describes a retrieved value. -struct ValueInfo { - /// Where the config value was retrieved from (Default Config or Active - /// Config). - ValueSource source; - /// If true this indicates conversion to the requested type - /// succeeded, otherwise conversion failed so the static value for the - /// requested type was retrieved instead. - bool conversion_successful; -}; - -/// @brief Keys of API settings. -/// -/// @see SetConfigSetting -/// @see GetConfigSetting -enum ConfigSetting { - /// Set the value associated with this key to "1" to enable developer mode - /// (i.e disable throttling) and "0" to disable. - kConfigSettingDeveloperMode, -}; - -/// @brief The default cache expiration used by Fetch(), equal to 12 hours, -/// in milliseconds. -static const uint64_t kDefaultCacheExpiration = 60 * 60 * 12 * 1000; - -/// @brief The default timeout used by Fetch(), equal to 30 seconds, -/// in milliseconds. -static const uint64_t kDefaultTimeoutInMilliseconds = 30 * 1000; - -/// @brief Describes a mapping of a key to a string value. Used to set default -/// values. -struct ConfigKeyValue { - /// The lookup key string. -#ifndef SWIG - /// - /// @note Ensure this string stays valid for the duration of the - /// call to SetDefaults. -#endif // SWIG - const char* key; - /// The value string to be stored. -#ifndef SWIG - /// - /// @note Ensure this string stays valid for the duration of the - /// call to SetDefaults. -#endif // SWIG - const char* value; -}; - -#ifndef SWIG -/// @brief Describes a mapping of a key to a value of any type. Used to set -/// default values. -struct ConfigKeyValueVariant { - /// The lookup key string. - /// - /// @note Ensure this string stays valid for the duration of the - /// call to SetDefaults. - const char* key; - /// The value to be stored. The type of the Variant determines the type of - /// default data for the given key. - /// - /// @note If you use a Variant of type StaticString, ensure it stays - /// valid for the duration of the call to SetDefaults. - Variant value; -}; -#endif // SWIG - -/// @brief Configurations for Remote Config behavior. -struct ConfigSettings { - /// The timeout specifies how long the client should wait for a connection to - /// the Firebase Remote Config servers. - /// - /// @note A fetch call will fail if it takes longer than the specified timeout - /// to connect to the Remote Config servers. Default is 60 seconds. - uint64_t fetch_timeout_in_milliseconds = kDefaultTimeoutInMilliseconds; - - /// The minimum interval between successive fetch calls. - /// - /// @note Fetches less than duration seconds after the last fetch from the - /// Firebase Remote Config server would use values returned during the last - /// fetch. Default is 12 hours. - uint64_t minimum_fetch_interval_in_milliseconds = kDefaultCacheExpiration; -}; - -namespace internal { -class RemoteConfigInternal; -} // namespace internal - -#ifndef SWIG -/// @brief Entry point for the Firebase C++ SDK for Remote Config. -/// -/// To use the SDK, call firebase::remote_config::RemoteConfig::GetInstance() to -/// obtain an instance of RemoteConfig, then call operations on that instance. -/// The instance contains the complete set of FRC parameter values available to -/// your app. The instance also stores values fetched from the FRC Server until -/// they are made available for use with a call to @ref Activate(). -#endif // SWIG -class RemoteConfig { - public: - ~RemoteConfig(); - - /// @brief Returns a Future that contains ConfigInfo representing the - /// initialization status of this Firebase Remote Config instance. - /// Use this method to ensure Set/Get call not being blocked. - Future EnsureInitialized(); - - /// @brief Get the (possibly still pending) results of the most recent - /// EnsureInitialized() call. - /// - /// @return The future result from the last call to EnsureInitialized(). - Future EnsureInitializedLastResult(); - - /// Asynchronously activates the most recently fetched configs, so that the - /// fetched key value pairs take effect. - /// - /// @return A Future that contains true if fetched configs were - /// activated. The future will contain false if the configs were already - /// activated. - Future Activate(); - - /// @brief Get the (possibly still pending) results of the most recent - /// Activate() call. - /// - /// @return The future result from the last call to Activate(). - Future ActivateLastResult(); - - /// Asynchronously fetches and then activates the fetched configs. - /// - /// If the time elapsed since the last fetch from the Firebase Remote Config - /// backend is more than the default minimum fetch interval, configs are - /// fetched from the backend. - /// - /// After the fetch is complete, the configs are activated so that the fetched - /// key value pairs take effect. - /// - /// @return A Future that contains true if the current call - /// activated the fetched configs; if no configs were fetched from the backend - /// and the local fetched configs have already been activated, the future will - /// contain false. - Future FetchAndActivate(); - - /// @brief Get the (possibly still pending) results of the most recent - /// FetchAndActivate() call. - /// - /// @return The future result from the last call to FetchAndActivate(). - Future FetchAndActivateLastResult(); - - /// @brief Fetches config data from the server. - /// - /// @note This does not actually apply the data or make it accessible, - /// it merely retrieves it and caches it. To accept and access the newly - /// retrieved values, you must call @ref Activate(). - /// - /// Note that this function is asynchronous, and will normally take an - /// unspecified amount of time before completion. - /// - /// @return A Future which can be used to determine when the fetch is - /// complete. - Future Fetch(); - - /// @brief Fetches config data from the server. - /// - /// @note This does not actually apply the data or make it accessible, - /// it merely retrieves it and caches it. To accept and access the newly - /// retrieved values, you must call @ref Activate(). - /// Note that this function is asynchronous, and will normally take an - /// unspecified amount of time before completion. - /// - /// @param[in] cache_expiration_in_seconds The number of seconds to keep - /// previously fetch data available. If cached data is available that is - /// newer than cache_expiration_in_seconds, then the function returns - /// immediately and does not fetch any data. A cache_expiration_in_seconds of - /// zero will always cause a fetch. - /// - /// @return A Future which can be used to determine when the fetch is - /// complete. - Future Fetch(uint64_t cache_expiration_in_seconds); - - /// @brief Get the (possibly still pending) results of the most recent Fetch() - /// call. - /// - /// @return The future result from the last call to Fetch(). - Future FetchLastResult(); - -#if defined(__ANDROID__) - /// @brief Sets the default values, using an XML resource. - /// - /// @note This method is specific to the Android implementation. - /// - /// This completely overwrites all previous default values. - /// - /// @param[in] defaults_resource_id Id for the XML resource, which should be - /// in your applications res/xml folder. - /// - /// @return a Future which can be used to determine when the operation is - /// complete. - Future SetDefaults(int defaults_resource_id); -#endif // __ANDROID__ - -#ifndef SWIG - /// @brief Sets the default values based on a mapping of string to Variant. - /// This allows you to specify defaults of type other than string. - /// - /// The type of each Variant in the map determines the type of data for which - /// you are providing a default. For example, boolean values can be retrieved - /// with GetBool(), integer values can be retrieved with GetLong(), double - /// values can be retrieved with GetDouble(), string values can be retrieved - /// with GetString(), and binary data can be retrieved with GetData(). - /// Aggregate Variant types are not allowed. - /// - /// @see firebase::Variant for more information on how to create a Variant of - /// each type. - /// - /// @note This completely overrides all previous values. - /// - /// @param defaults Array of ConfigKeyValueVariant, representing the new set - /// of defaults to apply. If the same key is specified multiple times, the - /// value associated with the last duplicate key is applied. - /// @param number_of_defaults Number of elements in the defaults array. - /// - /// @return a Future which can be used to determine when the operation is - /// complete. - Future SetDefaults(const ConfigKeyValueVariant* defaults, - size_t number_of_defaults); -#endif // SWIG - - /// @brief Sets the default values based on a string map. - /// - /// @note This completely overrides all previous values. - /// - /// @param defaults Array of ConfigKeyValue, representing the new set of - /// defaults to apply. If the same key is specified multiple times, the - /// value associated with the last duplicate key is applied. - /// @param number_of_defaults Number of elements in the defaults array. - /// - /// @return a Future which can be used to determine when the operation is - /// complete. - Future SetDefaults(const ConfigKeyValue* defaults, - size_t number_of_defaults); - - /// @brief Get the (possibly still pending) results of the most recent - /// SetDefaults() call. - /// - /// @return The future result from the last call to SetDefaults(). - Future SetDefaultsLastResult(); - - /// @brief Asynchronously changes the settings for this Remote Config - /// instance. - /// - /// @param settings The new settings to be applied. - /// - /// @return a Future which can be used to determine when the operation is - /// complete. - Future SetConfigSettings(ConfigSettings settings); - - /// @brief Gets the current settings of the RemoteConfig object. - /// - /// @return A ConfigSettings struct. - ConfigSettings GetConfigSettings(); - - /// @brief Get the (possibly still pending) results of the most recent - /// SetConfigSettings() call. - /// - /// @return The future result from the last call to SetConfigSettings(). - Future SetConfigSettingsLastResult(); - - /// @brief Returns the value associated with a key, converted to a bool. - /// - /// Values of "1", "true", "t", "yes", "y" and "on" are interpreted (case - /// insensitive) as true and "0", "false", "f", "no", "n", "off", - /// and empty strings are interpreted (case insensitive) as - /// false. - /// - /// @param[in] key Key of the value to be retrieved. - /// - /// @return Value associated with the specified key converted to a boolean - /// value. - bool GetBoolean(const char* key); - - /// @brief Returns the value associated with a key, converted to a bool. - /// - /// Values of "1", "true", "t", "yes", "y" and "on" are interpreted (case - /// insensitive) as true and "0", "false", "f", "no", "n", "off", - /// and empty strings are interpreted (case insensitive) as - /// false. - /// - /// @param[in] key Key of the value to be retrieved. - /// @param[out] info A return value, specifying the source of the returned - /// value. - /// - /// @return Value associated with the specified key converted to a boolean - /// value. - bool GetBoolean(const char* key, ValueInfo* info); - - /// @brief Returns the value associated with a key, converted to a 64-bit - /// integer. - /// - /// @param[in] key Key of the value to be retrieved. - /// - /// @return Value associated with the specified key converted to a 64-bit - /// integer. - int64_t GetLong(const char* key); - - /// @brief Returns the value associated with a key, converted to a 64-bit - /// integer. - /// - /// @param[in] key Key of the value to be retrieved. - /// @param[out] info A return value, specifying the source of the returned - /// value. - /// - /// @return Value associated with the specified key converted to a 64-bit - /// integer. - int64_t GetLong(const char* key, ValueInfo* info); - - /// @brief Returns the value associated with a key, converted to a double. - /// - /// @param[in] key Key of the value to be retrieved. - /// - /// @return Value associated with the specified key converted to a double. - double GetDouble(const char* key); - - /// @brief Returns the value associated with a key, converted to a double. - /// - /// @param[in] key Key of the value to be retrieved. - /// @param[out] info A return value, specifying the source of the returned - /// value. - /// - /// @return Value associated with the specified key converted to a double. - double GetDouble(const char* key, ValueInfo* info); - - /// @brief Returns the value associated with a key, converted to a string. - /// - /// @param[in] key Key of the value to be retrieved. - /// - /// @return Value as a string associated with the specified key. - std::string GetString(const char* key); - - /// @brief Returns the value associated with a key, converted to a string. - /// - /// @param[in] key Key of the value to be retrieved. - /// @param[out] info A return value, specifying the source of the returned - /// value. - /// - /// @return Value as a string associated with the specified key. - std::string GetString(const char* key, ValueInfo* info); - - /// @brief Returns the value associated with a key, as a vector of raw - /// byte-data. - /// - /// @param[in] key Key of the value to be retrieved. - /// - /// @return Vector of bytes. - std::vector GetData(const char* key); - - /// @brief Returns the value associated with a key, as a vector of raw - /// byte-data. - /// - /// @param[in] key Key of the value to be retrieved. - /// @param[out] info A return value, specifying the source of the returned - /// value. - /// - /// @return Vector of bytes. - std::vector GetData(const char* key, ValueInfo* info); - - /// @brief Gets the set of keys that start with the given prefix. - /// - /// @param[in] prefix The key prefix to look for. If empty or null, this - /// method will return all keys. - /// - /// @return Set of Remote Config parameter keys that start with the specified - /// prefix. Will return an empty set if there are no keys with the given - /// prefix. - std::vector GetKeysByPrefix(const char* prefix); - - /// @brief Gets the set of all keys. - /// - /// @return Set of all Remote Config parameter keys. - std::vector GetKeys(); - - /// @brief Returns a Map of Firebase Remote Config key value pairs. - /// - /// Evaluates the values of the parameters in the following order: - /// The activated value, if the last successful @ref Activate() contained the - /// key. The default value, if the key was set with @ref SetDefaults(). - std::map GetAll(); - - /// @brief Returns information about the last fetch request, in the form - /// of a ConfigInfo struct. - /// - /// @return A ConfigInfo struct, containing fields reflecting the state - /// of the most recent fetch request. - const ConfigInfo GetInfo(); - - /// Gets the App this remote config object is connected to. - App* app() { return app_; } - - /// Returns the RemoteConfig object for an App. Creates the RemoteConfig if - /// required. - /// - /// To get the RemoteConfig object for the default app, use, - /// GetInstance(GetDefaultFirebaseApp()); - /// - /// If the library RemoteConfig fails to initialize, init_result_out will be - /// written with the result status (if a pointer is given). - /// - /// @param[in] app The App to use for the RemoteConfig object. - static RemoteConfig* GetInstance(App* app); - - private: - explicit RemoteConfig(App* app); - - // Find RemoteConfig instance using App. Return null if the instance does not - // exist. - static RemoteConfig* FindRemoteConfig(App* app); - - // Clean up RemoteConfig instance. - void DeleteInternal(); - - /// The Firebase App this remote config is connected to. - App* app_; - - bool InitInternal(); - - internal::RemoteConfigInternal* internal_; -}; - -} // namespace remote_config -} // namespace firebase - -#endif // FIREBASE_REMOTE_CONFIG_SRC_INCLUDE_FIREBASE_REMOTE_CONFIG_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/storage.h b/packages/firebase_core/firebase_core/firebase_core/firebase/storage.h deleted file mode 100644 index 8d081e4c0ead..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/storage.h +++ /dev/null @@ -1,161 +0,0 @@ -// Copyright 2016 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_H_ -#define FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_H_ - -#include - -#include "firebase/app.h" -#include "firebase/internal/common.h" -#include "firebase/storage/common.h" -#include "firebase/storage/controller.h" -#include "firebase/storage/listener.h" -#include "firebase/storage/metadata.h" -#include "firebase/storage/storage_reference.h" - -#if !defined(DOXYGEN) -#ifndef SWIG -FIREBASE_APP_REGISTER_CALLBACKS_REFERENCE(storage) -#endif // SWIG -#endif // !defined(DOXYGEN) - -namespace firebase { - -/// Namespace for the Firebase C++ SDK for Cloud Storage. -namespace storage { - -namespace internal { -class StorageInternal; -class MetadataInternal; -} // namespace internal - -class StorageReference; - -#ifndef SWIG -/// @brief Entry point for the Firebase C++ SDK for Cloud Storage. -/// -/// To use the SDK, call firebase::storage::Storage::GetInstance() to -/// obtain an instance of Storage, then use GetReference() to obtain references -/// to child blobs. From there you can upload data with -/// StorageReference::PutStream(), get data via StorageReference::GetStream(). -#endif // SWIG -class Storage { - public: - /// @brief Destructor. You may delete an instance of Storage when - /// you are finished using it, to shut down the Storage library. - ~Storage(); - - /// @brief Get an instance of Storage corresponding to the given App. - /// - /// Cloud Storage uses firebase::App to communicate with Firebase - /// Authentication to authenticate users to the server backend. - /// - /// @param[in] app An instance of firebase::App. Cloud Storage will use - /// this to communicate with Firebase Authentication. - /// @param[out] init_result_out Optional: If provided, write the init result - /// here. Will be set to kInitResultSuccess if initialization succeeded, or - /// kInitResultFailedMissingDependency on Android if Google Play services is - /// not available on the current device. - /// - /// @returns An instance of Storage corresponding to the given App. - static Storage* GetInstance(::firebase::App* app, - InitResult* init_result_out = nullptr); - - /// @brief Get an instance of Storage corresponding to the given App, - /// with the given Cloud Storage URL. - /// - /// Cloud Storage uses firebase::App to communicate with Firebase - /// Authentication to authenticate users to the server backend. - /// - /// @param[in] app An instance of firebase::App. Cloud Storage will use - /// this to communicate with Firebase Authentication. - /// @param[in] url Cloud Storage URL. - /// @param[out] init_result_out Optional: If provided, write the init result - /// here. Will be set to kInitResultSuccess if initialization succeeded, or - /// kInitResultFailedMissingDependency on Android if Google Play services is - /// not available on the current device. - /// - /// @returns An instance of Storage corresponding to the given App. - static Storage* GetInstance(::firebase::App* app, const char* url, - InitResult* init_result_out = nullptr); - - /// @brief Get the firease::App that this Storage was created with. - /// - /// @returns The firebase::App this Storage was created with. - ::firebase::App* app(); - - /// @brief Get the URL that this Storage was created with. - /// - /// @returns The URL this Storage was created with, or an empty - /// string if this Storage was created with default parameters. - std::string url(); - - /// @brief Get a StorageReference to the root of the database. - StorageReference GetReference() const; - - /// @brief Get a StorageReference for the specified path. - StorageReference GetReference(const char* path) const; - /// @brief Get a StorageReference for the specified path. - StorageReference GetReference(const std::string& path) const { - return GetReference(path.c_str()); - } - - /// @brief Get a StorageReference for the provided URL. - StorageReference GetReferenceFromUrl(const char* url) const; - /// @brief Get a StorageReference for the provided URL. - StorageReference GetReferenceFromUrl(const std::string& url) const { - return GetReferenceFromUrl(url.c_str()); - } - - /// @brief Returns the maximum time in seconds to retry a download if a - /// failure occurs. - double max_download_retry_time(); - /// @brief Sets the maximum time to retry a download if a failure occurs. - /// Defaults to 600 seconds (10 minutes). - void set_max_download_retry_time(double max_transfer_retry_seconds); - - /// @brief Returns the maximum time to retry an upload if a failure occurs. - double max_upload_retry_time(); - /// @brief Sets the maximum time to retry an upload if a failure occurs. - /// Defaults to 600 seconds (10 minutes). - void set_max_upload_retry_time(double max_transfer_retry_seconds); - - /// @brief Returns the maximum time to retry operations other than upload - /// and download if a failure occurs. - double max_operation_retry_time(); - /// @brief Sets the maximum time to retry operations other than upload and - /// download if a failure occurs. Defaults to 120 seconds (2 minutes). - void set_max_operation_retry_time(double max_transfer_retry_seconds); - - private: - /// @cond FIREBASE_APP_INTERNAL - friend class Metadata; - friend class internal::MetadataInternal; - - Storage(::firebase::App* app, const char* url); - Storage(const Storage& src); - Storage& operator=(const Storage& src); - - // Destroy the internal_ object. - void DeleteInternal(); - - internal::StorageInternal* internal_; - /// @endcond -}; - -} // namespace storage -} // namespace firebase - -#endif // FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/storage/common.h b/packages/firebase_core/firebase_core/firebase_core/firebase/storage/common.h deleted file mode 100644 index 567ed714920c..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/storage/common.h +++ /dev/null @@ -1,62 +0,0 @@ -// Copyright 2016 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_COMMON_H_ -#define FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_COMMON_H_ - -namespace firebase { -namespace storage { - -/// Error code returned by Cloud Storage C++ functions. -enum Error { - /// The operation was a success, no error occurred. - kErrorNone = 0, - /// An unknown error occurred. - kErrorUnknown, - /// No object exists at the desired reference. - kErrorObjectNotFound, - /// No bucket is configured for Cloud Storage. - kErrorBucketNotFound, - /// No project is configured for Cloud Storage. - kErrorProjectNotFound, - /// Quota on your Cloud Storage bucket has been exceeded. - kErrorQuotaExceeded, - /// User is unauthenticated. - kErrorUnauthenticated, - /// User is not authorized to perform the desired action. - kErrorUnauthorized, - /// The maximum time limit on an operation (upload, download, delete, etc.) - /// has been exceeded. - kErrorRetryLimitExceeded, - /// File on the client does not match the checksum of the file received by the - /// server. - kErrorNonMatchingChecksum, - /// Size of the downloaded file exceeds the amount of memory allocated for the - /// download. - kErrorDownloadSizeExceeded, - /// User cancelled the operation. - kErrorCancelled, -}; - -/// @brief Get the human-readable error message corresponding to an error code. -/// -/// @param[in] error Error code to get the error message for. -/// -/// @returns Statically-allocated string describing the error. -const char* GetErrorMessage(Error error); - -} // namespace storage -} // namespace firebase - -#endif // FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_COMMON_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/storage/controller.h b/packages/firebase_core/firebase_core/firebase_core/firebase/storage/controller.h deleted file mode 100644 index 42f29aa0c73b..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/storage/controller.h +++ /dev/null @@ -1,146 +0,0 @@ -// Copyright 2016 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_CONTROLLER_H_ -#define FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_CONTROLLER_H_ - -#include "firebase/storage/storage_reference.h" - -namespace firebase { -namespace storage { - -/// @cond FIREBASE_APP_INTERNAL -namespace internal { -class ControllerInternal; -class ListenerInternal; -class RestOperation; -} // namespace internal -/// @endcond - -/// @brief Controls an ongoing operation, allowing the caller to Pause, Resume -/// or Cancel an ongoing download or upload. -/// -/// An instance of Controller can be constructed and passed to -/// StorageReference::GetBytes(), StorageReference::GetFile(), -/// StorageReference::PutBytes(), or StorageReference::PutFile() to become -/// associated with it. Each Controller can only be associated with one -/// operation at a time. -/// -/// A Controller is also passed as an argument to Listener's callbacks. The -/// Controller passed to a StorageReference operation is not the same object -/// passed to Listener callbacks (though it refers to the same operation), so -/// there are no restrictions on the lifetime of the Controller the user creates -/// (but the Controller passed into a Listener callbacks should only be used -/// from within that callback). -/// -/// This class is currently not thread safe and can only be called on the main -/// thread. -class Controller { - public: - /// @brief Default constructor. - /// - /// You may construct your own Controller to pass into various - /// StorageReference operations. - Controller(); - - /// @brief Destructor. - ~Controller(); - - /// @brief Copy constructor. - /// - /// @param[in] other Controller to copy from. - Controller(const Controller& other); - - /// @brief Copy assignment operator. - /// - /// @param[in] other Controller to copy from. - /// - /// @returns Reference to the destination Controller. - Controller& operator=(const Controller& other); - -#if defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) - /// @brief Move constructor. Moving is an efficient operation for - /// Controller instances. - /// - /// @param[in] other Controller to move from. - Controller(Controller&& other); - - /// @brief Move assignment operator. Moving is an efficient operation for - /// Controller instances. - /// - /// @param[in] other Controller to move from. - /// - /// @returns Reference to the destination Controller. - Controller& operator=(Controller&& other); -#endif // defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) - - /// @brief Pauses the operation currently in progress. - /// - /// @returns True if the operation was successfully paused, false otherwise. - bool Pause(); - - /// @brief Resumes the operation that is paused. - /// - /// @returns True if the operation was successfully resumed, false otherwise. - bool Resume(); - - /// @brief Cancels the operation currently in progress. - /// - /// @returns True if the operation was successfully canceled, false otherwise. - bool Cancel(); - - /// @brief Returns true if the operation is paused. - bool is_paused() const; - - /// @brief Returns the number of bytes transferred so far. - /// - /// @returns The number of bytes transferred so far. - int64_t bytes_transferred() const; - - /// @brief Returns the total bytes to be transferred. - /// - /// @returns The total bytes to be transferred. This will return -1 if - /// the size of the transfer is unknown. - int64_t total_byte_count() const; - - /// @brief Returns the StorageReference associated with this Controller. - /// - /// @returns The StorageReference associated with this Controller. - StorageReference GetReference() const; - - /// @brief Returns true if this Controller is valid, false if it is not - /// valid. An invalid Controller is one that is not associated with an - /// operation. - /// - /// @returns true if this Controller is valid, false if this Controller is - /// invalid. - bool is_valid() const; - - private: - /// @cond FIREBASE_APP_INTERNAL - friend class internal::StorageReferenceInternal; - friend class internal::ControllerInternal; - friend class internal::ListenerInternal; - friend class internal::RestOperation; - - Controller(internal::ControllerInternal* internal); - - internal::ControllerInternal* internal_; - /// @endcond -}; - -} // namespace storage -} // namespace firebase - -#endif // FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_CONTROLLER_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/storage/listener.h b/packages/firebase_core/firebase_core/firebase_core/firebase/storage/listener.h deleted file mode 100644 index 8bd624f61537..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/storage/listener.h +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright 2016 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_LISTENER_H_ -#define FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_LISTENER_H_ - -#include "firebase/storage/controller.h" - -namespace firebase { -namespace storage { - -/// @cond FIREBASE_APP_INTERNAL -namespace internal { -class ListenerInternal; -class StorageInternal; -class StorageReferenceInternal; -class RestOperation; -} // namespace internal -/// @endcond - -/// @brief Base class used to receive pause and progress events on a running -/// read or write operation. -/// -/// Subclasses of this listener class can be used to receive events about data -/// transfer progress a location. Attach the listener to a location using -/// StorageReference::GetBytes(), StorageReference::GetFile(), -/// StorageReference::PutBytes(), and StorageReference::PutFile(); then -/// OnPaused() will be called whenever the Read or Write operation is paused, -/// and OnProgress() will be called periodically as the transfer makes progress. -class Listener { - public: - /// @brief Constructor. - Listener(); - - /// @brief Virtual destructor. - virtual ~Listener(); - - /// @brief The operation was paused. - /// - /// @param[in] controller A controller that can be used to check the status - /// and make changes to the ongoing operation. - virtual void OnPaused(Controller* controller) = 0; - - /// @brief There has been progress event. - /// - /// @param[in] controller A controller that can be used to check the status - /// and make changes to the ongoing operation. - virtual void OnProgress(Controller* controller) = 0; - - private: - /// @cond FIREBASE_APP_INTERNAL - friend class internal::StorageReferenceInternal; - friend class internal::RestOperation; - - // Platform specific data. - internal::ListenerInternal* impl_; - /// @endcond -}; - -} // namespace storage -} // namespace firebase - -#endif // FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_LISTENER_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/storage/metadata.h b/packages/firebase_core/firebase_core/firebase_core/firebase/storage/metadata.h deleted file mode 100644 index 8d697c1072e7..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/storage/metadata.h +++ /dev/null @@ -1,276 +0,0 @@ -// Copyright 2016 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_METADATA_H_ -#define FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_METADATA_H_ - -#include -#include -#include -#include - -#include "firebase/internal/common.h" - -namespace firebase { -namespace storage { - -namespace internal { -class MetadataInternal; -class MetadataInternalCommon; -class StorageInternal; -class StorageReferenceInternal; -} // namespace internal - -class Storage; -class StorageReference; - -/// @brief Metadata stores default attributes such as size and content type. -/// -/// Metadata for a StorageReference. You may also store custom metadata key -/// value pairs. Metadata values may be used to authorize operations using -/// declarative validation rules. -class Metadata { - public: - /// @brief Create a default Metadata that you can modify and use. - Metadata(); - -#ifdef INTERNAL_EXPERIMENTAL - Metadata(internal::MetadataInternal* internal); -#endif - - /// @brief Copy constructor. - /// - /// @param[in] other Metadata to copy from. - Metadata(const Metadata& other); - - /// @brief Copy assignment operator. - /// - /// @param[in] other Metadata to copy from. - /// - /// @returns Reference to the destination Metadata. - Metadata& operator=(const Metadata& other); - -#if defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) - /// @brief Move constructor. Moving is an efficient operation for Metadata. - /// - /// @param[in] other Metadata to move from. - Metadata(Metadata&& other); - - /// @brief Move assignment operator. Moving is an efficient operation for - /// Metadata. - /// - /// @param[in] other Metadata to move from. - /// - /// @returns Reference to the destination Metadata. - Metadata& operator=(Metadata&& other); -#endif // defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) - - ~Metadata(); - - /// @brief Return the owning Google Cloud Storage bucket for the - /// StorageReference. - /// - /// @returns The owning Google Cloud Storage bucket for the StorageReference. - const char* bucket() const; - - /// @brief Set the Cache Control setting of the StorageReference. - /// - /// @see https://tools.ietf.org/html/rfc7234#section-5.2 - void set_cache_control(const char* cache_control); - - /// @brief Set the Cache Control setting of the StorageReference. - /// - /// @see https://tools.ietf.org/html/rfc7234#section-5.2 - void set_cache_control(const std::string& cache_control) { - set_cache_control(cache_control.c_str()); - } - - /// @brief Return the Cache Control setting of the StorageReference. - /// - /// @returns The Cache Control setting of the StorageReference. - /// - /// @see https://tools.ietf.org/html/rfc7234#section-5.2 - const char* cache_control() const; - - /// @brief Set the content disposition of the StorageReference. - /// - /// @see https://tools.ietf.org/html/rfc6266 - void set_content_disposition(const char* disposition); - - /// @brief Set the content disposition of the StorageReference. - /// - /// @see https://tools.ietf.org/html/rfc6266 - void set_content_disposition(const std::string& disposition) { - set_content_disposition(disposition.c_str()); - } - - /// @brief Return the content disposition of the StorageReference. - /// - /// @returns The content disposition of the StorageReference. - /// - /// @see https://tools.ietf.org/html/rfc6266 - const char* content_disposition() const; - - /// @brief Set the content encoding for the StorageReference. - /// - /// @see https://tools.ietf.org/html/rfc2616#section-14.11 - void set_content_encoding(const char* encoding); - - /// @brief Set the content encoding for the StorageReference. - /// - /// @see https://tools.ietf.org/html/rfc2616#section-14.11 - void set_content_encoding(const std::string& encoding) { - set_content_encoding(encoding.c_str()); - } - - /// @brief Return the content encoding for the StorageReference. - /// - /// @returns The content encoding for the StorageReference. - /// - /// @see https://tools.ietf.org/html/rfc2616#section-14.11 - const char* content_encoding() const; - - /// @brief Set the content language for the StorageReference. - /// - /// @see https://tools.ietf.org/html/rfc2616#section-14.12 - void set_content_language(const char* language); - - /// @brief Set the content language for the StorageReference. - /// - /// This must be an ISO 639-1 two-letter language code. - /// E.g. "zh", "es", "en". - /// - /// @see https://www.loc.gov/standards/iso639-2/php/code_list.php - void set_content_language(const std::string& language) { - set_content_language(language.c_str()); - } - - /// @brief Return the content language for the StorageReference. - /// - /// @returns The content language for the StorageReference. - /// - /// @see https://tools.ietf.org/html/rfc2616#section-14.12 - const char* content_language() const; - - /// @brief Set the content type of the StorageReference. - /// - /// @see https://tools.ietf.org/html/rfc2616#section-14.17 - void set_content_type(const char* type); - - /// @brief Set the content type of the StorageReference. - /// - /// @see https://tools.ietf.org/html/rfc2616#section-14.17 - void set_content_type(const std::string& type) { - set_content_type(type.c_str()); - } - - /// @brief Return the content type of the StorageReference. - /// - /// @returns The content type of the StorageReference. - /// - /// @see https://tools.ietf.org/html/rfc2616#section-14.17 - const char* content_type() const; - - /// @brief Return the time the StorageReference was created in milliseconds - /// since the epoch. - /// - /// @returns The time the StorageReference was created in milliseconds since - /// the epoch. - int64_t creation_time() const; - - /// @brief Return a map of custom metadata key value pairs. - /// - /// The pointer returned is only valid during the lifetime of the Metadata - /// object that owns it. - /// - /// @returns The keys for custom metadata. - std::map* custom_metadata() const; - - // download_url() and download_urls() are deprecated and removed. - // Please use StorageReference::GetDownloadUrl() instead. - - /// @brief Return a version String indicating what version of the - /// StorageReference. - /// - /// @returns A value indicating the version of the StorageReference. - int64_t generation() const; - - /// @brief Return a version String indicating the version of this - /// StorageMetadata. - /// - /// @returns A value indicating the version of this StorageMetadata. - int64_t metadata_generation() const; - - /// @brief Return a simple name of the StorageReference object. - /// - /// @returns A simple name of the StorageReference object. - const char* name() const; - - /// @brief Return the path of the StorageReference object. - /// - /// @returns The path of the StorageReference object. - const char* path() const; - - /// @brief Return the associated StorageReference to which this Metadata - /// belongs. - /// - /// @returns The associated StorageReference to which this Metadata belongs. - /// If this Metadata is invalid or is not associated with any file, an invalid - /// StorageReference is returned. - StorageReference GetReference() const; - - /// @brief Return the stored Size in bytes of the StorageReference object. - /// - /// @returns The stored Size in bytes of the StorageReference object. - int64_t size_bytes() const; - - /// @brief Return the time the StorageReference was last updated in - /// milliseconds since the epoch. - /// - /// @return The time the StorageReference was last updated in milliseconds - /// since the epoch. - int64_t updated_time() const; - - /// @brief Returns true if this Metadata is valid, false if it is not - /// valid. An invalid Metadata is returned when a method such as - /// StorageReference::GetMetadata() completes with an error. - /// - /// @returns true if this Metadata is valid, false if this Metadata is - /// invalid. - bool is_valid() const; - - /// @brief MD5 hash of the data; encoded using base64. - /// - /// @returns MD5 hash of the data; encoded using base64. - const char* md5_hash() const; - - private: - /// @cond FIREBASE_APP_INTERNAL - friend class StorageReference; - friend class internal::MetadataInternal; - friend class internal::MetadataInternalCommon; - friend class internal::StorageReferenceInternal; - -#ifndef INTERNAL_EXPERIMENTAL - Metadata(internal::MetadataInternal* internal); -#endif - - internal::MetadataInternal* internal_; - /// @endcond -}; - -} // namespace storage -} // namespace firebase - -#endif // FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_METADATA_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/storage/storage_reference.h b/packages/firebase_core/firebase_core/firebase_core/firebase/storage/storage_reference.h deleted file mode 100644 index e5c7c2f85ae6..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/storage/storage_reference.h +++ /dev/null @@ -1,361 +0,0 @@ -// Copyright 2016 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_STORAGE_REFERENCE_H_ -#define FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_STORAGE_REFERENCE_H_ - -#include -#include - -#include "firebase/future.h" -#include "firebase/internal/common.h" -#include "firebase/storage/metadata.h" - -namespace firebase { -namespace storage { - -class Controller; -class Listener; -class Storage; - -/// @cond FIREBASE_APP_INTERNAL -namespace internal { -class ControllerInternal; -class MetadataInternal; -class StorageInternal; -class StorageReferenceInternalCommon; -class StorageReferenceInternal; -} // namespace internal -/// @endcond FIREBASE_APP_INTERNAL - -#ifndef SWIG -/// Represents a reference to a Cloud Storage object. -/// Developers can upload and download objects, get/set object metadata, and -/// delete an object at a specified path. -#endif // SWIG -class StorageReference { - public: - /// @brief Default constructor. This creates an invalid StorageReference. - /// Attempting to perform any operations on this reference will fail unless a - /// valid StorageReference has been assigned to it. - StorageReference() : internal_(nullptr) {} - - ~StorageReference(); - - /// @brief Copy constructor. It's totally okay (and efficient) to copy - /// StorageReference instances, as they simply point to the same location. - /// - /// @param[in] reference StorageReference to copy from. - StorageReference(const StorageReference& reference); - - /// @brief Copy assignment operator. It's totally okay (and efficient) to copy - /// StorageReference instances, as they simply point to the same location. - /// - /// @param[in] reference StorageReference to copy from. - /// - /// @returns Reference to the destination StorageReference. - StorageReference& operator=(const StorageReference& reference); - -#if defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) - /// @brief Move constructor. Moving is an efficient operation for - /// StorageReference instances. - /// - /// @param[in] other StorageReference to move data from. - StorageReference(StorageReference&& other); - - /// @brief Move assignment operator. Moving is an efficient operation for - /// StorageReference instances. - /// - /// @param[in] other StorageReference to move data from. - /// - /// @returns Reference to the destination StorageReference. - StorageReference& operator=(StorageReference&& other); -#endif // defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) - - /// @brief Gets the firebase::storage::Storage instance to which we refer. - /// - /// The pointer will remain valid indefinitely. - /// - /// @returns The firebase::storage::Storage instance that this - /// StorageReference refers to. - Storage* storage(); - - /// @brief Gets a reference to a location relative to this one. - /// - /// @param[in] path Path relative to this reference's location. - /// The pointer only needs to be valid during this call. - /// - /// @returns Child relative to this location. - StorageReference Child(const char* path) const; - - /// @brief Gets a reference to a location relative to this one. - /// - /// @param[in] path Path relative to this reference's location. - /// - /// @returns Child relative to this location. - StorageReference Child(const std::string& path) const { - return Child(path.c_str()); - } - - /// @brief Deletes the object at the current path. - /// - /// @returns A Future result, which will complete when the operation either - /// succeeds or fails. When the Future is completed, if its Error is - /// kErrorNone, the operation succeeded. - Future Delete(); - - /// @brief Returns the result of the most recent call to RemoveValue(); - /// - /// @returns The result of the most recent call to RemoveValue(); - Future DeleteLastResult(); - - /// @brief Return the Google Cloud Storage bucket that holds this object. - /// - /// @returns The bucket. - std::string bucket(); - - /// @brief Return the full path of the storage reference, not including - /// the Google Cloud Storage bucket. - /// - /// @returns Full path to the storage reference, not including GCS bucket. - /// For example, for the reference "gs://bucket/path/to/object.txt", the full - /// path would be "path/to/object.txt". - std::string full_path(); - - /// @brief Asynchronously downloads the object from this StorageReference. - /// - /// A byte array will be allocated large enough to hold the entire file in - /// memory. Therefore, using this method will impact memory usage of your - /// process. - /// - /// @param[in] path Path to local file on device to download into. - /// @param[in] listener A listener that will respond to events on this read - /// operation. If not nullptr, a listener that will respond to events on this - /// read operation. The caller is responsible for allocating and deallocating - /// the listener. The same listener can be used for multiple operations. - /// @param[out] controller_out Controls the write operation, providing the - /// ability to pause, resume or cancel an ongoing write operation. If not - /// nullptr, this method will output a Controller here that you can use to - /// control the write operation. - /// - /// @returns A future that returns the number of bytes read. - Future GetFile(const char* path, Listener* listener = nullptr, - Controller* controller_out = nullptr); - - /// @brief Returns the result of the most recent call to GetFile(); - /// - /// @returns The result of the most recent call to GetFile(); - Future GetFileLastResult(); - - /// @brief Asynchronously downloads the object from this StorageReference. - /// - /// A byte array will be allocated large enough to hold the entire file in - /// memory. Therefore, using this method will impact memory usage of your - /// process. - /// - /// @param[in] buffer A byte buffer to read the data into. This buffer must - /// be valid for the duration of the transfer. - /// @param[in] buffer_size The size of the byte buffer. - /// @param[in] listener A listener that will respond to events on this read - /// operation. If not nullptr, a listener that will respond to events on this - /// read operation. The caller is responsible for allocating and deallocating - /// the listener. The same listener can be used for multiple operations. - /// @param[out] controller_out Controls the write operation, providing the - /// ability to pause, resume or cancel an ongoing write operation. If not - /// nullptr, this method will output a Controller here that you can use to - /// control the write operation. - /// - /// @returns A future that returns the number of bytes read. - Future GetBytes(void* buffer, size_t buffer_size, - Listener* listener = nullptr, - Controller* controller_out = nullptr); - - /// @brief Returns the result of the most recent call to GetBytes(); - /// - /// @returns The result of the most recent call to GetBytes(); - Future GetBytesLastResult(); - - /// @brief Asynchronously retrieves a long lived download URL with a revokable - /// token. - /// - /// This can be used to share the file with others, but can be revoked by a - /// developer in the Firebase Console if desired. - /// - /// @returns A Future result, which will complete when the operation either - /// succeeds or fails. When the Future is completed, if its Error is - /// kErrorNone, the operation succeeded and the URL is returned. - Future GetDownloadUrl(); - - /// @brief Returns the result of the most recent call to GetDownloadUrl(); - /// - /// @returns The result of the most recent call to GetDownloadUrl(); - Future GetDownloadUrlLastResult(); - - /// @brief Retrieves metadata associated with an object at this - /// StorageReference. - /// - /// @returns A Future result, which will complete when the operation either - /// succeeds or fails. When the Future is completed, if its Error is - /// kErrorNone, the operation succeeded and the Metadata is returned. - Future GetMetadata(); - - /// @brief Returns the result of the most recent call to GetMetadata(); - /// - /// @returns The result of the most recent call to GetMetadata(); - Future GetMetadataLastResult(); - - /// @brief Updates the metadata associated with this StorageReference. - /// - /// @returns A Future result, which will complete when the operation either - /// succeeds or fails. When the Future is completed, if its Error is - /// kErrorNone, the operation succeeded and the Metadata is returned. - Future UpdateMetadata(const Metadata& metadata); - - /// @brief Returns the result of the most recent call to UpdateMetadata(); - /// - /// @returns The result of the most recent call to UpdateMetadata(); - Future UpdateMetadataLastResult(); - - /// @brief Returns the short name of this object. - /// - /// @returns the short name of this object. - std::string name(); - - /// @brief Returns a new instance of StorageReference pointing to the parent - /// location or null if this instance references the root location. - /// - /// @returns The parent StorageReference. - StorageReference GetParent(); - - /// @brief Asynchronously uploads data to the currently specified - /// StorageReference, without additional metadata. - /// - /// @param[in] buffer A byte buffer to write data from. This buffer must be - /// valid for the duration of the transfer. - /// @param[in] buffer_size The size of the byte buffer. - /// @param[in] listener A listener that will respond to events on this read - /// operation. If not nullptr, a listener that will respond to events on this - /// write operation. The caller is responsible for allocating and deallocating - /// the listener. The same listener can be used for multiple operations. - /// @param[out] controller_out Controls the write operation, providing the - /// ability to pause, resume or cancel an ongoing write operation. If not - /// nullptr, this method will output a Controller here that you can use to - /// control the write operation. - /// - /// @returns A future that returns the Metadata. - Future PutBytes(const void* buffer, size_t buffer_size, - Listener* listener = nullptr, - Controller* controller_out = nullptr); - - /// @brief Asynchronously uploads data to the currently specified - /// StorageReference, without additional metadata. - /// - /// @param[in] buffer A byte buffer to write data from. This buffer must be - /// valid for the duration of the transfer. - /// @param[in] buffer_size The number of bytes to write. - /// @param[in] metadata Metadata containing additional information (MIME type, - /// etc.) about the object being uploaded. - /// @param[in] listener A listener that will respond to events on this read - /// operation. If not nullptr, a listener that will respond to events on this - /// write operation. The caller is responsible for allocating and deallocating - /// the listener. The same listener can be used for multiple operations. - /// @param[out] controller_out Controls the write operation, providing the - /// ability to pause, resume or cancel an ongoing write operation. If not - /// nullptr, this method will output a Controller here that you can use to - /// control the write operation. - /// - /// @returns A future that returns the Metadata. - Future PutBytes(const void* buffer, size_t buffer_size, - const Metadata& metadata, - Listener* listener = nullptr, - Controller* controller_out = nullptr); - - /// @brief Returns the result of the most recent call to PutBytes(); - /// - /// @returns The result of the most recent call to PutBytes(); - Future PutBytesLastResult(); - - /// @brief Asynchronously uploads data to the currently specified - /// StorageReference, without additional metadata. - /// - /// @param[in] path Path to local file on device to upload to Firebase - /// Storage. - /// @param[in] listener A listener that will respond to events on this read - /// operation. If not nullptr, a listener that will respond to events on this - /// write operation. The caller is responsible for allocating and deallocating - /// the listener. The same listener can be used for multiple operations. - /// @param[out] controller_out Controls the write operation, providing the - /// ability to pause, resume or cancel an ongoing write operation. If not - /// nullptr, this method will output a Controller here that you can use to - /// control the write operation. - /// - /// @returns A future that returns the Metadata. - Future PutFile(const char* path, Listener* listener = nullptr, - Controller* controller_out = nullptr); - - /// @brief Asynchronously uploads data to the currently specified - /// StorageReference, without additional metadata. - /// - /// @param[in] path Path to local file on device to upload to Firebase - /// Storage. - /// @param[in] metadata Metadata containing additional information (MIME type, - /// etc.) about the object being uploaded. - /// @param[in] listener A listener that will respond to events on this read - /// operation. If not nullptr, a listener that will respond to events on this - /// write operation. The caller is responsible for allocating and deallocating - /// the listener. The same listener can be used for multiple operations. - /// @param[out] controller_out Controls the write operation, providing the - /// ability to pause, resume or cancel an ongoing write operation. If not - /// nullptr, this method will output a Controller here that you can use to - /// control the write operation. - /// - /// @returns A future that returns the Metadata. - Future PutFile(const char* path, const Metadata& metadata, - Listener* listener = nullptr, - Controller* controller_out = nullptr); - - /// @brief Returns the result of the most recent call to PutFile(); - /// - /// @returns The result of the most recent call to PutFile(); - Future PutFileLastResult(); - - /// @brief Returns true if this StorageReference is valid, false if it is not - /// valid. An invalid StorageReference indicates that the reference is - /// uninitialized (created with the default constructor) or that there was an - /// error retrieving the reference. - /// - /// @returns true if this StorageReference is valid, false if this - /// StorageReference is invalid. - bool is_valid() const; - - private: - /// @cond FIREBASE_APP_INTERNAL - friend class Controller; - friend class internal::ControllerInternal; - friend class Metadata; - friend class internal::MetadataInternal; - friend class Storage; - friend class internal::StorageReferenceInternal; - friend class internal::StorageReferenceInternalCommon; - - StorageReference(internal::StorageReferenceInternal* internal); - - internal::StorageReferenceInternal* internal_; - /// @endcond -}; - -} // namespace storage -} // namespace firebase - -#endif // FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_STORAGE_REFERENCE_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/util.h b/packages/firebase_core/firebase_core/firebase_core/firebase/util.h deleted file mode 100644 index 4c78d45f3ac8..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/util.h +++ /dev/null @@ -1,101 +0,0 @@ -/* - * Copyright 2016 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_APP_SRC_INCLUDE_FIREBASE_UTIL_H_ -#define FIREBASE_APP_SRC_INCLUDE_FIREBASE_UTIL_H_ - -#include "firebase/app.h" -#include "firebase/future.h" - -namespace firebase { - -struct ModuleInitializerData; - -/// @brief Utility class to help with initializing Firebase modules. -/// -/// This optional class handles a basic Firebase C++ SDK code pattern: attempt -/// to initialize a Firebase module, and if the initialization fails on Android -/// due to Google Play services being unavailable, prompt the user to -/// update/enable Google Play services on their device. -/// -/// If the developer wants more advanced behavior (for example, wait to prompt -/// the user to update or enable Google Play services until later, or opt not to -/// use Firebase modules), they can still initialize each Firebase module -/// individually, and use google_play_services::MakeAvailable() directly if any -/// initializations fail. -class ModuleInitializer { - public: - /// @brief Initialization function, which should initialize a single Firebase - /// module and return the InitResult. - typedef InitResult (*InitializerFn)(App* app, void* context); - - ModuleInitializer(); - virtual ~ModuleInitializer(); - - /// @brief Initialize Firebase modules by calling one or more user-supplied - /// functions, each of which must initialize at most one library, and should - /// return the InitResult of the initialization. - /// - /// This function will run the initializers in order, checking the return - /// value of each. On Android, if the InitResult returned is - /// kInitResultFailedMissingDependency, this indicates that Google Play - /// services is not available and a Firebase module requires it. This function - /// will attempt to fix Google Play services, and will retry initializations - /// where it left off, beginning with the one that failed. - /// - /// @returns A future result. When all of the initializers are completed, the - /// Future will be completed with Error() = 0. If an initializer fails and the - /// situation cannot be fixed, the Future will be completed with Error() equal - /// to the number of initializers that did not succeed (since they are run in - /// order, this tells you which ones failed). - /// - /// @param[in] app The firebase::App that will be passed to the initializers, - /// as well as used to fix Google Play services on Android if needed. - /// - /// @param[in] context User-defined context, which will be passed to the - /// initializer functions. If you don't need this, you can use nullptr. - /// - /// @param[in] init_fns Your initialization functions to call, in an array. At - /// their simplest, these will each simply call a single Firebase module's - /// Initialize(app) and return the result, but you can perform more complex - /// logic if you prefer. - /// - /// @param[in] init_fns_count Number of initialization functions in the - /// supplied array. - /// - /// @note If a pending Initialize() is already running, this function will - /// return the existing Future rather than adding any new functions to the - /// initializer list. - Future Initialize(App* app, void* context, - const InitializerFn* init_fns, size_t init_fns_count); - - /// @brief Initialize one Firebase module by calling a single user-supplied - /// function that should initialize a Firebase module and return the - /// InitResult. @see Initialize(::firebase::App*, void*, const InitializerFn*) - /// for more information. - Future Initialize(App* app, void* context, InitializerFn init_fn); - - /// @brief Get the result of the most recent call to @see Initialize(). - Future InitializeLastResult(); - - private: - ModuleInitializerData* data_; -}; - -// NOLINTNEXTLINE - allow namespace overridden -} // namespace firebase - -#endif // FIREBASE_APP_SRC_INCLUDE_FIREBASE_UTIL_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/variant.h b/packages/firebase_core/firebase_core/firebase_core/firebase/variant.h deleted file mode 100644 index ef1d552dffa4..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/variant.h +++ /dev/null @@ -1,1197 +0,0 @@ -/* - * Copyright 2016 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_APP_SRC_INCLUDE_FIREBASE_VARIANT_H_ -#define FIREBASE_APP_SRC_INCLUDE_FIREBASE_VARIANT_H_ - -#include - -#include -#include -#include -#include -#include - -#include "firebase/internal/common.h" - -/// @brief Namespace that encompasses all Firebase APIs. - -namespace firebase { -namespace internal { -class VariantInternal; -} -} // namespace firebase - -namespace firebase { - -// -// SWIG uses the Variant class as a readonly object, and so ignores most of the -// functions. In order to keep things clean, functions that should be exposed -// are explicitly listed in app.SWIG, and everything else is ignored. -// - -/// Variant data type used by Firebase libraries. -class Variant { - public: - /// Type of data that this variant object contains. - enum Type { - /// Null, or no data. - kTypeNull, - /// A 64-bit integer. - kTypeInt64, - /// A double-precision floating point number. - kTypeDouble, - /// A boolean value. - kTypeBool, - /// A statically-allocated string we point to. - kTypeStaticString, - /// A std::string. - kTypeMutableString, - /// A std::vector of Variant. - kTypeVector, - /// A std::map, mapping Variant to Variant. - kTypeMap, - /// An statically-allocated blob of data that we point to. Never constructed - /// by default. Use Variant::FromStaticBlob() to create a Variant of this - /// type. - kTypeStaticBlob, - /// A blob of data that the Variant holds. Never constructed by default. Use - /// Variant::FromMutableBlob() to create a Variant of this type, and copy - /// binary data from an existing source. - kTypeMutableBlob, - - // Note: If you add new types update enum InternalType; - }; - -// -// Because of the VariantVariantMap C# class, we need to hide the constructors -// explicitly, as the SWIG ignore does not seem to work with that macro. -// -#ifndef SWIG - /// @brief Construct a null Variant. - /// - /// The Variant constructed will be of type Null. - Variant() : type_(kInternalTypeNull), value_({}) {} - - /// @brief Construct a Variant with the given templated type. - /// - /// @param[in] value The value to construct the variant. - /// - /// Valid types for this constructor are `int`, `int64_t`, `float`, `double`, - /// `bool`, `const char*`, and `char*` (but see below for additional Variant - /// types). - /// - /// - /// Type `int` or `int64_t`: - /// * The Variant constructed will be of type Int64. - /// - /// Type `double` or `float`: - /// * The Variant constructed will be of type Double. - /// - /// Type `bool`: - /// * The Variant constructed will be of type Bool. - /// - /// Type `const char*`: - /// * The Variant constructed will be of type StaticString, and is_string() - /// will return true. **Note:** If you use this constructor, you must - /// ensure that the memory pointed to stays valid for the life of the - /// Variant, otherwise call mutable_string() or set_mutable_string(), - /// which will copy the string to an internal buffer. - /// - /// Type `char*`: - /// * The Variant constructed will be of type MutableString, and is_string() - /// will return true. - /// - /// Other types will result in compiler error unless using the following - /// constructor overloads: - /// * `std::string` - /// * `std::vector` - /// * `std::vector` where T is convertible to variant type - /// * `T*`, `size_t` where T is convertible to variant type - /// * `std::map` - /// * `std::map` where K and V is convertible to variant type - template - Variant(T value) // NOLINT - : type_(kInternalTypeNull) { - set_value_t(value); - } - - /// @brief Construct a Variant containing the given string value (makes a - /// copy). - /// - /// The Variant constructed will be of type MutableString, and is_string() - /// will return true. - /// - /// @param[in] value The string to use for the Variant. - Variant(const std::string& value) // NOLINT - : type_(kInternalTypeNull) { - set_mutable_string(value); - } - - /// @brief Construct a Variant containing the given std::vector of Variant. - /// - /// The Variant constructed will be of type Vector. - /// - /// @param[in] value The STL vector to copy into the Variant. - Variant(const std::vector& value) // NOLINT - : type_(kInternalTypeNull) { - set_vector(value); - } - - /// @brief Construct a Variant containing the given std::vector of something - /// that can be constructed into a Variant. - /// - /// The Variant constructed will be of type Vector. - /// - /// @param[in] value An STL vector containing elements that can be converted - /// to Variant (such as ints, strings, vectors). A Variant will be created for - /// each element, and copied into the Vector Variant constructed here. - template - Variant(const std::vector& value) // NOLINT - : type_(kInternalTypeNull) { - Clear(kTypeVector); - vector().reserve(value.size()); - for (size_t i = 0; i < value.size(); i++) { - vector().push_back(Variant(static_cast(value[i]))); - } - } - - /// @brief Construct a Variant from an array of supported types into a Vector. - /// - /// The Variant constructed will be of type Vector. - /// - /// @param[in] array_of_values A C array containing elements that can be - /// converted to Variant (such as ints, strings, vectors). A Variant will be - /// created for each element, and copied into the Vector Variant constructed - /// here. - /// @param[in] array_size Number of elements of the array. - template - Variant(const T array_of_values[], size_t array_size) - : type_(kInternalTypeNull) { - Clear(kTypeVector); - vector().reserve(array_size); - for (size_t i = 0; i < array_size; i++) { - vector()[i] = Variant(array_of_values[i]); - } - } - - /// @brief Construct a Variatn containing the given std::map of Variant to - /// Variant. - /// - /// The Variant constructed will be of type Map. - /// - /// @param[in] value The STL map to copy into the Variant. - Variant(const std::map& value) // NOLINT - : type_(kInternalTypeNull) { - set_map(value); - } - - /// @brief Construct a Variant containing the given std::map of something that - /// can be constructed into a Variant, to something that can be constructed - /// into a Variant. - /// - /// The Variant constructed will be of type Map. - /// - /// @param[in] value An STL map containing keys and values that can be - /// converted to Variant (such as ints, strings, vectors). A Variant will be - /// created for each key and for each value, and copied by pairs into the Map - /// Variant constructed here. - template - Variant(const std::map& value) // NOLINT - : type_(kInternalTypeNull) { - Clear(kTypeMap); - for (typename std::map::const_iterator i = value.begin(); - i != value.end(); ++i) { - map().insert(std::make_pair(Variant(i->first), Variant(i->second))); - } - } - - /// @brief Copy constructor. Performs a deep copy. - /// - /// @param[in] other Source Variant to copy from. - Variant(const Variant& other) : type_(kInternalTypeNull) { *this = other; } - - /// @brief Copy assignment operator. Performs a deep copy. - /// - /// @param[in] other Source Variant to copy from. - Variant& operator=(const Variant& other); - -#if defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) - - /// @brief Move constructor. Efficiently moves the more complex data types by - /// simply reassigning pointer ownership. - /// - /// @param[in] other Source Variant to move from. - Variant(Variant&& other) noexcept : type_(kInternalTypeNull) { - *this = std::move(other); - } - - /// @brief Move assignment operator. Efficiently moves the more complex data - /// types by simply reassigning pointer ownership. - /// - /// @param[in] other Source Variant to move from. - Variant& operator=(Variant&& other) noexcept; - -#endif // defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) -#endif // SWIG - - /// Destructor. Frees the memory that this Variant owns. - ~Variant() { Clear(); } - - /// @brief Equality operator. Both the type and the value must be equal - /// (except that static strings CAN be == to mutable strings). For container - /// types, element-by-element comparison is performed. For strings, string - /// comparison is performed. - /// - /// @param[in] other Variant to compare to. - /// - /// @return True if the Variants are of identical types and values, false - /// otherwise. - bool operator==(const Variant& other) const; - - /// @brief Inequality operator, only meant for internal use. - /// - /// Explanation: In order to use Variant as a key for std::map, we must - /// provide a comparison function. This comparison function is ONLY for - /// std::map to be able to use a Variant as a map key. - /// - /// We define v1 < v2 IFF: - /// * If different types, compare type as int: v1.type() < v2.type() - /// (note: this means that Variant(1) < Variant(0.0) - be careful!) - /// * If both are int64: v1.int64_value() < v2.int64_value(); - /// * If both are double: v1.double_value() < v2.double_value() - /// * If both are bool: v1.bool_value() < v2.bool_value(); - /// * If both are either static or mutable strings: strcmp(v1, v2) < 0 - /// * If both are vectors: - /// * If v1[0] < v2[0], that means v1 < v2 == true. Otherwise: - /// * If v1[0] > v2[0], that means v1 < v2 == false. Otherwise: - /// * Continue to the next element of both vectors and compare again. - /// * If you reach the end of one vector first, that vector is considered - /// to be lesser. - /// * If both are maps, iterate similar to vectors (since maps are ordered), - /// but for each element, first compare the key, then the value. - /// * If both are blobs, the smaller-sized blob is considered lesser. If both - /// blobs are the same size, use memcmp to compare the bytes. - /// - /// We have defined this operation such that if !(v1 < v2) && !(v2 < v1), it - /// must follow that v1 == v2. - /// - /// @param[in] other Variant to compare to. - /// - /// @return Results of the comparison, as described in this documentation. - /// - /// @note This will not give you the results you expect if you compare - /// Variants of different types! For example, Variant(0.0) < Variant(1). - bool operator<(const Variant& other) const; - - /// @brief Inequality operator: x != y is evaluated as !(x == y). - /// - /// @param[in] other Variant to compare to. - /// - /// @return Results of the comparison. - bool operator!=(const Variant& other) const { return !(*this == other); } - - /// @brief Inequality operator: x > y is evaluated as y < x - /// - /// @param[in] other Variant to compare to. - /// - /// @return Results of the comparison. - bool operator>(const Variant& other) const { return other < *this; } - - /// @brief Inequality operator: x >= y is evaluated as !(x < y) - /// - /// @param[in] other Variant to compare to. - /// - /// @return Results of the comparison. - bool operator>=(const Variant& other) const { return !(*this < other); } - - /// @brief Inequality operator: x <= y is evaluated as !(x > y) - /// - /// @param[in] other Variant to compare to. - /// - /// @return Results of the comparison. - bool operator<=(const Variant& other) const { return !(*this > other); } - - /// @brief Clear the given Variant data, optionally into a new type. Frees up - /// any memory that might have been allocated. After calling this, you can - /// access the Variant as the new type. - /// - /// @param[in] new_type Optional new type to clear the Variant to. You may - /// immediately begin using the Variant as that new type. - void Clear(Type new_type = kTypeNull); - - // Convenience functions (used similarly to constants). - - /// @brief Get a Variant of type Null. - /// - /// @return A Variant of type Null. - static Variant Null() { return Variant(); } - - /// @brief Get a Variant of integer value 0. - /// - /// @return A Variant of type Int64, with value 0. - static Variant Zero() { return Variant::FromInt64(0L); } - - /// @brief Get a Variant of integer value 1. - /// - /// @return A Variant of type Int64, with value 1. - static Variant One() { return Variant::FromInt64(1L); } - - /// @brief Get a Variant of double value 0.0. - /// - /// @return A Variant of type Double, with value 0.0. - static Variant ZeroPointZero() { return Variant::FromDouble(0.0); } - - /// @brief Get a Variant of double value 1.0. - /// - /// @return A Variant of type Double, with value 1.0. - static Variant OnePointZero() { return Variant::FromDouble(1.0); } - - /// @brief Get a Variant of bool value false. - /// - /// @return A Variant of type Bool, with value false. - static Variant False() { return Variant::FromBool(false); } - - /// @brief Get a Variant of bool value true. - /// - /// @return A Variant of type Bool, with value true. - static Variant True() { return Variant::FromBool(true); } - - /// @brief Get an empty string variant. - /// - /// @return A Variant of type StaticString, referring to an empty string. - static Variant EmptyString() { return Variant::FromStaticString(""); } - - /// @brief Get a Variant containing an empty mutable string. - /// - /// @return A Variant of type MutableString, containing an empty string. - static Variant EmptyMutableString() { - Variant v; - v.Clear(kTypeMutableString); - return v; - } - - /// @brief Get a Variant containing an empty vector. You can immediately call - /// vector() on it to work with the vector it contains. - /// - /// @return A Variant of type Vector, containing no elements. - static Variant EmptyVector() { - Variant v; - v.Clear(kTypeVector); - return v; - } - - /// @brief Get a Variant containing an empty map. You can immediately call - /// map() on - /// it to work with the map it contains. - /// - /// @return A Variant of type Map, containing no elements. - static Variant EmptyMap() { - Variant v; - v.Clear(kTypeMap); - return v; - } - - /// @brief Return a Variant containing an empty mutable blob of the requested - /// size, filled with 0-bytes. - /// - /// @param[in] size_bytes Size of the buffer you want, in bytes. - /// - /// @returns A Variant containing a mutable blob of the requested size, filled - /// with 0-bytes. - static Variant EmptyMutableBlob(size_t size_bytes) { - Variant v; - uint8_t* blank_data = new uint8_t[size_bytes]; - memset(blank_data, 0, size_bytes); - v.Clear(kTypeMutableBlob); - v.set_blob_pointer(blank_data, size_bytes); - return v; - } - - /// @brief Get the current type contained in this Variant. - /// - /// @return The Variant's type. - Type type() const { - // To avoid breaking user code, alias the small string type to mutable - // string. - if (type_ == kInternalTypeSmallString) { - return kTypeMutableString; - } - - return static_cast(type_); - } - - /// @brief Get whether this Variant is currently null. - /// - /// @return True if the Variant is Null, false otherwise. - bool is_null() const { return type() == kTypeNull; } - - /// @brief Get whether this Variant contains an integer. - /// - /// @return True if the Variant's type is Int64, false otherwise. - bool is_int64() const { return type() == kTypeInt64; } - - /// @brief Get whether this Variant contains a double. - /// - /// @return True if the Variant's type is Double, false otherwise. - bool is_double() const { return type() == kTypeDouble; } - - /// @brief Get whether this Variant contains a bool. - /// - /// @return True if the Variant's type is Bool, false otherwise. - bool is_bool() const { return type() == kTypeBool; } - - /// @brief Get whether this Variant contains a vector. - /// - /// @return True if the Variant's type is Vector, false otherwise. - bool is_vector() const { return type() == kTypeVector; } - - /// @brief Get whether this Variant contains a map. - /// - /// @return True if the Variant's type is Map, false otherwise. - bool is_map() const { return type() == kTypeMap; } - - /// @brief Get whether this Variant contains a static string. - /// - /// @return True if the Variant's type is StaticString, false otherwise. - bool is_static_string() const { return type() == kTypeStaticString; } - - /// @brief Get whether this Variant contains a mutable string. - /// - /// @return True if the Variant's type is MutableString, false otherwise. - bool is_mutable_string() const { return type() == kTypeMutableString; } - - /// @brief Get whether this Variant contains a string. - /// - /// @return True if the Variant's type is either StaticString or - /// MutableString or SmallString; false otherwise. - /// - /// @note No matter which type of string the Variant contains, you can read - /// its value via string_value(). - bool is_string() const { - return is_static_string() || is_mutable_string() || is_small_string(); - } - - /// @brief Get whether this Variant contains a static blob. - /// - /// @return True if the Variant's type is StaticBlob, false otherwise. - bool is_static_blob() const { return type() == kTypeStaticBlob; } - - /// @brief Get whether this Variant contains a mutable blob. - /// - /// @return True if the Variant's type is MutableBlob, false otherwise. - bool is_mutable_blob() const { return type() == kTypeMutableBlob; } - - /// @brief Get whether this Variant contains a blob. - /// - /// @return True if the Variant's type is either StaticBlob or - /// MutableBlob; false otherwise. - /// - /// @note No matter which type of blob the Variant contains, you can read - /// its data via blob_data() and get its size via blob_size(). - bool is_blob() const { return is_static_blob() || is_mutable_blob(); } - - /// @brief Get whether this Variant contains a numeric type, Int64 or Double. - /// - /// @return True if the Variant's type is either Int64 or Double; false - /// otherwise. - bool is_numeric() const { return is_int64() || is_double(); } - - /// @brief Get whether this Variant contains a fundamental type: Null, Int64, - /// Double, Bool, or one of the two String types. Essentially - /// !is_containerType(). - /// - /// @return True if the Variant's type is Int64, Double, Bool, or Null; false - /// otherwise. - bool is_fundamental_type() const { - return is_int64() || is_double() || is_string() || is_bool() || is_null(); - } - - /// @brief Get whether this Variant contains a container type: Vector or Map. - /// - /// @return True if the Variant's type is Vector or Map; false otherwise. - bool is_container_type() const { return is_vector() || is_map(); } - - /// @brief Get the current Variant converted into a string. Only valid for - /// fundamental types. - /// - /// Special cases: Booleans will be returned as "true" or "false". Null will - /// be returned as an empty string. The returned string may be either mutable - /// or static, depending on the source type. All other cases will return an - /// empty string. - /// - /// @return A Variant containing a String that represents the value of this - /// original Variant. - Variant AsString() const; - - /// @brief Get the current Variant converted into an integer. Only valid for - /// fundamental types. - /// - /// Special cases: If a String can be parsed as a number - /// via strtol(), it will be. If a Bool is true, this will return 1. All other - /// cases (including non-fundamental types) will return 0. - /// - /// @return A Variant containing an Int64 that represents the value of this - /// original Variant. - Variant AsInt64() const; - - /// @brief Get the current Variant converted into a floating-point - /// number. Only valid for fundamental types. - /// - /// Special cases: If a Bool is true, this will return 1. All other cases will - /// return 0. - /// - /// @return A Variant containing a Double that represents the value of this - /// original Variant. - Variant AsDouble() const; - - /// @brief Get the current Variant converted into a boolean. Null, 0, 0.0, - /// empty strings, empty vectors, empty maps, blobs of size 0, and "false" - /// (case-sensitive) are all considered false. All other values are true. - /// - /// @return A Variant of type Bool containing the original Variant interpreted - /// as a Bool. - Variant AsBool() const; - - /// @brief Mutable accessor for a Variant containing a string. - /// - /// If the Variant contains a static string, it will be converted into a - /// mutable string, which copies the const char*'s data into a std::string. - /// - /// @return Reference to the string contained in this Variant. - /// - /// @note If the Variant is not one of the two String types, this will assert. - std::string& mutable_string() { - if (type_ == kInternalTypeStaticString || - type_ == kInternalTypeSmallString) { - // Automatically promote a static or small string to a mutable string. - set_mutable_string(string_value(), false); - } - assert_is_type(kTypeMutableString); - return *value_.mutable_string_value; - } - - /// @brief Get the size of a blob. This method works with both static - /// and mutable blobs. - /// - /// @return Number of bytes of binary data contained in the blob. - size_t blob_size() const { - assert_is_blob(); - return value_.blob_value.size; - } - - /// @brief Get the pointer to the binary data contained in a blob. - /// This method works with both static and mutable blob. - /// - /// @return Pointer to the binary data. Use blob_size() to get the - /// number of bytes. - const uint8_t* blob_data() const { - assert_is_blob(); - return value_.blob_value.ptr; - } - - /// @brief Get a mutable pointer to the binary data contained in - /// a blob. - /// - /// If the Variant contains a static blob, it will be converted into a mutable - /// blob, which copies the binary data into the Variant's buffer. - /// - /// @returns Pointer to a mutable buffer of binary data. The size of the - /// buffer cannot be changed, but the contents are mutable. - uint8_t* mutable_blob_data() { - if (type_ == kInternalTypeStaticBlob) { - // Automatically promote a static blob to a mutable blob. - set_mutable_blob(blob_data(), blob_size()); - } - assert_is_type(kTypeMutableBlob); - return const_cast(value_.blob_value.ptr); - } - - /// @brief Const accessor for a Variant contianing mutable blob data. - /// - /// @note Unlike the non-const accessor, this accessor cannot "promote" a - /// static blob to mutable, and thus will assert if the Variant you pass in - /// is not of MutableBlob type. - /// - /// @returns Pointer to a mutable buffer of binary data. The size of the - /// buffer cannot be changed, but the contents are mutable. - uint8_t* mutable_blob_data() const { - assert_is_type(kTypeMutableBlob); - return const_cast(value_.blob_value.ptr); - } - - /// @brief Mutable accessor for a Variant containing a vector of Variant - /// data. - /// - /// @return Reference to the vector contained in this Variant. - /// - /// @note If the Variant is not of Vector type, this will assert. - std::vector& vector() { - assert_is_type(kTypeVector); - return *value_.vector_value; - } - /// @brief Mutable accessor for a Variant containing a map of Variant data. - /// - /// @return Reference to the map contained in this Variant. - /// - /// @note If the Variant is not of Map type, this will assert. - std::map& map() { - assert_is_type(kTypeMap); - return *value_.map_value; - } - - /// @brief Const accessor for a Variant containing an integer. - /// - /// @return The integer contained in this Variant. - /// - /// @note If the Variant is not of Int64 type, this will assert. - int64_t int64_value() const { - assert_is_type(kTypeInt64); - return value_.int64_value; - } - - /// @brief Const accessor for a Variant containing a double. - /// - /// @return The double contained in this Variant. - /// - /// @note If the Variant is not of Double type, this will assert. - double double_value() const { - assert_is_type(kTypeDouble); - return value_.double_value; - } - - /// @brief Const accessor for a Variant containing a bool. - /// - /// @return The bool contained in this Variant. - /// - /// @note If the Variant is not of Bool type, this will assert. - const bool& bool_value() const { - assert_is_type(kTypeBool); - return value_.bool_value; - } - - /// @brief Const accessor for a Variant containing a string. - /// - /// This can return both static and mutable strings. The pointer is only - /// guaranteed to persist if this Variant's type is StaticString. - /// - /// @return The string contained in this Variant. - /// - /// @note If the Variant is not of StaticString or MutableString type, this - /// will assert. - const char* string_value() const { - assert_is_string(); - if (type_ == kInternalTypeMutableString) - return value_.mutable_string_value->c_str(); - else if (type_ == kInternalTypeStaticString) - return value_.static_string_value; - else // if (type_ == kInternalTypeSmallString) - return value_.small_string; - } - - /// @brief Const accessor for a Variant containing a string. - /// - /// @note Unlike the non-const accessor, this accessor cannot "promote" a - /// static string to mutable, and thus returns a std::string copy instead of a - /// const reference to a std::string - /// - /// @return std::string with the string contents contained in this Variant. - std::string mutable_string() const { - assert_is_string(); - return string_value(); - } - - /// @brief Const accessor for a Variant containing a vector of Variant data. - /// - /// @return Reference to the vector contained in this Variant. - /// - /// @note If the Variant is not of Vector type, this will assert. - const std::vector& vector() const { - assert_is_type(kTypeVector); - return *value_.vector_value; - } - - /// @brief Const accessor for a Variant containing a map of strings to - /// Variant - /// data. - /// - /// @return Reference to the map contained in this Variant. - /// - /// @note If the Variant is not of Map type, this will assert. - const std::map& map() const { - assert_is_type(kTypeMap); - return *value_.map_value; - } - - /// @brief Sets the Variant value to null. - /// - /// The Variant's type will be Null. - void set_null() { Clear(kTypeNull); } - - /// @brief Sets the Variant to an 64-bit integer value. - /// - /// The Variant's type will be set to Int64. - /// - /// @param[in] value The 64-bit integer value for the Variant. - void set_int64_value(int64_t value) { - Clear(kTypeInt64); - value_.int64_value = value; - } - - /// @brief Sets the Variant to an double-precision floating point value. - /// - /// The Variant's type will be set to Double. - /// - /// @param[in] value The double-precision floating point value for the - /// Variant. - void set_double_value(double value) { - Clear(kTypeDouble); - value_.double_value = value; - } - - /// @brief Sets the Variant to the given boolean value. - /// - /// The Variant's type will be set to Bool. - /// - /// @param[in] value The boolean value for the Variant. - void set_bool_value(bool value) { - Clear(kTypeBool); - value_.bool_value = value; - } - - /// @brief Sets the Variant to point to a static string buffer. - /// - /// The Variant's type will be set to StaticString. - /// - /// @note If you use this method, you must ensure that the memory pointed to - /// stays valid for the life of the Variant, or otherwise call - /// mutable_string() or set_mutable_string(), which will copy the string to an - /// internal buffer. - /// - /// @param[in] value A pointer to the static null-terminated string for the - /// Variant. - void set_string_value(const char* value) { - Clear(kTypeStaticString); - value_.static_string_value = value; - } - - /// @brief Sets the Variant to a mutable string. - /// - /// The Variant's type will be set to MutableString. - /// - /// @param[in] value A pointer to a null-terminated string, which will be - /// copied into to the Variant. - void set_string_value(char* value) { - size_t len = strlen(value); - if (len < kMaxSmallStringSize) { - Clear(static_cast(kInternalTypeSmallString)); - strncpy(value_.small_string, value, len + 1); - } else { - set_mutable_string(std::string(value, len)); - } - } - - /// @brief Sets the Variant to a mutable string. - /// - /// The Variant's type will be set to MutableString. - /// - /// @param[in] value The string to use for the Variant. - void set_string_value(const std::string& value) { set_mutable_string(value); } - - /// @brief Sets the Variant to a copy of the given string. - /// - /// The Variant's type will be set to SmallString if the size of the string is - /// less than kMaxSmallStringSize (8 bytes on x86, 16 bytes on x64) or - /// otherwise set to MutableString. - /// - /// @param[in] value The string to use for the Variant. - /// @param[in] use_small_string Check to see if the input string should be - /// treated as a small string or left as a mutable string - void set_mutable_string(const std::string& value, - bool use_small_string = true) { - if (value.size() < kMaxSmallStringSize && use_small_string) { - Clear(static_cast(kInternalTypeSmallString)); - strncpy(value_.small_string, value.data(), value.size() + 1); - } else { - Clear(kTypeMutableString); - *value_.mutable_string_value = value; - } - } - - /// @brief Sets the Variant to a copy of the given binary data. - /// - /// The Variant's type will be set to MutableBlob. - /// - /// @param[in] src_data The data to use for the Variant. If you - /// pass in nullptr, no data will be copied, but a buffer of the - /// requested size will be allocated. - /// @param[in] size_bytes The size of the data, in bytes. - void set_mutable_blob(const void* src_data, size_t size_bytes) { - uint8_t* dest_data = new uint8_t[size_bytes]; // Will be deleted when - // `this` is deleted. - if (src_data != nullptr) { - memcpy(dest_data, src_data, size_bytes); - } - Clear(kTypeMutableBlob); - set_blob_pointer(dest_data, size_bytes); - } - - /// @brief Sets the Variant to point to static binary data. - /// - /// The Variant's type will be set to kTypeStaticBlob. - /// - /// @param[in] static_data Pointer to statically-allocated binary data. The - /// Variant will point to the data, not copy it. - /// @param[in] size_bytes Size of the data, in bytes. - /// - /// @note If you use this method, you must ensure that the memory pointer to - /// stays valid for the life of the Variant, or otherwise call - /// mutable_blob_data() or set_mutable_blob(), which will copy the data into - /// an internal buffer. - void set_static_blob(const void* static_data, size_t size_bytes) { - Clear(kTypeStaticBlob); - set_blob_pointer(static_data, size_bytes); - } - - /// @brief Sets the Variant to a copy of the given vector. - /// - /// The Variant's type will be set to Vector. - /// - /// @param[in] value The STL vector to copy into the Variant. - - void set_vector(const std::vector& value) { - Clear(kTypeVector); - *value_.vector_value = value; - } - - /// @brief Sets the Variant to a copy of the given map. - /// - /// The Variant's type will be set to Map. - /// - /// @param[in] value The STL map to copy into the Variant. - void set_map(const std::map& value) { - Clear(kTypeMap); - *value_.map_value = value; - } - - /// @brief Assigns an existing string which was allocated on the heap into the - /// Variant without performing a copy. This object will take over ownership of - /// the pointer, and will set the std::string* you pass in to NULL. - /// - /// The Variant's type will be set to MutableString. - /// - /// @param[in, out] str Pointer to a pointer to an STL string. The Variant - /// will take over ownership of the pointer to the string, and set the - /// pointer - /// you passed in to NULL. - void AssignMutableString(std::string** str) { - Clear(kTypeNull); - type_ = kInternalTypeMutableString; - value_.mutable_string_value = *str; - *str = NULL; // NOLINT - } - - /// @brief Assigns an existing vector which was allocated on the heap into the - /// Variant without performing a copy. This object will take over ownership of - /// the pointer, and will set the std::vector* you pass in to NULL. - /// - /// The Variant's type will be set to Vector. - /// - /// @param[in, out] vect Pointer to a pointer to an STL vector. The Variant - /// will take over ownership of the pointer to the vector, and set the - /// pointer - /// you passed in to NULL. - void AssignVector(std::vector** vect) { - Clear(kTypeNull); - type_ = kInternalTypeVector; - value_.vector_value = *vect; - *vect = NULL; // NOLINT - } - - /// @brief Assigns an existing map which was allocated on the heap into the - /// Variant without performing a copy. This object will take over ownership - /// of - /// the map, and will set the std::map** you pass in to NULL. - /// - /// The Variant's type will be set to Map. - /// - /// @param[in, out] map Pointer to a pointer to an STL map. The Variant will - /// take over ownership of the pointer to the map, and set the pointer you - /// passed in to NULL. - void AssignMap(std::map** map) { - Clear(kTypeNull); - type_ = kInternalTypeMap; - value_.map_value = *map; - *map = NULL; // NOLINT - } - - // Convenience methods for the times when constructors are too ambiguious. - - /// @brief Return a Variant from a 64-bit integer. - /// - /// @param[in] value 64-bit integer value to put into the Variant. - /// - /// @returns A Variant containing the 64-bit integer. - static Variant FromInt64(int64_t value) { return Variant(value); } - - /// @brief Return a Variant from a double-precision floating point number. - /// - /// @param[in] value Double-precision floating point value to put into the - /// Variant; - /// - /// @returns A Variant containing the double-precision floating point number. - static Variant FromDouble(double value) { return Variant(value); } - - /// @brief Return a Variant from a boolean. - /// - /// @param[in] value Boolean value to put into the Variant. - /// - /// @returns A Variant containing the Boolean. - static Variant FromBool(bool value) { return Variant(value); } - - /// @brief Return a Variant from a static string. - /// - /// @param[in] value Pointer to statically-allocated null-terminated string. - /// - /// @returns A Variant referring to the string pointer you passed in. - /// - /// @note If you use this function, you must ensure that the memory pointed - /// to stays valid for the life of the Variant, otherwise call - /// mutable_string() or set_mutable_string(), which will copy the string to an - /// internal buffer. - static Variant FromStaticString(const char* value) { return Variant(value); } - - /// @brief Return a Variant from a string. - /// - /// This method makes a copy of the string. - /// - /// @param[in] value String value to copy into the Variant. - /// - /// @returns A Variant containing a copy of the string. - static Variant FromMutableString(const std::string& value) { - return Variant(value); - } - - /// @brief Return a Variant that points to static binary data. - /// - /// @param[in] static_data Pointer to statically-allocated binary data. The - /// Variant will point to the data, not copy it. - /// @param[in] size_bytes Size of the data, in bytes. - /// - /// @returns A Variant pointing to the binary data. - /// - /// @note If you use this function, you must ensure that the memory pointed - /// to stays valid for the life of the Variant, otherwise call - /// mutable_blob() or set_mutable_blob(), which will copy the data to an - /// internal buffer. - static Variant FromStaticBlob(const void* static_data, size_t size_bytes) { - Variant v; - v.set_static_blob(static_data, size_bytes); - return v; - } - - /// @brief Return a Variant containing a copy of binary data. - /// - /// @param[in] src_data Pointer to binary data to be copied into the Variant. - /// @param[in] size_bytes Size of the data, in bytes. - /// - /// @returns A Variant containing a copy of the binary data. - static Variant FromMutableBlob(const void* src_data, size_t size_bytes) { - Variant v; - v.set_mutable_blob(src_data, size_bytes); - return v; - } - - /// @brief Return a Variant from a string, but make it mutable. - /// - /// Only copies the string once, unlike Variant(std::string(value)), which - /// copies the string twice. - /// - /// @param[in] value String value to copy into the Variant and make mutable. - /// - /// @returns A Variant containing a mutable copy of the string. - static Variant MutableStringFromStaticString(const char* value) { - std::string* str = new std::string(value); - Variant v; - v.AssignMutableString(&str); - return v; - } - - /// @brief Get the human-readable type name of a Variant type. - /// - /// @param[in] type Variant type to describe. - /// - /// @returns A string describing the type, suitable for error messages or - /// debugging. For example "Int64" or "MutableString". - static const char* TypeName(Type type); - - private: - // Internal Type of data that this variant object contains to avoid breaking - // API - enum InternalType { - /// Null, or no data. - kInternalTypeNull = kTypeNull, - /// A 64-bit integer. - kInternalTypeInt64 = kTypeInt64, - /// A double-precision floating point number. - kInternalTypeDouble = kTypeDouble, - /// A boolean value. - kInternalTypeBool = kTypeBool, - /// A statically-allocated string we point to. - kInternalTypeStaticString = kTypeStaticString, - /// A std::string. - kInternalTypeMutableString = kTypeMutableString, - /// A std::vector of Variant. - kInternalTypeVector = kTypeVector, - /// A std::map, mapping Variant to Variant. - kInternalTypeMap = kTypeMap, - /// An statically-allocated blob of data that we point to. Never constructed - /// by default. Use Variant::FromStaticBlob() to create a Variant of this - /// type. - kInternalTypeStaticBlob = kTypeStaticBlob, - /// A blob of data that the Variant holds. Never constructed by default. Use - /// Variant::FromMutableBlob() to create a Variant of this type, and copy - /// binary data from an existing source. - kInternalTypeMutableBlob = kTypeMutableBlob, - // A c string stored in the Variant internal data blob as opposed to be - // newed as a std::string. Max size is 16 bytes on x64 and 8 bytes on x86. - kInternalTypeSmallString = kTypeMutableBlob + 1, - // Not a valid type. Used to get the total number of Variant types. - kMaxTypeValue, - }; - - /// Human-readable type names, for error logging. - static const char* const kTypeNames[]; - - /// Assert that this Variant is of the given type, failing if it is not. - void assert_is_type(Type type) const; - - /// Assert that this Variant is NOT of the given type, failing if it is. - void assert_is_not_type(Type type) const; - - /// Assert that this Variant is a static string or mutable string, failing if - /// it is not. - void assert_is_string() const; - - /// Assert that this Variant is a static blob or mutable blob, failing if - /// it is not. - void assert_is_blob() const; - - /// Sets the blob's data pointer, for kTypeStaticBlob and kTypeMutableBlob. - /// Asserts if the Variant isn't a blob. Caller is responsible for managing - /// the pointer's memory and deleting any existing data at the location. - void set_blob_pointer(const void* blob_ptr, size_t size) { - assert_is_blob(); - value_.blob_value.ptr = static_cast(blob_ptr); - value_.blob_value.size = size; - } - - // If you hit a compiler error here it means you are trying to construct a - // variant with unsupported type. Ether cast to correct type or add support - // below. - template - void set_value_t(T value) = delete; - - // Get whether this Variant contains a small string. - bool is_small_string() const { return type_ == kInternalTypeSmallString; } - - // Current type contained in this Variant. - InternalType type_; - - // Older versions of visual studio cant have this inline in the union and do - // sizeof for small string - typedef struct { - const uint8_t* ptr; - size_t size; - } BlobValue; - - // Union of plain old data (scalars or pointers). - union Value { - int64_t int64_value; - double double_value; - bool bool_value; - const char* static_string_value; - std::string* mutable_string_value; - std::vector* vector_value; - std::map* map_value; - BlobValue blob_value; - char small_string[sizeof(BlobValue)]; - } value_; - - static constexpr size_t kMaxSmallStringSize = sizeof(Value::small_string); - - friend class firebase::internal::VariantInternal; -}; - -template <> -inline void Variant::set_value_t(int64_t value) { - set_int64_value(value); -} - -template <> -inline void Variant::set_value_t(int value) { - set_int64_value(static_cast(value)); -} - -template <> -inline void Variant::set_value_t(int16_t value) { - set_int64_value(static_cast(value)); -} - -template <> -inline void Variant::set_value_t(uint8_t value) { - set_int64_value(static_cast(value)); -} - -template <> -inline void Variant::set_value_t(int8_t value) { - set_int64_value(static_cast(value)); -} - -template <> -inline void Variant::set_value_t(char value) { - set_int64_value(static_cast(value)); -} - -template <> -inline void Variant::set_value_t(double value) { - set_double_value(value); -} - -template <> -inline void Variant::set_value_t(float value) { - set_double_value(static_cast(value)); -} - -template <> -inline void Variant::set_value_t(bool value) { - set_bool_value(value); -} - -template <> -inline void Variant::set_value_t(const char* value) { - set_string_value(value); -} - -template <> -inline void Variant::set_value_t(char* value) { - set_mutable_string(value); -} - -// NOLINTNEXTLINE - allow namespace overridden -} // namespace firebase - -#endif // FIREBASE_APP_SRC_INCLUDE_FIREBASE_VARIANT_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/version.h b/packages/firebase_core/firebase_core/firebase_core/firebase/version.h deleted file mode 100644 index 79d77fc8af4a..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/version.h +++ /dev/null @@ -1,68 +0,0 @@ -// Copyright 2016 Google Inc. All Rights Reserved. - -#ifndef FIREBASE_APP_CLIENT_CPP_SRC_VERSION_H_ -#define FIREBASE_APP_CLIENT_CPP_SRC_VERSION_H_ - -/// @def FIREBASE_VERSION_MAJOR -/// @brief Major version number of the Firebase C++ SDK. -/// @see kFirebaseVersionString -#define FIREBASE_VERSION_MAJOR 10 -/// @def FIREBASE_VERSION_MINOR -/// @brief Minor version number of the Firebase C++ SDK. -/// @see kFirebaseVersionString -#define FIREBASE_VERSION_MINOR 5 -/// @def FIREBASE_VERSION_REVISION -/// @brief Revision number of the Firebase C++ SDK. -/// @see kFirebaseVersionString -#define FIREBASE_VERSION_REVISION 0 - -/// @cond FIREBASE_APP_INTERNAL -#define FIREBASE_STRING_EXPAND(X) #X -#define FIREBASE_STRING(X) FIREBASE_STRING_EXPAND(X) -/// @endcond - -// Version number. -// clang-format off -#define FIREBASE_VERSION_NUMBER_STRING \ - FIREBASE_STRING(FIREBASE_VERSION_MAJOR) "." \ - FIREBASE_STRING(FIREBASE_VERSION_MINOR) "." \ - FIREBASE_STRING(FIREBASE_VERSION_REVISION) -// clang-format on - -// Identifier for version string, e.g. kFirebaseVersionString. -#define FIREBASE_VERSION_IDENTIFIER(library) k##library##VersionString - -// Concatenated version string, e.g. "Firebase C++ x.y.z". -#define FIREBASE_VERSION_STRING(library) \ - #library " C++ " FIREBASE_VERSION_NUMBER_STRING - -#if !defined(DOXYGEN) -#if !defined(_WIN32) && !defined(__CYGWIN__) -#define DEFINE_FIREBASE_VERSION_STRING(library) \ - extern volatile __attribute__((weak)) \ - const char* FIREBASE_VERSION_IDENTIFIER(library); \ - volatile __attribute__((weak)) \ - const char* FIREBASE_VERSION_IDENTIFIER(library) = \ - FIREBASE_VERSION_STRING(library) -#else -#define DEFINE_FIREBASE_VERSION_STRING(library) \ - static const char* FIREBASE_VERSION_IDENTIFIER(library) = \ - FIREBASE_VERSION_STRING(library) -#endif // !defined(_WIN32) && !defined(__CYGWIN__) -#else // if defined(DOXYGEN) - -/// @brief Namespace that encompasses all Firebase APIs. -namespace firebase { - -/// @brief String which identifies the current version of the Firebase C++ -/// SDK. -/// -/// @see FIREBASE_VERSION_MAJOR -/// @see FIREBASE_VERSION_MINOR -/// @see FIREBASE_VERSION_REVISION -static const char* kFirebaseVersionString = FIREBASE_VERSION_STRING; - -} // namespace firebase -#endif // !defined(DOXYGEN) - -#endif // FIREBASE_APP_CLIENT_CPP_SRC_VERSION_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/generate_xml_from_google_services_json.py b/packages/firebase_core/firebase_core/firebase_core/generate_xml_from_google_services_json.py deleted file mode 100644 index 8996cd8490f3..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/generate_xml_from_google_services_json.py +++ /dev/null @@ -1,496 +0,0 @@ -#!/usr/bin/python - -# Copyright 2016 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Stand-alone implementation of the Gradle Firebase plugin. - -Converts the services json file to xml: -https://googleplex-android.googlesource.com/platform/tools/base/+/studio-master-dev/build-system/google-services/src/main/groovy/com/google/gms/googleservices -""" - -__author__ = 'Wouter van Oortmerssen' - -import argparse -import ctypes -import json -import os -import platform -import sys -from xml.etree import ElementTree - -if platform.system().lower() == 'windows': - import ctypes.wintypes # pylint: disable=g-import-not-at-top - -# Map Python 2's unicode method to encode a string as bytes in python 3. -try: - unicode('') # See whether unicode class is available (Python < 3) -except NameError: - unicode = str # pylint: disable=redefined-builtin,invalid-name - -# Input filename if it isn't set. -DEFAULT_INPUT_FILENAME = 'app/google-services.json' -# Output filename if it isn't set. -DEFAULT_OUTPUT_FILENAME = 'res/values/googleservices.xml' -# Input filename for .plist files, if it isn't set. -DEFAULT_PLIST_INPUT_FILENAME = 'GoogleService-Info.plist' -# Output filename for .json files, if it isn't set. -DEFAULT_JSON_OUTPUT_FILENAME = 'google-services-desktop.json' - -OAUTH_CLIENT_TYPE_ANDROID_APP = 1 -OAUTH_CLIENT_TYPE_WEB = 3 - - -def read_xml_value(xml_node): - """Utility method for reading values from the plist XML. - - Args: - xml_node: An ElementTree node, that contains a value. - - Returns: - The value of the node, or None, if it could not be read. - """ - if xml_node.tag == 'string': - return xml_node.text - elif xml_node.tag == 'integer': - return int(xml_node.text) - elif xml_node.tag == 'real': - return float(xml_node.text) - elif xml_node.tag == 'false': - return 0 - elif xml_node.tag == 'true': - return 1 - else: - # other types of input are ignored. (data, dates, arrays, etc.) - return None - - -def construct_plist_dictionary(xml_root): - """Constructs a dictionary of values based on the contents of a plist file. - - Args: - xml_root: An ElementTree node, that represents the root of the xml file - that is to be parsed. (Which should be a dictionary containing - key-value pairs of the properties that need to be extracted.) - - Returns: - A dictionary, containing key-value pairs for all (supported) entries in the - node. - """ - xml_dict = xml_root.find('dict') - - if xml_dict is None: - return None - - plist_dict = {} - i = 0 - while i < len(xml_dict): - if xml_dict[i].tag == 'key': - key = xml_dict[i].text - i += 1 - if i < len(xml_dict): - value = read_xml_value(xml_dict[i]) - if value is not None: - plist_dict[key] = value - i += 1 - - return plist_dict - - -def update_dict_keys(key_map, input_dict): - """Creates a dict from input_dict with the same values but new keys. - - Two dictionaries are passed to this function: the key_map that represents a - mapping of source keys to destination keys, and the input_dict that is the - dictionary that is to be duplicated, replacing any key that matches a source - key with a destination key. Source keys that are not present in the - input_dict will not have their destination key represented in the result. - - In other words, if key_map is `{'old': 'new', 'foo': 'bar'}`, and input_dict - is `{'old': 10}`, the result will be `{'new': 10}`. - - Args: - key_map (dict): A dictionary of strings to strings that maps source keys to - destination keys. - input_dict (dict): The dictionary of string keys to any value type, which - is to be duplicated, replacing source keys with the corresponding - destination keys from key_map. - - Returns: - dict: A new dictionary with updated keys. - """ - return { - new_key: input_dict[old_key] - for (old_key, new_key) in key_map.items() - if old_key in input_dict - } - - -def construct_google_services_json(xml_dict): - """Constructs a google services json file from a dictionary. - - Args: - xml_dict: A dictionary of all the key/value pairs that are needed for the - output json file. - Returns: - A string representing the output json file. - """ - - try: - json_struct = { - 'project_info': - update_dict_keys( - { - 'GCM_SENDER_ID': 'project_number', - 'DATABASE_URL': 'firebase_url', - 'PROJECT_ID': 'project_id', - 'STORAGE_BUCKET': 'storage_bucket' - }, xml_dict), - 'client': [{ - 'client_info': { - 'mobilesdk_app_id': xml_dict['GOOGLE_APP_ID'], - 'android_client_info': { - 'package_name': xml_dict['BUNDLE_ID'] - } - }, - 'oauth_client': [{ - 'client_id': xml_dict['CLIENT_ID'], - }], - 'api_key': [{ - 'current_key': xml_dict['API_KEY'] - }], - 'services': { - 'analytics_service': { - 'status': xml_dict['IS_ANALYTICS_ENABLED'] - }, - 'appinvite_service': { - 'status': xml_dict['IS_APPINVITE_ENABLED'] - } - } - },], - 'configuration_version': - '1' - } - return json.dumps(json_struct, indent=2) - except KeyError as e: - sys.stderr.write('Could not find key in plist file: [%s]\n' % (e.args[0])) - return None - - -def convert_plist_to_json(plist_string, input_filename): - """Converts an input plist string into a .json file and saves it. - - Args: - plist_string: The contents of the loaded plist file. - - input_filename: The file name that the plist data was read from. - Returns: - the converted string, or None if there were errors. - """ - - try: - root = ElementTree.fromstring(plist_string) - except ElementTree.ParseError: - sys.stderr.write('Error parsing file %s.\n' - 'It does not appear to be valid XML.\n' % (input_filename)) - return None - - plist_dict = construct_plist_dictionary(root) - if plist_dict is None: - sys.stderr.write('In file %s, could not locate a top-level \'dict\' ' - 'element.\n' - 'File format should be plist XML, with a top-level ' - 'dictionary containing project settings as key-value ' - 'pairs.\n' % (input_filename)) - return None - - json_string = construct_google_services_json(plist_dict) - return json_string - - -def gen_string(parent, name, text): - """Generate one element and put into the list of keeps. - - Args: - parent: The object that will hold the string. - name: The name to store the string under. - text: The text of the string. - """ - if text: - prev = parent.get('tools:keep', '') - if prev: - prev += ',' - parent.set('tools:keep', prev + '@string/' + name) - child = ElementTree.SubElement(parent, 'string', { - 'name': name, - 'translatable': 'false' - }) - child.text = text - - -def indent(elem, level=0): - """Recurse through XML tree and add indentation. - - Args: - elem: The element to recurse over - level: The current indentation level. - """ - i = '\n' + level*' ' - if elem is not None: - if not elem.text or not elem.text.strip(): - elem.text = i + ' ' - if not elem.tail or not elem.tail.strip(): - elem.tail = i - for elem in elem: - indent(elem, level+1) - if not elem.tail or not elem.tail.strip(): - elem.tail = i - else: - if level and (not elem.tail or not elem.tail.strip()): - elem.tail = i - - -def argv_as_unicode_win32(): - """Returns unicode command line arguments on windows. - """ - - get_command_line_w = ctypes.cdll.kernel32.GetCommandLineW - get_command_line_w.restype = ctypes.wintypes.LPCWSTR - - # CommandLineToArgvW parses the Unicode command line - command_line_to_argv_w = ctypes.windll.shell32.CommandLineToArgvW - command_line_to_argv_w.argtypes = [ - ctypes.wintypes.LPCWSTR, - ctypes.POINTER(ctypes.c_int) - ] - command_line_to_argv_w.restype = ctypes.POINTER( - ctypes.wintypes.LPWSTR) - - argc = ctypes.c_int(0) - argv = command_line_to_argv_w(get_command_line_w(), argc) - - # Strip the python executable from the arguments if it exists - # (It would be listed as the first argument on the windows command line, but - # not in the arguments to the python script) - sys_argv_len = len(sys.argv) - return [unicode(argv[i]) for i in - range(argc.value - sys_argv_len, argc.value)] - - -def main(): - parser = argparse.ArgumentParser( - description=(( - 'Converts a Firebase %s into %s similar to the Gradle plugin, or ' - 'converts a Firebase %s into a %s suitible for use on desktop apps.' % - (DEFAULT_INPUT_FILENAME, DEFAULT_OUTPUT_FILENAME, - DEFAULT_PLIST_INPUT_FILENAME, DEFAULT_JSON_OUTPUT_FILENAME)))) - parser.add_argument('-i', help='Override input file name', - metavar='FILE', required=False) - parser.add_argument('-o', help='Override destination file name', - metavar='FILE', required=False) - parser.add_argument('-p', help=('Package ID to select within the set of ' - 'packages in the input file. If this is ' - 'not specified, the first package in the ' - 'input file is selected.')) - parser.add_argument('-l', help=('List all package IDs referenced by the ' - 'input file. If this is specified, ' - 'the output file is not created.'), - action='store_true', default=False, required=False) - parser.add_argument('-f', help=('Print project fields from the input file ' - 'in the form \'name=value\\n\' for each ' - 'field. If this is specified, the output ' - 'is not created.'), - action='store_true', default=False, required=False) - parser.add_argument( - '--plist', - help=( - 'Specifies a plist file to convert to a JSON configuration file. ' - 'If this is enabled, the script will expect a .plist file as input, ' - 'which it will convert into %s file. The output file is ' - '*not* suitable for use with Firebase on Android.' % - (DEFAULT_JSON_OUTPUT_FILENAME)), - action='store_true', - default=False, - required=False) - - # python 2 on Windows doesn't handle unicode arguments well, so we need to - # pre-process the command line arguments before trying to parse them. - if platform.system() == 'Windows': - sys.argv = argv_as_unicode_win32() - - args = parser.parse_args() - - if args.plist: - input_filename = DEFAULT_PLIST_INPUT_FILENAME - output_filename = DEFAULT_JSON_OUTPUT_FILENAME - else: - input_filename = DEFAULT_INPUT_FILENAME - output_filename = DEFAULT_OUTPUT_FILENAME - - if args.i: - # Encode the input string (type unicode) as a normal string (type str) - # using the 'utf-8' encoding so that it can be worked with the same as - # input names from other sources (like the defaults). - input_filename_raw = args.i.encode('utf-8') - # Decode the filename to a unicode string using the 'utf-8' encoding to - # properly handle filepaths with unicode characters in them. - input_filename = input_filename_raw.decode('utf-8') - - if args.o: - output_filename = args.o - - with open(input_filename, 'r') as ifile: - file_string = ifile.read() - - json_string = None - if args.plist: - json_string = convert_plist_to_json(file_string, input_filename) - if json_string is None: - return 1 - jsobj = json.loads(json_string) - else: - jsobj = json.loads(file_string) - - root = ElementTree.Element('resources') - root.set('xmlns:tools', 'http://schemas.android.com/tools') - - project_info = jsobj.get('project_info') - if project_info: - gen_string(root, 'firebase_database_url', project_info.get('firebase_url')) - gen_string(root, 'gcm_defaultSenderId', project_info.get('project_number')) - gen_string(root, 'google_storage_bucket', - project_info.get('storage_bucket')) - gen_string(root, 'project_id', project_info.get('project_id')) - - if args.f: - if not project_info: - sys.stderr.write('No project info found in %s.' % input_filename) - return 1 - for field, value in sorted(project_info.items()): - sys.stdout.write('%s=%s\n' % (field, value)) - return 0 - - packages = set() - client_list = jsobj.get('client') - if client_list: - # Search for the user specified package in the file. - selected_package_name = '' - selected_client = client_list[0] - find_package_name = args.p - for client in client_list: - package_name = client.get('client_info', {}).get( - 'android_client_info', {}).get('package_name', '') - if not package_name: - package_name = client.get('oauth_client', {}).get( - 'android_info', {}).get('package_name', '') - if package_name: - if not selected_package_name: - selected_package_name = package_name - selected_client = client - if package_name == find_package_name: - selected_package_name = package_name - selected_client = client - packages.add(package_name) - - if args.p and selected_package_name != find_package_name: - sys.stderr.write('No packages found in %s which match the package ' - 'name %s\n' - '\n' - 'Found the following:\n' - '%s\n' % (input_filename, find_package_name, - '\n'.join(packages))) - return 1 - - client_api_key = selected_client.get('api_key') - if client_api_key: - client_api_key0 = client_api_key[0] - gen_string(root, 'google_api_key', client_api_key0.get('current_key')) - gen_string(root, 'google_crash_reporting_api_key', - client_api_key0.get('current_key')) - - client_info = selected_client.get('client_info') - if client_info: - gen_string(root, 'google_app_id', client_info.get('mobilesdk_app_id')) - - # Only include the first matching OAuth client ID per type. - client_id_web_parsed = False - client_id_android_parsed = False - - oauth_client_list = selected_client.get('oauth_client') - if oauth_client_list: - for oauth_client in oauth_client_list: - client_type = oauth_client.get('client_type') - client_id = oauth_client.get('client_id') - if not (client_type and client_id): continue - if (client_type == OAUTH_CLIENT_TYPE_WEB and - not client_id_web_parsed): - gen_string(root, 'default_web_client_id', client_id) - client_id_web_parsed = True - if (client_type == OAUTH_CLIENT_TYPE_ANDROID_APP and - not client_id_android_parsed): - gen_string(root, 'default_android_client_id', client_id) - client_id_android_parsed = True - - services = selected_client.get('services') - if services: - ads_service = services.get('ads_service') - if ads_service: - gen_string(root, 'test_banner_ad_unit_id', - ads_service.get('test_banner_ad_unit_id')) - gen_string(root, 'test_interstitial_ad_unit_id', - ads_service.get('test_interstitial_ad_unit_id')) - analytics_service = services.get('analytics_service') - if analytics_service: - analytics_property = analytics_service.get('analytics_property') - if analytics_property: - gen_string(root, 'ga_trackingId', - analytics_property.get('tracking_id')) - # enable this once we have an example if this service being present - # in the json data: - maps_service_enabled = False - if maps_service_enabled: - maps_service = services.get('maps_service') - if maps_service: - maps_api_key = maps_service.get('api_key') - if maps_api_key: - for k in range(0, len(maps_api_key)): - # generates potentially multiple of these keys, which is - # the same behavior as the java plugin. - gen_string(root, 'google_maps_key', - maps_api_key[k].get('maps_api_key')) - - tree = ElementTree.ElementTree(root) - - indent(root) - - if args.l: - for package in sorted(packages): - if package: - sys.stdout.write(package + '\n') - else: - path = os.path.dirname(output_filename) - - if path and not os.path.exists(path): - os.makedirs(path) - - if not args.plist: - tree.write(output_filename, 'utf-8', True) - else: - with open(output_filename, 'w') as ofile: - ofile.write(json_string) - - return 0 - -if __name__ == '__main__': - sys.exit(main()) \ No newline at end of file diff --git a/packages/firebase_core/firebase_core/firebase_core/generated_bindings.dart b/packages/firebase_core/firebase_core/firebase_core/generated_bindings.dart deleted file mode 100644 index f58d1524bee8..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/generated_bindings.dart +++ /dev/null @@ -1,26 +0,0 @@ -// AUTO GENERATED FILE, DO NOT EDIT. -// -// Generated by `package:ffigen`. -import 'dart:ffi' as ffi; - -class NativeLibrary { - /// Holds the symbol lookup function. - final ffi.Pointer Function(String symbolName) - _lookup; - - /// The symbols are looked up in [dynamicLibrary]. - NativeLibrary(ffi.DynamicLibrary dynamicLibrary) - : _lookup = dynamicLibrary.lookup; - - /// The symbols are looked up with [lookup]. - NativeLibrary.fromLookup( - ffi.Pointer Function(String symbolName) - lookup) - : _lookup = lookup; - - late final ffi.Pointer _firebase = _lookup('firebase'); - - int get firebase => _firebase.value; - - set firebase(int value) => _firebase.value = value; -} diff --git a/packages/firebase_core/firebase_core/firebase_core/google-services-desktop.json b/packages/firebase_core/firebase_core/firebase_core/google-services-desktop.json deleted file mode 100644 index a3bf216f4de0..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/google-services-desktop.json +++ /dev/null @@ -1,37 +0,0 @@ -{ - "project_info": { - "project_number": "406099696497", - "firebase_url": "https://flutterfire-e2e-tests-default-rtdb.europe-west1.firebasedatabase.app", - "project_id": "flutterfire-e2e-tests", - "storage_bucket": "flutterfire-e2e-tests.appspot.com" - }, - "client": [ - { - "client_info": { - "mobilesdk_app_id": "1:406099696497:ios:58cbc26aca8e5cf83574d0", - "android_client_info": { - "package_name": "io.flutter.plugins.firebase.auth.example" - } - }, - "oauth_client": [ - { - "client_id": "406099696497-134k3722m01rtrsklhf3b7k8sqa5r7in.apps.googleusercontent.com" - } - ], - "api_key": [ - { - "current_key": "AIzaSyDooSUGSf63Ghq02_iIhtnmwMDs4HlWS6c" - } - ], - "services": { - "analytics_service": { - "status": 0 - }, - "appinvite_service": { - "status": 1 - } - } - } - ], - "configuration_version": "1" -} \ No newline at end of file diff --git a/packages/firebase_core/firebase_core/firebase_core/lib/firebase_core.dart b/packages/firebase_core/firebase_core/firebase_core/lib/firebase_core.dart deleted file mode 100644 index d1295e26ad15..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/lib/firebase_core.dart +++ /dev/null @@ -1,8 +0,0 @@ - -import 'firebase_core_platform_interface.dart'; - -class FirebaseCore { - Future getPlatformVersion() { - return FirebaseCorePlatform.instance.getPlatformVersion(); - } -} diff --git a/packages/firebase_core/firebase_core/firebase_core/lib/firebase_core_method_channel.dart b/packages/firebase_core/firebase_core/firebase_core/lib/firebase_core_method_channel.dart deleted file mode 100644 index 5da300fa9013..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/lib/firebase_core_method_channel.dart +++ /dev/null @@ -1,17 +0,0 @@ -import 'package:flutter/foundation.dart'; -import 'package:flutter/services.dart'; - -import 'firebase_core_platform_interface.dart'; - -/// An implementation of [FirebaseCorePlatform] that uses method channels. -class MethodChannelFirebaseCore extends FirebaseCorePlatform { - /// The method channel used to interact with the native platform. - @visibleForTesting - final methodChannel = const MethodChannel('firebase_core'); - - @override - Future getPlatformVersion() async { - final version = await methodChannel.invokeMethod('getPlatformVersion'); - return version; - } -} diff --git a/packages/firebase_core/firebase_core/firebase_core/lib/firebase_core_platform_interface.dart b/packages/firebase_core/firebase_core/firebase_core/lib/firebase_core_platform_interface.dart deleted file mode 100644 index 6f6e165b7957..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/lib/firebase_core_platform_interface.dart +++ /dev/null @@ -1,29 +0,0 @@ -import 'package:plugin_platform_interface/plugin_platform_interface.dart'; - -import 'firebase_core_method_channel.dart'; - -abstract class FirebaseCorePlatform extends PlatformInterface { - /// Constructs a FirebaseCorePlatform. - FirebaseCorePlatform() : super(token: _token); - - static final Object _token = Object(); - - static FirebaseCorePlatform _instance = MethodChannelFirebaseCore(); - - /// The default instance of [FirebaseCorePlatform] to use. - /// - /// Defaults to [MethodChannelFirebaseCore]. - static FirebaseCorePlatform get instance => _instance; - - /// Platform-specific implementations should set this with their own - /// platform-specific class that extends [FirebaseCorePlatform] when - /// they register themselves. - static set instance(FirebaseCorePlatform instance) { - PlatformInterface.verifyToken(instance, _token); - _instance = instance; - } - - Future getPlatformVersion() { - throw UnimplementedError('platformVersion() has not been implemented.'); - } -} diff --git a/packages/firebase_core/firebase_core/firebase_core/linux/CMakeLists.txt b/packages/firebase_core/firebase_core/firebase_core/linux/CMakeLists.txt deleted file mode 100644 index 5cec31c86b71..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/linux/CMakeLists.txt +++ /dev/null @@ -1,47 +0,0 @@ -# The Flutter tooling requires that developers have CMake 3.10 or later -# installed. You should not increase this version, as doing so will cause -# the plugin to fail to compile for some customers of the plugin. -cmake_minimum_required(VERSION 3.10) - -# Project-level configuration. -set(PROJECT_NAME "firebase_core") -project(${PROJECT_NAME} LANGUAGES CXX) - -# This value is used when generating builds using this plugin, so it must -# not be changed. -set(PLUGIN_NAME "firebase_core_plugin") - -# Define the plugin library target. Its name must not be changed (see comment -# on PLUGIN_NAME above). -# -# Any new source files that you add to the plugin should be added here. -add_library(${PLUGIN_NAME} SHARED - "firebase_core_plugin.cc" -) - -# Apply a standard set of build settings that are configured in the -# application-level CMakeLists.txt. This can be removed for plugins that want -# full control over build settings. -apply_standard_settings(${PLUGIN_NAME}) - -# Symbols are hidden by default to reduce the chance of accidental conflicts -# between plugins. This should not be removed; any symbols that should be -# exported should be explicitly exported with the FLUTTER_PLUGIN_EXPORT macro. -set_target_properties(${PLUGIN_NAME} PROPERTIES - CXX_VISIBILITY_PRESET hidden) -target_compile_definitions(${PLUGIN_NAME} PRIVATE FLUTTER_PLUGIN_IMPL) - -# Source include directories and library dependencies. Add any plugin-specific -# dependencies here. -target_include_directories(${PLUGIN_NAME} INTERFACE - "${CMAKE_CURRENT_SOURCE_DIR}/include") -target_link_libraries(${PLUGIN_NAME} PRIVATE flutter) -target_link_libraries(${PLUGIN_NAME} PRIVATE PkgConfig::GTK) - -# List of absolute paths to libraries that should be bundled with the plugin. -# This list could contain prebuilt libraries, or libraries created by an -# external build triggered from this build file. -set(firebase_core_bundled_libraries - "" - PARENT_SCOPE -) diff --git a/packages/firebase_core/firebase_core/firebase_core/linux/firebase_core_plugin.cc b/packages/firebase_core/firebase_core/firebase_core/linux/firebase_core_plugin.cc deleted file mode 100644 index 4fd897624ca4..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/linux/firebase_core_plugin.cc +++ /dev/null @@ -1,70 +0,0 @@ -#include "include/firebase_core/firebase_core_plugin.h" - -#include -#include -#include - -#include - -#define FIREBASE_CORE_PLUGIN(obj) \ - (G_TYPE_CHECK_INSTANCE_CAST((obj), firebase_core_plugin_get_type(), \ - FirebaseCorePlugin)) - -struct _FirebaseCorePlugin { - GObject parent_instance; -}; - -G_DEFINE_TYPE(FirebaseCorePlugin, firebase_core_plugin, g_object_get_type()) - -// Called when a method call is received from Flutter. -static void firebase_core_plugin_handle_method_call( - FirebaseCorePlugin* self, - FlMethodCall* method_call) { - g_autoptr(FlMethodResponse) response = nullptr; - - const gchar* method = fl_method_call_get_name(method_call); - - if (strcmp(method, "getPlatformVersion") == 0) { - struct utsname uname_data = {}; - uname(&uname_data); - g_autofree gchar *version = g_strdup_printf("Linux %s", uname_data.version); - g_autoptr(FlValue) result = fl_value_new_string(version); - response = FL_METHOD_RESPONSE(fl_method_success_response_new(result)); - } else { - response = FL_METHOD_RESPONSE(fl_method_not_implemented_response_new()); - } - - fl_method_call_respond(method_call, response, nullptr); -} - -static void firebase_core_plugin_dispose(GObject* object) { - G_OBJECT_CLASS(firebase_core_plugin_parent_class)->dispose(object); -} - -static void firebase_core_plugin_class_init(FirebaseCorePluginClass* klass) { - G_OBJECT_CLASS(klass)->dispose = firebase_core_plugin_dispose; -} - -static void firebase_core_plugin_init(FirebaseCorePlugin* self) {} - -static void method_call_cb(FlMethodChannel* channel, FlMethodCall* method_call, - gpointer user_data) { - FirebaseCorePlugin* plugin = FIREBASE_CORE_PLUGIN(user_data); - firebase_core_plugin_handle_method_call(plugin, method_call); -} - -void firebase_core_plugin_register_with_registrar(FlPluginRegistrar* registrar) { - FirebaseCorePlugin* plugin = FIREBASE_CORE_PLUGIN( - g_object_new(firebase_core_plugin_get_type(), nullptr)); - - g_autoptr(FlStandardMethodCodec) codec = fl_standard_method_codec_new(); - g_autoptr(FlMethodChannel) channel = - fl_method_channel_new(fl_plugin_registrar_get_messenger(registrar), - "firebase_core", - FL_METHOD_CODEC(codec)); - fl_method_channel_set_method_call_handler(channel, method_call_cb, - g_object_ref(plugin), - g_object_unref); - - g_object_unref(plugin); -} diff --git a/packages/firebase_core/firebase_core/firebase_core/linux/include/firebase_core/firebase_core_plugin.h b/packages/firebase_core/firebase_core/firebase_core/linux/include/firebase_core/firebase_core_plugin.h deleted file mode 100644 index 3f15a61a3e72..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/linux/include/firebase_core/firebase_core_plugin.h +++ /dev/null @@ -1,26 +0,0 @@ -#ifndef FLUTTER_PLUGIN_FIREBASE_CORE_PLUGIN_H_ -#define FLUTTER_PLUGIN_FIREBASE_CORE_PLUGIN_H_ - -#include - -G_BEGIN_DECLS - -#ifdef FLUTTER_PLUGIN_IMPL -#define FLUTTER_PLUGIN_EXPORT __attribute__((visibility("default"))) -#else -#define FLUTTER_PLUGIN_EXPORT -#endif - -typedef struct _FirebaseCorePlugin FirebaseCorePlugin; -typedef struct { - GObjectClass parent_class; -} FirebaseCorePluginClass; - -FLUTTER_PLUGIN_EXPORT GType firebase_core_plugin_get_type(); - -FLUTTER_PLUGIN_EXPORT void firebase_core_plugin_register_with_registrar( - FlPluginRegistrar* registrar); - -G_END_DECLS - -#endif // FLUTTER_PLUGIN_FIREBASE_CORE_PLUGIN_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/pubspec.yaml b/packages/firebase_core/firebase_core/firebase_core/pubspec.yaml deleted file mode 100644 index c942173c517b..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/pubspec.yaml +++ /dev/null @@ -1,36 +0,0 @@ -name: firebase_core -description: A new Flutter plugin project. -version: 0.0.1 -homepage: - -environment: - sdk: '>=2.19.2 <3.0.0' - flutter: '>=2.5.0' - -dependencies: - ffi: ^2.0.1 - flutter: - sdk: flutter - plugin_platform_interface: ^2.0.2 - -dev_dependencies: - flutter_test: - sdk: flutter - flutter_lints: ^2.0.0 - ffigen: ^7.2.6 - -flutter: - plugin: - platforms: - linux: - pluginClass: FirebaseCorePlugin - windows: - pluginClass: FirebaseCorePluginCApi - -ffigen: - output: 'generated_bindings.dart' - headers: - entry-points: - - 'firebase/app.h' - include-directives: - - 'firebase/**.h' diff --git a/packages/firebase_core/firebase_core/firebase_core/test/firebase_core_method_channel_test.dart b/packages/firebase_core/firebase_core/firebase_core/test/firebase_core_method_channel_test.dart deleted file mode 100644 index 70c7fc5e7362..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/test/firebase_core_method_channel_test.dart +++ /dev/null @@ -1,24 +0,0 @@ -import 'package:flutter/services.dart'; -import 'package:flutter_test/flutter_test.dart'; -import 'package:firebase_core/firebase_core_method_channel.dart'; - -void main() { - MethodChannelFirebaseCore platform = MethodChannelFirebaseCore(); - const MethodChannel channel = MethodChannel('firebase_core'); - - TestWidgetsFlutterBinding.ensureInitialized(); - - setUp(() { - channel.setMockMethodCallHandler((MethodCall methodCall) async { - return '42'; - }); - }); - - tearDown(() { - channel.setMockMethodCallHandler(null); - }); - - test('getPlatformVersion', () async { - expect(await platform.getPlatformVersion(), '42'); - }); -} diff --git a/packages/firebase_core/firebase_core/firebase_core/test/firebase_core_test.dart b/packages/firebase_core/firebase_core/firebase_core/test/firebase_core_test.dart deleted file mode 100644 index bb8e54416b4e..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/test/firebase_core_test.dart +++ /dev/null @@ -1,29 +0,0 @@ -import 'package:flutter_test/flutter_test.dart'; -import 'package:firebase_core/firebase_core.dart'; -import 'package:firebase_core/firebase_core_platform_interface.dart'; -import 'package:firebase_core/firebase_core_method_channel.dart'; -import 'package:plugin_platform_interface/plugin_platform_interface.dart'; - -class MockFirebaseCorePlatform - with MockPlatformInterfaceMixin - implements FirebaseCorePlatform { - - @override - Future getPlatformVersion() => Future.value('42'); -} - -void main() { - final FirebaseCorePlatform initialPlatform = FirebaseCorePlatform.instance; - - test('$MethodChannelFirebaseCore is the default instance', () { - expect(initialPlatform, isInstanceOf()); - }); - - test('getPlatformVersion', () async { - FirebaseCore firebaseCorePlugin = FirebaseCore(); - MockFirebaseCorePlatform fakePlatform = MockFirebaseCorePlatform(); - FirebaseCorePlatform.instance = fakePlatform; - - expect(await firebaseCorePlugin.getPlatformVersion(), '42'); - }); -} diff --git a/packages/firebase_core/firebase_core/firebase_core/windows/.gitignore b/packages/firebase_core/firebase_core/firebase_core/windows/.gitignore deleted file mode 100644 index b3eb2be169a5..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/windows/.gitignore +++ /dev/null @@ -1,17 +0,0 @@ -flutter/ - -# Visual Studio user-specific files. -*.suo -*.user -*.userosscache -*.sln.docstates - -# Visual Studio build-related files. -x64/ -x86/ - -# Visual Studio cache files -# files ending in .cache can be ignored -*.[Cc]ache -# but keep track of directories ending in .cache -!*.[Cc]ache/ diff --git a/packages/firebase_core/firebase_core/firebase_core/windows/CMakeLists.txt b/packages/firebase_core/firebase_core/firebase_core/windows/CMakeLists.txt deleted file mode 100644 index 35c68f4a1910..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/windows/CMakeLists.txt +++ /dev/null @@ -1,61 +0,0 @@ -# The Flutter tooling requires that developers have a version of Visual Studio -# installed that includes CMake 3.14 or later. You should not increase this -# version, as doing so will cause the plugin to fail to compile for some -# customers of the plugin. -cmake_minimum_required(VERSION 3.14) - -# Project-level configuration. -set(PROJECT_NAME "firebase_core") -project(${PROJECT_NAME} LANGUAGES CXX) - -# This value is used when generating builds using this plugin, so it must -# not be changed -set(PLUGIN_NAME "firebase_core_plugin") - -# Any new source files that you add to the plugin should be added here. -list(APPEND PLUGIN_SOURCES - "firebase_core_plugin.cpp" - "firebase_core_plugin.h" -) - -# Define the plugin library target. Its name must not be changed (see comment -# on PLUGIN_NAME above). -add_library(${PLUGIN_NAME} SHARED - "include/firebase_core/firebase_core_plugin_c_api.h" - "firebase_core_plugin_c_api.cpp" - ${PLUGIN_SOURCES} -) - - -# Apply a standard set of build settings that are configured in the -# application-level CMakeLists.txt. This can be removed for plugins that want -# full control over build settings. -apply_standard_settings(${PLUGIN_NAME}) - -# Symbols are hidden by default to reduce the chance of accidental conflicts -# between plugins. This should not be removed; any symbols that should be -# exported should be explicitly exported with the FLUTTER_PLUGIN_EXPORT macro. -set_target_properties(${PLUGIN_NAME} PROPERTIES - CXX_VISIBILITY_PRESET hidden) -target_compile_definitions(${PLUGIN_NAME} PRIVATE FLUTTER_PLUGIN_IMPL) - -# Source include directories and library dependencies. Add any plugin-specific -# dependencies here. -set(MSVC_RUNTIME_MODE MD) -add_subdirectory(${FIREBASE_CPP_SDK_DIR} bin/ EXCLUDE_FROM_ALL) -target_include_directories(${PLUGIN_NAME} INTERFACE - "${FIREBASE_CPP_SDK_DIR}/include") -set(firebase_libs firebase_auth firebase_database firebase_app) -target_link_libraries(${PLUGIN_NAME} PRIVATE "${firebase_libs}") - -target_include_directories(${PLUGIN_NAME} INTERFACE - "${CMAKE_CURRENT_SOURCE_DIR}/include") -target_link_libraries(${PLUGIN_NAME} PRIVATE flutter flutter_wrapper_plugin) - -# List of absolute paths to libraries that should be bundled with the plugin. -# This list could contain prebuilt libraries, or libraries created by an -# external build triggered from this build file. -set(firebase_core_bundled_libraries - "" - PARENT_SCOPE -) diff --git a/packages/firebase_core/firebase_core/firebase_core/windows/firebase_core_plugin.cpp b/packages/firebase_core/firebase_core/firebase_core/windows/firebase_core_plugin.cpp deleted file mode 100644 index 7dd2b9945a72..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/windows/firebase_core_plugin.cpp +++ /dev/null @@ -1,63 +0,0 @@ -#include "firebase_core_plugin.h" - -// This must be included before many other Windows headers. -#include -#include "firebase/app.h" - -// For getPlatformVersion; remove unless needed for your plugin implementation. -#include - -#include -#include -#include - -#include -#include -using ::firebase::App; - -namespace firebase_core { - -// static -void FirebaseCorePlugin::RegisterWithRegistrar( - flutter::PluginRegistrarWindows *registrar) { - auto channel = - std::make_unique>( - registrar->messenger(), "firebase_core", - &flutter::StandardMethodCodec::GetInstance()); - - auto plugin = std::make_unique(); - - channel->SetMethodCallHandler( - [plugin_pointer = plugin.get()](const auto &call, auto result) { - plugin_pointer->HandleMethodCall(call, std::move(result)); - }); - - registrar->AddPlugin(std::move(plugin)); -} - -FirebaseCorePlugin::FirebaseCorePlugin() {} - -FirebaseCorePlugin::~FirebaseCorePlugin() {} - -void FirebaseCorePlugin::HandleMethodCall( - const flutter::MethodCall &method_call, - std::unique_ptr> result) { - if (method_call.method_name().compare("getPlatformVersion") == 0) { - App* app = App::Create(); - std::cout << static_cast(reinterpret_cast(app)); - std::ostringstream version_stream; - version_stream << "Windows "; - if (IsWindows10OrGreater()) { - version_stream << "10+"; - } else if (IsWindows8OrGreater()) { - version_stream << "8"; - } else if (IsWindows7OrGreater()) { - version_stream << "7"; - } - result->Success(flutter::EncodableValue(version_stream.str())); - } else { - result->NotImplemented(); - } -} - -} // namespace firebase_core diff --git a/packages/firebase_core/firebase_core/firebase_core/windows/firebase_core_plugin.h b/packages/firebase_core/firebase_core/firebase_core/windows/firebase_core_plugin.h deleted file mode 100644 index fe99490af2c2..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/windows/firebase_core_plugin.h +++ /dev/null @@ -1,32 +0,0 @@ -#ifndef FLUTTER_PLUGIN_FIREBASE_CORE_PLUGIN_H_ -#define FLUTTER_PLUGIN_FIREBASE_CORE_PLUGIN_H_ - -#include -#include - -#include - -namespace firebase_core { - -class FirebaseCorePlugin : public flutter::Plugin { - public: - static void RegisterWithRegistrar(flutter::PluginRegistrarWindows *registrar); - - FirebaseCorePlugin(); - - virtual ~FirebaseCorePlugin(); - - // Disallow copy and assign. - FirebaseCorePlugin(const FirebaseCorePlugin&) = delete; - FirebaseCorePlugin& operator=(const FirebaseCorePlugin&) = delete; - - private: - // Called when a method is called on this plugin's channel from Dart. - void HandleMethodCall( - const flutter::MethodCall &method_call, - std::unique_ptr> result); -}; - -} // namespace firebase_core - -#endif // FLUTTER_PLUGIN_FIREBASE_CORE_PLUGIN_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/windows/firebase_core_plugin_c_api.cpp b/packages/firebase_core/firebase_core/firebase_core/windows/firebase_core_plugin_c_api.cpp deleted file mode 100644 index f0ca223fcf26..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/windows/firebase_core_plugin_c_api.cpp +++ /dev/null @@ -1,12 +0,0 @@ -#include "include/firebase_core/firebase_core_plugin_c_api.h" - -#include - -#include "firebase_core_plugin.h" - -void FirebaseCorePluginCApiRegisterWithRegistrar( - FlutterDesktopPluginRegistrarRef registrar) { - firebase_core::FirebaseCorePlugin::RegisterWithRegistrar( - flutter::PluginRegistrarManager::GetInstance() - ->GetRegistrar(registrar)); -} diff --git a/packages/firebase_core/firebase_core/firebase_core/windows/include/firebase_core/firebase_core_plugin_c_api.h b/packages/firebase_core/firebase_core/firebase_core/windows/include/firebase_core/firebase_core_plugin_c_api.h deleted file mode 100644 index 4ef141db19bd..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/windows/include/firebase_core/firebase_core_plugin_c_api.h +++ /dev/null @@ -1,23 +0,0 @@ -#ifndef FLUTTER_PLUGIN_FIREBASE_CORE_PLUGIN_C_API_H_ -#define FLUTTER_PLUGIN_FIREBASE_CORE_PLUGIN_C_API_H_ - -#include - -#ifdef FLUTTER_PLUGIN_IMPL -#define FLUTTER_PLUGIN_EXPORT __declspec(dllexport) -#else -#define FLUTTER_PLUGIN_EXPORT __declspec(dllimport) -#endif - -#if defined(__cplusplus) -extern "C" { -#endif - -FLUTTER_PLUGIN_EXPORT void FirebaseCorePluginCApiRegisterWithRegistrar( - FlutterDesktopPluginRegistrarRef registrar); - -#if defined(__cplusplus) -} // extern "C" -#endif - -#endif // FLUTTER_PLUGIN_FIREBASE_CORE_PLUGIN_C_API_H_ From a35e3e6f52462faa1f894bfefc57fdf8bfc26de8 Mon Sep 17 00:00:00 2001 From: Guillaume Bernos Date: Mon, 20 Mar 2023 15:06:39 +0100 Subject: [PATCH 21/65] add intializeApp --- .../firebase_core/windows/CMakeLists.txt | 2 + .../windows/firebase_core_plugin.cpp | 86 ++++++++++++------- .../windows/firebase_core_plugin.h | 37 ++++++-- .../windows/firebase_core_plugin_c_api.cpp | 2 +- 4 files changed, 89 insertions(+), 38 deletions(-) diff --git a/packages/firebase_core/firebase_core/windows/CMakeLists.txt b/packages/firebase_core/firebase_core/windows/CMakeLists.txt index 35c68f4a1910..efe90b40d4d1 100644 --- a/packages/firebase_core/firebase_core/windows/CMakeLists.txt +++ b/packages/firebase_core/firebase_core/windows/CMakeLists.txt @@ -16,6 +16,8 @@ set(PLUGIN_NAME "firebase_core_plugin") list(APPEND PLUGIN_SOURCES "firebase_core_plugin.cpp" "firebase_core_plugin.h" + "messages.g.cpp" + "messages.g.h" ) # Define the plugin library target. Its name must not be changed (see comment diff --git a/packages/firebase_core/firebase_core/windows/firebase_core_plugin.cpp b/packages/firebase_core/firebase_core/windows/firebase_core_plugin.cpp index 03f7e887904c..a1d000c6a96a 100644 --- a/packages/firebase_core/firebase_core/windows/firebase_core_plugin.cpp +++ b/packages/firebase_core/firebase_core/windows/firebase_core_plugin.cpp @@ -4,6 +4,7 @@ #include #include "firebase/app.h" +#include "messages.g.h" // For getPlatformVersion; remove unless needed for your plugin implementation. #include @@ -13,51 +14,74 @@ #include #include +#include +#include using ::firebase::App; -namespace firebase_core { +namespace firebase_core_windows { // static void FirebaseCorePlugin::RegisterWithRegistrar( flutter::PluginRegistrarWindows *registrar) { - auto channel = - std::make_unique>( - registrar->messenger(), "firebase_core", - &flutter::StandardMethodCodec::GetInstance()); auto plugin = std::make_unique(); - channel->SetMethodCallHandler( - [plugin_pointer = plugin.get()](const auto &call, auto result) { - plugin_pointer->HandleMethodCall(call, std::move(result)); - }); + FirebaseCoreHostApi::SetUp(registrar->messenger(), plugin.get()); registrar->AddPlugin(std::move(plugin)); } FirebaseCorePlugin::FirebaseCorePlugin() {} -FirebaseCorePlugin::~FirebaseCorePlugin() {} - -void FirebaseCorePlugin::HandleMethodCall( - const flutter::MethodCall &method_call, - std::unique_ptr> result) { - if (method_call.method_name().compare("getPlatformVersion") == 0) { - App *app = App::Create(); - std::cout << static_cast(reinterpret_cast(app)); - std::ostringstream version_stream; - version_stream << "Windows "; - if (IsWindows10OrGreater()) { - version_stream << "10+"; - } else if (IsWindows8OrGreater()) { - version_stream << "8"; - } else if (IsWindows7OrGreater()) { - version_stream << "7"; - } - result->Success(flutter::EncodableValue(version_stream.str())); - } else { - result->NotImplemented(); - } +FirebaseCorePlugin::~FirebaseCorePlugin() = default; + + +// Convert a Pigeon FirebaseOptions to a Firebase Options. +firebase::AppOptions PigeonFirebaseOptionsToAppOptions( + const PigeonFirebaseOptions& pigeon_options) { + firebase::AppOptions options; + options.set_api_key(pigeon_options.api_key().c_str()); + options.set_app_id(pigeon_options.app_id().c_str()); + options.set_database_url(pigeon_options.database_u_r_l()->c_str()); + options.set_messaging_sender_id(pigeon_options.messaging_sender_id().c_str()); + options.set_project_id(pigeon_options.project_id().c_str()); + options.set_storage_bucket(pigeon_options.storage_bucket()->c_str()); + return options; +} + +void FirebaseCorePlugin::InitializeApp( + const std::string &app_name, + const PigeonFirebaseOptions &initialize_app_request, + std::function reply)> result) { + // Create an app + App *app; + app = App::Create(PigeonFirebaseOptionsToAppOptions(initialize_app_request), + app_name.c_str()); + + // Send back the result to Flutter + result(PigeonInitializeResponse()); + + // Log everything is OK + std::cout << "FirebaseCorePlugin::InitializeApp: OK" << std::endl; } -} // namespace firebase_core +void FirebaseCorePlugin::InitializeCore( + std::function reply)> result) {} + +void FirebaseCorePlugin::OptionsFromResource( + std::function reply)> result) {} + +void FirebaseCorePlugin::SetAutomaticDataCollectionEnabled( + const std::string &app_name, bool enabled, + std::function reply)> result) {} + +void FirebaseCorePlugin::SetAutomaticResourceManagementEnabled( + const std::string &app_name, bool enabled, + std::function reply)> result) {} + +void FirebaseCorePlugin::Delete( + const std::string &app_name, + std::function reply)> result) {} + + +} // namespace firebase_core_windows diff --git a/packages/firebase_core/firebase_core/windows/firebase_core_plugin.h b/packages/firebase_core/firebase_core/windows/firebase_core_plugin.h index 52794b6a0e51..f0fbfd29239d 100644 --- a/packages/firebase_core/firebase_core/windows/firebase_core_plugin.h +++ b/packages/firebase_core/firebase_core/windows/firebase_core_plugin.h @@ -5,10 +5,11 @@ #include #include +#include "messages.g.h" -namespace firebase_core { +namespace firebase_core_windows { -class FirebaseCorePlugin : public flutter::Plugin { +class FirebaseCorePlugin : public flutter::Plugin, public FirebaseCoreHostApi, public FirebaseAppHostApi { public: static void RegisterWithRegistrar(flutter::PluginRegistrarWindows *registrar); @@ -20,11 +21,35 @@ class FirebaseCorePlugin : public flutter::Plugin { FirebaseCorePlugin(const FirebaseCorePlugin &) = delete; FirebaseCorePlugin &operator=(const FirebaseCorePlugin &) = delete; + + // FirebaseCoreHostApi + virtual void InitializeApp( + const std::string &app_name, + const PigeonFirebaseOptions &initialize_app_request, + std::function reply)> result) override; + virtual void InitializeCore( + std::function reply)> result) + override; + virtual void OptionsFromResource( + std::function reply)> result) + override; + + + // FirebaseAppHostApi + virtual void SetAutomaticDataCollectionEnabled( + const std::string &app_name, bool enabled, + std::function reply)> result) override; + virtual void SetAutomaticResourceManagementEnabled( + const std::string &app_name, bool enabled, + std::function reply)> result) override; + virtual void Delete( + const std::string &app_name, + std::function reply)> result) override; + + + private: - // Called when a method is called on this plugin's channel from Dart. - void HandleMethodCall( - const flutter::MethodCall &method_call, - std::unique_ptr> result); + }; } // namespace firebase_core diff --git a/packages/firebase_core/firebase_core/windows/firebase_core_plugin_c_api.cpp b/packages/firebase_core/firebase_core/windows/firebase_core_plugin_c_api.cpp index f0ca223fcf26..478de00182e5 100644 --- a/packages/firebase_core/firebase_core/windows/firebase_core_plugin_c_api.cpp +++ b/packages/firebase_core/firebase_core/windows/firebase_core_plugin_c_api.cpp @@ -6,7 +6,7 @@ void FirebaseCorePluginCApiRegisterWithRegistrar( FlutterDesktopPluginRegistrarRef registrar) { - firebase_core::FirebaseCorePlugin::RegisterWithRegistrar( + firebase_core_windows::FirebaseCorePlugin::RegisterWithRegistrar( flutter::PluginRegistrarManager::GetInstance() ->GetRegistrar(registrar)); } From 49dd1fbccda3563fa16ef836483fad5a42161591 Mon Sep 17 00:00:00 2001 From: Guillaume Bernos Date: Mon, 20 Mar 2023 16:34:04 +0100 Subject: [PATCH 22/65] initalizeCore --- .../windows/firebase_core_plugin.cpp | 38 +++++++++++++++++-- .../windows/firebase_core_plugin.h | 4 +- 2 files changed, 36 insertions(+), 6 deletions(-) diff --git a/packages/firebase_core/firebase_core/windows/firebase_core_plugin.cpp b/packages/firebase_core/firebase_core/windows/firebase_core_plugin.cpp index a1d000c6a96a..2f5334881822 100644 --- a/packages/firebase_core/firebase_core/windows/firebase_core_plugin.cpp +++ b/packages/firebase_core/firebase_core/windows/firebase_core_plugin.cpp @@ -15,6 +15,9 @@ #include #include #include +#include +#include +#include #include using ::firebase::App; @@ -36,6 +39,10 @@ FirebaseCorePlugin::FirebaseCorePlugin() {} FirebaseCorePlugin::~FirebaseCorePlugin() = default; + + + + // Convert a Pigeon FirebaseOptions to a Firebase Options. firebase::AppOptions PigeonFirebaseOptionsToAppOptions( const PigeonFirebaseOptions& pigeon_options) { @@ -46,6 +53,7 @@ firebase::AppOptions PigeonFirebaseOptionsToAppOptions( options.set_messaging_sender_id(pigeon_options.messaging_sender_id().c_str()); options.set_project_id(pigeon_options.project_id().c_str()); options.set_storage_bucket(pigeon_options.storage_bucket()->c_str()); + options.set_ga_tracking_id(pigeon_options.tracking_id()->c_str()); return options; } @@ -66,22 +74,44 @@ void FirebaseCorePlugin::InitializeApp( } void FirebaseCorePlugin::InitializeCore( - std::function reply)> result) {} + std::function reply)> result) { + result(flutter::EncodableList()); +} void FirebaseCorePlugin::OptionsFromResource( std::function reply)> result) {} void FirebaseCorePlugin::SetAutomaticDataCollectionEnabled( const std::string &app_name, bool enabled, - std::function reply)> result) {} + std::function reply)> result) { + App* firebaseApp = App::GetInstance(app_name.c_str()); + if (firebaseApp != nullptr) { + // Missing method + } + result(std::nullopt); +} void FirebaseCorePlugin::SetAutomaticResourceManagementEnabled( const std::string &app_name, bool enabled, - std::function reply)> result) {} + std::function reply)> result) { + App* firebaseApp = App::GetInstance(app_name.c_str()); + if (firebaseApp != nullptr) { + // Missing method + } + + result(std::nullopt); +} void FirebaseCorePlugin::Delete( const std::string &app_name, - std::function reply)> result) {} + std::function reply)> result) { + App* firebaseApp = App::GetInstance(app_name.c_str()); + if (firebaseApp != nullptr) { + // Missing method + } + + result(std::nullopt); +} } // namespace firebase_core_windows diff --git a/packages/firebase_core/firebase_core/windows/firebase_core_plugin.h b/packages/firebase_core/firebase_core/windows/firebase_core_plugin.h index f0fbfd29239d..12161246ec4d 100644 --- a/packages/firebase_core/firebase_core/windows/firebase_core_plugin.h +++ b/packages/firebase_core/firebase_core/windows/firebase_core_plugin.h @@ -48,8 +48,8 @@ class FirebaseCorePlugin : public flutter::Plugin, public FirebaseCoreHostApi, p - private: - +private: + bool coreInitialized = false; }; } // namespace firebase_core From 1a5cd02d446164a6ba5e5f2dfe8e04b6ff48b2c0 Mon Sep 17 00:00:00 2001 From: Guillaume Bernos Date: Tue, 21 Mar 2023 10:14:07 +0100 Subject: [PATCH 23/65] ready windows --- .../windows/firebase_core_plugin.cpp | 84 +++++++++++++------ 1 file changed, 60 insertions(+), 24 deletions(-) diff --git a/packages/firebase_core/firebase_core/windows/firebase_core_plugin.cpp b/packages/firebase_core/firebase_core/windows/firebase_core_plugin.cpp index 2f5334881822..65889e092ce3 100644 --- a/packages/firebase_core/firebase_core/windows/firebase_core_plugin.cpp +++ b/packages/firebase_core/firebase_core/windows/firebase_core_plugin.cpp @@ -12,13 +12,13 @@ #include #include +#include +#include #include #include -#include -#include -#include #include #include +#include using ::firebase::App; namespace firebase_core_windows { @@ -26,7 +26,6 @@ namespace firebase_core_windows { // static void FirebaseCorePlugin::RegisterWithRegistrar( flutter::PluginRegistrarWindows *registrar) { - auto plugin = std::make_unique(); FirebaseCoreHostApi::SetUp(registrar->messenger(), plugin.get()); @@ -38,25 +37,57 @@ FirebaseCorePlugin::FirebaseCorePlugin() {} FirebaseCorePlugin::~FirebaseCorePlugin() = default; - - - - - // Convert a Pigeon FirebaseOptions to a Firebase Options. firebase::AppOptions PigeonFirebaseOptionsToAppOptions( - const PigeonFirebaseOptions& pigeon_options) { + const PigeonFirebaseOptions &pigeon_options) { firebase::AppOptions options; options.set_api_key(pigeon_options.api_key().c_str()); options.set_app_id(pigeon_options.app_id().c_str()); - options.set_database_url(pigeon_options.database_u_r_l()->c_str()); + if (pigeon_options.database_u_r_l() != nullptr) { + options.set_database_url(pigeon_options.database_u_r_l()->c_str()); + } + if (pigeon_options.tracking_id() != nullptr) { + options.set_ga_tracking_id(pigeon_options.tracking_id()->c_str()); + } options.set_messaging_sender_id(pigeon_options.messaging_sender_id().c_str()); + options.set_project_id(pigeon_options.project_id().c_str()); - options.set_storage_bucket(pigeon_options.storage_bucket()->c_str()); - options.set_ga_tracking_id(pigeon_options.tracking_id()->c_str()); + + if (pigeon_options.storage_bucket() != nullptr) { + options.set_storage_bucket(pigeon_options.storage_bucket()->c_str()); + } return options; } +// Convert a AppOptions to PigeonInitializeOption +PigeonFirebaseOptions optionsFromFIROptions( + const firebase::AppOptions &options) { + PigeonFirebaseOptions pigeon_options = PigeonFirebaseOptions(); + pigeon_options.set_api_key(options.api_key()); + pigeon_options.set_app_id(options.app_id()); + if (options.database_url() != nullptr) { + pigeon_options.set_database_u_r_l(options.database_url()); + } + if (options.ga_tracking_id() != nullptr) { + pigeon_options.set_tracking_id(options.ga_tracking_id()); + } + pigeon_options.set_messaging_sender_id(options.messaging_sender_id()); + pigeon_options.set_project_id(options.project_id()); + if (options.storage_bucket() != nullptr) { + pigeon_options.set_storage_bucket(options.storage_bucket()); + } + return pigeon_options; +} + +// Convert a firebase::App to PigeonInitializeResponse +PigeonInitializeResponse AppToPigeonInitializeResponse( + const App& app) { + PigeonInitializeResponse response = PigeonInitializeResponse(); + response.set_name(app.name()); + response.set_options(optionsFromFIROptions(app.options())); + return response; +} + void FirebaseCorePlugin::InitializeApp( const std::string &app_name, const PigeonFirebaseOptions &initialize_app_request, @@ -67,14 +98,20 @@ void FirebaseCorePlugin::InitializeApp( app_name.c_str()); // Send back the result to Flutter - result(PigeonInitializeResponse()); - - // Log everything is OK - std::cout << "FirebaseCorePlugin::InitializeApp: OK" << std::endl; + result(AppToPigeonInitializeResponse(*app)); } void FirebaseCorePlugin::InitializeCore( std::function reply)> result) { + // TODO: Missing function to get the list of currently initialized apps + std::vector initializedApps; + + flutter::EncodableList encodableList; + + // Insert the contents of the vector into the EncodableList + // for (const auto &item : initializedApps) { + // encodableList.push_back(flutter::EncodableValue(item)); + //} result(flutter::EncodableList()); } @@ -84,9 +121,9 @@ void FirebaseCorePlugin::OptionsFromResource( void FirebaseCorePlugin::SetAutomaticDataCollectionEnabled( const std::string &app_name, bool enabled, std::function reply)> result) { - App* firebaseApp = App::GetInstance(app_name.c_str()); + App *firebaseApp = App::GetInstance(app_name.c_str()); if (firebaseApp != nullptr) { - // Missing method + // TODO: Missing method } result(std::nullopt); } @@ -94,9 +131,9 @@ void FirebaseCorePlugin::SetAutomaticDataCollectionEnabled( void FirebaseCorePlugin::SetAutomaticResourceManagementEnabled( const std::string &app_name, bool enabled, std::function reply)> result) { - App* firebaseApp = App::GetInstance(app_name.c_str()); + App *firebaseApp = App::GetInstance(app_name.c_str()); if (firebaseApp != nullptr) { - // Missing method + // TODO: Missing method } result(std::nullopt); @@ -105,13 +142,12 @@ void FirebaseCorePlugin::SetAutomaticResourceManagementEnabled( void FirebaseCorePlugin::Delete( const std::string &app_name, std::function reply)> result) { - App* firebaseApp = App::GetInstance(app_name.c_str()); + App *firebaseApp = App::GetInstance(app_name.c_str()); if (firebaseApp != nullptr) { - // Missing method + // TODO: Missing method } result(std::nullopt); } - } // namespace firebase_core_windows From c8ffe08082416bce7cf640a298cf41837c609701 Mon Sep 17 00:00:00 2001 From: Guillaume Bernos Date: Tue, 21 Feb 2023 07:50:40 +0100 Subject: [PATCH 24/65] feat: integration of C++ desktop SDK --- .../firebase_core/firebase_core/.gitignore | 30 + .../firebase_core/firebase_core/.metadata | 30 + .../firebase_core/.vscode/settings.json | 3 + .../firebase_core/firebase_core/CHANGELOG.md | 3 + .../firebase_core/GoogleService-Info.plist | 38 + .../firebase_core/firebase_core/LICENSE | 1 + .../firebase_core/firebase_core/README.md | 15 + .../firebase_core/analysis_options.yaml | 4 + .../firebase_core/example/.gitignore | 44 + .../firebase_core/example/README.md | 16 + .../example/analysis_options.yaml | 29 + .../firebase_core/example/lib/main.dart | 63 + .../firebase_core/example/linux/.gitignore | 1 + .../example/linux/CMakeLists.txt | 150 +++ .../example/linux/flutter/CMakeLists.txt | 88 ++ .../flutter/generated_plugin_registrant.cc | 15 + .../flutter/generated_plugin_registrant.h | 15 + .../linux/flutter/generated_plugins.cmake | 24 + .../firebase_core/example/linux/main.cc | 6 + .../example/linux/my_application.cc | 104 ++ .../example/linux/my_application.h | 18 + .../firebase_core/example/pubspec.yaml | 83 ++ .../example/test/widget_test.dart | 27 + .../firebase_core/firebase/admob.h | 215 +++ .../firebase/admob/banner_view.h | 427 ++++++ .../firebase/admob/interstitial_ad.h | 259 ++++ .../firebase/admob/native_express_ad_view.h | 446 ++++++ .../firebase/admob/rewarded_video.h | 407 ++++++ .../firebase_core/firebase/admob/types.h | 244 ++++ .../firebase_core/firebase/analytics.h | 569 ++++++++ .../firebase/analytics/event_names.h | 472 +++++++ .../firebase/analytics/parameter_names.h | 755 +++++++++++ .../firebase/analytics/user_property_names.h | 50 + .../firebase_core/firebase/app.h | 787 +++++++++++ .../firebase_core/firebase/auth.h | 939 +++++++++++++ .../firebase_core/firebase/auth/credential.h | 633 +++++++++ .../firebase_core/firebase/auth/types.h | 473 +++++++ .../firebase_core/firebase/auth/user.h | 501 +++++++ .../firebase_core/firebase/database.h | 199 +++ .../firebase_core/firebase/database/common.h | 83 ++ .../firebase/database/data_snapshot.h | 205 +++ .../firebase/database/database_reference.h | 477 +++++++ .../firebase/database/disconnection.h | 156 +++ .../firebase/database/listener.h | 112 ++ .../firebase/database/mutable_data.h | 165 +++ .../firebase_core/firebase/database/query.h | 358 +++++ .../firebase/database/transaction.h | 102 ++ .../firebase_core/firebase/dynamic_links.h | 117 ++ .../firebase/dynamic_links/components.h | 336 +++++ .../firebase_core/firebase/firestore.h | 458 +++++++ .../firebase/firestore/collection_reference.h | 183 +++ .../firebase/firestore/document_change.h | 203 +++ .../firebase/firestore/document_reference.h | 351 +++++ .../firebase/firestore/document_snapshot.h | 297 ++++ .../firebase/firestore/field_path.h | 205 +++ .../firebase/firestore/field_value.h | 436 ++++++ .../firebase/firestore/firestore_errors.h | 116 ++ .../firebase/firestore/firestore_version.h | 29 + .../firebase/firestore/geo_point.h | 120 ++ .../firestore/listener_registration.h | 130 ++ .../firestore/load_bundle_task_progress.h | 101 ++ .../firebase/firestore/map_field_value.h | 37 + .../firebase/firestore/metadata_changes.h | 41 + .../firebase_core/firebase/firestore/query.h | 683 ++++++++++ .../firebase/firestore/query_snapshot.h | 194 +++ .../firebase/firestore/set_options.h | 161 +++ .../firebase/firestore/settings.h | 247 ++++ .../firebase/firestore/snapshot_metadata.h | 159 +++ .../firebase_core/firebase/firestore/source.h | 59 + .../firebase/firestore/timestamp.h | 252 ++++ .../firebase/firestore/transaction.h | 143 ++ .../firebase/firestore/transaction_options.h | 137 ++ .../firebase/firestore/write_batch.h | 188 +++ .../firebase_core/firebase/functions.h | 115 ++ .../firebase/functions/callable_reference.h | 124 ++ .../firebase/functions/callable_result.h | 96 ++ .../firebase_core/firebase/functions/common.h | 202 +++ .../firebase_core/firebase/future.h | 533 ++++++++ .../firebase_core/firebase/gma.h | 207 +++ .../firebase_core/firebase/gma/ad_view.h | 267 ++++ .../firebase/gma/interstitial_ad.h | 128 ++ .../firebase_core/firebase/gma/rewarded_ad.h | 152 +++ .../firebase_core/firebase/gma/types.h | 939 +++++++++++++ .../firebase_core/firebase/installations.h | 123 ++ .../firebase_core/firebase/internal/common.h | 128 ++ .../firebase/internal/future_impl.h | 359 +++++ .../firebase_core/firebase/internal/mutex.h | 100 ++ .../firebase/internal/platform.h | 110 ++ .../firebase/internal/type_traits.h | 134 ++ .../firebase_core/firebase/log.h | 54 + .../firebase_core/firebase/messaging.h | 728 ++++++++++ .../firebase_core/firebase/remote_config.h | 526 ++++++++ .../firebase_core/firebase/storage.h | 161 +++ .../firebase_core/firebase/storage/common.h | 62 + .../firebase/storage/controller.h | 146 ++ .../firebase_core/firebase/storage/listener.h | 74 + .../firebase_core/firebase/storage/metadata.h | 276 ++++ .../firebase/storage/storage_reference.h | 361 +++++ .../firebase_core/firebase/util.h | 101 ++ .../firebase_core/firebase/variant.h | 1197 +++++++++++++++++ .../firebase_core/firebase/version.h | 68 + .../generate_xml_from_google_services_json.py | 496 +++++++ .../firebase_core/generated_bindings.dart | 26 + .../google-services-desktop.json | 37 + .../firebase_core/lib/firebase_core.dart | 8 + .../lib/firebase_core_method_channel.dart | 17 + .../lib/firebase_core_platform_interface.dart | 29 + .../firebase_core/linux/CMakeLists.txt | 47 + .../linux/firebase_core_plugin.cc | 70 + .../firebase_core/firebase_core_plugin.h | 26 + .../firebase_core/firebase_core/pubspec.yaml | 34 + .../firebase_core_method_channel_test.dart | 24 + .../test/firebase_core_test.dart | 29 + 113 files changed, 23538 insertions(+) create mode 100644 packages/firebase_core/firebase_core/firebase_core/.gitignore create mode 100644 packages/firebase_core/firebase_core/firebase_core/.metadata create mode 100644 packages/firebase_core/firebase_core/firebase_core/.vscode/settings.json create mode 100644 packages/firebase_core/firebase_core/firebase_core/CHANGELOG.md create mode 100644 packages/firebase_core/firebase_core/firebase_core/GoogleService-Info.plist create mode 100644 packages/firebase_core/firebase_core/firebase_core/LICENSE create mode 100644 packages/firebase_core/firebase_core/firebase_core/README.md create mode 100644 packages/firebase_core/firebase_core/firebase_core/analysis_options.yaml create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/.gitignore create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/README.md create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/analysis_options.yaml create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/lib/main.dart create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/linux/.gitignore create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/linux/CMakeLists.txt create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/linux/flutter/CMakeLists.txt create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/linux/flutter/generated_plugin_registrant.cc create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/linux/flutter/generated_plugin_registrant.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/linux/flutter/generated_plugins.cmake create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/linux/main.cc create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/linux/my_application.cc create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/linux/my_application.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/pubspec.yaml create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/test/widget_test.dart create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/admob.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/admob/banner_view.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/admob/interstitial_ad.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/admob/native_express_ad_view.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/admob/rewarded_video.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/admob/types.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/analytics.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/analytics/event_names.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/analytics/parameter_names.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/analytics/user_property_names.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/app.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/auth.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/auth/credential.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/auth/types.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/auth/user.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/database.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/database/common.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/database/data_snapshot.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/database/database_reference.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/database/disconnection.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/database/listener.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/database/mutable_data.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/database/query.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/database/transaction.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/dynamic_links.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/dynamic_links/components.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/collection_reference.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/document_change.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/document_reference.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/document_snapshot.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/field_path.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/field_value.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/firestore_errors.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/firestore_version.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/geo_point.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/listener_registration.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/load_bundle_task_progress.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/map_field_value.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/metadata_changes.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/query.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/query_snapshot.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/set_options.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/settings.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/snapshot_metadata.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/source.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/timestamp.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/transaction.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/transaction_options.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/write_batch.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/functions.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/functions/callable_reference.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/functions/callable_result.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/functions/common.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/future.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/gma.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/gma/ad_view.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/gma/interstitial_ad.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/gma/rewarded_ad.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/gma/types.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/installations.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/internal/common.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/internal/future_impl.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/internal/mutex.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/internal/platform.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/internal/type_traits.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/log.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/messaging.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/remote_config.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/storage.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/storage/common.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/storage/controller.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/storage/listener.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/storage/metadata.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/storage/storage_reference.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/util.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/variant.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/version.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/generate_xml_from_google_services_json.py create mode 100644 packages/firebase_core/firebase_core/firebase_core/generated_bindings.dart create mode 100644 packages/firebase_core/firebase_core/firebase_core/google-services-desktop.json create mode 100644 packages/firebase_core/firebase_core/firebase_core/lib/firebase_core.dart create mode 100644 packages/firebase_core/firebase_core/firebase_core/lib/firebase_core_method_channel.dart create mode 100644 packages/firebase_core/firebase_core/firebase_core/lib/firebase_core_platform_interface.dart create mode 100644 packages/firebase_core/firebase_core/firebase_core/linux/CMakeLists.txt create mode 100644 packages/firebase_core/firebase_core/firebase_core/linux/firebase_core_plugin.cc create mode 100644 packages/firebase_core/firebase_core/firebase_core/linux/include/firebase_core/firebase_core_plugin.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/pubspec.yaml create mode 100644 packages/firebase_core/firebase_core/firebase_core/test/firebase_core_method_channel_test.dart create mode 100644 packages/firebase_core/firebase_core/firebase_core/test/firebase_core_test.dart diff --git a/packages/firebase_core/firebase_core/firebase_core/.gitignore b/packages/firebase_core/firebase_core/firebase_core/.gitignore new file mode 100644 index 000000000000..96486fd93024 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/.gitignore @@ -0,0 +1,30 @@ +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.buildlog/ +.history +.svn/ +migrate_working_dir/ + +# IntelliJ related +*.iml +*.ipr +*.iws +.idea/ + +# The .vscode folder contains launch configuration and tasks you configure in +# VS Code which you may wish to be included in version control, so this line +# is commented out by default. +#.vscode/ + +# Flutter/Dart/Pub related +# Libraries should not include pubspec.lock, per https://dart.dev/guides/libraries/private-files#pubspeclock. +/pubspec.lock +**/doc/api/ +.dart_tool/ +.packages +build/ diff --git a/packages/firebase_core/firebase_core/firebase_core/.metadata b/packages/firebase_core/firebase_core/firebase_core/.metadata new file mode 100644 index 000000000000..74867a0b132b --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/.metadata @@ -0,0 +1,30 @@ +# This file tracks properties of this Flutter project. +# Used by Flutter tool to assess capabilities and perform upgrades etc. +# +# This file should be version controlled. + +version: + revision: 9944297138845a94256f1cf37beb88ff9a8e811a + channel: stable + +project_type: plugin + +# Tracks metadata for the flutter migrate command +migration: + platforms: + - platform: root + create_revision: 9944297138845a94256f1cf37beb88ff9a8e811a + base_revision: 9944297138845a94256f1cf37beb88ff9a8e811a + - platform: linux + create_revision: 9944297138845a94256f1cf37beb88ff9a8e811a + base_revision: 9944297138845a94256f1cf37beb88ff9a8e811a + + # User provided section + + # List of Local paths (relative to this file) that should be + # ignored by the migrate tool. + # + # Files that are not part of the templates will be ignored by default. + unmanaged_files: + - 'lib/main.dart' + - 'ios/Runner.xcodeproj/project.pbxproj' diff --git a/packages/firebase_core/firebase_core/firebase_core/.vscode/settings.json b/packages/firebase_core/firebase_core/firebase_core/.vscode/settings.json new file mode 100644 index 000000000000..deec1e1d3994 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/.vscode/settings.json @@ -0,0 +1,3 @@ +{ + "cmake.sourceDirectory": "${workspaceFolder}/linux" +} diff --git a/packages/firebase_core/firebase_core/firebase_core/CHANGELOG.md b/packages/firebase_core/firebase_core/firebase_core/CHANGELOG.md new file mode 100644 index 000000000000..41cc7d8192ec --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/CHANGELOG.md @@ -0,0 +1,3 @@ +## 0.0.1 + +* TODO: Describe initial release. diff --git a/packages/firebase_core/firebase_core/firebase_core/GoogleService-Info.plist b/packages/firebase_core/firebase_core/firebase_core/GoogleService-Info.plist new file mode 100644 index 000000000000..f325ead98dbc --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/GoogleService-Info.plist @@ -0,0 +1,38 @@ + + + + + CLIENT_ID + 406099696497-134k3722m01rtrsklhf3b7k8sqa5r7in.apps.googleusercontent.com + REVERSED_CLIENT_ID + com.googleusercontent.apps.406099696497-134k3722m01rtrsklhf3b7k8sqa5r7in + ANDROID_CLIENT_ID + 406099696497-17qn06u8a0dc717u8ul7s49ampk13lul.apps.googleusercontent.com + API_KEY + AIzaSyDooSUGSf63Ghq02_iIhtnmwMDs4HlWS6c + GCM_SENDER_ID + 406099696497 + PLIST_VERSION + 1 + BUNDLE_ID + io.flutter.plugins.firebase.auth.example + PROJECT_ID + flutterfire-e2e-tests + STORAGE_BUCKET + flutterfire-e2e-tests.appspot.com + IS_ADS_ENABLED + + IS_ANALYTICS_ENABLED + + IS_APPINVITE_ENABLED + + IS_GCM_ENABLED + + IS_SIGNIN_ENABLED + + GOOGLE_APP_ID + 1:406099696497:ios:58cbc26aca8e5cf83574d0 + DATABASE_URL + https://flutterfire-e2e-tests-default-rtdb.europe-west1.firebasedatabase.app + + \ No newline at end of file diff --git a/packages/firebase_core/firebase_core/firebase_core/LICENSE b/packages/firebase_core/firebase_core/firebase_core/LICENSE new file mode 100644 index 000000000000..ba75c69f7f21 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/LICENSE @@ -0,0 +1 @@ +TODO: Add your license here. diff --git a/packages/firebase_core/firebase_core/firebase_core/README.md b/packages/firebase_core/firebase_core/firebase_core/README.md new file mode 100644 index 000000000000..b373aba55a5f --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/README.md @@ -0,0 +1,15 @@ +# firebase_core + +A new Flutter plugin project. + +## Getting Started + +This project is a starting point for a Flutter +[plug-in package](https://flutter.dev/developing-packages/), +a specialized package that includes platform-specific implementation code for +Android and/or iOS. + +For help getting started with Flutter development, view the +[online documentation](https://flutter.dev/docs), which offers tutorials, +samples, guidance on mobile development, and a full API reference. + diff --git a/packages/firebase_core/firebase_core/firebase_core/analysis_options.yaml b/packages/firebase_core/firebase_core/firebase_core/analysis_options.yaml new file mode 100644 index 000000000000..a5744c1cfbe7 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/analysis_options.yaml @@ -0,0 +1,4 @@ +include: package:flutter_lints/flutter.yaml + +# Additional information about this file can be found at +# https://dart.dev/guides/language/analysis-options diff --git a/packages/firebase_core/firebase_core/firebase_core/example/.gitignore b/packages/firebase_core/firebase_core/firebase_core/example/.gitignore new file mode 100644 index 000000000000..24476c5d1eb5 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/.gitignore @@ -0,0 +1,44 @@ +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.buildlog/ +.history +.svn/ +migrate_working_dir/ + +# IntelliJ related +*.iml +*.ipr +*.iws +.idea/ + +# The .vscode folder contains launch configuration and tasks you configure in +# VS Code which you may wish to be included in version control, so this line +# is commented out by default. +#.vscode/ + +# Flutter/Dart/Pub related +**/doc/api/ +**/ios/Flutter/.last_build_id +.dart_tool/ +.flutter-plugins +.flutter-plugins-dependencies +.packages +.pub-cache/ +.pub/ +/build/ + +# Symbolication related +app.*.symbols + +# Obfuscation related +app.*.map.json + +# Android Studio will place build artifacts here +/android/app/debug +/android/app/profile +/android/app/release diff --git a/packages/firebase_core/firebase_core/firebase_core/example/README.md b/packages/firebase_core/firebase_core/firebase_core/example/README.md new file mode 100644 index 000000000000..d1f452146bce --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/README.md @@ -0,0 +1,16 @@ +# firebase_core_example + +Demonstrates how to use the firebase_core plugin. + +## Getting Started + +This project is a starting point for a Flutter application. + +A few resources to get you started if this is your first Flutter project: + +- [Lab: Write your first Flutter app](https://docs.flutter.dev/get-started/codelab) +- [Cookbook: Useful Flutter samples](https://docs.flutter.dev/cookbook) + +For help getting started with Flutter development, view the +[online documentation](https://docs.flutter.dev/), which offers tutorials, +samples, guidance on mobile development, and a full API reference. diff --git a/packages/firebase_core/firebase_core/firebase_core/example/analysis_options.yaml b/packages/firebase_core/firebase_core/firebase_core/example/analysis_options.yaml new file mode 100644 index 000000000000..61b6c4de17c9 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/analysis_options.yaml @@ -0,0 +1,29 @@ +# This file configures the analyzer, which statically analyzes Dart code to +# check for errors, warnings, and lints. +# +# The issues identified by the analyzer are surfaced in the UI of Dart-enabled +# IDEs (https://dart.dev/tools#ides-and-editors). The analyzer can also be +# invoked from the command line by running `flutter analyze`. + +# The following line activates a set of recommended lints for Flutter apps, +# packages, and plugins designed to encourage good coding practices. +include: package:flutter_lints/flutter.yaml + +linter: + # The lint rules applied to this project can be customized in the + # section below to disable rules from the `package:flutter_lints/flutter.yaml` + # included above or to enable additional rules. A list of all available lints + # and their documentation is published at + # https://dart-lang.github.io/linter/lints/index.html. + # + # Instead of disabling a lint rule for the entire project in the + # section below, it can also be suppressed for a single line of code + # or a specific dart file by using the `// ignore: name_of_lint` and + # `// ignore_for_file: name_of_lint` syntax on the line or in the file + # producing the lint. + rules: + # avoid_print: false # Uncomment to disable the `avoid_print` rule + # prefer_single_quotes: true # Uncomment to enable the `prefer_single_quotes` rule + +# Additional information about this file can be found at +# https://dart.dev/guides/language/analysis-options diff --git a/packages/firebase_core/firebase_core/firebase_core/example/lib/main.dart b/packages/firebase_core/firebase_core/firebase_core/example/lib/main.dart new file mode 100644 index 000000000000..4e2b473ad9e0 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/lib/main.dart @@ -0,0 +1,63 @@ +import 'package:flutter/material.dart'; +import 'dart:async'; + +import 'package:flutter/services.dart'; +import 'package:firebase_core/firebase_core.dart'; + +void main() { + runApp(const MyApp()); +} + +class MyApp extends StatefulWidget { + const MyApp({super.key}); + + @override + State createState() => _MyAppState(); +} + +class _MyAppState extends State { + String _platformVersion = 'Unknown'; + final _firebaseCorePlugin = FirebaseCore(); + + @override + void initState() { + super.initState(); + initPlatformState(); + } + + // Platform messages are asynchronous, so we initialize in an async method. + Future initPlatformState() async { + String platformVersion; + // Platform messages may fail, so we use a try/catch PlatformException. + // We also handle the message potentially returning null. + try { + platformVersion = + await _firebaseCorePlugin.getPlatformVersion() ?? 'Unknown platform version'; + } on PlatformException { + platformVersion = 'Failed to get platform version.'; + } + + // If the widget was removed from the tree while the asynchronous platform + // message was in flight, we want to discard the reply rather than calling + // setState to update our non-existent appearance. + if (!mounted) return; + + setState(() { + _platformVersion = platformVersion; + }); + } + + @override + Widget build(BuildContext context) { + return MaterialApp( + home: Scaffold( + appBar: AppBar( + title: const Text('Plugin example app'), + ), + body: Center( + child: Text('Running on: $_platformVersion\n'), + ), + ), + ); + } +} diff --git a/packages/firebase_core/firebase_core/firebase_core/example/linux/.gitignore b/packages/firebase_core/firebase_core/firebase_core/example/linux/.gitignore new file mode 100644 index 000000000000..d3896c98444f --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/linux/.gitignore @@ -0,0 +1 @@ +flutter/ephemeral diff --git a/packages/firebase_core/firebase_core/firebase_core/example/linux/CMakeLists.txt b/packages/firebase_core/firebase_core/firebase_core/example/linux/CMakeLists.txt new file mode 100644 index 000000000000..9ae42276201e --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/linux/CMakeLists.txt @@ -0,0 +1,150 @@ +# Project-level configuration. +cmake_minimum_required(VERSION 3.10) +project(runner LANGUAGES CXX) + +# The name of the executable created for the application. Change this to change +# the on-disk name of your application. +set(BINARY_NAME "firebase_core_example") +# The unique GTK application identifier for this application. See: +# https://wiki.gnome.org/HowDoI/ChooseApplicationID +set(APPLICATION_ID "com.example.firebase_core") + +# Explicitly opt in to modern CMake behaviors to avoid warnings with recent +# versions of CMake. +cmake_policy(SET CMP0063 NEW) + +# Load bundled libraries from the lib/ directory relative to the binary. +set(CMAKE_INSTALL_RPATH "$ORIGIN/lib") + +# Root filesystem for cross-building. +if(FLUTTER_TARGET_PLATFORM_SYSROOT) + set(CMAKE_SYSROOT ${FLUTTER_TARGET_PLATFORM_SYSROOT}) + set(CMAKE_FIND_ROOT_PATH ${CMAKE_SYSROOT}) + set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) + set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY) + set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) + set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) +endif() + +# Define build configuration options. +if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) + set(CMAKE_BUILD_TYPE "Debug" CACHE + STRING "Flutter build mode" FORCE) + set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS + "Debug" "Profile" "Release") +endif() + +# Compilation settings that should be applied to most targets. +# +# Be cautious about adding new options here, as plugins use this function by +# default. In most cases, you should add new options to specific targets instead +# of modifying this function. +function(APPLY_STANDARD_SETTINGS TARGET) + target_compile_features(${TARGET} PUBLIC cxx_std_14) + target_compile_options(${TARGET} PRIVATE -Wall -Werror) + target_compile_options(${TARGET} PRIVATE "$<$>:-O3>") + target_compile_definitions(${TARGET} PRIVATE "$<$>:NDEBUG>") +endfunction() + +# Flutter library and tool build rules. +set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") +add_subdirectory(${FLUTTER_MANAGED_DIR}) + +# Add Firebase libraries to the target using the function from the SDK. +add_subdirectory(${FIREBASE_CPP_SDK_DIR} bin/ EXCLUDE_FROM_ALL) + +# The Firebase C++ library `firebase_app` is required, +# and it must always be listed last. + +# Add the Firebase SDKs for the products you want to use in your app +# For example, to use Firebase Authentication and Firebase Realtime Database +set(firebase_libs firebase_auth firebase_database firebase_app) +target_link_libraries(${target_name} "${firebase_libs}") + + +# System-level dependencies. +find_package(PkgConfig REQUIRED) +pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) + +add_definitions(-DAPPLICATION_ID="${APPLICATION_ID}") + +# Define the application target. To change its name, change BINARY_NAME above, +# not the value here, or `flutter run` will no longer work. +# +# Any new source files that you add to the application should be added here. +add_executable(${BINARY_NAME} + "main.cc" + "my_application.cc" + "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" +) + +# Apply the standard set of build settings. This can be removed for applications +# that need different build settings. +apply_standard_settings(${BINARY_NAME}) + +# Add dependency libraries. Add any application-specific dependencies here. +target_link_libraries(${BINARY_NAME} PRIVATE flutter) +target_link_libraries(${BINARY_NAME} PRIVATE PkgConfig::GTK) + +# Run the Flutter tool portions of the build. This must not be removed. +add_dependencies(${BINARY_NAME} flutter_assemble) + +# Only the install-generated bundle's copy of the executable will launch +# correctly, since the resources must in the right relative locations. To avoid +# people trying to run the unbundled copy, put it in a subdirectory instead of +# the default top-level location. +set_target_properties(${BINARY_NAME} + PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/intermediates_do_not_run" +) + +# Generated plugin build rules, which manage building the plugins and adding +# them to the application. +include(flutter/generated_plugins.cmake) + + +# === Installation === +# By default, "installing" just makes a relocatable bundle in the build +# directory. +set(BUILD_BUNDLE_DIR "${PROJECT_BINARY_DIR}/bundle") +if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) + set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) +endif() + +# Start with a clean build bundle directory every time. +install(CODE " + file(REMOVE_RECURSE \"${BUILD_BUNDLE_DIR}/\") + " COMPONENT Runtime) + +set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") +set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}/lib") + +install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +foreach(bundled_library ${PLUGIN_BUNDLED_LIBRARIES}) + install(FILES "${bundled_library}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endforeach(bundled_library) + +# Fully re-copy the assets directory on each build to avoid having stale files +# from a previous install. +set(FLUTTER_ASSET_DIR_NAME "flutter_assets") +install(CODE " + file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") + " COMPONENT Runtime) +install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" + DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) + +# Install the AOT library on non-Debug builds only. +if(NOT CMAKE_BUILD_TYPE MATCHES "Debug") + install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endif() diff --git a/packages/firebase_core/firebase_core/firebase_core/example/linux/flutter/CMakeLists.txt b/packages/firebase_core/firebase_core/firebase_core/example/linux/flutter/CMakeLists.txt new file mode 100644 index 000000000000..d5bd01648a96 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/linux/flutter/CMakeLists.txt @@ -0,0 +1,88 @@ +# This file controls Flutter-level build steps. It should not be edited. +cmake_minimum_required(VERSION 3.10) + +set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") + +# Configuration provided via flutter tool. +include(${EPHEMERAL_DIR}/generated_config.cmake) + +# TODO: Move the rest of this into files in ephemeral. See +# https://github.com/flutter/flutter/issues/57146. + +# Serves the same purpose as list(TRANSFORM ... PREPEND ...), +# which isn't available in 3.10. +function(list_prepend LIST_NAME PREFIX) + set(NEW_LIST "") + foreach(element ${${LIST_NAME}}) + list(APPEND NEW_LIST "${PREFIX}${element}") + endforeach(element) + set(${LIST_NAME} "${NEW_LIST}" PARENT_SCOPE) +endfunction() + +# === Flutter Library === +# System-level dependencies. +find_package(PkgConfig REQUIRED) +pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) +pkg_check_modules(GLIB REQUIRED IMPORTED_TARGET glib-2.0) +pkg_check_modules(GIO REQUIRED IMPORTED_TARGET gio-2.0) + +set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/libflutter_linux_gtk.so") + +# Published to parent scope for install step. +set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) +set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) +set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) +set(AOT_LIBRARY "${PROJECT_DIR}/build/lib/libapp.so" PARENT_SCOPE) + +list(APPEND FLUTTER_LIBRARY_HEADERS + "fl_basic_message_channel.h" + "fl_binary_codec.h" + "fl_binary_messenger.h" + "fl_dart_project.h" + "fl_engine.h" + "fl_json_message_codec.h" + "fl_json_method_codec.h" + "fl_message_codec.h" + "fl_method_call.h" + "fl_method_channel.h" + "fl_method_codec.h" + "fl_method_response.h" + "fl_plugin_registrar.h" + "fl_plugin_registry.h" + "fl_standard_message_codec.h" + "fl_standard_method_codec.h" + "fl_string_codec.h" + "fl_value.h" + "fl_view.h" + "flutter_linux.h" +) +list_prepend(FLUTTER_LIBRARY_HEADERS "${EPHEMERAL_DIR}/flutter_linux/") +add_library(flutter INTERFACE) +target_include_directories(flutter INTERFACE + "${EPHEMERAL_DIR}" +) +target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}") +target_link_libraries(flutter INTERFACE + PkgConfig::GTK + PkgConfig::GLIB + PkgConfig::GIO +) +add_dependencies(flutter flutter_assemble) + +# === Flutter tool backend === +# _phony_ is a non-existent file to force this command to run every time, +# since currently there's no way to get a full input/output list from the +# flutter tool. +add_custom_command( + OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} + ${CMAKE_CURRENT_BINARY_DIR}/_phony_ + COMMAND ${CMAKE_COMMAND} -E env + ${FLUTTER_TOOL_ENVIRONMENT} + "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.sh" + ${FLUTTER_TARGET_PLATFORM} ${CMAKE_BUILD_TYPE} + VERBATIM +) +add_custom_target(flutter_assemble DEPENDS + "${FLUTTER_LIBRARY}" + ${FLUTTER_LIBRARY_HEADERS} +) diff --git a/packages/firebase_core/firebase_core/firebase_core/example/linux/flutter/generated_plugin_registrant.cc b/packages/firebase_core/firebase_core/firebase_core/example/linux/flutter/generated_plugin_registrant.cc new file mode 100644 index 000000000000..15034725064f --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/linux/flutter/generated_plugin_registrant.cc @@ -0,0 +1,15 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#include "generated_plugin_registrant.h" + +#include + +void fl_register_plugins(FlPluginRegistry* registry) { + g_autoptr(FlPluginRegistrar) firebase_core_registrar = + fl_plugin_registry_get_registrar_for_plugin(registry, "FirebaseCorePlugin"); + firebase_core_plugin_register_with_registrar(firebase_core_registrar); +} diff --git a/packages/firebase_core/firebase_core/firebase_core/example/linux/flutter/generated_plugin_registrant.h b/packages/firebase_core/firebase_core/firebase_core/example/linux/flutter/generated_plugin_registrant.h new file mode 100644 index 000000000000..e0f0a47bc08f --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/linux/flutter/generated_plugin_registrant.h @@ -0,0 +1,15 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#ifndef GENERATED_PLUGIN_REGISTRANT_ +#define GENERATED_PLUGIN_REGISTRANT_ + +#include + +// Registers Flutter plugins. +void fl_register_plugins(FlPluginRegistry* registry); + +#endif // GENERATED_PLUGIN_REGISTRANT_ diff --git a/packages/firebase_core/firebase_core/firebase_core/example/linux/flutter/generated_plugins.cmake b/packages/firebase_core/firebase_core/firebase_core/example/linux/flutter/generated_plugins.cmake new file mode 100644 index 000000000000..1d55b5b0bf79 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/linux/flutter/generated_plugins.cmake @@ -0,0 +1,24 @@ +# +# Generated file, do not edit. +# + +list(APPEND FLUTTER_PLUGIN_LIST + firebase_core +) + +list(APPEND FLUTTER_FFI_PLUGIN_LIST +) + +set(PLUGIN_BUNDLED_LIBRARIES) + +foreach(plugin ${FLUTTER_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/linux plugins/${plugin}) + target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) + list(APPEND PLUGIN_BUNDLED_LIBRARIES $) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) +endforeach(plugin) + +foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/linux plugins/${ffi_plugin}) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries}) +endforeach(ffi_plugin) diff --git a/packages/firebase_core/firebase_core/firebase_core/example/linux/main.cc b/packages/firebase_core/firebase_core/firebase_core/example/linux/main.cc new file mode 100644 index 000000000000..e7c5c5437037 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/linux/main.cc @@ -0,0 +1,6 @@ +#include "my_application.h" + +int main(int argc, char** argv) { + g_autoptr(MyApplication) app = my_application_new(); + return g_application_run(G_APPLICATION(app), argc, argv); +} diff --git a/packages/firebase_core/firebase_core/firebase_core/example/linux/my_application.cc b/packages/firebase_core/firebase_core/firebase_core/example/linux/my_application.cc new file mode 100644 index 000000000000..b699538ff8ee --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/linux/my_application.cc @@ -0,0 +1,104 @@ +#include "my_application.h" + +#include +#ifdef GDK_WINDOWING_X11 +#include +#endif + +#include "flutter/generated_plugin_registrant.h" + +struct _MyApplication { + GtkApplication parent_instance; + char** dart_entrypoint_arguments; +}; + +G_DEFINE_TYPE(MyApplication, my_application, GTK_TYPE_APPLICATION) + +// Implements GApplication::activate. +static void my_application_activate(GApplication* application) { + MyApplication* self = MY_APPLICATION(application); + GtkWindow* window = + GTK_WINDOW(gtk_application_window_new(GTK_APPLICATION(application))); + + // Use a header bar when running in GNOME as this is the common style used + // by applications and is the setup most users will be using (e.g. Ubuntu + // desktop). + // If running on X and not using GNOME then just use a traditional title bar + // in case the window manager does more exotic layout, e.g. tiling. + // If running on Wayland assume the header bar will work (may need changing + // if future cases occur). + gboolean use_header_bar = TRUE; +#ifdef GDK_WINDOWING_X11 + GdkScreen* screen = gtk_window_get_screen(window); + if (GDK_IS_X11_SCREEN(screen)) { + const gchar* wm_name = gdk_x11_screen_get_window_manager_name(screen); + if (g_strcmp0(wm_name, "GNOME Shell") != 0) { + use_header_bar = FALSE; + } + } +#endif + if (use_header_bar) { + GtkHeaderBar* header_bar = GTK_HEADER_BAR(gtk_header_bar_new()); + gtk_widget_show(GTK_WIDGET(header_bar)); + gtk_header_bar_set_title(header_bar, "firebase_core_example"); + gtk_header_bar_set_show_close_button(header_bar, TRUE); + gtk_window_set_titlebar(window, GTK_WIDGET(header_bar)); + } else { + gtk_window_set_title(window, "firebase_core_example"); + } + + gtk_window_set_default_size(window, 1280, 720); + gtk_widget_show(GTK_WIDGET(window)); + + g_autoptr(FlDartProject) project = fl_dart_project_new(); + fl_dart_project_set_dart_entrypoint_arguments(project, self->dart_entrypoint_arguments); + + FlView* view = fl_view_new(project); + gtk_widget_show(GTK_WIDGET(view)); + gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(view)); + + fl_register_plugins(FL_PLUGIN_REGISTRY(view)); + + gtk_widget_grab_focus(GTK_WIDGET(view)); +} + +// Implements GApplication::local_command_line. +static gboolean my_application_local_command_line(GApplication* application, gchar*** arguments, int* exit_status) { + MyApplication* self = MY_APPLICATION(application); + // Strip out the first argument as it is the binary name. + self->dart_entrypoint_arguments = g_strdupv(*arguments + 1); + + g_autoptr(GError) error = nullptr; + if (!g_application_register(application, nullptr, &error)) { + g_warning("Failed to register: %s", error->message); + *exit_status = 1; + return TRUE; + } + + g_application_activate(application); + *exit_status = 0; + + return TRUE; +} + +// Implements GObject::dispose. +static void my_application_dispose(GObject* object) { + MyApplication* self = MY_APPLICATION(object); + g_clear_pointer(&self->dart_entrypoint_arguments, g_strfreev); + G_OBJECT_CLASS(my_application_parent_class)->dispose(object); +} + +static void my_application_class_init(MyApplicationClass* klass) { + G_APPLICATION_CLASS(klass)->activate = my_application_activate; + G_APPLICATION_CLASS(klass)->local_command_line = my_application_local_command_line; + G_OBJECT_CLASS(klass)->dispose = my_application_dispose; +} + +static void my_application_init(MyApplication* self) {} + +MyApplication* my_application_new() { + return MY_APPLICATION(g_object_new(my_application_get_type(), + "application-id", APPLICATION_ID, + "flags", G_APPLICATION_NON_UNIQUE, + nullptr)); +} diff --git a/packages/firebase_core/firebase_core/firebase_core/example/linux/my_application.h b/packages/firebase_core/firebase_core/firebase_core/example/linux/my_application.h new file mode 100644 index 000000000000..72271d5e4170 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/linux/my_application.h @@ -0,0 +1,18 @@ +#ifndef FLUTTER_MY_APPLICATION_H_ +#define FLUTTER_MY_APPLICATION_H_ + +#include + +G_DECLARE_FINAL_TYPE(MyApplication, my_application, MY, APPLICATION, + GtkApplication) + +/** + * my_application_new: + * + * Creates a new Flutter-based application. + * + * Returns: a new #MyApplication. + */ +MyApplication* my_application_new(); + +#endif // FLUTTER_MY_APPLICATION_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/example/pubspec.yaml b/packages/firebase_core/firebase_core/firebase_core/example/pubspec.yaml new file mode 100644 index 000000000000..dd3d2b2c7b7e --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/pubspec.yaml @@ -0,0 +1,83 @@ +name: firebase_core_example +description: Demonstrates how to use the firebase_core plugin. +# The following line prevents the package from being accidentally published to +# pub.dev using `flutter pub publish`. This is preferred for private packages. +publish_to: 'none' # Remove this line if you wish to publish to pub.dev + +environment: + sdk: '>=2.19.2 <3.0.0' + +# Dependencies specify other packages that your package needs in order to work. +# To automatically upgrade your package dependencies to the latest versions +# consider running `flutter pub upgrade --major-versions`. Alternatively, +# dependencies can be manually updated by changing the version numbers below to +# the latest version available on pub.dev. To see which dependencies have newer +# versions available, run `flutter pub outdated`. +dependencies: + flutter: + sdk: flutter + + firebase_core: + # When depending on this package from a real application you should use: + # firebase_core: ^x.y.z + # See https://dart.dev/tools/pub/dependencies#version-constraints + # The example app is bundled with the plugin so we use a path dependency on + # the parent directory to use the current plugin's version. + path: ../ + + # The following adds the Cupertino Icons font to your application. + # Use with the CupertinoIcons class for iOS style icons. + cupertino_icons: ^1.0.2 + +dev_dependencies: + flutter_test: + sdk: flutter + + # The "flutter_lints" package below contains a set of recommended lints to + # encourage good coding practices. The lint set provided by the package is + # activated in the `analysis_options.yaml` file located at the root of your + # package. See that file for information about deactivating specific lint + # rules and activating additional ones. + flutter_lints: ^2.0.0 + +# For information on the generic Dart part of this file, see the +# following page: https://dart.dev/tools/pub/pubspec + +# The following section is specific to Flutter packages. +flutter: + + # The following line ensures that the Material Icons font is + # included with your application, so that you can use the icons in + # the material Icons class. + uses-material-design: true + + # To add assets to your application, add an assets section, like this: + # assets: + # - images/a_dot_burr.jpeg + # - images/a_dot_ham.jpeg + + # An image asset can refer to one or more resolution-specific "variants", see + # https://flutter.dev/assets-and-images/#resolution-aware + + # For details regarding adding assets from package dependencies, see + # https://flutter.dev/assets-and-images/#from-packages + + # To add custom fonts to your application, add a fonts section here, + # in this "flutter" section. Each entry in this list should have a + # "family" key with the font family name, and a "fonts" key with a + # list giving the asset and other descriptors for the font. For + # example: + # fonts: + # - family: Schyler + # fonts: + # - asset: fonts/Schyler-Regular.ttf + # - asset: fonts/Schyler-Italic.ttf + # style: italic + # - family: Trajan Pro + # fonts: + # - asset: fonts/TrajanPro.ttf + # - asset: fonts/TrajanPro_Bold.ttf + # weight: 700 + # + # For details regarding fonts from package dependencies, + # see https://flutter.dev/custom-fonts/#from-packages diff --git a/packages/firebase_core/firebase_core/firebase_core/example/test/widget_test.dart b/packages/firebase_core/firebase_core/firebase_core/example/test/widget_test.dart new file mode 100644 index 000000000000..d343f68407e8 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/test/widget_test.dart @@ -0,0 +1,27 @@ +// This is a basic Flutter widget test. +// +// To perform an interaction with a widget in your test, use the WidgetTester +// utility in the flutter_test package. For example, you can send tap and scroll +// gestures. You can also use WidgetTester to find child widgets in the widget +// tree, read text, and verify that the values of widget properties are correct. + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'package:firebase_core_example/main.dart'; + +void main() { + testWidgets('Verify Platform version', (WidgetTester tester) async { + // Build our app and trigger a frame. + await tester.pumpWidget(const MyApp()); + + // Verify that platform version is retrieved. + expect( + find.byWidgetPredicate( + (Widget widget) => widget is Text && + widget.data!.startsWith('Running on:'), + ), + findsOneWidget, + ); + }); +} diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/admob.h b/packages/firebase_core/firebase_core/firebase_core/firebase/admob.h new file mode 100644 index 000000000000..957c86b7e168 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/admob.h @@ -0,0 +1,215 @@ +/* + * Copyright 2016 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_H_ +#define FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_H_ + +#include "firebase/internal/platform.h" + +#if FIREBASE_PLATFORM_ANDROID +#include +#endif // FIREBASE_PLATFORM_ANDROID + +#include "firebase/admob/banner_view.h" +#include "firebase/admob/interstitial_ad.h" +#include "firebase/admob/rewarded_video.h" +#include "firebase/admob/types.h" +#include "firebase/app.h" +#include "firebase/internal/common.h" + +#if !defined(DOXYGEN) && !defined(SWIG) +FIREBASE_APP_REGISTER_CALLBACKS_REFERENCE(admob) +#endif // !defined(DOXYGEN) && !defined(SWIG) + +namespace firebase { + +/// @deprecated The functionality in the firebase::admob namespace +/// has been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the new +/// SDK in our migration guide. +/// +/// @brief API for AdMob with Firebase. +/// +/// The AdMob API allows you to load and display mobile ads using the Google +/// Mobile Ads SDK. Each ad format has its own header file. +namespace admob { + +/// @deprecated +/// @brief Initializes AdMob via Firebase. +/// +/// The functionality in the firebase::admob namespace has +/// been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the +/// new SDK in our migration +/// guide. +/// +/// @param app The Firebase app for which to initialize mobile ads. +/// +/// @return kInitResultSuccess if initialization succeeded, or +/// kInitResultFailedMissingDependency on Android if Google Play services is not +/// available on the current device and the Google Mobile Ads SDK requires +/// Google Play services (for example, when using 'play-services-ads-lite'). +FIREBASE_DEPRECATED InitResult Initialize(const ::firebase::App& app); + +/// @deprecated +/// @brief Initializes AdMob via Firebase with the publisher's AdMob app ID. +/// +/// The functionality in the firebase::admob namespace has +/// been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the +/// new SDK in our migration +/// guide. +/// +/// Initializing the Google Mobile Ads SDK with the AdMob app ID at app launch +/// allows the SDK to fetch app-level settings and perform configuration tasks +/// as early as possible. This can help reduce latency for the initial ad +/// request. AdMob app IDs are unique identifiers given to mobile apps when +/// they're registered in the AdMob console. To find your app ID in the AdMob +/// console, click the App management (https://apps.admob.com/#account/appmgmt:) +/// option under the settings dropdown (located in the upper right-hand corner). +/// App IDs have the form ca-app-pub-XXXXXXXXXXXXXXXX~NNNNNNNNNN. +/// +/// @param[in] app The Firebase app for which to initialize mobile ads. +/// @param[in] admob_app_id The publisher's AdMob app ID. +/// +/// @return kInitResultSuccess if initialization succeeded, or +/// kInitResultFailedMissingDependency on Android if Google Play services is not +/// available on the current device and the Google Mobile Ads SDK requires +/// Google Play services (for example, when using 'play-services-ads-lite'). +FIREBASE_DEPRECATED InitResult Initialize(const ::firebase::App& app, + const char* admob_app_id); + +#if FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) +/// @deprecated +/// @brief Initializes AdMob without Firebase for Android. +/// +/// The functionality in the firebase::admob namespace has +/// been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the +/// new SDK in our migration +/// guide. +/// +/// The arguments to @ref Initialize are platform-specific so the caller must do +/// something like this: +/// @code +/// #if defined(__ANDROID__) +/// firebase::admob::Initialize(jni_env, activity); +/// #else +/// firebase::admob::Initialize(); +/// #endif +/// @endcode +/// +/// @param[in] jni_env JNIEnv pointer. +/// @param[in] activity Activity used to start the application. +/// +/// @return kInitResultSuccess if initialization succeeded, or +/// kInitResultFailedMissingDependency on Android if Google Play services is not +/// available on the current device and the AdMob SDK requires +/// Google Play services (for example when using 'play-services-ads-lite'). +FIREBASE_DEPRECATED InitResult Initialize(JNIEnv* jni_env, jobject activity); + +/// @deprecated +/// @brief Initializes AdMob via Firebase with the publisher's AdMob app ID. +/// +/// The functionality in the firebase::admob namespace has +/// been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the +/// new SDK in our migration +/// guide. +/// +/// Initializing the Google Mobile Ads SDK with the AdMob app ID at app launch +/// allows the SDK to fetch app-level settings and perform configuration tasks +/// as early as possible. This can help reduce latency for the initial ad +/// request. AdMob app IDs are unique identifiers given to mobile apps when +/// they're registered in the AdMob console. To find your app ID in the AdMob +/// console, click the App management (https://apps.admob.com/#account/appmgmt:) +/// option under the settings dropdown (located in the upper right-hand corner). +/// App IDs have the form ca-app-pub-XXXXXXXXXXXXXXXX~NNNNNNNNNN. +/// +/// The arguments to @ref Initialize are platform-specific so the caller must do +/// something like this: +/// @code +/// #if defined(__ANDROID__) +/// firebase::admob::Initialize(jni_env, activity, admob_app_id); +/// #else +/// firebase::admob::Initialize(admob_app_id); +/// #endif +/// @endcode +/// +/// @param[in] jni_env JNIEnv pointer. +/// @param[in] activity Activity used to start the application. +/// @param[in] admob_app_id The publisher's AdMob app ID. +/// +/// @return kInitResultSuccess if initialization succeeded, or +/// kInitResultFailedMissingDependency on Android if Google Play services is not +/// available on the current device and the AdMob SDK requires +/// Google Play services (for example when using 'play-services-ads-lite'). +FIREBASE_DEPRECATED InitResult Initialize(JNIEnv* jni_env, jobject activity, + const char* admob_app_id); +#endif // defined(__ANDROID__) || defined(DOXYGEN) +#if !FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) +/// @deprecated +/// @brief Initializes AdMob without Firebase for iOS. +/// +/// The functionality in the firebase::admob namespace has +/// been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the +/// new SDK in our migration +/// guide. +FIREBASE_DEPRECATED InitResult Initialize(); + +/// @deprecated +/// @brief Initializes AdMob with the publisher's AdMob app ID and without +/// Firebase for iOS. +/// +/// The functionality in the firebase::admob namespace has +/// been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the +/// new SDK in our migration +/// guide. +/// +/// Initializing the Google Mobile Ads SDK with the AdMob app ID at app launch +/// allows the SDK to fetch app-level settings and perform configuration tasks +/// as early as possible. This can help reduce latency for the initial ad +/// request. AdMob app IDs are unique identifiers given to mobile apps when +/// they're registered in the AdMob console. To find your app ID in the AdMob +/// console, click the App management (https://apps.admob.com/#account/appmgmt:) +/// option under the settings dropdown (located in the upper right-hand corner). +/// App IDs have the form ca-app-pub-XXXXXXXXXXXXXXXX~NNNNNNNNNN. +/// +/// @param[in] admob_app_id The publisher's AdMob app ID. +/// +/// @return kInitResultSuccess if initialization succeeded +FIREBASE_DEPRECATED InitResult Initialize(const char* admob_app_id); +#endif // !defined(__ANDROID__) || defined(DOXYGEN) + +/// @deprecated +/// @brief Terminate AdMob. +/// +/// The functionality in the firebase::admob namespace has +/// been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the +/// new SDK in our migration +/// guide. +/// +/// Frees resources associated with AdMob that were allocated during +/// @ref firebase::admob::Initialize(). +FIREBASE_DEPRECATED void Terminate(); + +} // namespace admob +} // namespace firebase + +#endif // FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/admob/banner_view.h b/packages/firebase_core/firebase_core/firebase_core/firebase/admob/banner_view.h new file mode 100644 index 000000000000..2d691f2d3a77 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/admob/banner_view.h @@ -0,0 +1,427 @@ +/* + * Copyright 2016 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_BANNER_VIEW_H_ +#define FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_BANNER_VIEW_H_ + +#include "firebase/admob/types.h" +#include "firebase/future.h" +#include "firebase/internal/common.h" + +namespace firebase { +namespace admob { + +namespace internal { +// Forward declaration for platform-specific data, implemented in each library. +class BannerViewInternal; +} // namespace internal + +/// @deprecated The functionality in the firebase::admob namespace +/// has been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the new +/// SDK in our migration guide. +/// +/// @brief Loads and displays AdMob banner ads. +/// +/// Each BannerView object corresponds to a single AdMob banner placement. There +/// are methods to load an ad, move it, show it and hide it, and retrieve the +/// bounds of the ad onscreen. +/// +/// BannerView objects maintain a presentation state that indicates whether +/// or not they're currently onscreen, as well as a set of bounds (stored in a +/// @ref BoundingBox struct), but otherwise provide information about +/// their current state through Futures. Methods like @ref Initialize, +/// @ref LoadAd, and @ref Hide each have a corresponding @ref Future from which +/// the result of the last call can be determined. The two variants of +/// @ref MoveTo share a single result @ref Future, since they're essentially the +/// same action. +/// +/// In addition, applications can create their own subclasses of +/// @ref BannerView::Listener, pass an instance to the @ref SetListener method, +/// and receive callbacks whenever the presentation state or bounding box of the +/// ad changes. +/// +/// For example, you could initialize, load, and show a banner view while +/// checking the result of the previous action at each step as follows: +/// +/// @code +/// namespace admob = ::firebase::admob; +/// admob::BannerView* banner_view = new admob::BannerView(); +/// banner_view->Initialize(ad_parent, "YOUR_AD_UNIT_ID", desired_ad_size) +/// @endcode +/// +/// Then, later: +/// +/// @code +/// if (banner_view->InitializeLastResult().status() == +/// ::firebase::kFutureStatusComplete && +/// banner_view->InitializeLastResult().error() == +/// firebase::admob::kAdMobErrorNone) { +/// banner_view->LoadAd(your_ad_request); +/// } +/// @endcode +/// +class BannerView { + public: +#ifdef INTERNAL_EXPERIMENTAL +// LINT.IfChange +#endif // INTERNAL_EXPERIMENTAL + /// @deprecated + /// @brief The presentation state of a @ref BannerView. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + enum PresentationState { + /// BannerView is currently hidden. + kPresentationStateHidden = 0, + /// BannerView is visible, but does not contain an ad. + kPresentationStateVisibleWithoutAd, + /// BannerView is visible and contains an ad. + kPresentationStateVisibleWithAd, + /// BannerView is visible and has opened a partial overlay on the screen. + kPresentationStateOpenedPartialOverlay, + /// BannerView is completely covering the screen or has caused focus to + /// leave the application (for example, when opening an external browser + /// during a clickthrough). + kPresentationStateCoveringUI, + }; +#ifdef INTERNAL_EXPERIMENTAL +// LINT.ThenChange(//depot_firebase_cpp/admob/client/cpp/src_java/com/google/firebase/admob/internal/cpp/ConstantsHelper.java) +#endif // INTERNAL_EXPERIMENTAL + +#ifdef INTERNAL_EXPERIMENTAL +// LINT.IfChange +#endif // INTERNAL_EXPERIMENTAL + /// @deprecated + /// @brief The possible screen positions for a @ref BannerView. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + enum Position { + /// Top of the screen, horizontally centered. + kPositionTop = 0, + /// Bottom of the screen, horizontally centered. + kPositionBottom, + /// Top-left corner of the screen. + kPositionTopLeft, + /// Top-right corner of the screen. + kPositionTopRight, + /// Bottom-left corner of the screen. + kPositionBottomLeft, + /// Bottom-right corner of the screen. + kPositionBottomRight, + }; +#ifdef INTERNAL_EXPERIMENTAL +// LINT.ThenChange(//depot_firebase_cpp/admob/client/cpp/src_java/com/google/firebase/admob/internal/cpp/ConstantsHelper.java) +#endif // INTERNAL_EXPERIMENTAL + + /// @deprecated + /// @brief A listener class that developers can extend and pass to a @ref + /// BannerView object's @ref SetListener method to be notified of changes to + /// the presentation state and bounding box. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + class Listener { + public: + /// @deprecated + /// @brief This method is called when the @ref BannerView object's + /// presentation state changes. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + /// @param[in] banner_view The banner view whose presentation state changed. + /// @param[in] state The new presentation state. + virtual void OnPresentationStateChanged(BannerView* banner_view, + PresentationState state) = 0; + /// @deprecated + /// @brief This method is called when the @ref BannerView object's bounding + /// box changes. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + /// @param[in] banner_view The banner view whose bounding box changed. + /// @param[in] box The new bounding box. + virtual void OnBoundingBoxChanged(BannerView* banner_view, + BoundingBox box) = 0; + virtual ~Listener(); + }; + + /// @deprecated + /// @brief Creates an uninitialized @ref BannerView object. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + /// + /// @ref Initialize must be called before the object is used. + FIREBASE_DEPRECATED BannerView(); + + ~BannerView(); + + /// @deprecated + /// @brief Initializes the @ref BannerView object. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + /// @param[in] parent The platform-specific UI element that will host the ad. + /// @param[in] ad_unit_id The ad unit ID to use when requesting ads. + /// @param[in] size The desired ad size for the banner. + FIREBASE_DEPRECATED Future Initialize(AdParent parent, + const char* ad_unit_id, + AdSize size); + + /// @deprecated + /// @brief Returns a @ref Future that has the status of the last call to + /// @ref Initialize. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + FIREBASE_DEPRECATED Future InitializeLastResult() const; + + /// @deprecated + /// @brief Begins an asynchronous request for an ad. If successful, the ad + /// will automatically be displayed in the BannerView. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + /// @param[in] request An AdRequest struct with information about the request + /// to be made (such as targeting info). + FIREBASE_DEPRECATED Future LoadAd(const AdRequest& request); + + /// @deprecated + /// @brief Returns a @ref Future containing the status of the last call to + /// @ref LoadAd. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + FIREBASE_DEPRECATED Future LoadAdLastResult() const; + + /// @deprecated + /// @brief Hides the BannerView. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + FIREBASE_DEPRECATED Future Hide(); + + /// @deprecated + /// @brief Returns a @ref Future containing the status of the last call to + /// @ref Hide. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + FIREBASE_DEPRECATED Future HideLastResult() const; + + /// @deprecated + /// @brief Shows the @ref BannerView. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + FIREBASE_DEPRECATED Future Show(); + + /// @deprecated + /// @brief Returns a @ref Future containing the status of the last call to + /// @ref Show. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + FIREBASE_DEPRECATED Future ShowLastResult() const; + + /// @deprecated + /// @brief Pauses the @ref BannerView. Should be called whenever the C++ + /// engine pauses or the application loses focus. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + FIREBASE_DEPRECATED Future Pause(); + + /// @deprecated + /// @brief Returns a @ref Future containing the status of the last call to + /// @ref Pause. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + FIREBASE_DEPRECATED Future PauseLastResult() const; + + /// @deprecated + /// @brief Resumes the @ref BannerView after pausing. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + FIREBASE_DEPRECATED Future Resume(); + + /// @deprecated + /// @brief Returns a @ref Future containing the status of the last call to + /// @ref Resume. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + FIREBASE_DEPRECATED Future ResumeLastResult() const; + + /// @deprecated + /// @brief Cleans up and deallocates any resources used by the @ref + /// BannerView. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + FIREBASE_DEPRECATED Future Destroy(); + + /// @deprecated + /// @brief Returns a @ref Future containing the status of the last call to + /// @ref Destroy. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + FIREBASE_DEPRECATED Future DestroyLastResult() const; + + /// @deprecated + /// @brief Moves the @ref BannerView so that its top-left corner is located at + /// (x, y). Coordinates are in pixels from the top-left corner of the screen. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + /// @param[in] x The desired horizontal coordinate. + /// @param[in] y The desired vertical coordinate. + FIREBASE_DEPRECATED Future MoveTo(int x, int y); + + /// @deprecated + /// @brief Moves the @ref BannerView so that it's located at the given + /// pre-defined position. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + /// @param[in] position The pre-defined position to which to move the + /// @ref BannerView. + FIREBASE_DEPRECATED Future MoveTo(Position position); + + /// @deprecated + /// @brief Returns a @ref Future containing the status of the last call to + /// either version of @ref MoveTo. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + FIREBASE_DEPRECATED Future MoveToLastResult() const; + + /// @deprecated + /// @brief Returns the current presentation state of the @ref BannerView. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + /// @return The current presentation state. + FIREBASE_DEPRECATED PresentationState presentation_state() const; + + /// @deprecated + /// @brief Retrieves the @ref BannerView's current onscreen size and location. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + FIREBASE_DEPRECATED BoundingBox bounding_box() const; + + /// @deprecated + /// @brief Sets the @ref Listener for this object. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + /// @param[in] listener A valid BannerView::Listener to receive callbacks. + FIREBASE_DEPRECATED void SetListener(Listener* listener); + + private: + // An internal, platform-specific implementation object that this class uses + // to interact with the Google Mobile Ads SDKs for iOS and Android. + internal::BannerViewInternal* internal_; +}; + +} // namespace admob +} // namespace firebase + +#endif // FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_BANNER_VIEW_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/admob/interstitial_ad.h b/packages/firebase_core/firebase_core/firebase_core/firebase/admob/interstitial_ad.h new file mode 100644 index 000000000000..b201ab7c3487 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/admob/interstitial_ad.h @@ -0,0 +1,259 @@ +/* + * Copyright 2016 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_INTERSTITIAL_AD_H_ +#define FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_INTERSTITIAL_AD_H_ + +#include "firebase/admob/types.h" +#include "firebase/future.h" +#include "firebase/internal/common.h" + +namespace firebase { +namespace admob { + +namespace internal { +// Forward declaration for platform-specific data, implemented in each library. +class InterstitialAdInternal; +} // namespace internal + +/// @deprecated The functionality in the firebase::admob namespace +/// has been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the new +/// SDK in our migration guide. +/// +/// @brief Loads and displays AdMob interstitial ads. +/// +/// @ref InterstitialAd is a single-use object that can load and show a +/// single AdMob interstitial ad. +/// +/// InterstitialAd objects maintain a presentation state that indicates whether +/// or not they're currently onscreen, but otherwise provide information about +/// their current state through Futures. @ref Initialize, @ref LoadAd, and +/// @ref Show each have a corresponding @ref Future from which you can determine +/// result of the previous call. +/// +/// In addition, applications can create their own subclasses of +/// @ref InterstitialAd::Listener, pass an instance to the @ref SetListener +/// method, and receive callbacks whenever the presentation state changes. +/// +/// Here's how one might initialize, load, and show an interstitial ad while +/// checking against the result of the previous action at each step: +/// +/// @code +/// namespace admob = ::firebase::admob; +/// admob::InterstitialAd* interstitial = new admob::InterstitialAd(); +/// interstitial->Initialize(ad_parent, "YOUR_AD_UNIT_ID") +/// @endcode +/// +/// Then, later: +/// +/// @code +/// if (interstitial->InitializeLastResult().status() == +/// ::firebase::kFutureStatusComplete && +/// interstitial->InitializeLastResult().error() == +/// firebase::admob::kAdMobErrorNone) { +/// interstitial->LoadAd(my_ad_request); +/// } +/// @endcode +/// +/// And after that: +/// +/// @code +/// if (interstitial->LoadAdLastResult().status() == +/// ::firebase::kFutureStatusComplete && +/// interstitial->LoadAdLastResult().error() == +/// firebase::admob::kAdMobErrorNone)) { +/// interstitial->Show(); +/// } +/// @endcode +/// +class InterstitialAd { + public: +#ifdef INTERNAL_EXPERIMENTAL +// LINT.IfChange +#endif // INTERNAL_EXPERIMENTAL + /// @deprecated + /// @brief The presentation states of an @ref InterstitialAd. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + enum PresentationState { + /// InterstitialAd is not currently being shown. + kPresentationStateHidden = 0, + /// InterstitialAd is being shown or has caused focus to leave the + /// application (for example, when opening an external browser during a + /// clickthrough). + kPresentationStateCoveringUI, + }; +#ifdef INTERNAL_EXPERIMENTAL +// LINT.ThenChange(//depot_firebase_cpp/admob/client/cpp/src_java/com/google/firebase/admob/internal/cpp/InterstitialAdHelper.java) +#endif // INTERNAL_EXPERIMENTAL + + /// @deprecated + /// @brief A listener class that developers can extend and pass to an + /// @ref InterstitialAd object's @ref SetListener method to be notified of + /// presentation state changes. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + /// @param[in] interstitial_ad The interstitial ad whose presentation state + /// changed. + /// @param[in] state The new presentation state. + virtual void OnPresentationStateChanged(InterstitialAd* interstitial_ad, + PresentationState state) = 0; + virtual ~Listener(); + }; + + /// @deprecated + /// @brief Creates an uninitialized @ref InterstitialAd object. + /// @ref Initialize must be called before the object is used. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + FIREBASE_DEPRECATED InterstitialAd(); + + ~InterstitialAd(); + + /// @deprecated + /// @brief Initialize the @ref InterstitialAd object. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + /// @param[in] parent The platform-specific UI element that will host the ad. + /// @param[in] ad_unit_id The ad unit ID to use in loading the ad. + FIREBASE_DEPRECATED Future Initialize(AdParent parent, + const char* ad_unit_id); + + /// @deprecated + /// @brief Returns a @ref Future containing the status of the last call to + /// @ref Initialize. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + FIREBASE_DEPRECATED Future InitializeLastResult() const; + + /// @deprecated + /// @brief Begins an asynchronous request for an ad. + /// + /// The @ref InterstitialAd::presentation_state method can be used to track + /// the progress of the request. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + /// @param[in] request An AdRequest struct with information about the request + /// to be made (such as targeting info). + FIREBASE_DEPRECATED Future LoadAd(const AdRequest& request); + + /// @deprecated + /// @brief Returns a @ref Future containing the status of the last call to + /// @ref LoadAd. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + FIREBASE_DEPRECATED Future LoadAdLastResult() const; + + /// @deprecated + /// @brief Shows the @ref InterstitialAd. This should not be called unless an + /// ad has already been loaded. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + FIREBASE_DEPRECATED Future Show(); + + /// @deprecated + /// @brief Returns a @ref Future containing the status of the last call to + /// @ref Show. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + FIREBASE_DEPRECATED Future ShowLastResult() const; + + /// @deprecated + /// @brief Returns the current presentation state of the @ref InterstitialAd. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + /// @return The current presentation state. + FIREBASE_DEPRECATED PresentationState presentation_state() const; + + /// @deprecated + /// @brief Sets the @ref Listener for this @ref InterstitialAd. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + /// @param[in] listener A valid InterstititalAd::Listener to receive + /// callbacks. + FIREBASE_DEPRECATED void SetListener(Listener* listener); + + private: + // An internal, platform-specific implementation object that this class uses + // to interact with the Google Mobile Ads SDKs for iOS and Android. + internal::InterstitialAdInternal* internal_; +}; + +} // namespace admob +} // namespace firebase + +#endif // FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_INTERSTITIAL_AD_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/admob/native_express_ad_view.h b/packages/firebase_core/firebase_core/firebase_core/firebase/admob/native_express_ad_view.h new file mode 100644 index 000000000000..7e571967825e --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/admob/native_express_ad_view.h @@ -0,0 +1,446 @@ +/* + * Copyright 2016 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_NATIVE_EXPRESS_AD_VIEW_H_ +#define FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_NATIVE_EXPRESS_AD_VIEW_H_ + +#include "firebase/admob/types.h" +#include "firebase/future.h" +#include "firebase/internal/common.h" + +namespace firebase { +namespace admob { + +namespace internal { +// Forward declaration for platform-specific data, implemented in each library. +class NativeExpressAdViewInternal; +} // namespace internal + +/// @deprecated The functionality in the firebase::admob namespace +/// has been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the new +/// SDK in our migration guide. +/// Native Express Ads has been discontinued, and are no longer served. +/// +/// @brief Loads and displays ads from AdMob Native Ads Express. +/// +/// Each NativeExpressAdView object corresponds to a single AdMob Native Express +/// ad placement. There are methods to load an ad, move it, show it and hide it, +/// and retrieve the bounds of the ad onscreen. +/// +/// NativeExpressAdView objects maintain a presentation state that indicates +/// whether or not they're currently onscreen, as well as a set of bounds +/// (stored in a @ref BoundingBox struct), but otherwise provide information +/// about their current state through Futures. Methods like @ref Initialize, +/// @ref LoadAd, and @ref Hide each have a corresponding @ref Future from which +/// the result of the last call can be determined. The two variants of +/// @ref MoveTo share a single result @ref Future, since they're essentially the +/// same action. +/// +/// In addition, applications can create their own subclasses of +/// @ref NativeExpressAdView::Listener, pass an instance to the @ref SetListener +/// method, and receive callbacks whenever the presentation state or bounding +/// box of the ad changes. +/// +/// For example, you could initialize, load, and show a native express ad view +/// while checking the result of the previous action at each step as follows: +/// +/// @code +/// namespace admob = ::firebase::admob; +/// admob::NativeExpressAdView* ad_view = new admob::NativeExpressAdView(); +/// ad_view->Initialize(ad_parent, "YOUR_AD_UNIT_ID", desired_ad_size) +/// @endcode +/// +/// Then, later: +/// +/// @code +/// if (ad_view->InitializeLastResult().Status() == +/// ::firebase::kFutureStatusComplete && +/// ad_view->InitializeLastResult().Error() == +/// firebase::admob::kAdMobErrorNone) { +/// ad_view->LoadAd(your_ad_request); +/// } +/// @endcode +class NativeExpressAdView { + public: +#ifdef INTERNAL_EXPERIMENTAL +// LINT.IfChange +#endif // INTERNAL_EXPERIMENTAL + /// @deprecated + /// @brief The presentation state of a @ref NativeExpressAdView. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + enum PresentationState { + /// NativeExpressAdView is currently hidden. + kPresentationStateHidden = 0, + /// NativeExpressAdView is visible, but does not contain an ad. + kPresentationStateVisibleWithoutAd, + /// NativeExpressAdView is visible and contains an ad. + kPresentationStateVisibleWithAd, + /// NativeExpressAdView is visible and has opened a partial overlay on the + /// screen. + kPresentationStateOpenedPartialOverlay, + /// NativeExpressAdView is completely covering the screen or has caused + /// focus to leave the application (for example, when opening an external + /// browser during a clickthrough). + kPresentationStateCoveringUI, + }; +#ifdef INTERNAL_EXPERIMENTAL +// LINT.ThenChange(//depot_firebase_cpp/admob/client/cpp/src_java/com/google/firebase/admob/internal/cpp/ConstantsHelper.java) +#endif // INTERNAL_EXPERIMENTAL + +#ifdef INTERNAL_EXPERIMENTAL +// LINT.IfChange +#endif // INTERNAL_EXPERIMENTAL + /// @deprecated + /// @brief The possible screen positions for a @ref NativeExpressAdView. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + enum Position { + /// Top of the screen, horizontally centered. + kPositionTop = 0, + /// Bottom of the screen, horizontally centered. + kPositionBottom, + /// Top-left corner of the screen. + kPositionTopLeft, + /// Top-right corner of the screen. + kPositionTopRight, + /// Bottom-left corner of the screen. + kPositionBottomLeft, + /// Bottom-right corner of the screen. + kPositionBottomRight, + }; +#ifdef INTERNAL_EXPERIMENTAL +// LINT.ThenChange(//depot_firebase_cpp/admob/client/cpp/src_java/com/google/firebase/admob/internal/cpp/ConstantsHelper.java) +#endif // INTERNAL_EXPERIMENTAL + + /// @deprecated + /// @brief A listener class that developers can extend and pass to a + /// @ref NativeExpressAdView object's @ref SetListener method to be notified + /// of changes to the presentation state and bounding box. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + class Listener { + public: + /// @deprecated + /// @brief This method is called when the @ref NativeExpressAdView object's + /// presentation state changes. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + /// @param[in] ad_view The native express ad view whose presentation state + /// changed. + /// @param[in] state The new presentation state. + FIREBASE_DEPRECATED virtual void OnPresentationStateChanged( + NativeExpressAdView* ad_view, PresentationState state) = 0; + + /// @deprecated + /// @brief This method is called when the @ref NativeExpressAdView object's + /// bounding box changes. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + /// + /// @ref Initialize must be called before the object is used. + FIREBASE_DEPRECATED NativeExpressAdView(); + + ~NativeExpressAdView(); + + /// @deprecated + /// @brief Initializes the @ref NativeExpressAdView object. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + /// @param[in] parent The platform-specific UI element that will host the ad. + /// @param[in] ad_unit_id The ad unit ID to use when requesting ads. + /// @param[in] size The desired ad size for the native express ad. + FIREBASE_DEPRECATED Future Initialize(AdParent parent, + const char* ad_unit_id, + AdSize size); + + /// @deprecated + /// @brief Returns a @ref Future that has the status of the last call to + /// @ref Initialize. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + FIREBASE_DEPRECATED Future InitializeLastResult() const; + + /// @deprecated + /// @brief Begins an asynchronous request for an ad. If successful, the ad + /// will automatically be displayed in the NativeExpressAdView. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + /// @param[in] request An AdRequest struct with information about the request + /// to be made (such as targeting info). + FIREBASE_DEPRECATED Future LoadAd(const AdRequest& request); + + /// @deprecated + /// @brief Returns a @ref Future containing the status of the last call to + /// @ref LoadAd. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + FIREBASE_DEPRECATED Future LoadAdLastResult() const; + + /// @deprecated + /// @brief Hides the NativeExpressAdView. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + FIREBASE_DEPRECATED Future Hide(); + + /// @deprecated + /// @brief Returns a @ref Future containing the status of the last call to + /// @ref Hide. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + FIREBASE_DEPRECATED Future HideLastResult() const; + + /// @deprecated + /// @brief Shows the @ref NativeExpressAdView. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + FIREBASE_DEPRECATED Future Show(); + + /// @deprecated + /// @brief Returns a @ref Future containing the status of the last call to + /// @ref Show. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + FIREBASE_DEPRECATED Future ShowLastResult() const; + + /// @deprecated + /// @brief Pauses the @ref NativeExpressAdView. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + /// + /// Should be called whenever the C++ engine pauses or the application loses + /// focus. + FIREBASE_DEPRECATED Future Pause(); + + /// @deprecated + /// @brief Returns a @ref Future containing the status of the last call to + /// @ref Pause. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + FIREBASE_DEPRECATED Future PauseLastResult() const; + + /// @deprecated + /// @brief Resumes the @ref NativeExpressAdView after pausing. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + FIREBASE_DEPRECATED Future Resume(); + + /// @deprecated + /// @brief Returns a @ref Future containing the status of the last call to + /// @ref Resume. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + FIREBASE_DEPRECATED Future ResumeLastResult() const; + + /// @deprecated + /// @brief Cleans up and deallocates any resources used by the + /// @ref NativeExpressAdView. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + FIREBASE_DEPRECATED Future Destroy(); + + /// @deprecated + /// @brief Returns a @ref Future containing the status of the last call to + /// @ref Destroy. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + FIREBASE_DEPRECATED Future DestroyLastResult() const; + + /// @deprecated + /// @brief Moves the @ref NativeExpressAdView so that its top-left corner is + /// located at (x, y). Coordinates are in pixels from the top-left corner of + /// the screen. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + /// + /// When built for Android, the library will not display an ad on top of or + /// beneath an Activity's status bar. If a call to MoveTo would result in an + /// overlap, the @ref NativeExpressAdView is placed just below the status bar, + /// so no overlap occurs. + /// @param[in] x The desired horizontal coordinate. + /// @param[in] y The desired vertical coordinate. + FIREBASE_DEPRECATED Future MoveTo(int x, int y); + + /// @deprecated + /// @brief Moves the @ref NativeExpressAdView so that it's located at the + /// given pre-defined position. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + /// @param[in] position The pre-defined position to which to move the + /// @ref NativeExpressAdView. + FIREBASE_DEPRECATED Future MoveTo(Position position); + + /// @deprecated + /// @brief Returns a @ref Future containing the status of the last call to + /// either version of @ref MoveTo. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + FIREBASE_DEPRECATED Future MoveToLastResult() const; + + /// @deprecated + /// @brief Returns the current presentation state of the + /// @ref NativeExpressAdView. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + /// @return The current presentation state. + FIREBASE_DEPRECATED PresentationState GetPresentationState() const; + + /// @deprecated + /// @brief Retrieves the @ref NativeExpressAdView's current onscreen size and + /// location. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + /// @return The current size and location. Values are in pixels, and location + /// coordinates originate from the top-left corner of the screen. + FIREBASE_DEPRECATED BoundingBox GetBoundingBox() const; + + /// @deprecated + /// @brief Sets the @ref Listener for this object. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + /// @param[in] listener A valid NativeExpressAdView::Listener to receive + /// callbacks. + FIREBASE_DEPRECATED void SetListener(Listener* listener); + + private: + // An internal, platform-specific implementation object that this class uses + // to interact with the Google Mobile Ads SDKs for iOS and Android. + internal::NativeExpressAdViewInternal* internal_; +}; + +} // namespace admob +} // namespace firebase + +#endif // FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_NATIVE_EXPRESS_AD_VIEW_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/admob/rewarded_video.h b/packages/firebase_core/firebase_core/firebase_core/firebase/admob/rewarded_video.h new file mode 100644 index 000000000000..32bea80b5550 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/admob/rewarded_video.h @@ -0,0 +1,407 @@ +/* + * Copyright 2016 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_REWARDED_VIDEO_H_ +#define FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_REWARDED_VIDEO_H_ + +#include +#include + +#include "firebase/admob/types.h" +#include "firebase/future.h" + +namespace firebase { + +// Forward declaration of Firebase's internal Mutex. +class Mutex; + +namespace admob { + +/// @deprecated The functionality in the firebase::admob namespace +/// has been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the new +/// SDK in our migration guide. +/// +/// @brief Loads and displays rewarded video ads via AdMob mediation. +/// +/// The rewarded_video namespace contains methods to load and display rewarded +/// video ads via the Google Mobile Ads SDK. The underlying SDK objects for +/// rewarded video on Android and iOS are singletons, so there are no objects +/// to represent individual ads here. Instead, methods in the rewarded_video +/// namespace are invoked to initialize, load, and show. +/// +/// The basic steps for loading and displaying an ad are: +/// +/// 1. Call @ref Initialize to init the library and mediation adapters. +/// 2. Call @ref LoadAd to load an ad (some SDKs may have cached an ad at init +/// time). +/// 3. Call @ref Show to show the ad to the user. +/// 4. Repeat steps 2 and 3 as desired. +/// 5. Call @ref Destroy when your app is completely finished showing rewarded +/// video ads. +/// +/// Note that Initialize must be the very first thing called, and @ref Destroy +/// must be the very last. +/// +/// The library maintains a presentation state that indicates whether or not an +/// ad is currently onscreen, but otherwise provides information about its +/// current state through Futures. @ref Initialize, @ref LoadAd, and so on each +/// have a corresponding @ref Future from which apps can determine the result of +/// the previous call. +/// +/// In addition, applications can create their own subclasses of @ref Listener, +/// pass an instance to the @ref SetListener method, and receive callbacks +/// whenever the presentation state changes or an ad has been viewed in full and +/// the user is due a reward. +/// +/// Here's how one might initialize, load, and show a rewarded video ad while +/// checking against the result of the previous action at each step: +/// +/// @code +/// firebase::admob::rewarded_video::Initialize(); +/// @endcode +/// +/// Then, later: +/// +/// @code +/// if (firebase::admob::rewarded_video::InitializeLastResult().status() == +/// firebase::kFutureStatusComplete && +/// firebase::admob::rewarded_video::InitializeLastResult().error() == +/// firebase::admob::kAdMobErrorNone) { +/// firebase::admob::rewarded_video::LoadAd(my_ad_unit_str, my_ad_request); +/// } +/// @endcode +/// +/// And after that: +/// +/// @code +/// if (firebase::admob::rewarded_video::LoadAdLastResult().status() == +/// firebase::kFutureStatusComplete && +/// firebase::admob::rewarded_video::LoadAdLastResult().error() == +/// firebase::admob::kAdMobErrorNone) { +/// firebase::admob::rewarded_video::Show(my_ad_parent); +/// } +/// @endcode +namespace rewarded_video { +#ifdef INTERNAL_EXPERIMENTAL +// LINT.IfChange +#endif // INTERNAL_EXPERIMENTAL +/// @deprecated +/// @brief The possible presentation states for rewarded video. +/// +/// The functionality in the firebase::admob namespace has +/// been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the +/// new SDK in our migration +/// guide. +enum PresentationState { + /// No ad is currently being shown. + kPresentationStateHidden = 0, + /// A rewarded video ad is completely covering the screen or has caused + /// focus to leave the application (for example, when opening an external + /// browser during a clickthrough), but the video associated with the ad has + /// yet to begin playing. + kPresentationStateCoveringUI, + /// All of the above conditions are true *except* that the video associated + /// with the ad began playing at some point in the past. + kPresentationStateVideoHasStarted, + /// The rewarded video has played and completed. + kPresentationStateVideoHasCompleted, +}; +#ifdef INTERNAL_EXPERIMENTAL +// LINT.ThenChange(//depot_firebase_cpp/admob/client/cpp/src_java/com/google/firebase/admob/internal/cpp/RewardedVideoHelper.java) +#endif // INTERNAL_EXPERIMENTAL + +/// @deprecated +/// @brief A reward to be given to the user in exchange for watching a rewarded +/// video ad. +/// +/// The functionality in the firebase::admob namespace has +/// been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the +/// new SDK in our migration +/// guide. +struct RewardItem { + /// The reward amount. + float amount; + /// A string description of the type of reward (such as "coins" or "points"). + std::string reward_type; +}; + +/// @deprecated +/// @brief A listener class that developers can extend and pass to @ref +/// SetListener to be notified of rewards and changes to the presentation state. +/// +/// The functionality in the firebase::admob namespace has +/// been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the +/// new SDK in our migration +/// guide. +class Listener { + public: + /// @deprecated + /// @brief Invoked when the user should be given a reward for watching an ad. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + /// @param[in] reward The user's reward. + FIREBASE_DEPRECATED virtual void OnRewarded(RewardItem reward) = 0; + + /// @deprecated + /// @brief Invoked when the presentation state of the ad changes. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + /// @param[in] state The new presentation state. + FIREBASE_DEPRECATED virtual void OnPresentationStateChanged( + PresentationState state) = 0; + + virtual ~Listener(); +}; + +/// @deprecated +/// @brief A polling-based listener that developers can instantiate and pass to +/// @ref SetListener in order to queue rewards for later retrieval. +/// +/// The functionality in the firebase::admob namespace has +/// been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the +/// new SDK in our migration +/// guide. +/// +/// The @ref PollReward method should be used to retrieve awards granted by the +/// Mobile Ads SDK and queued by this class. +/// @ref rewarded_video::presentation_state can be used to poll the current +/// presentation state, so no additional method has been added for it. +class PollableRewardListener : public Listener { + public: + /// @deprecated + /// @brief Default constructor. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + FIREBASE_DEPRECATED PollableRewardListener(); + ~PollableRewardListener(); + + /// @deprecated + /// @brief Invoked when the user should be given a reward for watching an ad. + /// + /// Deprecated. The functionality in the firebase::admob + /// namespace has been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the new + /// SDK in our migration + /// guide. + FIREBASE_DEPRECATED void OnRewarded(RewardItem reward); + + /// @deprecated + /// @brief nvoked when the presentation state of the ad changes. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + FIREBASE_DEPRECATED void OnPresentationStateChanged(PresentationState state); + + /// @deprecated + /// @brief Pop the oldest queued reward, and copy its data into the provided + /// RewardItem. + /// + /// The functionality in the firebase::admob namespace has + /// been replaced by the Google Mobile Ads SDK in the + /// firebase::gma namespace. Learn how to transition to the + /// new SDK in our migration + /// guide. + /// + /// If no reward is available, the struct is unchanged. + /// @param reward Pointer to a struct that reward data can be copied into. + /// @returns true if a reward was popped and data was copied, false otherwise. + FIREBASE_DEPRECATED bool PollReward(RewardItem* reward); + + private: + Mutex* mutex_; + + // Rewards granted by the Mobile Ads SDK. + std::queue rewards_; +}; + +/// @deprecated +/// @brief Initializes rewarded video. This must be the first method invoked in +/// this namespace. +/// +/// The functionality in the firebase::admob namespace has +/// been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the +/// new SDK in our migration +/// guide. +FIREBASE_DEPRECATED Future Initialize(); + +/// @deprecated +/// @brief Returns a @ref Future that has the status of the last call to +/// @ref Initialize. +/// +/// The functionality in the firebase::admob namespace has +/// been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the +/// new SDK in our migration +/// guide. +FIREBASE_DEPRECATED Future InitializeLastResult(); + +/// @deprecated +/// @brief Begins an asynchronous request for an ad. +/// +/// The functionality in the firebase::admob namespace has +/// been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the +/// new SDK in our migration +/// guide. +/// @param[in] ad_unit_id The ad unit ID to use in the request. +/// @param[in] request An AdRequest struct with information about the request +/// to be made (such as targeting info). +FIREBASE_DEPRECATED Future LoadAd(const char* ad_unit_id, + const AdRequest& request); + +/// @deprecated +/// @brief Returns a @ref Future containing the status of the last call to +/// @ref LoadAd. +/// +/// The functionality in the firebase::admob namespace has +/// been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the +/// new SDK in our migration +/// guide. +FIREBASE_DEPRECATED Future LoadAdLastResult(); + +/// @deprecated +/// @brief Shows an ad, assuming one has loaded. +/// +/// The functionality in the firebase::admob namespace has +/// been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the +/// new SDK in our migration +/// guide. +/// +/// @ref LoadAd must be called before this method. +/// @param[in] parent An @ref AdParent that is a reference to an iOS +/// UIView or an Android Activity. +FIREBASE_DEPRECATED Future Show(AdParent parent); + +/// @deprecated +/// @brief Returns a @ref Future containing the status of the last call to +/// @ref Show. +/// +/// Deprecated. The functionality in the firebase::admob +/// namespace has been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the new +/// SDK in our migration +/// guide. +FIREBASE_DEPRECATED Future ShowLastResult(); + +/// @deprecated +/// @brief Pauses any background processing associated with rewarded video. +/// +/// The functionality in the firebase::admob namespace has +/// been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the +/// new SDK in our migration +/// guide. +/// +/// Should be called whenever the C++ engine pauses or the application loses +/// focus. +FIREBASE_DEPRECATED Future Pause(); + +/// @deprecated +/// @brief Returns a @ref Future containing the status of the last call to +/// @ref Pause. +/// +/// The functionality in the firebase::admob namespace has +/// been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the +/// new SDK in our migration +/// guide. +FIREBASE_DEPRECATED Future PauseLastResult(); + +/// @deprecated +/// @brief Resumes the rewarded video system after pausing. +/// +/// The functionality in the firebase::admob namespace has +/// been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the +/// new SDK in our migration +/// guide. +FIREBASE_DEPRECATED Future Resume(); + +/// @deprecated +/// @brief Returns a @ref Future containing the status of the last call to +/// @ref Resume. +/// +/// The functionality in the firebase::admob namespace has +/// been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the +/// new SDK in our migration +/// guide. +FIREBASE_DEPRECATED Future ResumeLastResult(); + +/// @deprecated +/// @brief Cleans up and deallocates any resources used by rewarded video. +/// +/// The functionality in the firebase::admob namespace has +/// been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the +/// new SDK in our migration +/// guide. +/// +/// No other methods in rewarded_video should be called once this method has +/// been invoked. The system is closed for business at that point. +FIREBASE_DEPRECATED void Destroy(); + +/// @deprecated +/// @brief Returns the current presentation state, indicating if an ad is +/// visible or if a video has started playing. +/// +/// The functionality in the firebase::admob namespace has +/// been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the +/// new SDK in our migration +/// guide. +/// @return The current presentation state. +FIREBASE_DEPRECATED PresentationState presentation_state(); + +/// @deprecated +/// @brief Sets the @ref Listener that should receive callbacks. +/// +/// The functionality in the firebase::admob namespace has +/// been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the +/// new SDK in our migration +/// guide. +/// @param[in] listener A valid Listener. +FIREBASE_DEPRECATED void SetListener(Listener* listener); + +} // namespace rewarded_video +} // namespace admob +} // namespace firebase + +#endif // FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_REWARDED_VIDEO_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/admob/types.h b/packages/firebase_core/firebase_core/firebase_core/firebase/admob/types.h new file mode 100644 index 000000000000..21a8379f2d96 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/admob/types.h @@ -0,0 +1,244 @@ +/* + * Copyright 2016 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_TYPES_H_ +#define FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_TYPES_H_ + +#include "firebase/internal/platform.h" + +#if FIREBASE_PLATFORM_ANDROID +#include +#elif FIREBASE_PLATFORM_IOS || FIREBASE_PLATFORM_TVOS +extern "C" { +#include +} // extern "C" +#endif // FIREBASE_PLATFORM_ANDROID, FIREBASE_PLATFORM_IOS, + // FIREBASE_PLATFORM_TVOS + +namespace firebase { +namespace admob { + +/// @deprecated The functionality in the firebase::admob namespace +/// has been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the new +/// SDK in our migration guide. +/// +/// @brief This is a platform specific datatype that is required to create an +/// AdMob ad. +/// +/// The following defines the datatype on each platform: +///

    +///
  • Android: A `jobject` which references an Android Activity.
  • +///
  • iOS: An `id` which references an iOS UIView.
  • +///
+/// +#if FIREBASE_PLATFORM_ANDROID +/// An Android Activity from Java. +typedef jobject AdParent; +#elif FIREBASE_PLATFORM_IOS || FIREBASE_PLATFORM_TVOS +/// A pointer to an iOS UIView. +typedef id AdParent; +#else +/// A void pointer for stub classes. +typedef void *AdParent; +#endif // FIREBASE_PLATFORM_ANDROID, FIREBASE_PLATFORM_IOS, + // FIREBASE_PLATFORM_TVOS + +#ifdef INTERNAL_EXPERIMENTAL +// LINT.IfChange +#endif // INTERNAL_EXPERIMENTAL +/// @deprecated +/// @brief Error codes returned by Future::error(). +/// +/// The functionality in the firebase::admob namespace has +/// been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the +/// new SDK in our migration +/// guide. +enum AdMobError { + /// Call completed successfully. + kAdMobErrorNone, + /// The ad has not been fully initialized. + kAdMobErrorUninitialized, + /// The ad is already initialized (repeat call). + kAdMobErrorAlreadyInitialized, + /// A call has failed because an ad is currently loading. + kAdMobErrorLoadInProgress, + /// A call to load an ad has failed due to an internal SDK error. + kAdMobErrorInternalError, + /// A call to load an ad has failed due to an invalid request. + kAdMobErrorInvalidRequest, + /// A call to load an ad has failed due to a network error. + kAdMobErrorNetworkError, + /// A call to load an ad has failed because no ad was available to serve. + kAdMobErrorNoFill, + /// An attempt has been made to show an ad on an Android Activity that has + /// no window token (such as one that's not done initializing). + kAdMobErrorNoWindowToken, + /// Fallback error for any unidentified cases. + kAdMobErrorUnknown, +}; +#ifdef INTERNAL_EXPERIMENTAL +// LINT.ThenChange(//depot_firebase_cpp/admob/client/cpp/src_java/com/google/firebase/admob/internal/cpp/ConstantsHelper.java) +#endif // INTERNAL_EXPERIMENTAL + +/// @deprecated +/// @brief Types of ad sizes. +/// +/// The functionality in the firebase::admob namespace has +/// been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the +/// new SDK in our migration +/// guide. +enum AdSizeType { kAdSizeStandard = 0 }; + +/// @deprecated +/// @brief An ad size value to be used in requesting ads. +/// +/// The functionality in the firebase::admob namespace has +/// been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the +/// new SDK in our migration +/// guide. +struct AdSize { + /// The type of ad size. + AdSizeType ad_size_type; + /// Height of the ad (in points or dp). + int height; + /// Width of the ad (in points or dp). + int width; +}; + +/// @deprecated +/// @brief Gender information used as part of the +/// @ref firebase::admob::AdRequest struct. +/// +/// The functionality in the firebase::admob namespace has +/// been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the +/// new SDK in our migration +/// guide. +enum Gender { + /// The gender of the current user is unknown or unspecified by the + /// publisher. + kGenderUnknown = 0, + /// The current user is known to be male. + kGenderMale, + /// The current user is known to be female. + kGenderFemale +}; + +/// @deprecated +/// @brief Indicates whether an ad request is considered tagged for +/// child-directed treatment. +/// +/// The functionality in the firebase::admob namespace has +/// been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the +/// new SDK in our migration +/// guide. +enum ChildDirectedTreatmentState { + /// The child-directed status for the request is not indicated. + kChildDirectedTreatmentStateUnknown = 0, + /// The request is tagged for child-directed treatment. + kChildDirectedTreatmentStateTagged, + /// The request is not tagged for child-directed treatment. + kChildDirectedTreatmentStateNotTagged +}; + +/// @deprecated +/// @brief Generic Key-Value container used for the "extras" values in an +/// @ref firebase::admob::AdRequest. +/// +/// The functionality in the firebase::admob namespace has +/// been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the +/// new SDK in our migration +/// guide. +struct KeyValuePair { + /// The name for an "extra." + const char *key; + /// The value for an "extra." + const char *value; +}; + +/// @deprecated +/// @brief The information needed to request an ad. +/// +/// The functionality in the firebase::admob namespace has +/// been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the +/// new SDK in our migration +/// guide. +struct AdRequest { + /// An array of test device IDs specifying devices that test ads will be + /// returned for. + const char **test_device_ids; + /// The number of entries in the array referenced by test_device_ids. + unsigned int test_device_id_count; + /// An array of keywords or phrases describing the current user activity, such + /// as "Sports Scores" or "Football." + const char **keywords; + /// The number of entries in the array referenced by keywords. + unsigned int keyword_count; + /// A @ref KeyValuePair specifying additional parameters accepted by an ad + /// network. + const KeyValuePair *extras; + /// The number of entries in the array referenced by extras. + unsigned int extras_count; + /// The day the user was born. Specify the user's birthday to increase ad + /// relevancy. + int birthday_day; + /// The month the user was born. Specify the user's birthday to increase ad + /// relevancy. + int birthday_month; + /// The year the user was born. Specify the user's birthday to increase ad + /// relevancy. + int birthday_year; + /// The user's @ref Gender. Specify the user's gender to increase ad + /// relevancy. + Gender gender; + /// Specifies whether the request should be considered as child-directed for + /// purposes of the Children’s Online Privacy Protection Act (COPPA). + ChildDirectedTreatmentState tagged_for_child_directed_treatment; +}; + +/// @deprecated +/// @brief The screen location and dimensions of an ad view once it has been +/// initialized. +/// +/// The functionality in the firebase::admob namespace has +/// been replaced by the Google Mobile Ads SDK in the +/// firebase::gma namespace. Learn how to transition to the +/// new SDK in our migration +/// guide. +struct BoundingBox { + /// Default constructor which initializes all member variables to 0. + BoundingBox() : height(0), width(0), x(0), y(0) {} + /// Height of the ad in pixels. + int height; + /// Width of the ad in pixels. + int width; + /// Horizontal position of the ad in pixels from the left. + int x; + /// Vertical position of the ad in pixels from the top. + int y; +}; + +} // namespace admob +} // namespace firebase + +#endif // FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_TYPES_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/analytics.h b/packages/firebase_core/firebase_core/firebase_core/firebase/analytics.h new file mode 100644 index 000000000000..973890b20fce --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/analytics.h @@ -0,0 +1,569 @@ +/* + * Copyright 2016 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_ANALYTICS_SRC_INCLUDE_FIREBASE_ANALYTICS_H_ +#define FIREBASE_ANALYTICS_SRC_INCLUDE_FIREBASE_ANALYTICS_H_ + +#include +#include +#include +#include + +#include "firebase/app.h" +#include "firebase/future.h" +#include "firebase/internal/common.h" +#include "firebase/variant.h" + +#if !defined(DOXYGEN) && !defined(SWIG) +FIREBASE_APP_REGISTER_CALLBACKS_REFERENCE(analytics) +#endif // !defined(DOXYGEN) && !defined(SWIG) + +/// @brief Namespace that encompasses all Firebase APIs. +namespace firebase { + +/// @brief Firebase Analytics API. +/// +/// See the developer guides for general +/// information on using Firebase Analytics in your apps. +namespace analytics { + +/// @brief Event parameter. +/// +/// Parameters supply information that contextualize events (see @ref LogEvent). +/// You can associate up to 25 unique Parameters with each event type (name). +/// +/// +/// @if swig_examples +/// Common event types are provided as static properties of the +/// FirebaseAnalytics class (e.g FirebaseAnalytics.EventPostScore) where +/// parameters of these events are also provided in this FirebaseAnalytics +/// class (e.g FirebaseAnalytics.ParameterScore). +/// +/// You are not limited to the set of event types and parameter names +/// suggested in FirebaseAnalytics class properties. Additional Parameters can +/// be supplied for suggested event types or custom Parameters for custom event +/// types. +/// @endif +/// +/// @if cpp_examples +/// Common event types (names) are suggested in @ref event_names +/// (%event_names.h) with parameters of common event types defined in +/// @ref parameter_names (%parameter_names.h). +/// +/// You are not limited to the set of event types and parameter names suggested +/// in @ref event_names (%event_names.h) and %parameter_names.h respectively. +/// Additional Parameters can be supplied for suggested event types or custom +/// Parameters for custom event types. +/// @endif +/// +/// Parameter names must be a combination of letters and digits +/// (matching the regular expression [a-zA-Z0-9]) between 1 and 40 characters +/// long starting with a letter [a-zA-Z] character. The "firebase_", +/// "google_" and "ga_" prefixes are reserved and should not be used. +/// +/// Parameter string values can be up to 100 characters long. +/// +/// +/// @if swig_examples +/// An array of Parameter class instances can be passed to LogEvent in order +/// to associate parameters's of an event with values where each value can be +/// a double, 64-bit integer or string. +/// @endif +/// +/// @if cpp_examples +/// An array of this structure is passed to LogEvent in order to associate +/// parameter's of an event (Parameter::name) with values (Parameter::value) +/// where each value can be a double, 64-bit integer or string. +/// @endif +/// +/// For example, a game may log an achievement event along with the +/// character the player is using and the level they're currently on: +/// +/// +/// @if swig_examples +/// @code{.cs} +/// using Firebase.Analytics; +/// +/// int currentLevel = GetCurrentLevel(); +/// Parameter[] AchievementParameters = { +/// new Parameter(FirebaseAnalytics.ParameterAchievementID, +/// "ultimate_wizard"), +/// new Parameter(FirebaseAnalytics.ParameterCharacter, "mysterion"), +/// new Parameter(FirebaseAnalytics.ParameterLevel, currentLevel), +/// }; +/// FirebaseAnalytics.LogEvent(FirebaseAnalytics.EventLevelUp, +/// AchievementParameters); +/// @endcode +/// @endif +/// +/// @if cpp_examples +/// @code{.cpp} +/// using namespace firebase::analytics; +/// int64_t current_level = GetCurrentLevel(); +/// const Parameter achievement_parameters[] = { +/// Parameter(kParameterAchievementID, "ultimate_wizard"), +/// Parameter(kParameterCharacter, "mysterion"), +/// Parameter(kParameterLevel, current_level), +/// }; +/// LogEvent(kEventUnlockAchievement, achievement_parameters, +/// sizeof(achievement_parameters) / +/// sizeof(achievement_parameters[0])); +/// @endcode +/// @endif +/// +struct Parameter { +#ifndef SWIG + /// Construct an empty parameter. + /// + /// This is provided to allow initialization after construction. + Parameter() : name(nullptr) {} +#endif // !SWIG + +// +// We don't want to pull in Variant in the C# interface. +// +#ifndef SWIG + /// Construct a parameter. + /// + /// @param parameter_name Name of the parameter (see Parameter::name). + /// @param parameter_value Value for the parameter. Variants can + /// hold numbers and strings. + Parameter(const char* parameter_name, Variant parameter_value) + : name(parameter_name) { + value = parameter_value; + } +#endif // !SWIG + + /// Construct a 64-bit integer parameter. + /// + /// @param parameter_name Name of the parameter. + /// @if cpp_examples + /// (see Parameter::name). + /// @endif + /// + /// @if swig_examples + /// Parameter names must be a combination of letters and digits + /// (matching the regular expression [a-zA-Z0-9]) between 1 and 40 characters + /// long starting with a letter [a-zA-Z] character. + /// @endif + /// + /// @param parameter_value Integer value for the parameter. + Parameter(const char* parameter_name, int parameter_value) + : name(parameter_name) { + value = parameter_value; + } + + /// Construct a 64-bit integer parameter. + /// + /// @param parameter_name Name of the parameter. + /// @if cpp_examples + /// (see Parameter::name). + /// @endif + /// + /// @if swig_examples + /// Parameter names must be a combination of letters and digits + /// (matching the regular expression [a-zA-Z0-9]) between 1 and 40 characters + /// long starting with a letter [a-zA-Z] character. + /// @endif + /// + /// @param parameter_value Integer value for the parameter. + Parameter(const char* parameter_name, int64_t parameter_value) + : name(parameter_name) { + value = parameter_value; + } + + /// Construct a floating point parameter. + /// + /// @param parameter_name Name of the parameter. + /// @if cpp_examples + /// (see Parameter::name). + /// @endif + /// + /// @if swig_examples + /// Parameter names must be a combination of letters and digits + /// (matching the regular expression [a-zA-Z0-9]) between 1 and 40 characters + /// long starting with a letter [a-zA-Z] character. + /// @endif + /// + /// @param parameter_value Floating point value for the parameter. + Parameter(const char* parameter_name, double parameter_value) + : name(parameter_name) { + value = parameter_value; + } + + /// Construct a string parameter. + /// + /// @param parameter_name Name of the parameter. + /// @if cpp_examples + /// (see Parameter::name). + /// @endif + /// + /// @if swig_examples + /// Parameter names must be a combination of letters and digits + /// (matching the regular expression [a-zA-Z0-9]) between 1 and 40 characters + /// long starting with a letter [a-zA-Z] character. + /// @endif + /// + /// @param parameter_value String value for the parameter, can be up to 100 + /// characters long. + Parameter(const char* parameter_name, const char* parameter_value) + : name(parameter_name) { + value = parameter_value; + } + +#ifndef SWIG + // + // Skipping implementation values because the C# API members are + // immutable, and there's no other need to read these values in + // C#. The class just needs to be passed to the C++ layers. + // This also avoids having to solve the nested union, which is + // unsupported in swig. + // + + /// @brief Name of the parameter. + /// + /// Parameter names must be a combination of letters and digits + /// (matching the regular expression [a-zA-Z0-9]) between 1 and 40 characters + /// long starting with a letter [a-zA-Z] character. The "firebase_", + /// "google_" and "ga_" prefixes are reserved and should not be used. + const char* name; + /// @brief Value of the parameter. + /// + /// See firebase::Variant for usage information. + /// @note String values can be up to 100 characters long. + Variant value; +#endif // SWIG +}; + +/// @brief Initialize the Analytics API. +/// +/// This must be called prior to calling any other methods in the +/// firebase::analytics namespace. +/// +/// @param[in] app Default @ref firebase::App instance. +/// +/// @see firebase::App::GetInstance(). +void Initialize(const App& app); + +/// @brief Terminate the Analytics API. +/// +/// Cleans up resources associated with the API. +void Terminate(); + +/// @brief Sets whether analytics collection is enabled for this app on this +/// device. +/// +/// This setting is persisted across app sessions. By default it is enabled. +/// +/// @param[in] enabled true to enable analytics collection, false to disable. +void SetAnalyticsCollectionEnabled(bool enabled); + +/// @brief The type of consent to set. +/// +/// Supported consent types are kConsentTypeAdStorage and +/// kConsentTypeAnalyticsStorage. Omitting a type retains its previous status. +enum ConsentType { kConsentTypeAdStorage = 0, kConsentTypeAnalyticsStorage }; + +/// @brief The status value of the consent type. +/// +/// Supported statuses are kConsentStatusGranted and kConsentStatusDenied. +enum ConsentStatus { kConsentStatusGranted = 0, kConsentStatusDenied }; + +/// @brief Sets the applicable end user consent state (e.g., for device +/// identifiers) for this app on this device. +/// +/// Use the consent map to specify individual consent type values. Settings are +/// persisted across app sessions. By default consent types are set to +/// "granted". +void SetConsent(const std::map& consent_settings); + +/// @brief Log an event with one string parameter. +/// +/// @param[in] name Name of the event to log. Should contain 1 to 40 +/// alphanumeric characters or underscores. The name must start with an +/// alphabetic character. Some event names are reserved. +/// +/// @if swig_examples +/// See the FirebaseAnalytics.Event properties for the list of reserved event +/// names. +/// @endif +/// +/// @if cpp_examples +/// See @ref event_names (%event_names.h) for the list of reserved event names. +/// @endif +/// The "firebase_" prefix is reserved and should not be used. Note that event +/// names are case-sensitive and that logging two events whose names differ +/// only in case will result in two distinct events. +/// @param[in] parameter_name Name of the parameter to log. +/// For more information, see @ref Parameter. +/// @param[in] parameter_value Value of the parameter to log. +/// +/// +/// @if swig_examples +/// @see LogEvent(string, Parameter[]) +/// @endif +/// +/// @if cpp_examples +/// @see LogEvent(const char*, const Parameter*, size_t) +/// @endif +void LogEvent(const char* name, const char* parameter_name, + const char* parameter_value); + +/// @brief Log an event with one float parameter. +/// +/// @param[in] name Name of the event to log. Should contain 1 to 40 +/// alphanumeric characters or underscores. The name must start with an +/// alphabetic character. Some event names are reserved. +/// +/// @if swig_examples +/// See the FirebaseAnalytics.Event properties for the list of reserved event +/// names. +/// @endif +/// +/// @if cpp_examples +/// See @ref event_names (%event_names.h) for the list of reserved event names. +/// @endif +/// The "firebase_" prefix is reserved and should not be used. Note that event +/// names are case-sensitive and that logging two events whose names differ +/// only in case will result in two distinct events. +/// @param[in] parameter_name Name of the parameter to log. +/// For more information, see @ref Parameter. +/// @param[in] parameter_value Value of the parameter to log. +/// +/// +/// @if swig_examples +/// @see LogEvent(string, Parameter[]) +/// @endif +/// +/// @if cpp_examples +/// @see LogEvent(const char*, const Parameter*, size_t) +/// @endif +void LogEvent(const char* name, const char* parameter_name, + const double parameter_value); + +/// @brief Log an event with one 64-bit integer parameter. +/// +/// @param[in] name Name of the event to log. Should contain 1 to 40 +/// alphanumeric characters or underscores. The name must start with an +/// alphabetic character. Some event names are reserved. +/// +/// @if swig_examples +/// See the FirebaseAnalytics.Event properties for the list of reserved event +/// names. +/// @endif +/// +/// @if cpp_examples +/// See @ref event_names (%event_names.h) for the list of reserved event names. +/// @endif +/// The "firebase_" prefix is reserved and should not be used. Note that event +/// names are case-sensitive and that logging two events whose names differ +/// only in case will result in two distinct events. +/// @param[in] parameter_name Name of the parameter to log. +/// For more information, see @ref Parameter. +/// @param[in] parameter_value Value of the parameter to log. +/// +/// +/// @if swig_examples +/// @see LogEvent(string, Parameter[]) +/// @endif +/// +/// @if cpp_examples +/// @see LogEvent(const char*, const Parameter*, size_t) +/// @endif +void LogEvent(const char* name, const char* parameter_name, + const int64_t parameter_value); + +/// @brief Log an event with one integer parameter +/// (stored as a 64-bit integer). +/// +/// @param[in] name Name of the event to log. Should contain 1 to 40 +/// alphanumeric characters or underscores. The name must start with an +/// alphabetic character. Some event names are reserved. +/// +/// @if swig_examples +/// See the FirebaseAnalytics.Event properties for the list of reserved event +/// names. +/// @endif +/// +/// @if cpp_examples +/// See @ref event_names (%event_names.h) for the list of reserved event names. +/// @endif +/// The "firebase_" prefix is reserved and should not be used. Note that event +/// names are case-sensitive and that logging two events whose names differ +/// only in case will result in two distinct events. +/// @param[in] parameter_name Name of the parameter to log. +/// For more information, see @ref Parameter. +/// @param[in] parameter_value Value of the parameter to log. +/// +/// +/// @if swig_examples +/// @see LogEvent(string, Parameter[]) +/// @endif +/// +/// @if cpp_examples +/// @see LogEvent(const char*, const Parameter*, size_t) +/// @endif +void LogEvent(const char* name, const char* parameter_name, + const int parameter_value); + +/// @brief Log an event with no parameters. +/// +/// @param[in] name Name of the event to log. Should contain 1 to 40 +/// alphanumeric characters or underscores. The name must start with an +/// alphabetic character. Some event names are reserved. +/// +/// @if swig_examples +/// See the FirebaseAnalytics.Event properties for the list of reserved event +/// names. +/// @endif +/// +/// @if cpp_examples +/// See @ref event_names (%event_names.h) for the list of reserved event names. +/// @endif +/// The "firebase_" prefix is reserved and should not be used. Note that event +/// names are case-sensitive and that logging two events whose names differ +/// only in case will result in two distinct events. +/// +/// +/// @if swig_examples +/// @see LogEvent(string, Parameter[]) +/// @endif +/// +/// @if cpp_examples +/// @see LogEvent(const char*, const Parameter*, size_t) +/// @endif +void LogEvent(const char* name); + +// clang-format off +#ifdef SWIG +// Modify the following overload with unsafe, so that we can do some pinning +// in the C# code. +%csmethodmodifiers LogEvent "public unsafe" +#endif // SWIG +// clang-format on + +/// @brief Log an event with associated parameters. +/// +/// An Event is an important occurrence in your app that you want to +/// measure. You can report up to 500 different types of events per app and +/// you can associate up to 25 unique parameters with each Event type. +/// +/// Some common events are documented in @ref event_names (%event_names.h), +/// but you may also choose to specify custom event types that are associated +/// with your specific app. +/// +/// @param[in] name Name of the event to log. Should contain 1 to 40 +/// alphanumeric characters or underscores. The name must start with an +/// alphabetic character. Some event names are reserved. See @ref event_names +/// (%event_names.h) for the list of reserved event names. The "firebase_" +/// prefix is reserved and should not be used. Note that event names are +/// case-sensitive and that logging two events whose names differ only in +/// case will result in two distinct events. +/// @param[in] parameters Array of Parameter structures. +/// @param[in] number_of_parameters Number of elements in the parameters +/// array. +void LogEvent(const char* name, const Parameter* parameters, + size_t number_of_parameters); + +/// Initiates on-device conversion measurement given a user email address on iOS +/// and tvOS (no-op on Android). On iOS and tvOS, this method requires the +/// dependency GoogleAppMeasurementOnDeviceConversion to be linked in, +/// otherwise the invocation results in a no-op. +/// @param[in] email_address User email address. Include a domain name for all +/// email addresses (e.g. gmail.com or hotmail.co.jp). +void InitiateOnDeviceConversionMeasurementWithEmailAddress( + const char* email_address); + +/// @brief Set a user property to the given value. +/// +/// Properties associated with a user allow a developer to segment users +/// into groups that are useful to their application. Up to 25 properties +/// can be associated with a user. +/// +/// Suggested property names are listed @ref user_property_names +/// (%user_property_names.h) but you're not limited to this set. For example, +/// the "gamertype" property could be used to store the type of player where +/// a range of values could be "casual", "mid_core", or "core". +/// +/// @param[in] name Name of the user property to set. This must be a +/// combination of letters and digits (matching the regular expression +/// [a-zA-Z0-9] between 1 and 40 characters long starting with a letter +/// [a-zA-Z] character. +/// @param[in] property Value to set the user property to. Set this +/// argument to NULL or nullptr to remove the user property. The value can be +/// between 1 to 100 characters long. +void SetUserProperty(const char* name, const char* property); + +/// @brief Sets the user ID property. +/// +/// This feature must be used in accordance with +/// Google's Privacy +/// Policy +/// +/// @param[in] user_id The user ID associated with the user of this app on this +/// device. The user ID must be non-empty and no more than 256 characters long. +/// Setting user_id to NULL or nullptr removes the user ID. +void SetUserId(const char* user_id); + +/// @brief Sets the duration of inactivity that terminates the current session. +/// +/// @note The default value is 1800000 (30 minutes). +/// +/// @param milliseconds The duration of inactivity that terminates the current +/// session. +void SetSessionTimeoutDuration(int64_t milliseconds); + +/// Clears all analytics data for this app from the device and resets the app +/// instance id. +void ResetAnalyticsData(); + +/// Get the instance ID from the analytics service. +/// +/// @note This is *not* the same ID as the ID returned by +/// @if cpp_examples +/// firebase::instance_id::InstanceId. +/// @else +/// Firebase.InstanceId.FirebaseInstanceId. +/// @endif +/// +/// @returns Object which can be used to retrieve the analytics instance ID. +Future GetAnalyticsInstanceId(); + +/// Get the result of the most recent GetAnalyticsInstanceId() call. +/// +/// @returns Object which can be used to retrieve the analytics instance ID. +Future GetAnalyticsInstanceIdLastResult(); + +/// Asynchronously retrieves the identifier of the current app +/// session. +/// +/// The session ID retrieval could fail due to Analytics collection +/// disabled, or if the app session was expired. +/// +/// @returns Object which can be used to retrieve the identifier of the current +/// app session. +Future GetSessionId(); + +/// Get the result of the most recent GetSessionId() call. +/// +/// @returns Object which can be used to retrieve the identifier of the current +/// app session. +Future GetSessionIdLastResult(); + +} // namespace analytics +} // namespace firebase + +#endif // FIREBASE_ANALYTICS_SRC_INCLUDE_FIREBASE_ANALYTICS_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/analytics/event_names.h b/packages/firebase_core/firebase_core/firebase_core/firebase/analytics/event_names.h new file mode 100644 index 000000000000..4f1d4e5a0e2b --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/analytics/event_names.h @@ -0,0 +1,472 @@ +// Copyright 2023 Google Inc. All Rights Reserved. + +#ifndef FIREBASE_ANALYTICS_CLIENT_CPP_INCLUDE_FIREBASE_ANALYTICS_EVENT_NAMES_H_ +#define FIREBASE_ANALYTICS_CLIENT_CPP_INCLUDE_FIREBASE_ANALYTICS_EVENT_NAMES_H_ + +/// @brief Namespace that encompasses all Firebase APIs. +namespace firebase { +/// @brief Firebase Analytics API. +namespace analytics { + + + +/// @defgroup event_names Analytics Events +/// +/// Predefined event names. +/// +/// An Event is an important occurrence in your app that you want to +/// measure. You can report up to 500 different types of Events per app +/// and you can associate up to 25 unique parameters with each Event type. +/// Some common events are suggested below, but you may also choose to +/// specify custom Event types that are associated with your specific app. +/// Each event type is identified by a unique name. Event names can be up +/// to 40 characters long, may only contain alphanumeric characters and +/// underscores ("_"), and must start with an alphabetic character. The +/// "firebase_", "google_", and "ga_" prefixes are reserved and should not +/// be used. +/// @{ + + +/// Ad Impression event. This event signifies when a user sees an ad +/// impression. Note: If you supply the @c AnalyticsParameterValue +/// parameter, you must also supply the @c AnalyticsParameterCurrency +/// parameter so that revenue metrics can be computed accurately. Params: +/// +///
    +///
  • @c AnalyticsParameterAdPlatform (String) (optional)
  • +///
  • @c AnalyticsParameterAdFormat (String) (optional)
  • +///
  • @c AnalyticsParameterAdSource (String) (optional)
  • +///
  • @c AnalyticsParameterAdUnitName (String) (optional)
  • +///
  • @c AnalyticsParameterCurrency (String) (optional)
  • +///
  • @c AnalyticsParameterValue (Double) (optional)
  • +///
+static const char*const kEventAdImpression = + "ad_impression"; + +/// Add Payment Info event. This event signifies that a user has submitted +/// their payment information. Note: If you supply the @c +/// AnalyticsParameterValue parameter, you must also supply the @c +/// AnalyticsParameterCurrency parameter so that revenue metrics can be +/// computed accurately. Params: +/// +///
    +///
  • @c AnalyticsParameterCoupon (String) (optional)
  • +///
  • @c AnalyticsParameterCurrency (String) (optional)
  • +///
  • @c AnalyticsParameterItems ([[String: Any]]) (optional)
  • +///
  • @c AnalyticsParameterPaymentType (String) (optional)
  • +///
  • @c AnalyticsParameterValue (Double) (optional)
  • +///
+static const char*const kEventAddPaymentInfo = + "add_payment_info"; + +/// Add Shipping Info event. This event signifies that a user has +/// submitted their shipping information. Note: If you supply the @c +/// AnalyticsParameterValue parameter, you must also supply the @c +/// AnalyticsParameterCurrency parameter so that revenue metrics can be +/// computed accurately. Params: +/// +///
    +///
  • @c AnalyticsParameterCoupon (String) (optional)
  • +///
  • @c AnalyticsParameterCurrency (String) (optional)
  • +///
  • @c AnalyticsParameterItems ([[String: Any]]) (optional)
  • +///
  • @c AnalyticsParameterShippingTier (String) (optional)
  • +///
  • @c AnalyticsParameterValue (Double) (optional)
  • +///
+static const char*const kEventAddShippingInfo = + "add_shipping_info"; + +/// E-Commerce Add To Cart event. This event signifies that an item(s) was +/// added to a cart for purchase. Add this event to a funnel with @c +/// AnalyticsEventPurchase to gauge the effectiveness of your +/// checParameter(kout, If you supply the @c AnalyticsParameterValue +/// parameter), you must also supply the @c AnalyticsParameterCurrency +/// parameter so that revenue metrics can be computed accurately. Params: +/// +///
    +///
  • @c AnalyticsParameterCurrency (String) (optional)
  • +///
  • @c AnalyticsParameterItems ([[String: Any]]) (optional)
  • +///
  • @c AnalyticsParameterValue (Double) (optional)
  • +///
+static const char*const kEventAddToCart = "add_to_cart"; + +/// E-Commerce Add To Wishlist event. This event signifies that an item +/// was added to a wishlist. Use this event to identify popular gift +/// items. Note: If you supply the @c AnalyticsParameterValue parameter, +/// you must also supply the @c AnalyticsParameterCurrency parameter so +/// that revenue metrics can be computed accurately. Params: +/// +///
    +///
  • @c AnalyticsParameterCurrency (String) (optional)
  • +///
  • @c AnalyticsParameterItems ([[String: Any]]) (optional)
  • +///
  • @c AnalyticsParameterValue (Double) (optional)
  • +///
+static const char*const kEventAddToWishlist = + "add_to_wishlist"; + +/// App Open event. By logging this event when an App becomes active, +/// developers can understand how often users leave and return during the +/// course of a Session. Although Sessions are automatically reported, +/// this event can provide further clarification around the continuous +/// engagement of app-users. +static const char*const kEventAppOpen = "app_open"; + +/// E-Commerce Begin Checkout event. This event signifies that a user has +/// begun the process of checking out. Add this event to a funnel with +/// your @c AnalyticsEventPurchase event to gauge the effectiveness of +/// your checkout process. Note: If you supply the @c +/// AnalyticsParameterValue parameter, you must also supply the @c +/// AnalyticsParameterCurrency parameter so that revenue metrics can be +/// computed accurately. Params: +/// +///
    +///
  • @c AnalyticsParameterCoupon (String) (optional)
  • +///
  • @c AnalyticsParameterCurrency (String) (optional)
  • +///
  • @c AnalyticsParameterItems ([[String: Any]]) (optional)
  • +///
  • @c AnalyticsParameterValue (Double) (optional)
  • +///
+static const char*const kEventBeginCheckout = + "begin_checkout"; + +/// Campaign Detail event. Log this event to supply the referral details +/// of a re-engagement campaign. Note: you must supply at least one of the +/// required parameters AnalyticsParameterSource, AnalyticsParameterMedium +/// or AnalyticsParameterCampaign. Params: +/// +///
    +///
  • @c AnalyticsParameterSource (String)
  • +///
  • @c AnalyticsParameterMedium (String)
  • +///
  • @c AnalyticsParameterCampaign (String)
  • +///
  • @c AnalyticsParameterTerm (String) (optional)
  • +///
  • @c AnalyticsParameterContent (String) (optional)
  • +///
  • @c AnalyticsParameterAdNetworkClickID (String) (optional)
  • +///
  • @c AnalyticsParameterCP1 (String) (optional)
  • +///
  • @c AnalyticsParameterCampaignID (String) (optional)
  • +///
  • @c AnalyticsParameterCreativeFormat (String) (optional)
  • +///
  • @c AnalyticsParameterMarketingTactic (String) (optional)
  • +///
  • @c AnalyticsParameterSourcePlatform (String) (optional)
  • +///
+static const char*const kEventCampaignDetails = + "campaign_details"; + +/// Earn Virtual Currency event. This event tracks the awarding of virtual +/// currency in your app. Log this along with @c +/// AnalyticsEventSpendVirtualCurrency to better understand your virtual +/// economy. Params: +/// +///
    +///
  • @c AnalyticsParameterVirtualCurrencyName (String)
  • +///
  • @c AnalyticsParameterValue (Int or Double)
  • +///
+static const char*const kEventEarnVirtualCurrency + = "earn_virtual_currency"; + +/// Generate Lead event. Log this event when a lead has been generated in +/// the app to understand the efficacy of your install and re-engagement +/// campaigns. Note: If you supply the @c AnalyticsParameterValue +/// parameter, you must also supply the @c AnalyticsParameterCurrency +/// parameter so that revenue metrics can be computed accurately. Params: +/// +///
    +///
  • @c AnalyticsParameterCurrency (String) (optional)
  • +///
  • @c AnalyticsParameterValue (Double) (optional)
  • +///
+static const char*const kEventGenerateLead = + "generate_lead"; + +/// Join Group event. Log this event when a user joins a group such as a +/// guild, team or family. Use this event to analyze how popular certain +/// groups or social features are in your app. Params: +/// +///
    +///
  • @c AnalyticsParameterGroupID (String)
  • +///
+static const char*const kEventJoinGroup = "join_group"; + +/// Level End event. Log this event when the user finishes a level. +/// Params: +/// +///
    +///
  • @c AnalyticsParameterLevelName (String)
  • +///
  • @c AnalyticsParameterSuccess (String)
  • +///
+static const char*const kEventLevelEnd = "level_end"; + +/// Level Start event. Log this event when the user starts a new level. +/// Params: +/// +///
    +///
  • @c AnalyticsParameterLevelName (String)
  • +///
+static const char*const kEventLevelStart = "level_start"; + +/// Level Up event. This event signifies that a player has leveled up in +/// your gaming app. It can help you gauge the level distribution of your +/// userbase and help you identify certain levels that are difficult to +/// pass. Params: +/// +///
    +///
  • @c AnalyticsParameterLevel (Int)
  • +///
  • @c AnalyticsParameterCharacter (String) (optional)
  • +///
+static const char*const kEventLevelUp = "level_up"; + +/// Login event. Apps with a login feature can report this event to +/// signify that a user has logged in. +static const char*const kEventLogin = "login"; + +/// Post Score event. Log this event when the user posts a score in your +/// gaming app. This event can help you understand how users are actually +/// performing in your game and it can help you correlate high scores with +/// certain audiences or behaviors. Params: +/// +///
    +///
  • @c AnalyticsParameterScore (Int)
  • +///
  • @c AnalyticsParameterLevel (Int) (optional)
  • +///
  • @c AnalyticsParameterCharacter (String) (optional)
  • +///
+static const char*const kEventPostScore = "post_score"; + +/// E-Commerce Purchase event. This event signifies that an item(s) was +/// purchased by a user. Note: This is different from the in-app purchase +/// event, which is reported automatically for App Store-based apps. Note: +/// If you supply the @c AnalyticsParameterValue parameter, you must also +/// supply the @c AnalyticsParameterCurrency parameter so that revenue +/// metrics can be computed accurately. Params: +/// +///
    +///
  • @c AnalyticsParameterAffiliation (String) (optional)
  • +///
  • @c AnalyticsParameterCoupon (String) (optional)
  • +///
  • @c AnalyticsParameterCurrency (String) (optional)
  • +///
  • @c AnalyticsParameterEndDate (String) (optional)
  • +///
  • @c AnalyticsParameterItemID (String) (optional)
  • +///
  • @c AnalyticsParameterItems ([[String: Any]]) (optional)
  • +///
  • @c AnalyticsParameterShipping (Double) (optional)
  • +///
  • @c AnalyticsParameterStartDate (String) (optional)
  • +///
  • @c AnalyticsParameterTax (Double) (optional)
  • +///
  • @c AnalyticsParameterTransactionID (String) (optional)
  • +///
  • @c AnalyticsParameterValue (Double) (optional)
  • +///
+static const char*const kEventPurchase = "purchase"; + +/// E-Commerce Refund event. This event signifies that a refund was +/// issued. Note: If you supply the @c AnalyticsParameterValue parameter, +/// you must also supply the @c AnalyticsParameterCurrency parameter so +/// that revenue metrics can be computed accurately. Params: +/// +///
    +///
  • @c AnalyticsParameterAffiliation (String) (optional)
  • +///
  • @c AnalyticsParameterCoupon (String) (optional)
  • +///
  • @c AnalyticsParameterCurrency (String) (optional)
  • +///
  • @c AnalyticsParameterItems ([[String: Any]]) (optional)
  • +///
  • @c AnalyticsParameterShipping (Double) (optional)
  • +///
  • @c AnalyticsParameterTax (Double) (optional)
  • +///
  • @c AnalyticsParameterTransactionID (String) (optional)
  • +///
  • @c AnalyticsParameterValue (Double) (optional)
  • +///
+static const char*const kEventRefund = "refund"; + +/// E-Commerce Remove from Cart event. This event signifies that an +/// item(s) was removed from a cart. Note: If you supply the @c +/// AnalyticsParameterValue parameter, you must also supply the @c +/// AnalyticsParameterCurrency parameter so that revenue metrics can be +/// computed accurately. Params: +/// +///
    +///
  • @c AnalyticsParameterCurrency (String) (optional)
  • +///
  • @c AnalyticsParameterItems ([[String: Any]]) (optional)
  • +///
  • @c AnalyticsParameterValue (Double) (optional)
  • +///
+static const char*const kEventRemoveFromCart = + "remove_from_cart"; + +/// Screen View event. This event signifies a screen view. Use this when a +/// screen transition occurs. This event can be logged irrespective of +/// whether automatic screen tracking is enabled. Params: +/// +///
    +///
  • @c AnalyticsParameterScreenClass (String) (optional)
  • +///
  • @c AnalyticsParameterScreenName (String) (optional)
  • +///
+static const char*const kEventScreenView = "screen_view"; + +/// Search event. Apps that support search features can use this event to +/// contextualize search operations by supplying the appropriate, +/// corresponding parameters. This event can help you identify the most +/// popular content in your app. Params: +/// +///
    +///
  • @c AnalyticsParameterSearchTerm (String)
  • +///
  • @c AnalyticsParameterStartDate (String) (optional)
  • +///
  • @c AnalyticsParameterEndDate (String) (optional)
  • +///
  • @c AnalyticsParameterNumberOfNights (Int) (optional) for hotel bookings
  • +///
  • @c AnalyticsParameterNumberOfRooms (Int) (optional) for hotel bookings
  • +///
  • @c AnalyticsParameterNumberOfPassengers (Int) (optional) for travel bookings
  • +///
  • @c AnalyticsParameterOrigin (String) (optional)
  • +///
  • @c AnalyticsParameterDestination (String) (optional)
  • +///
  • @c AnalyticsParameterTravelClass (String) (optional) for travel bookings
  • +///
+static const char*const kEventSearch = "search"; + +/// Select Content event. This general purpose event signifies that a user +/// has selected some content of a certain type in an app. The content can +/// be any object in your app. This event can help you identify popular +/// content and categories of content in your app. Params: +/// +///
    +///
  • @c AnalyticsParameterContentType (String)
  • +///
  • @c AnalyticsParameterItemID (String)
  • +///
+static const char*const kEventSelectContent = + "select_content"; + +/// Select Item event. This event signifies that an item was selected by a +/// user from a list. Use the appropriate parameters to contextualize the +/// event. Use this event to discover the most popular items selected. +/// Params: +/// +///
    +///
  • @c AnalyticsParameterItems ([[String: Any]]) (optional)
  • +///
  • @c AnalyticsParameterItemListID (String) (optional)
  • +///
  • @c AnalyticsParameterItemListName (String) (optional)
  • +///
+static const char*const kEventSelectItem = "select_item"; + +/// Select promotion event. This event signifies that a user has selected +/// a promotion offer. Use the appropriate parameters to contextualize the +/// event, such as the item(s) for which the promotion applies. Params: +/// +///
    +///
  • @c AnalyticsParameterCreativeName (String) (optional)
  • +///
  • @c AnalyticsParameterCreativeSlot (String) (optional)
  • +///
  • @c AnalyticsParameterItems ([[String: Any]]) (optional)
  • +///
  • @c AnalyticsParameterLocationID (String) (optional)
  • +///
  • @c AnalyticsParameterPromotionID (String) (optional)
  • +///
  • @c AnalyticsParameterPromotionName (String) (optional)
  • +///
+static const char*const kEventSelectPromotion = + "select_promotion"; + +/// Share event. Apps with social features can log the Share event to +/// identify the most viral content. Params: +/// +///
    +///
  • @c AnalyticsParameterContentType (String)
  • +///
  • @c AnalyticsParameterItemID (String)
  • +///
+static const char*const kEventShare = "share"; + +/// Sign Up event. This event indicates that a user has signed up for an +/// account in your app. The parameter signifies the method by which the +/// user signed up. Use this event to understand the different behaviors +/// between logged in and logged out users. Params: +/// +///
    +///
  • @c AnalyticsParameterMethod (String)
  • +///
+static const char*const kEventSignUp = "sign_up"; + +/// Spend Virtual Currency event. This event tracks the sale of virtual +/// goods in your app and can help you identify which virtual goods are +/// the most popular objects of purchase. Params: +/// +///
    +///
  • @c AnalyticsParameterItemName (String)
  • +///
  • @c AnalyticsParameterVirtualCurrencyName (String)
  • +///
  • @c AnalyticsParameterValue (Int or Double)
  • +///
+static const char*const kEventSpendVirtualCurrency + = "spend_virtual_currency"; + +/// Tutorial Begin event. This event signifies the start of the +/// on-boarding process in your app. Use this in a funnel with @c +/// AnalyticsEventTutorialComplete to understand how many users complete +/// this process and move on to the full app experience. +static const char*const kEventTutorialBegin = + "tutorial_begin"; + +/// Tutorial End event. Use this event to signify the user's completion of +/// your app's on-boarding process. Add this to a funnel with @c +/// AnalyticsEventTutorialBegin to gauge the completion rate of your +/// on-boarding process. +static const char*const kEventTutorialComplete = + "tutorial_complete"; + +/// Unlock Achievement event. Log this event when the user has unlocked an +/// achievement in your game. Since achievements generally represent the +/// breadth of a gaming experience, this event can help you understand how +/// many users are experiencing all that your game has to offer. Params: +/// +///
    +///
  • @c AnalyticsParameterAchievementID (String)
  • +///
+static const char*const kEventUnlockAchievement = + "unlock_achievement"; + +/// E-commerce View Cart event. This event signifies that a user has +/// viewed their cart. Use this to analyze your purchase funnel. Note: If +/// you supply the @c AnalyticsParameterValue parameter, you must also +/// supply the @c AnalyticsParameterCurrency parameter so that revenue +/// metrics can be computed accurately. Params: +/// +///
    +///
  • @c AnalyticsParameterCurrency (String) (optional)
  • +///
  • @c AnalyticsParameterItems ([[String: Any]]) (optional)
  • +///
  • @c AnalyticsParameterValue (Double) (optional)
  • +///
+static const char*const kEventViewCart = "view_cart"; + +/// View Item event. This event signifies that a user has viewed an item. +/// Use the appropriate parameters to contextualize the event. Use this +/// event to discover the most popular items viewed in your app. Note: If +/// you supply the @c AnalyticsParameterValue parameter, you must also +/// supply the @c AnalyticsParameterCurrency parameter so that revenue +/// metrics can be computed accurately. Params: +/// +///
    +///
  • @c AnalyticsParameterCurrency (String) (optional)
  • +///
  • @c AnalyticsParameterItems ([[String: Any]]) (optional)
  • +///
  • @c AnalyticsParameterValue (Double) (optional)
  • +///
+static const char*const kEventViewItem = "view_item"; + +/// View Item List event. Log this event when a user sees a list of items +/// or offerings. Params: +/// +///
    +///
  • @c AnalyticsParameterItems ([[String: Any]]) (optional)
  • +///
  • @c AnalyticsParameterItemListID (String) (optional)
  • +///
  • @c AnalyticsParameterItemListName (String) (optional)
  • +///
+static const char*const kEventViewItemList = + "view_item_list"; + +/// View Promotion event. This event signifies that a promotion was shown +/// to a user. Add this event to a funnel with the @c +/// AnalyticsEventAddToCart and @c AnalyticsEventPurchase to gauge your +/// conversion process. Params: +/// +///
    +///
  • @c AnalyticsParameterCreativeName (String) (optional)
  • +///
  • @c AnalyticsParameterCreativeSlot (String) (optional)
  • +///
  • @c AnalyticsParameterItems ([[String: Any]]) (optional)
  • +///
  • @c AnalyticsParameterLocationID (String) (optional)
  • +///
  • @c AnalyticsParameterPromotionID (String) (optional)
  • +///
  • @c AnalyticsParameterPromotionName (String) (optional)
  • +///
+static const char*const kEventViewPromotion = + "view_promotion"; + +/// View Search Results event. Log this event when the user has been +/// presented with the results of a search. Params: +/// +///
    +///
  • @c AnalyticsParameterSearchTerm (String)
  • +///
+static const char*const kEventViewSearchResults = + "view_search_results"; +/// @} + +} // namespace analytics +} // namespace firebase + +#endif // FIREBASE_ANALYTICS_CLIENT_CPP_INCLUDE_FIREBASE_ANALYTICS_EVENT_NAMES_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/analytics/parameter_names.h b/packages/firebase_core/firebase_core/firebase_core/firebase/analytics/parameter_names.h new file mode 100644 index 000000000000..fcc43c22fbc8 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/analytics/parameter_names.h @@ -0,0 +1,755 @@ +// Copyright 2023 Google Inc. All Rights Reserved. + +#ifndef FIREBASE_ANALYTICS_CLIENT_CPP_INCLUDE_FIREBASE_ANALYTICS_PARAMETER_NAMES_H_ +#define FIREBASE_ANALYTICS_CLIENT_CPP_INCLUDE_FIREBASE_ANALYTICS_PARAMETER_NAMES_H_ + +/// @brief Namespace that encompasses all Firebase APIs. +namespace firebase { +/// @brief Firebase Analytics API. +namespace analytics { + + + +/// @defgroup parameter_names Analytics Parameters +/// +/// Predefined event parameter names. +/// +/// Params supply information that contextualize Events. You can associate +/// up to 25 unique Params with each Event type. Some Params are suggested +/// below for certain common Events, but you are not limited to these. You +/// may supply extra Params for suggested Events or custom Params for +/// Custom events. Param names can be up to 40 characters long, may only +/// contain alphanumeric characters and underscores ("_"), and must start +/// with an alphabetic character. Param values can be up to 100 characters +/// long. The "firebase_", "google_", and "ga_" prefixes are reserved and +/// should not be used. +/// @{ + + +/// Game achievement ID (String). +/// @code +/// let params = [ +/// AnalyticsParameterAchievementID : "10_matches_won", +/// // ... +/// ] +/// @endcode +static const char*const kParameterAchievementID = + "achievement_id"; + +/// The ad format (e.g. Banner, Interstitial, Rewarded, Native, Rewarded +/// Interstitial, Instream). (String). +/// @code +/// let params = [ +/// AnalyticsParameterAdFormat : "Banner", +/// // ... +/// ] +/// @endcode +static const char*const kParameterAdFormat = + "ad_format"; + +/// Ad Network Click ID (String). Used for network-specific click IDs +/// which vary in format. +/// @code +/// let params = [ +/// AnalyticsParameterAdNetworParameter(kClickID, "1234567"), +/// // ... +/// ] +/// @endcode +static const char*const kParameterAdNetworkClickID + = "aclid"; + +/// The ad platform (e.g. MoPub, IronSource) (String). +/// @code +/// let params = [ +/// AnalyticsParameterAdPlatform : "MoPub", +/// // ... +/// ] +/// @endcode +static const char*const kParameterAdPlatform = + "ad_platform"; + +/// The ad source (e.g. AdColony) (String). +/// @code +/// let params = [ +/// AnalyticsParameterAdSource : "AdColony", +/// // ... +/// ] +/// @endcode +static const char*const kParameterAdSource = + "ad_source"; + +/// The ad unit name (e.g. Banner_03) (String). +/// @code +/// let params = [ +/// AnalyticsParameterAdUnitName : "Banner_03", +/// // ... +/// ] +/// @endcode +static const char*const kParameterAdUnitName = + "ad_unit_name"; + +/// A product affiliation to designate a supplying company or brick and +/// mortar store location +/// (String). @code +/// let params = [ +/// AnalyticsParameterAffiliation : "Google Store", +/// // ... +/// ] +/// @endcode +static const char*const kParameterAffiliation = + "affiliation"; + +/// Campaign custom parameter (String). Used as a method of capturing +/// custom data in a campaign. Use varies by network. +/// @code +/// let params = [ +/// AnalyticsParameterCP1 : "custom_data", +/// // ... +/// ] +/// @endcode +static const char*const kParameterCP1 = "cp1"; + +/// The individual campaign name, slogan, promo code, etc. Some networks +/// have pre-defined macro to capture campaign information, otherwise can +/// be populated by developer. Highly Recommended (String). +/// @code +/// let params = [ +/// AnalyticsParameterCampaign : "winter_promotion", +/// // ... +/// ] +/// @endcode +static const char*const kParameterCampaign = + "campaign"; + +/// Campaign ID (String). Used for keyword analysis to identify a specific +/// product promotion or strategic campaign. This is a required key for +/// GA4 data import. +/// @code +/// let params = [ +/// AnalyticsParameterCampaignID : "7877652710", +/// // ... +/// ] +/// @endcode +static const char*const kParameterCampaignID = + "campaign_id"; + +/// Character used in game (String). +/// @code +/// let params = [ +/// AnalyticsParameterCharacter : "beat_boss", +/// // ... +/// ] +/// @endcode +static const char*const kParameterCharacter = + "character"; + +/// Campaign content (String). +static const char*const kParameterContent = "content"; + +/// Type of content selected (String). +/// @code +/// let params = [ +/// AnalyticsParameterContentType : "news article", +/// // ... +/// ] +/// @endcode +static const char*const kParameterContentType = + "content_type"; + +/// Coupon code used for a purchase (String). +/// @code +/// let params = [ +/// AnalyticsParameterCoupon : "SUMMER_FUN", +/// // ... +/// ] +/// @endcode +static const char*const kParameterCoupon = "coupon"; + +/// Creative Format (String). Used to identify the high-level +/// classification of the type of ad served by a specific campaign. +/// @code +/// let params = [ +/// AnalyticsParameterCreativeFormat : "display", +/// // ... +/// ] +/// @endcode +static const char*const kParameterCreativeFormat = + "creative_format"; + +/// The name of a creative used in a promotional spot (String). +/// @code +/// let params = [ +/// AnalyticsParameterCreativeName : "Summer Sale", +/// // ... +/// ] +/// @endcode +static const char*const kParameterCreativeName = + "creative_name"; + +/// The name of a creative slot (String). +/// @code +/// let params = [ +/// AnalyticsParameterCreativeSlot : "summer_banner2", +/// // ... +/// ] +/// @endcode +static const char*const kParameterCreativeSlot = + "creative_slot"; + +/// Currency of the purchase or items associated with the event, in +/// 3-letter +/// ISO_4217 format (String). +/// @code +/// let params = [ +/// AnalyticsParameterCurrency : "USD", +/// // ... +/// ] +/// @endcode +static const char*const kParameterCurrency = + "currency"; + +/// Flight or Travel destination (String). +/// @code +/// let params = [ +/// AnalyticsParameterDestination : "Mountain View, CA", +/// // ... +/// ] +/// @endcode +static const char*const kParameterDestination = + "destination"; + +/// Monetary value of discount associated with a purchase (Double). +/// @code +/// let params = [ +/// AnalyticsParameterDiscount : 2.0, +/// AnalyticsParameterCurrency : "USD", // e.g. $2.00 USD +/// // ... +/// ] +/// @endcode +static const char*const kParameterDiscount = + "discount"; + +/// The arrival date, check-out date or rental end date for the item. This +/// should be in YYYY-MM-DD format (String). +/// @code +/// let params = [ +/// AnalyticsParameterEndDate : "2015-09-14", +/// // ... +/// ] +/// @endcode +static const char*const kParameterEndDate = "end_date"; + +/// Indicates that the associated event should either extend the current +/// session or start a new session if no session was active when the event +/// was logged. Specify 1 to extend the current session or to start a new +/// session; any other value will not extend or start a session. +/// @code +/// let params = [ +/// AnalyticsParameterExtendSession : 1, +/// // ... +/// ] +/// @endcode +static const char*const kParameterExtendSession = + "extend_session"; + +/// Flight number for travel events (String). +/// @code +/// let params = [ +/// AnalyticsParameterFlightNumber : "ZZ800", +/// // ... +/// ] +/// @endcode +static const char*const kParameterFlightNumber = + "flight_number"; + +/// Group/clan/guild ID (String). +/// @code +/// let params = [ +/// AnalyticsParameterGroupID : "g1", +/// // ... +/// ] +/// @endcode +static const char*const kParameterGroupID = "group_id"; + +/// The index of the item in a list (Int). +/// @code +/// let params = [ +/// AnalyticsParameterIndex : 5, +/// // ... +/// ] +/// @endcode +static const char*const kParameterIndex = "index"; + +/// Item brand (String). +/// @code +/// let params = [ +/// AnalyticsParameterItemBrand : "Google", +/// // ... +/// ] +/// @endcode +static const char*const kParameterItemBrand = + "item_brand"; + +/// Item category (context-specific) (String). +/// @code +/// let params = [ +/// AnalyticsParameterItemCategory : "pants", +/// // ... +/// ] +/// @endcode +static const char*const kParameterItemCategory = + "item_category"; + +/// Item Category (context-specific) (String). +/// @code +/// let params = [ +/// AnalyticsParameterItemCategory2 : "pants", +/// // ... +/// ] +/// @endcode +static const char*const kParameterItemCategory2 = + "item_category2"; + +/// Item Category (context-specific) (String). +/// @code +/// let params = [ +/// AnalyticsParameterItemCategory3 : "pants", +/// // ... +/// ] +/// @endcode +static const char*const kParameterItemCategory3 = + "item_category3"; + +/// Item Category (context-specific) (String). +/// @code +/// let params = [ +/// AnalyticsParameterItemCategory4 : "pants", +/// // ... +/// ] +/// @endcode +static const char*const kParameterItemCategory4 = + "item_category4"; + +/// Item Category (context-specific) (String). +/// @code +/// let params = [ +/// AnalyticsParameterItemCategory5 : "pants", +/// // ... +/// ] +/// @endcode +static const char*const kParameterItemCategory5 = + "item_category5"; + +/// Item ID (context-specific) (String). +/// @code +/// let params = [ +/// AnalyticsParameterItemID : "SKU_12345", +/// // ... +/// ] +/// @endcode +static const char*const kParameterItemID = "item_id"; + +/// The ID of the list in which the item was presented to the +/// user (String). +/// @code +/// let params = [ +/// AnalyticsParameterItemListID : "ABC123", +/// // ... +/// ] +/// @endcode +static const char*const kParameterItemListID = + "item_list_id"; + +/// The name of the list in which the item was presented to the user +/// (String). +/// @code +/// let params = [ +/// AnalyticsParameterItemListName : "Related products", +/// // ... +/// ] +/// @endcode +static const char*const kParameterItemListName = + "item_list_name"; + +/// Item Name (context-specific) (String). +/// @code +/// let params = [ +/// AnalyticsParameterItemName : "jeggings", +/// // ... +/// ] +/// @endcode +static const char*const kParameterItemName = + "item_name"; + +/// Item variant (String). +/// @code +/// let params = [ +/// AnalyticsParameterItemVariant : "Black", +/// // ... +/// ] +/// @endcode +static const char*const kParameterItemVariant = + "item_variant"; + +/// The list of items involved in the transaction expressed as `[[String: +/// Any]]`. +/// @code +/// let params = [ +/// AnalyticsParameterItems : [ +/// [AnalyticsParameterItemName : "jeggings", AnalyticsParameterItemCategory : "pants"], +/// [AnalyticsParameterItemName : "boots", AnalyticsParameterItemCategory : "shoes"], +/// ], +/// ] +/// @endcode +static const char*const kParameterItems = "items"; + +/// Level in game (Int). +/// @code +/// let params = [ +/// AnalyticsParameterLevel : 42, +/// // ... +/// ] +/// @endcode +static const char*const kParameterLevel = "level"; + +/// The name of a level in a game (String). +/// @code +/// let params = [ +/// AnalyticsParameterLevelName : "room_1", +/// // ... +/// ] +/// @endcode +static const char*const kParameterLevelName = + "level_name"; + +/// Location (String). The Google Place ID +/// that corresponds to the associated event. Alternatively, you can supply your own custom +/// Location ID. +/// @code +/// let params = [ +/// AnalyticsParameterLocation : "ChIJiyj437sx3YAR9kUWC8QkLzQ", +/// // ... +/// ] +/// @endcode +static const char*const kParameterLocation = + "location"; + +/// The location associated with the event. Preferred to be the Google +/// Place ID that corresponds to the +/// associated item but could be overridden to a custom location ID +/// string.(String). +/// @code +/// let params = [ +/// AnalyticsParameterLocationID : "ChIJiyj437sx3YAR9kUWC8QkLzQ", +/// // ... +/// ] +/// @endcode +static const char*const kParameterLocationID = + "location_id"; + +/// Marketing Tactic (String). Used to identify the targeting criteria +/// applied to a specific campaign. +/// @code +/// let params = [ +/// AnalyticsParameterMarParameter(ketingTactic, "Remarketing"), +/// // ... +/// ] +/// @endcode +static const char*const kParameterMarketingTactic + = "marketing_tactic"; + +/// The advertising or marParameter(keting, cpc, banner, email), push. +/// Highly recommended (String). +/// @code +/// let params = [ +/// AnalyticsParameterMedium : "email", +/// // ... +/// ] +/// @endcode +static const char*const kParameterMedium = "medium"; + +/// A particular approach used in an operation; for example, "facebook" or +/// "email" in the context of a sign_up or login event. (String). +/// @code +/// let params = [ +/// AnalyticsParameterMethod : "google", +/// // ... +/// ] +/// @endcode +static const char*const kParameterMethod = "method"; + +/// Number of nights staying at hotel (Int). +/// @code +/// let params = [ +/// AnalyticsParameterNumberOfNights : 3, +/// // ... +/// ] +/// @endcode +static const char*const kParameterNumberOfNights + = "number_of_nights"; + +/// Number of passengers traveling (Int). +/// @code +/// let params = [ +/// AnalyticsParameterNumberOfPassengers : 11, +/// // ... +/// ] +/// @endcode +static const char*const kParameterNumberOfPassengers + = "number_of_passengers"; + +/// Number of rooms for travel events (Int). +/// @code +/// let params = [ +/// AnalyticsParameterNumberOfRooms : 2, +/// // ... +/// ] +/// @endcode +static const char*const kParameterNumberOfRooms = + "number_of_rooms"; + +/// Flight or Travel origin (String). +/// @code +/// let params = [ +/// AnalyticsParameterOrigin : "Mountain View, CA", +/// // ... +/// ] +/// @endcode +static const char*const kParameterOrigin = "origin"; + +/// The chosen method of payment (String). +/// @code +/// let params = [ +/// AnalyticsParameterPaymentType : "Visa", +/// // ... +/// ] +/// @endcode +static const char*const kParameterPaymentType = + "payment_type"; + +/// Purchase price (Double). +/// @code +/// let params = [ +/// AnalyticsParameterPrice : 1.0, +/// AnalyticsParameterCurrency : "USD", // e.g. $1.00 USD +/// // ... +/// ] +/// @endcode +static const char*const kParameterPrice = "price"; + +/// The ID of a product promotion (String). +/// @code +/// let params = [ +/// AnalyticsParameterPromotionID : "ABC123", +/// // ... +/// ] +/// @endcode +static const char*const kParameterPromotionID = + "promotion_id"; + +/// The name of a product promotion (String). +/// @code +/// let params = [ +/// AnalyticsParameterPromotionName : "Summer Sale", +/// // ... +/// ] +/// @endcode +static const char*const kParameterPromotionName = + "promotion_name"; + +/// Purchase quantity (Int). +/// @code +/// let params = [ +/// AnalyticsParameterQuantity : 1, +/// // ... +/// ] +/// @endcode +static const char*const kParameterQuantity = + "quantity"; + +/// Score in game (Int). +/// @code +/// let params = [ +/// AnalyticsParameterScore : 4200, +/// // ... +/// ] +/// @endcode +static const char*const kParameterScore = "score"; + +/// Current screen class, such as the class name of the UIViewController, +/// logged with screen_view event and added to every event (String). +/// @code +/// let params = [ +/// AnalyticsParameterScreenClass : "LoginViewController", +/// // ... +/// ] +/// @endcode +static const char*const kParameterScreenClass = + "screen_class"; + +/// Current screen name, such as the name of the UIViewController, logged +/// with screen_view event and added to every event (String). +/// @code +/// let params = [ +/// AnalyticsParameterScreenName : "LoginView", +/// // ... +/// ] +/// @endcode +static const char*const kParameterScreenName = + "screen_name"; + +/// The search string/keywords used (String). +/// @code +/// let params = [ +/// AnalyticsParameterSearchTerm : "periodic table", +/// // ... +/// ] +/// @endcode +static const char*const kParameterSearchTerm = + "search_term"; + +/// Shipping cost associated with a transaction (Double). +/// @code +/// let params = [ +/// AnalyticsParameterShipping : 5.99, +/// AnalyticsParameterCurrency : "USD", // e.g. $5.99 USD +/// // ... +/// ] +/// @endcode +static const char*const kParameterShipping = + "shipping"; + +/// The shipping tier (e.g. Ground, Air, Next-day) selected for delivery +/// of the purchased item (String). +/// @code +/// let params = [ +/// AnalyticsParameterShippingTier : "Ground", +/// // ... +/// ] +/// @endcode +static const char*const kParameterShippingTier = + "shipping_tier"; + +/// The origin of your traffic, such as an Ad network (for example, +/// google) or partner (urban airship). Identify the advertiser, site, +/// publication, etc. that is sending traffic to your property. Highly +/// recommended (String). +/// @code +/// let params = [ +/// AnalyticsParameterSource : "InMobi", +/// // ... +/// ] +/// @endcode +static const char*const kParameterSource = "source"; + +/// Source Platform (String). Used to identify the platform responsible +/// for directing traffic to a given Analytics property (e.g., a buying +/// platform where budgets, targeting criteria, etc. are set, a platform +/// for managing organic traffic data, etc.). +/// @code +/// let params = [ +/// AnalyticsParameterSourcePlatform : "sa360", +/// // ... +/// ] +/// @endcode +static const char*const kParameterSourcePlatform = + "source_platform"; + +/// The departure date, check-in date or rental start date for the item. +/// This should be in YYYY-MM-DD format (String). +/// @code +/// let params = [ +/// AnalyticsParameterStartDate : "2015-09-14", +/// // ... +/// ] +/// @endcode +static const char*const kParameterStartDate = + "start_date"; + +/// The result of an operation. Specify 1 to indicate success and 0 to +/// indicate failure (Int). +/// @code +/// let params = [ +/// AnalyticsParameterSuccess : 1, +/// // ... +/// ] +/// @endcode +static const char*const kParameterSuccess = "success"; + +/// Tax cost associated with a transaction (Double). +/// @code +/// let params = [ +/// AnalyticsParameterTax : 2.43, +/// AnalyticsParameterCurrency : "USD", // e.g. $2.43 USD +/// // ... +/// ] +/// @endcode +static const char*const kParameterTax = "tax"; + +/// If you're manually tagging keyword campaigns, you should use utm_term +/// to specify the keyword (String). +/// @code +/// let params = [ +/// AnalyticsParameterTerm : "game", +/// // ... +/// ] +/// @endcode +static const char*const kParameterTerm = "term"; + +/// The unique identifier of a transaction (String). +/// @code +/// let params = [ +/// AnalyticsParameterTransactionID : "T12345", +/// // ... +/// ] +/// @endcode +static const char*const kParameterTransactionID = + "transaction_id"; + +/// Travel class (String). +/// @code +/// let params = [ +/// AnalyticsParameterTravelClass : "business", +/// // ... +/// ] +/// @endcode +static const char*const kParameterTravelClass = + "travel_class"; + +/// A context-specific numeric value which is accumulated automatically +/// for each event type. This is a general purpose parameter that is +/// useful for accumulating a key metric that pertains to an event. +/// Examples include revenue, distance, time and points. Value should be +/// specified as Int or Double. Notes: Values for pre-defined +/// currency-related events (such as @c AnalyticsEventAddToCart) should be +/// supplied using Double and must be accompanied by a @c +/// AnalyticsParameterCurrency parameter. The valid range of accumulated +/// values is [-9,223,372,036,854.77, 9,223,372,036,854.77]. Supplying a +/// non-numeric value, omitting the corresponding @c +/// AnalyticsParameterCurrency parameter, or supplying an invalid +/// currency code for conversion events will cause that +/// conversion to be omitted from reporting. +/// @code +/// let params = [ +/// AnalyticsParameterValue : 3.99, +/// AnalyticsParameterCurrency : "USD", // e.g. $3.99 USD +/// // ... +/// ] +/// @endcode +static const char*const kParameterValue = "value"; + +/// Name of virtual currency type (String). +/// @code +/// let params = [ +/// AnalyticsParameterVirtualCurrencyName : "virtual_currency_name", +/// // ... +/// ] +/// @endcode +static const char*const kParameterVirtualCurrencyName + = "virtual_currency_name"; +/// @} + +} // namespace analytics +} // namespace firebase + +#endif // FIREBASE_ANALYTICS_CLIENT_CPP_INCLUDE_FIREBASE_ANALYTICS_PARAMETER_NAMES_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/analytics/user_property_names.h b/packages/firebase_core/firebase_core/firebase_core/firebase/analytics/user_property_names.h new file mode 100644 index 000000000000..155fea86e6f9 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/analytics/user_property_names.h @@ -0,0 +1,50 @@ +// Copyright 2023 Google Inc. All Rights Reserved. + +#ifndef FIREBASE_ANALYTICS_CLIENT_CPP_INCLUDE_FIREBASE_ANALYTICS_USER_PROPERTY_NAMES_H_ +#define FIREBASE_ANALYTICS_CLIENT_CPP_INCLUDE_FIREBASE_ANALYTICS_USER_PROPERTY_NAMES_H_ + +/// @brief Namespace that encompasses all Firebase APIs. +namespace firebase { +/// @brief Firebase Analytics API. +namespace analytics { + + + +/// @defgroup user_property_names Analytics User Properties +/// +/// Predefined user property names. +/// +/// A UserProperty is an attribute that describes the app-user. By +/// supplying UserProperties, you can later analyze different behaviors of +/// various segments of your userbase. You may supply up to 25 unique +/// UserProperties per app, and you can use the name and value of your +/// choosing for each one. UserProperty names can be up to 24 characters +/// long, may only contain alphanumeric characters and underscores ("_"), +/// and must start with an alphabetic character. UserProperty values can +/// be up to 36 characters long. The "firebase_", "google_", and "ga_" +/// prefixes are reserved and should not be used. +/// @{ + + +/// Indicates whether events logged by Google Analytics can be used to +/// personalize ads for the user. Set to "YES" to enable, or "NO" to +/// disable. Default is enabled. See the +/// documentation for +/// more details and information about related settings. +/// +/// @code +/// Analytics.setUserProperty("NO", forName: AnalyticsUserPropertyAllowAdPersonalizationSignals) +/// @endcode +static const char*const kUserPropertyAllowAdPersonalizationSignals + = "allow_personalized_ads"; + +/// The method used to sign in. For example, "google", "facebook" or +/// "twitter". +static const char*const kUserPropertySignUpMethod + = "sign_up_method"; +/// @} + +} // namespace analytics +} // namespace firebase + +#endif // FIREBASE_ANALYTICS_CLIENT_CPP_INCLUDE_FIREBASE_ANALYTICS_USER_PROPERTY_NAMES_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/app.h b/packages/firebase_core/firebase_core/firebase_core/firebase/app.h new file mode 100644 index 000000000000..0501f38ac0c8 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/app.h @@ -0,0 +1,787 @@ +/* + * Copyright 2016 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_APP_SRC_INCLUDE_FIREBASE_APP_H_ +#define FIREBASE_APP_SRC_INCLUDE_FIREBASE_APP_H_ + +#include "firebase/internal/platform.h" + +#if FIREBASE_PLATFORM_ANDROID +#include +#endif // FIREBASE_PLATFORM_ANDROID + +#include +#include +#include + +#if FIREBASE_PLATFORM_IOS || FIREBASE_PLATFORM_TVOS +#ifdef __OBJC__ +@class FIRApp; +#endif // __OBJC__ +#endif // FIREBASE_PLATFORM_IOS + +namespace firebase { + +#ifdef FIREBASE_LINUX_BUILD_CONFIG_STRING +// Check to see if the shared object compiler string matches the input +void CheckCompilerString(const char* input); +#endif // FIREBASE_LINUX_BUILD_CONFIG_STRING + +// Predeclarations. +#ifdef INTERNAL_EXPERIMENTAL +namespace internal { +class FunctionRegistry; +} // namespace internal +#endif // INTERNAL_EXPERIMENTAL + +#ifdef INTERNAL_EXPERIMENTAL +#if FIREBASE_PLATFORM_DESKTOP +namespace heartbeat { +class HeartbeatController; // forward declaration +} // namespace heartbeat +#endif // FIREBASE_PLATFORM_DESKTOP +#endif // INTERNAL_EXPERIMENTAL + +namespace internal { +class AppInternal; +} // namespace internal + +/// @brief Reports whether a Firebase module initialized successfully. +enum InitResult { + /// The given library was successfully initialized. + kInitResultSuccess = 0, + + /// The given library failed to initialize due to a missing dependency. + /// + /// On Android, this typically means that Google Play services is not + /// available and the library requires it. + /// @if cpp_examples + /// Use google_play_services::CheckAvailability() and + /// google_play_services::MakeAvailable() to resolve this issue. + /// @endif + /// + /// @if swig_examples + /// Use FirebaseApp.CheckDependencies() and + /// FirebaseApp.FixDependenciesAsync() to resolve this issue. + /// @endif + /// + /// + /// Also, on Android, this value can be returned if the Java dependencies of a + /// Firebase component are not included in the application, causing + /// initialization to fail. This means that the application's build + /// environment is not configured correctly. To resolve the problem, + /// see the SDK setup documentation for the set of Java dependencies (AARs) + /// required for the component that failed to initialize. + kInitResultFailedMissingDependency +}; + +/// @brief Default name for firebase::App() objects. +extern const char* const kDefaultAppName; + +/// @brief Options that control the creation of a Firebase App. +/// @if cpp_examples +/// @see firebase::App +/// @endif +/// +/// @if swig_examples +/// @see FirebaseApp +/// @endif +/// +class AppOptions { + friend class App; + + public: + /// @brief Create AppOptions. + /// + /// @if cpp_examples + /// To create a firebase::App object, the Firebase application identifier + /// and API key should be set using set_app_id() and set_api_key() + /// respectively. + /// + /// @see firebase::App::Create(). + /// @endif + /// + /// @if swig_examples + /// To create a FirebaseApp object, the Firebase application identifier + /// and API key should be set using AppId and ApiKey respectively. + /// + /// @see FirebaseApp.Create(). + /// @endif + /// + AppOptions() {} + + /// Set the Firebase app ID used to uniquely identify an instance of an app. + /// + /// This is the mobilesdk_app_id in the Android google-services.json config + /// file or GOOGLE_APP_ID in the GoogleService-Info.plist. + /// + /// This only needs to be specified if your application does not include + /// google-services.json or GoogleService-Info.plist in its resources. + void set_app_id(const char* id) { app_id_ = id; } + + /// Retrieves the app ID. + /// + /// @if cpp_examples + /// @see set_app_id(). + /// @endif + /// + /// + /// @xmlonly + /// + /// Gets or sets the App Id. + /// + /// This is the mobilesdk_app_id in the Android google-services.json config + /// file or GOOGLE_APP_ID in the GoogleService-Info.plist. + /// + /// This only needs to be specified if your application does not include + /// google-services.json or GoogleService-Info.plist in its resources. + /// + /// @endxmlonly + /// + const char* app_id() const { return app_id_.c_str(); } + + /// API key used to authenticate requests from your app. + /// + /// For example, "AIzaSyDdVgKwhZl0sTTTLZ7iTmt1r3N2cJLnaDk" used to identify + /// your app to Google servers. + /// + /// This only needs to be specified if your application does not include + /// google-services.json or GoogleService-Info.plist in its resources. + void set_api_key(const char* key) { api_key_ = key; } + + /// Get the API key. + /// + /// @if cpp_examples + /// @see set_api_key(). + /// @endif + /// + /// + /// @xmlonly + /// + /// Gets or sets the API key used to authenticate requests from your app. + /// + /// For example, \"AIzaSyDdVgKwhZl0sTTTLZ7iTmt1r3N2cJLnaDk\" used to identify + /// your app to Google servers. + /// + /// This only needs to be specified if your application does not include + /// google-services.json or GoogleService-Info.plist in its resources. + /// + /// @endxmlonly + /// + const char* api_key() const { return api_key_.c_str(); } + + /// Set the Firebase Cloud Messaging sender ID. + /// + /// For example "012345678901", used to configure Firebase Cloud Messaging. + /// + /// This only needs to be specified if your application does not include + /// google-services.json or GoogleService-Info.plist in its resources. + void set_messaging_sender_id(const char* sender_id) { + fcm_sender_id_ = sender_id; + } + + /// Get the Firebase Cloud Messaging sender ID. + /// + /// @if cpp_examples + /// @see set_messaging_sender_id(). + /// @endif + /// + /// + /// @xmlonly + /// + /// Gets or sets the messaging sender Id. + /// + /// This only needs to be specified if your application does not include + /// google-services.json or GoogleService-Info.plist in its resources. + /// + /// @endxmlonly + /// + const char* messaging_sender_id() const { return fcm_sender_id_.c_str(); } + + /// Set the database root URL, e.g. @"http://abc-xyz-123.firebaseio.com". + void set_database_url(const char* url) { database_url_ = url; } + + /// Get database root URL, e.g. @"http://abc-xyz-123.firebaseio.com". + /// + /// + /// @xmlonly + /// + /// Gets or sets the database root URL, e.g. + /// @\"http://abc-xyz-123.firebaseio.com\". + /// + /// @endxmlonly + /// + const char* database_url() const { return database_url_.c_str(); } + + /// @cond FIREBASE_APP_INTERNAL + + /// Set the tracking ID for Google Analytics, e.g. @"UA-12345678-1". + void set_ga_tracking_id(const char* id) { ga_tracking_id_ = id; } + + /// Get the tracking ID for Google Analytics, + /// + /// @if cpp_examples + /// @see set_ga_tracking_id(). + /// @endif + /// + const char* ga_tracking_id() const { return ga_tracking_id_.c_str(); } + + /// @endcond + + /// Set the Google Cloud Storage bucket name, + /// e.g. @\"abc-xyz-123.storage.firebase.com\". + void set_storage_bucket(const char* bucket) { storage_bucket_ = bucket; } + + /// Get the Google Cloud Storage bucket name, + /// @see set_storage_bucket(). + /// + /// @xmlonly + /// + /// Gets or sets the Google Cloud Storage bucket name, e.g. + /// @\"abc-xyz-123.storage.firebase.com\". + /// + /// @endxmlonly + /// + const char* storage_bucket() const { return storage_bucket_.c_str(); } + + /// Set the Google Cloud project ID. + void set_project_id(const char* project) { project_id_ = project; } + + /// Get the Google Cloud project ID. + /// + /// This is the project_id in the Android google-services.json config + /// file or PROJECT_ID in the GoogleService-Info.plist. + /// + /// @xmlonly + /// + /// Gets the Google Cloud project ID. + /// + /// This is the project_id in the Android google-services.json config + /// file or PROJECT_ID in the GoogleService-Info.plist. + /// + /// @endxmlonly + /// + const char* project_id() const { return project_id_.c_str(); } + +#ifdef INTERNAL_EXPERIMENTAL + /// @brief set the iOS client ID. + /// + /// This is the clientID in the GoogleService-Info.plist. + void set_client_id(const char* client_id) { client_id_ = client_id; } + + /// @brief Get the iOS client ID. + /// + /// This is the client_id in the GoogleService-Info.plist. + const char* client_id() const { return client_id_.c_str(); } +#endif // INTERNAL_EXPERIMENTAL + +#ifdef INTERNAL_EXPERIMENTAL + /// @brief Set the Android or iOS client project name. + /// + /// This is the project_name in the Android google-services.json config + /// file or BUNDLE_ID in the GoogleService-Info.plist. + void set_package_name(const char* package_name) { + package_name_ = package_name; + } + + /// @brief Get the Android or iOS client project name. + /// + /// This is the project_name in the Android google-services.json config + /// file or BUNDLE_ID in the GoogleService-Info.plist. + const char* package_name() const { return package_name_.c_str(); } +#endif // INTERNAL_EXPERIMENTAL + + /// @brief Load options from a config string. + /// + /// @param[in] config A JSON string that contains Firebase configuration i.e. + /// the content of the downloaded google-services.json file. + /// @param[out] options Optional: If provided, load options into it. + /// + /// @returns An instance containing the loaded options if successful. + /// If the options argument to this function is null, this method returns an + /// AppOptions instance allocated from the heap. + static AppOptions* LoadFromJsonConfig(const char* config, + AppOptions* options = nullptr); + +#if INTERNAL_EXPERIMENTAL + /// @brief Determine whether the specified options match this set of options. + /// + /// Fields of this object that are empty are ignored in the comparison. + /// + /// @param[in] options Options to compare with. + bool operator==(const AppOptions& options) const { + return (package_name_.empty() || package_name_ == options.package_name_) && + (api_key_.empty() || api_key_ == options.api_key_) && + (app_id_.empty() || app_id_ == options.app_id_) && + (database_url_.empty() || database_url_ == options.database_url_) && + (ga_tracking_id_.empty() || + ga_tracking_id_ == options.ga_tracking_id_) && + (fcm_sender_id_.empty() || + fcm_sender_id_ == options.fcm_sender_id_) && + (storage_bucket_.empty() || + storage_bucket_ == options.storage_bucket_) && + (project_id_.empty() || project_id_ == options.project_id_); + } +#endif // INTERNAL_EXPERIMENTAL + +#if INTERNAL_EXPERIMENTAL + /// @brief Determine whether the specified options don't match this set of + /// options. + /// + /// Fields of this object that are empty are ignored in the comparison. + /// + /// @param[in] options Options to compare with. + bool operator!=(const AppOptions& options) const { + return !operator==(options); + } +#endif // INTERNAL_EXPERIMENTAL + +#if INTERNAL_EXPERIMENTAL +#if FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) + /// @brief Load default options from the resource file. + /// + /// @param[in] jni_env JNI environment required to allow Firebase services + /// to interact with the Android framework. + /// @param[in] activity JNI reference to the Android activity, required to + /// allow Firebase services to interact with the Android application. + /// @param options Options to populate from a resource file. + /// + /// @return An instance containing the loaded options if successful. + /// If the options argument to this function is null, this method returns an + /// AppOptions instance allocated from the heap.. + static AppOptions* LoadDefault(AppOptions* options, JNIEnv* jni_env, + jobject activity); +#endif // FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) + +#if !FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) + /// @brief Load default options from the resource file. + /// + /// @param options Options to populate from a resource file. + /// + /// @return An instance containing the loaded options if successful. + /// If the options argument to this function is null, this method returns an + /// AppOptions instance allocated from the heap. + static AppOptions* LoadDefault(AppOptions* options); +#endif // !FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) +#endif // INTERNAL_EXPERIMENTAL + +#if INTERNAL_EXPERIMENTAL +#if FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) + /// @brief Attempt to populate required options with default values if not + /// specified. + /// + /// @param[in] jni_env JNI environment required to allow Firebase services + /// to interact with the Android framework. + /// @param[in] activity JNI reference to the Android activity, required to + /// allow Firebase services to interact with the Android application. + /// + /// @return true if successful, false otherwise. + bool PopulateRequiredWithDefaults(JNIEnv* jni_env, jobject activity); +#endif // FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) + +#if !FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) + /// @brief Attempt to populate required options with default values if not + /// specified. + /// + /// @return true if successful, false otherwise. + bool PopulateRequiredWithDefaults(); +#endif // !FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) +#endif // INTERNAL_EXPERIMENTAL + + /// @cond FIREBASE_APP_INTERNAL + private: + /// Application package name (e.g Android package name or iOS bundle ID). + std::string package_name_; + /// API key used to communicate with Google Servers. + std::string api_key_; + /// ID of the app. + std::string app_id_; + /// ClientID of the app. + std::string client_id_; + /// Database root URL. + std::string database_url_; + /// Google analytics tracking ID. + std::string ga_tracking_id_; + /// FCM sender ID. + std::string fcm_sender_id_; + /// Google Cloud Storage bucket name. + std::string storage_bucket_; + /// Google Cloud project ID. + std::string project_id_; + /// @endcond +}; + +/// @brief Firebase application object. +/// +/// @if cpp_examples +/// firebase::App acts as a conduit for communication between all Firebase +/// services used by an application. +/// +/// For example: +/// @code +/// #if defined(__ANDROID__) +/// firebase::App::Create(firebase::AppOptions(), jni_env, activity); +/// #else +/// firebase::App::Create(firebase::AppOptions()); +/// #endif // defined(__ANDROID__) +/// @endcode +/// @endif +/// +/// @if swig_examples +/// FirebaseApp acts as a conduit for communication between all Firebase +/// services used by an application. A default instance is created +/// automatically, based on settings in your Firebase configuration file, +/// and all of the Firebase APIs connect with it automatically. +/// @endif +class App { + public: + ~App(); + +#if !FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) + /// @brief Initializes the default firebase::App with default options. + /// + /// @note This method is specific to non-Android implementations. + /// + /// @return New App instance, the App should not be destroyed for the + /// lifetime of the application. If default options can't be loaded this + /// will return null. + static App* Create(); +#endif // !FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) + +#ifndef SWIG +// +// For Unity, we actually use the simpler, iOS version for both platforms +// +#if FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) + /// @brief Initializes the default firebase::App with default options. + /// + /// @note This method is specific to the Android implementation. + /// + /// @param[in] jni_env JNI environment required to allow Firebase services + /// to interact with the Android framework. + /// @param[in] activity JNI reference to the Android activity, required to + /// allow Firebase services to interact with the Android application. + /// + /// @return New App instance. The App should not be destroyed for the + /// lifetime of the application. If default options can't be loaded this + /// will return null. + static App* Create(JNIEnv* jni_env, jobject activity); +#endif // FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) +#endif // SWIG + +#if !FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) + /// @brief Initializes the default firebase::App with the given options. + /// + /// @note This method is specific to non-Android implementations. + /// + /// Options are copied at initialization time, so changes to the object are + /// ignored. + /// @param[in] options Options that control the creation of the App. + /// + /// @return New App instance, the App should not be destroyed for the + /// lifetime of the application. + static App* Create(const AppOptions& options); +#endif // !FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) + +#ifndef SWIG +// +// For Unity, we actually use the simpler, iOS version for both platforms +// +#if FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) + /// @brief Initializes the default firebase::App with the given options. + /// + /// @note This method is specific to the Android implementation. + /// + /// Options are copied at initialization time, so changes to the object are + /// ignored. + /// @param[in] options Options that control the creation of the App. + /// @param[in] jni_env JNI environment required to allow Firebase services + /// to interact with the Android framework. + /// @param[in] activity JNI reference to the Android activity, required to + /// allow Firebase services to interact with the Android application. + /// + /// @return New App instance. The App should not be destroyed for the + /// lifetime of the application. + static App* Create(const AppOptions& options, JNIEnv* jni_env, + jobject activity); +#endif // FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) +#endif // SWIG + +#if !FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) + /// @brief Initializes a firebase::App with the given options that operates + /// on the named app. + /// + /// @note This method is specific to non-Android implementations. + /// + /// Options are copied at initialization time, so changes to the object are + /// ignored. + /// @param[in] options Options that control the creation of the App. + /// @param[in] name Name of this App instance. This is only required when + /// one application uses multiple App instances. + /// + /// @return New App instance, the App should not be destroyed for the + /// lifetime of the application. + static App* Create(const AppOptions& options, const char* name); +#endif // !FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) + +#ifndef SWIG +// +// For Unity, we actually use the simpler iOS version for both platforms +// +#if FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) + /// @brief Initializes a firebase::App with the given options that operates + /// on the named app. + /// + /// @note This method is specific to the Android implementation. + /// + /// Options are copied at initialization time, so changes to the object are + /// ignored. + /// @param[in] options Options that control the creation of the App. + /// @param[in] name Name of this App instance. This is only required when + /// one application uses multiple App instances. + /// @param[in] jni_env JNI environment required to allow Firebase services + /// to interact with the Android framework. + /// @param[in] activity JNI reference to the Android activity, required to + /// allow Firebase services to interact with the Android application. + /// + /// @return New App instance. The App should not be destroyed for the + /// lifetime of the application. + static App* Create(const AppOptions& options, const char* name, + JNIEnv* jni_env, jobject activity); +#endif // FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) +#endif // SWIG + + /// Get the default App, or nullptr if none has been created. + static App* GetInstance(); + + /// Get the App with the given name, or nullptr if none have been created. + static App* GetInstance(const char* name); + +#ifndef SWIG +// +// Unity doesn't need the JNI from here, it has its method to access JNI. +// +#if FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) + /// Get Java virtual machine, retrieved from the initial JNI environment. + /// @note This method is specific to the Android implementation. + /// + /// @return JNI Java virtual machine object. + JavaVM* java_vm() const; + /// Get JNI environment, needed for performing JNI calls, set on creation. + /// This is not trivial as the correct environment needs to retrieved per + /// thread. + /// @note This method is specific to the Android implementation. + /// + /// @return JNI environment object. + JNIEnv* GetJNIEnv() const; + /// Get a global reference to the Android activity provided to the App on + /// creation. Also serves as the Context needed for Firebase calls. + /// @note This method is specific to the Android implementation. + /// + /// @return Global JNI reference to the Android activity used to create + /// the App. The reference count of the returned object is not increased. + jobject activity() const { return activity_; } +#endif // FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) +#endif // SWIG + + /// Get the name of this App instance. + /// + /// @return The name of this App instance. If a name wasn't provided via + /// Create(), this returns @ref kDefaultAppName. + /// + /// @xmlonly + /// + /// Get the name of this FirebaseApp instance. + /// If a name wasn't provided via Create(), this will match @ref DefaultName. + /// + /// @endxmlonly + /// + const char* name() const { return name_.c_str(); } + + /// Get options the App was created with. + /// + /// @return Options used to create the App. + /// + /// @xmlonly + /// + /// @brief Get the AppOptions the FirebaseApp was created with. + /// @return AppOptions used to create the FirebaseApp. + /// + /// @endxmlonly + /// + const AppOptions& options() const { return options_; } + +#ifdef INTERNAL_EXPERIMENTAL + /// Sets whether automatic data collection is enabled for all products. + /// + /// By default, automatic data collection is enabled. To disable automatic + /// data collection in your mobile app, add to your Android application's + /// manifest: + /// + /// @if NOT_DOXYGEN + /// + /// @else + /// @code + /// <meta-data android:name="firebase_data_collection_default_enabled" + /// android:value="false" /> + /// @endcode + /// @endif + /// + /// or on iOS to your Info.plist: + /// + /// @if NOT_DOXYGEN + /// FirebaseDataCollectionDefaultEnabled + /// + /// @else + /// @code + /// <key>FirebaseDataCollectionDefaultEnabled</key> + /// <false/> + /// @endcode + /// @endif + /// + /// Once your mobile app is set to disable automatic data collection, you can + /// ask users to consent to data collection, and then enable it after their + /// approval by calling this method. + /// + /// This value is persisted across runs of the app so that it can be set once + /// when users have consented to collection. + /// + /// @param enabled Whether or not to enable automatic data collection. + void SetDataCollectionDefaultEnabled(bool enabled); + + /// Gets whether automatic data collection is enabled for all + /// products. Defaults to true unless + /// "firebase_data_collection_default_enabled" is set to false in your + /// Android manifest and FirebaseDataCollectionDefaultEnabled is set to NO + /// in your iOS app's Info.plist. + /// + /// @return Whether or not automatic data collection is enabled for all + /// products. + bool IsDataCollectionDefaultEnabled() const; +#endif // INTERNAL_EXPERIMENTAL +#ifdef SWIG + void SetDataCollectionDefaultEnabled(bool enabled); + bool IsDataCollectionDefaultEnabled() const; +#endif // SWIG + +#ifdef INTERNAL_EXPERIMENTAL + // This is only visible to SWIG and internal users of firebase::App. + /// Get the initialization results of modules that were initialized when + /// creating this app. + /// + /// @return Initialization results of modules indexed by module name. + const std::map& init_results() const { + return init_results_; + } + + // Returns a pointer to the function registry, used by components to expose + // methods to one another without introducing linkage dependencies. + internal::FunctionRegistry* function_registry(); + + /// @brief Register a library which utilizes the Firebase C++ SDK. + /// + /// @param library Name of the library to register as a user of the Firebase + /// C++ SDK. + /// @param version Version of the library being registered. + static void RegisterLibrary(const char* library, const char* version); + + // Internal method to retrieve the combined string of registered libraries. + static const char* GetUserAgent(); + + // On desktop, when App.Create() is invoked without parameters, it looks for a + // file named 'google-services-desktop.json', to load parameters from. + // This function sets the location to search in. + // Note - when setting this, make sure to end the path with the appropriate + // path separator! + static void SetDefaultConfigPath(const char* path); +#endif // INTERNAL_EXPERIMENTAL + +#ifdef INTERNAL_EXPERIMENTAL +#if FIREBASE_PLATFORM_DESKTOP + // These methods are only visible to SWIG and internal users of firebase::App. + + /// Logs a heartbeat using the internal HeartbeatController. + void LogHeartbeat() const; + + /// Get a pointer to the HeartbeatController associated with this app. + std::shared_ptr GetHeartbeatController() + const; +#endif // FIREBASE_PLATFORM_DESKTOP +#endif // INTERNAL_EXPERIMENTAL + +#ifdef INTERNAL_EXPERIMENTAL +#if FIREBASE_PLATFORM_ANDROID + /// Get the platform specific app implementation referenced by this object. + /// + /// @return Global reference to the FirebaseApp. The returned reference + /// most be deleted after use. + jobject GetPlatformApp() const; +#elif FIREBASE_PLATFORM_IOS || FIREBASE_PLATFORM_TVOS +#ifdef __OBJC__ + /// Get the platform specific app implementation referenced by this object. + /// + /// @return Reference to the FIRApp object owned by this app. + FIRApp* GetPlatformApp() const; +#endif // __OBJC__ +#endif // FIREBASE_PLATFORM_ANDROID, FIREBASE_PLATFORM_IOS, + // FIREBASE_PLATFORM_TVOS +#endif // INTERNAL_EXPERIMENTAL + + private: + /// Construct the object. + App() + : +#if FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) + activity_(nullptr), +#endif + internal_(nullptr) { + Initialize(); + +#ifdef FIREBASE_LINUX_BUILD_CONFIG_STRING + CheckCompilerString(FIREBASE_LINUX_BUILD_CONFIG_STRING); +#endif // FIREBASE_LINUX_BUILD_CONFIG_STRING + } + + /// Initialize internal implementation + void Initialize(); + +#ifndef SWIG +// +// Unity doesn't need the JNI from here, it has its method to access JNI. +// +#if FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) + /// Android activity. + /// @note This is specific to Android. + jobject activity_; +#endif // FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) +#endif // SWIG + + /// Name of the App instance. + std::string name_; + /// Options used to create this App instance. + AppOptions options_; + /// Module initialization results. + std::map init_results_; + /// Pointer to other internal data used by this instance. + internal::AppInternal* internal_; + + /// @endcond +}; + +} // namespace firebase + +#endif // FIREBASE_APP_SRC_INCLUDE_FIREBASE_APP_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/auth.h b/packages/firebase_core/firebase_core/firebase_core/firebase/auth.h new file mode 100644 index 000000000000..408c34ea9006 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/auth.h @@ -0,0 +1,939 @@ +/* + * Copyright 2016 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_AUTH_SRC_INCLUDE_FIREBASE_AUTH_H_ +#define FIREBASE_AUTH_SRC_INCLUDE_FIREBASE_AUTH_H_ + +#include + +#include "firebase/app.h" +#include "firebase/auth/user.h" +#include "firebase/future.h" +#include "firebase/internal/common.h" + +#if !defined(DOXYGEN) +#ifndef SWIG +FIREBASE_APP_REGISTER_CALLBACKS_REFERENCE(auth) +#endif // SWIG +#endif // !defined(DOXYGEN) + +namespace firebase { + +/// @brief Firebase Authentication API. +/// +/// Firebase Authentication provides backend services to securely authenticate +/// users. It can authenticate users using passwords and federated identity +/// provider credentials, and it can integrate with a custom auth backend. +namespace auth { + +// Predeclarations. +struct AuthData; +class AuthStateListener; +class IdTokenListener; +class PhoneAuthProvider; +struct AuthCompletionHandle; +class FederatedAuthProvider; +class FederatedOAuthProvider; +struct SignInResult; + +/// @brief Firebase authentication object. +/// +/// +/// @if swig_examples +/// Firebase.Auth.FirebaseAuth is the gateway to the Firebase authentication +/// API. With it, you can reference @ref Firebase.Auth.FirebaseAuth objects to +/// manage user accounts and credentials. +/// +/// Each @ref Firebase.FirebaseApp has up to one Firebase.Auth.FirebaseAuth +/// class. You acquire the Firebase.Auth.FirebaseAuth class through the static +/// function @ref Firebase.Auth.FirebaseAuth.GetAuth. +/// +/// For example: +/// @code{.cs} +/// // Get the Auth class for your App. +/// Firebase.Auth.FirebaseAuth auth = Firebase.Auth.FirebaseAuth.GetAuth(app); +/// +/// // Request anonymous sign-in and wait until asynchronous call completes. +/// auth.SignInAnonymouslyAsync().ContinueWith((authTask) => { +/// // Print sign in results. +/// if (authTask.IsCanceled) { +/// DebugLog("Sign-in canceled."); +/// } else if (authTask.IsFaulted) { +/// DebugLog("Sign-in encountered an error."); +/// DebugLog(authTask.Exception.ToString()); +/// } else if (authTask.IsCompleted) { +/// Firebase.Auth.User user = authTask.Result; +/// DebugLog(String.Format("Signed in as {0} user.", +/// user.Anonymous ? "an anonymous" : "a non-anonymous")); +/// DebugLog("Signing out."); +/// auth.SignOut(); +/// }); +/// @endcode +/// @endif +/// +/// @if cpp_examples +/// +/// firebase::auth::Auth is the gateway to the Firebase authentication API. +/// With it, you can reference @ref firebase::auth::User objects to manage user +/// accounts and credentials. +/// +/// Each @ref firebase::App has up to one firebase::auth::Auth class. You +/// acquire the firebase::auth::Auth class through the static function +/// @ref firebase::auth::Auth::GetAuth. +/// +/// For example: +/// @code{.cpp} +/// +/// // Get the Auth class for your App. +/// firebase::auth::Auth* auth = firebase::auth::Auth::GetAuth(app); +/// +/// // Request anonymous sign-in and wait until asynchronous call completes. +/// firebase::Future sign_in_future = +/// auth->SignInAnonymously(); +/// while(sign_in_future.status() == firebase::kFutureStatusPending) { +/// // when polling, like this, make sure you service your platform's +/// // message loop +/// // see https://github.com/firebase/quickstart-cpp for a sample +/// ProcessEvents(300); +/// std::cout << "Signing in...\n"; +/// } +/// +/// const firebase::auth::AuthError error = +/// static_cast(sign_in_future.error()); +/// if (error != firebase::auth::kAuthErrorNone) { +/// std::cout << "Sign in failed with error '" +/// << sign_in_future.error_message() << "'\n"; +/// } else { +/// firebase::auth::User* user = *sign_in_future.result(); +/// // is_anonymous from Anonymous +/// std::cout << "Signed in as " +/// << (user->is_anonymous() ? "an anonymous" : "a non-anonymous") +/// << " user\n"; +/// } +/// @endcode +/// @endif +class Auth { + public: + /// @brief Results of calls @ref FetchProvidersForEmail. + /// + /// + /// @if swig_examples + /// @see FirebaseAuth.FetchProvidersForEmailAsync(). + /// @endif + /// + struct FetchProvidersResult { + /// The IDPs (identity providers) that can be used for `email`. + /// An array of length `num_providers` of null-terminated strings. + /// + /// The C# doc string is in the SWIG file because nested structs are + /// causing problems b/35780150 + /// + std::vector providers; + }; + + ~Auth(); + + /// Synchronously gets the cached current user, or nullptr if there is none. + /// @note This function may block and wait until the Auth instance finishes + /// loading the saved user's state. This should only happen for a short + /// period of time after the Auth instance is created. + /// + /// @xmlonly + /// + /// Synchronously gets the cached current user, or null if there is none. + /// @note This function may block and wait until the Auth instance finishes + /// loading the saved user's state. This should only happen for a short + /// period of time after the Auth instance is created. + /// + /// @endxmlonly + /// + User* current_user(); + + /// The current user language code. This can be set to the app’s current + /// language by calling set_language_code. The string must be a language code + /// that follows BCP 47. This will return an empty string if the app default + /// language code is being used. + std::string language_code() const; + + /// Sets the user-facing language code for auth operations that can be + /// internationalized, such as FirebaseUser.sendEmailVerification(). This + /// language code should follow the conventions defined by the IETF in BCP 47. + void set_language_code(const char* language_code); + + /// Sets the user-facing language code to be the default app language. This + /// uses a language associated with the device's locale data. On desktop + /// this will set the language code to the Firebase service's default. You + /// may subsequently customize the language code again by invoking + /// set_language_code(). + void UseAppLanguage(); + + // ----- Providers ------------------------------------------------------- + /// Asynchronously requests the IDPs (identity providers) that can be used + /// for the given email address. + /// + /// Useful for an "identifier-first" login flow. + /// + /// @if cpp_examples + /// The following sample code illustrates a possible login screen + /// that allows the user to pick an identity provider. + /// @code{.cpp} + /// // This function is called every frame to display the login screen. + /// // Returns the identity provider name, or "" if none selected. + /// const char* DisplayIdentityProviders(firebase::auth::Auth& auth, + /// const char* email) { + /// // Get results of most recent call to FetchProvidersForEmail(). + /// firebase::Future future = + /// auth.FetchProvidersForEmailLastResult(); + /// const firebase::auth::Auth::FetchProvidersResult* result = + /// future.result(); + /// + /// // Header. + /// ShowTextBox("Sign in %s", email); + /// + /// // Fetch providers from the server if we need to. + /// const bool refetch = + /// future.status() == firebase::kFutureStatusInvalid || + /// (result != nullptr && strcmp(email, result->email.c_str()) != 0); + /// if (refetch) { + /// auth.FetchProvidersForEmail(email); + /// } + /// + /// // Show a waiting icon if we're waiting for the asynchronous call to + /// // complete. + /// if (future.status() != firebase::kFutureStatusComplete) { + /// ShowImage("waiting icon"); + /// return ""; + /// } + /// + /// // Show error code if the call failed. + /// if (future.error() != firebase::auth::kAuthErrorNone) { + /// ShowTextBox("Error fetching providers: %s", future.error_message()); + /// } + /// + /// // Show a button for each provider available to this email. + /// // Return the provider for the button that's pressed. + /// for (size_t i = 0; i < result->providers.size(); ++i) { + /// const bool selected = ShowTextButton(result->providers[i].c_str()); + /// if (selected) return result->providers[i].c_str(); + /// } + /// return ""; + /// } + /// @endcode + /// @endif + Future FetchProvidersForEmail(const char* email); + + /// Get results of the most recent call to @ref FetchProvidersForEmail. + Future FetchProvidersForEmailLastResult() const; + + // ----- Sign In --------------------------------------------------------- + /// Asynchronously logs into Firebase with the given Auth token. + /// + /// An error is returned, if the token is invalid, expired or otherwise + /// not accepted by the server. + Future SignInWithCustomToken(const char* token); + + /// Get results of the most recent call to @ref SignInWithCustomToken. + Future SignInWithCustomTokenLastResult() const; + + /// Convenience method for @ref SignInAndRetrieveDataWithCredential that + /// doesn't return additional identity provider data. + Future SignInWithCredential(const Credential& credential); + + /// Get results of the most recent call to @ref SignInWithCredential. + Future SignInWithCredentialLastResult() const; + + /// Sign-in a user authenticated via a federated auth provider. + /// + /// @param[in] provider Contains information on the provider to authenticate + /// with. + /// + /// @return A Future with the result of the sign-in request. + /// + /// @note: This operation is supported only on iOS, tvOS and Android + /// platforms. On other platforms this method will return a Future with a + /// preset error code: kAuthErrorUnimplemented. + Future SignInWithProvider(FederatedAuthProvider* provider); + + /// Asynchronously logs into Firebase with the given credentials. + /// + /// For example, the credential could wrap a Facebook login access token or + /// a Twitter token/token-secret pair. + /// + /// The SignInResult contains both a reference to the User (which can be null + /// if the sign in failed), and AdditionalUserInfo, which holds details + /// specific to the Identity Provider used to sign in. + /// + /// An error is returned if the token is invalid, expired, or otherwise not + /// accepted by the server. + Future SignInAndRetrieveDataWithCredential( + const Credential& credential); + + /// Get results of the most recent call to + /// @ref SignInAndRetrieveDataWithCredential. + Future SignInAndRetrieveDataWithCredentialLastResult() const; + + /// Asynchronously creates and becomes an anonymous user. + /// If there is already an anonymous user signed in, that user will be + /// returned instead. + /// If there is any other existing user, that user will be signed out. + /// + /// + /// @if swig_examples + /// @code{.cs} + /// bool SignIn(Firebase.Auth.FirebaseAuth auth) { + /// auth.SignInAnonymouslyAsync().ContinueWith((authTask) => { + /// if (authTask.IsCanceled) { + /// DebugLog("Anonymous sign in canceled."); + /// } else if (authTask.IsFaulted) { + /// DebugLog("Anonymous sign in encountered an error."); + /// DebugLog(authTask.Exception.ToString()); + /// } else if (authTask.IsCompleted) { + /// DebugLog("Anonymous sign in successful!"); + /// } + /// }); + /// } + /// @endcode + /// @endif + /// + /// @if cpp_examples + /// The following sample code illustrates the sign-in flow that might be + /// used by a game or some other program with a regular (for example, 30Hz) + /// update loop. + /// + /// The sample calls SignIn() every frame. We don’t maintain our own + /// Futures but instead call SignInAnonymouslyLastResult() to get the Future + /// of our most recent call. + /// + /// @code{.cpp} + /// // Try to ensure that we get logged in. + /// // This function is called every frame. + /// bool SignIn(firebase::auth::Auth& auth) { + /// // Grab the result of the latest sign-in attempt. + /// firebase::Future future = + /// auth.SignInAnonymouslyLastResult(); + /// + /// // If we're in a state where we can try to sign in, do so. + /// if (future.status() == firebase::kFutureStatusInvalid || + /// (future.status() == firebase::kFutureStatusComplete && + /// future.error() != firebase::auth::kAuthErrorNone)) { + /// auth.SignInAnonymously(); + /// } + /// + /// // We're signed in if the most recent result was successful. + /// return future.status() == firebase::kFutureStatusComplete && + /// future.error() == firebase::auth::kAuthErrorNone; + /// } + /// @endcode + /// @endif + Future SignInAnonymously(); + + /// Get results of the most recent call to @ref SignInAnonymously. + Future SignInAnonymouslyLastResult() const; + + /// Signs in using provided email address and password. + /// An error is returned if the password is wrong or otherwise not accepted + /// by the server. + Future SignInWithEmailAndPassword(const char* email, + const char* password); + + /// Get results of the most recent call to @ref SignInWithEmailAndPassword. + Future SignInWithEmailAndPasswordLastResult() const; + + /// Creates, and on success, logs in a user with the given email address + /// and password. + /// + /// An error is returned when account creation is unsuccessful + /// (due to another existing account, invalid password, etc.). + Future CreateUserWithEmailAndPassword(const char* email, + const char* password); + + /// Get results of the most recent call to + /// @ref CreateUserWithEmailAndPassword. + Future CreateUserWithEmailAndPasswordLastResult() const; + + /// Removes any existing authentication credentials from this client. + /// This function always succeeds. + void SignOut(); + + // ----- Password Reset ------------------------------------------------- + /// Initiates a password reset for the given email address. + /// + /// If the email address is not registered, then the returned task has a + /// status of IsFaulted. + /// + /// + /// @if swig_examples + /// @code{.cs} + /// void ResetPassword(string email) { + /// auth.SendPasswordResetEmail(email).ContinueWith((authTask) => { + /// if (authTask.IsCanceled) { + /// DebugLog("Password reset was canceled."); + /// } else if (authTask.IsFaulted) { + /// DebugLog("Password reset encountered an error."); + /// DebugLog(authTask.Exception.ToString()); + /// } else if (authTask.IsCompleted) { + /// DebugLog("Password reset successful!"); + /// } + /// }); + /// } + /// @endcode + /// @endif + /// + /// @if cpp_examples + /// The following sample code illustrating a possible password reset flow. + /// Like in the Anonymous Sign-In example above, the ResetPasswordScreen() + /// function is called once per frame (say 30 times per second). + /// + /// No state is persisted by the caller in this example. The state of the + /// most recent calls are instead accessed through calls to functions like + /// auth.SendPasswordResetEmailLastResult(). + /// @code{.cpp} + /// const char* ImageNameForStatus(const firebase::FutureBase& future) { + /// assert(future.status() != firebase::kFutureStatusInvalid); + /// return future.status() == firebase::kFutureStatusPending + /// ? "waiting icon" + /// : future.error() == firebase::auth::kAuthErrorNone + /// ? "checkmark icon" + /// : "x mark icon"; + /// } + /// + /// // This function is called once per frame. + /// void ResetPasswordScreen(firebase::auth::Auth& auth) { + /// // Gather email address. + /// // ShowInputBox() returns a value when `enter` is pressed. + /// const std::string email = ShowInputBox("Enter e-mail"); + /// if (email != "") { + /// auth.SendPasswordResetEmail(email.c_str()); + /// } + /// + /// // Show checkmark, X-mark, or waiting icon beside the + /// // email input box, to indicate if email has been sent. + /// firebase::Future send_future = + /// auth.SendPasswordResetEmailLastResult(); + /// ShowImage(ImageNameForStatus(send_future)); + /// + /// // Display error message if the e-mail could not be sent. + /// if (send_future.status() == firebase::kFutureStatusComplete && + /// send_future.error() != firebase::auth::kAuthErrorNone) { + /// ShowTextBox(send_future.error_message()); + /// } + /// } + /// @endcode + /// @endif + Future SendPasswordResetEmail(const char* email); + + /// Get results of the most recent call to @ref SendPasswordResetEmail. + Future SendPasswordResetEmailLastResult() const; + +#ifndef SWIG + /// @brief Registers a listener to changes in the authentication state. + /// + /// There can be more than one listener registered at the same time. + /// The listeners are called asynchronously, possibly on a different thread. + /// + /// Authentication state changes are: + /// - Right after the listener has been registered + /// - When a user signs in + /// - When the current user signs out + /// - When the current user changes + /// + /// It is a recommended practice to always listen to sign-out events, as you + /// may want to prompt the user to sign in again and maybe restrict the + /// information or actions they have access to. + /// + /// Use RemoveAuthStateListener to unregister a listener. + /// + /// @note The caller owns `listener` and is responsible for destroying it. + /// When `listener` is destroyed, or when @ref Auth is destroyed, + /// RemoveAuthStateListener is called automatically. + void AddAuthStateListener(AuthStateListener* listener); + + /// @brief Unregisters a listener of authentication changes. + /// + /// Listener must previously been added with AddAuthStateListener. + /// + /// Note that listeners unregister themselves automatically when they + /// are destroyed, and the Auth class unregisters its listeners when the + /// Auth class itself is destroyed, so this function does not normally need + /// to be called explicitly. + void RemoveAuthStateListener(AuthStateListener* listener); + + /// @brief Registers a listener to changes in the ID token state. + /// + /// There can be more than one listener registered at the same time. + /// The listeners are called asynchronously, possibly on a different thread. + /// + /// Authentication state changes are: + /// - Right after the listener has been registered + /// - When a user signs in + /// - When the current user signs out + /// - When the current user changes + /// - When there is a change in the current user's token + /// + /// Use RemoveIdTokenListener to unregister a listener. + /// + /// @note The caller owns `listener` and is responsible for destroying it. + /// When `listener` is destroyed, or when @ref Auth is destroyed, + /// RemoveIdTokenListener is called automatically. + void AddIdTokenListener(IdTokenListener* listener); + + /// @brief Unregisters a listener of ID token changes. + /// + /// Listener must previously been added with AddIdTokenListener. + /// + /// Note that listeners unregister themselves automatically when they + /// are destroyed, and the Auth class unregisters its listeners when the + /// Auth class itself is destroyed, so this function does not normally need + /// to be called explicitly. + void RemoveIdTokenListener(IdTokenListener* listener); +#endif // not SWIG + + /// Gets the App this auth object is connected to. + App& app(); + + /// Returns the Auth object for an App. Creates the Auth if required. + /// + /// To get the Auth object for the default app, use, + /// GetAuth(GetDefaultFirebaseApp()); + /// + /// If the library Auth fails to initialize, init_result_out will be + /// written with the result status (if a pointer is given). + /// + /// @param[in] app The App to use for the Auth object. + /// @param[out] init_result_out Optional: If provided, write the init result + /// here. Will be set to kInitResultSuccess if initialization succeeded, or + /// kInitResultFailedMissingDependency on Android if Google Play services is + /// not available on the current device. + static Auth* GetAuth(App* app, InitResult* init_result_out = nullptr); + + private: + /// @cond FIREBASE_APP_INTERNAL + friend class ::firebase::App; + friend class ::firebase::auth::PhoneAuthProvider; + friend class IdTokenRefreshListener; + friend class IdTokenRefreshThread; + friend class UserDataPersist; + friend class UserDesktopTest; + friend class AuthDesktopTest; + + friend void EnableTokenAutoRefresh(AuthData* authData); + friend void DisableTokenAutoRefresh(AuthData* authData); + friend void ResetTokenRefreshCounter(AuthData* authData); + friend void LogHeartbeat(Auth* auth); + /// @endcond + + // Find Auth instance using App. Return null if the instance does not exist. + static Auth* FindAuth(App* app); + + // Provides access to the auth token for the current user. Returns the + // current user's auth token, or an empty string, if there isn't one. + // Note that this can potentially return an expired token from the cache. + static bool GetAuthTokenForRegistry(App* app, void* /*unused*/, void* out); + + // Provides asynchronous access to the auth token for the current user. Allow + // the caller to force-refresh the token. Even without force-refresh, this + // ensure the future contain a fresh current user's auth token. This function + // returns invalid future if user data is not available. + static bool GetAuthTokenAsyncForRegistry(App* app, void* force_refresh, + void* out_future); + + // Provides access to the current user's uid, equivalent to calling + // this->current_user()->uid(). Returns the current user's uid or an empty + // string, if there isn't one. The out pointer is expected to point to an + // instance of std::string. + static bool GetCurrentUserUidForRegistry(App* app, void* /*unused*/, + void* out); + + // Starts and stops a thread to ensure that the cached auth token is never + // kept long enough for it to expire. Refcounted, so multiple classes can + // register this without causing problems. + static bool StartTokenRefreshThreadForRegistry(App* app, void* /*unused*/, + void* /*unused*/); + static bool StopTokenRefreshThreadForRegistry(App* app, void* /*unused*/, + void* /*unused*/); + + // Adds an indirect auth state listener implemented as a callback and a + // context object. + // + // @param callback a function pointer that takes a single void* argument and + // returns void (i.e. it has type void (*)(void*)). + // @param context a pointer to an arbitrary object that Auth will pass to + // the callback when the auth state changes. + static bool AddAuthStateListenerForRegistry(App* app, void* callback, + void* context); + + // Removes the indirect auth state listener that was added with the same + // arguments. + static bool RemoveAuthStateListenerForRegistry(App* app, void* callback, + void* context); + + // Init and Destroy the platform specific auth data. + void InitPlatformAuth(AuthData* const auth_data); + void DestroyPlatformAuth(AuthData* const auth_data); + + // Call GetAuth() to create an Auth object. + // Constructors and destructors don't make any external calls. + // They just initialize and deinitialize internal variables. + Auth(App* app, void* auth_impl); + + // Delete the internal AuthData object. + void DeleteInternal(); + + // This class uses the pimpl mechanism to avoid exposing platform-dependent + // implementation. + AuthData* auth_data_; +}; + +#ifndef SWIG +/// @brief Listener called when there is a change in the authentication state. +/// +/// Override base class method to handle authentication state changes. +/// Methods are invoked asynchronously and may be invoked on other threads. +class AuthStateListener { + public: + /// @note: Destruction of the listener automatically calls + /// RemoveAuthStateListener() from the Auths this listener is registered with, + /// if those Auths have not yet been destroyed. + virtual ~AuthStateListener(); + + /// Called when the authentication state of `auth` changes. + /// - Right after the listener has been registered + /// - When a user is signed in + /// - When the current user is signed out + /// - When the current user changes + /// + /// @param[in] auth Disambiguates which @ref Auth instance the event + /// corresponds to, in the case where you are using more than one at the same + /// time. + virtual void OnAuthStateChanged(Auth* auth) = 0; + + private: + /// @cond FIREBASE_APP_INTERNAL + friend class Auth; + /// @endcond + + /// The Auths with which this listener has been registered. + std::vector auths_; +}; +#endif // not SWIG + +#ifndef SWIG +/// @brief Listener called when there is a change in the ID token. +/// +/// Override base class method to handle ID token changes. +/// Methods are invoked asynchronously and may be invoked on other threads. +class IdTokenListener { + public: + /// @note: Destruction of the listener automatically calls + /// RemoveIdTokenListener() from the Auths this listener is registered with, + /// if those Auths have not yet been destroyed. + virtual ~IdTokenListener(); + + /// Called when there is a change in the current user's token. + /// - Right after the listener has been registered + /// - When a user signs in + /// - When the current user signs out + /// - When the current user changes + /// - When there is a change in the current user's token + /// + /// @param[in] auth Disambiguates which @ref Auth instance the event + /// corresponds to, in the case where you are using more than one at the same + /// time. + virtual void OnIdTokenChanged(Auth* auth) = 0; + + private: + /// @cond FIREBASE_APP_INTERNAL + friend class Auth; + /// @endcond + + /// The Auths with which this listener has been registered. + std::vector auths_; +}; + +#endif // not SWIG + +/// @brief Used to authenticate with Federated Auth Providers. +/// +/// The federated auth provider implementation may facilitate multiple provider +/// types in the future, with support for OAuth to start. +class FederatedAuthProvider { + public: +#ifdef INTERNAL_EXPERIMENTAL +#ifndef SWIG + /// @brief Contains resulting information of a user authenticated by a + /// Federated Auth Provider. This information will be used by the internal + /// implementation to construct a corresponding User object. + struct AuthenticatedUserData { + /// The unique ID identifies the IdP account. + const char* uid; + + /// [opt] The email of the account. + const char* email; + + /// Whether the sign-in email is verified. + bool is_email_verified; + + /// [opt] The display name for the account. + const char* display_name; + + /// [opt] The username for the account. + const char* user_name; + + /// [opt] The photo Url for the account, if one exists. + const char* photo_url; + + /// The linked provider ID (e.g. "google.com" for the Google provider). + const char* provider_id; + + /// A Firebase Auth ID token for the authenticated user. + const char* access_token; + + /// A Firebase Auth refresh token for the authenticated user. + const char* refresh_token; + + /// [opt] IdP user profile data corresponding to the provided credential. + std::map raw_user_info; + + /// The number of seconds in which the ID token expires. + uint64_t token_expires_in_seconds; + }; + + /// @brief Handlers for client applications to facilitate federated auth + /// requests on non-mobile systems. + template + class Handler { + public: + virtual ~Handler() {} + + /// @brief Application sign-in handler. + /// + /// The application must implement this method to handle federated auth user + /// sign-in requests on non-mobile systems. + /// + /// @param[in] provider_data Contains information on the provider to + /// authenticate with. + /// @param[in] completion_handle Internal data pertaining to this operation + /// which must be passed to SignInComplete once the handler has completed + /// the sign in operation. + /// + /// @see Auth#SignInWithProvider + /// @see SignInComplete + virtual void OnSignIn(const T& provider_data, + AuthCompletionHandle* completion_handle) = 0; + + /// Completion for OnSignIn events. + /// + /// Invoke this method once the corresponding OnSignIn has been fulfilled. + /// This method will trigger the associated Future previously + /// returned from the Auth::SignInWithProvider method. + /// + /// @param[in] completion_handle The handle provided to the application's + /// FederatedAuthProvider::Handler::OnSignIn method. + /// @param[in] user_data The application's resulting Firebase user + /// values following the authorization request. + /// @param[in] auth_error The enumerated status code of the authorization + /// request. + /// @param[in] error_message An optional error message to be set in the + /// Future. + /// + /// @see OnSignIn + /// @see Auth::SignInWithProvider + void SignInComplete(AuthCompletionHandle* completion_handle, + const AuthenticatedUserData& user_data, + AuthError auth_error, const char* error_message); + + /// @brief Application user account link handler. + /// + /// The application must implement this method to handle federated auth user + /// link requests on non-mobile systems. + /// + /// @param[in] provider_data Contains information on the provider to + /// authenticate with. + /// @param[in] completion_handle Internal data pertaining to this operation + /// which must be passed to LinkComplete once the handler has completed the + /// user link operation. + /// + /// @see User#LinkWithProvider + virtual void OnLink(const T& provider_data, + AuthCompletionHandle* completion_handle) = 0; + + /// Completion for non-mobile user authorization handlers. + /// + /// Invoke this method once the OnLine process has been fulfilled. This + /// method will trigger the associated Future previously + /// returned from an invocation of User::LinkWithProvider. + /// + /// @param[in] completion_handle The handle provided to the + /// application's FederatedAuthProvider::Handler::OnLink method. + /// @param[in] user_data The application's resulting Firebase user + /// values following the user link request. + /// @param[in] auth_error The enumerated status code of the user link + /// request. + /// @param[in] error_message An optional error message to be set in the + /// Future. + /// + /// @see OnLink + /// @see User#LinkWithProvider + void LinkComplete(AuthCompletionHandle* completion_handle, + const AuthenticatedUserData& user_data, + AuthError auth_error, const char* error_message); + + /// @brief Application user re-authentication handler. + /// + /// The application must implement this method to handle federated auth user + /// re-authentication requests on non-mobile systems. + /// + /// @param[in] provider_data Contains information on the provider to + /// authenticate with. + /// @param[in] completion_handle Internal data pertaining to this operation + /// which must be passed to ReauthenticateComplete once the handler has + /// completed the reauthentication operation. + /// + /// @see User#ReauthenticateWithProviderComplete + virtual void OnReauthenticate(const T& provider_data, + AuthCompletionHandle* completion_handle) = 0; + + /// Completion for non-mobile user authorization handlers. + /// + /// Invoke this method once the OnReauthenticate process has been + /// fulfilled. This method will trigger the associated Future + /// previously returned from an invocation of + /// User::ReauthenticateWithProvider. + /// + /// @param[in] completion_handle The handle provided to the application's + /// FederatedAuthProvider::Handler::OnReauthenticate method. + /// @param[in] user_data The application's resulting Firebase user + /// values following the user re-authentication request. + /// @param[in] auth_error The enumerated status code of the reauthentication + /// request. + /// @param[in] error_message An optional error message to be set in the + /// Future. + /// + /// @see OnReauthenticate + /// @see User#ReuthenticateWithProvider + void ReauthenticateComplete(AuthCompletionHandle* completion_handle, + const AuthenticatedUserData& user_data, + AuthError auth_error, + const char* error_message); + }; +#endif // not SWIG +#endif // INTERNAL_EXPERIMENTAL + + FederatedAuthProvider() {} + virtual ~FederatedAuthProvider() {} + + private: + friend class ::firebase::auth::Auth; + friend class ::firebase::auth::User; + virtual Future SignIn(AuthData* auth_data) = 0; + virtual Future Link(AuthData* auth_data) = 0; + virtual Future Reauthenticate(AuthData* auth_data) = 0; +}; + +/// @brief Authenticates with Federated OAuth Providers via the +/// firebase::auth::Auth and firebase::auth::User classes. +/// +/// Once configured with a provider id, and with OAuth scope and OAuth custom +/// parameters via an FedeartedOAuthProviderData structure, an object of +/// this class may be used via Auth::SignInWithProvider to sign-in users, or via +/// User::LinkWithProvider and User::ReauthenticateWithProvider for cross +/// account linking and user reauthentication, respectively. +class FederatedOAuthProvider : public FederatedAuthProvider { + public: +#ifdef INTERNAL_EXPERIMENTAL +#ifndef SWIG + /// @brief A FederatedAuthProvider typed specifically for OAuth Authentication + /// handling. + /// + /// To be used on non-mobile environments for custom OAuth implementations and + /// UI flows. + typedef FederatedAuthProvider::Handler + AuthHandler; +#endif // !SWIG +#endif // INTERNAL_EXPERIMENTAL + + /// Constructs an unconfigured provider. + FederatedOAuthProvider(); + + /// Constructs a FederatedOAuthProvider preconfigured with provider data. + /// + /// @param[in] provider_data Contains the federated provider id and OAuth + /// scopes and OAuth custom parameters required for user authentication and + /// user linking. + explicit FederatedOAuthProvider( + const FederatedOAuthProviderData& provider_data); + +#ifdef INTERNAL_EXPERIMENTAL +#ifndef SWIG + /// @brief Constructs a provider with the required information to authenticate + /// using an OAuth Provider. + /// + /// An AuthHandler is required on desktop platforms to facilitate custom + /// implementations of OAuth authentication. The AuthHandler must outlive the + /// instance of this OAuthProvider on desktop systems and is ignored on iOS, + /// tvOS, and Android platforms. + /// + /// @param[in] provider_data Contains information on the provider to + /// authenticate with. + /// @param[in] handler An FederatedOAuthProviderData typed + /// FederatedAuthProvider::Handler which be invoked on non-mobile systems + /// to handle authentication requests. + FederatedOAuthProvider(const FederatedOAuthProviderData& provider_data, + AuthHandler* handler); +#endif // !SWIG +#endif // INTERNAL_EXPERIMENTAL + + ~FederatedOAuthProvider() override; + + /// @brief Configures the provider with OAuth provider information. + /// + /// @param[in] provider_data Contains the federated provider id and OAuth + /// scopes and OAuth custom parameters required for user authentication and + /// user linking. + void SetProviderData(const FederatedOAuthProviderData& provider_data); + +#ifdef INTERNAL_EXPERIMENTAL +#ifndef SWIG + /// @brief Configures the use of an AuthHandler for non-mobile systems. + /// + /// The existence of a handler is required for non-mobile systems, and is + /// ignored on iOS, tvOS and Android platforms. + /// + /// @param[in] handler An FederatedOAuthProviderData typed + /// FederatedAuthProvider::Handler which be invoked on non-mobile systems + /// to handle authentication requests. The handler must outlive the instance + /// of this FederatedOAuthProvider. + void SetAuthHandler(AuthHandler* handler); +#endif // !SWIG +#endif // INTERNAL_EXPERIMENTAL + + private: + friend class ::firebase::auth::Auth; + + Future SignIn(AuthData* auth_data) override; + Future Link(AuthData* auth_data) override; + Future Reauthenticate(AuthData* auth_data) override; + + FederatedOAuthProviderData provider_data_; +#ifdef INTERNAL_EXPERIMENTAL + AuthHandler* handler_; +#endif // INTERNAL_EXPERIMENTAL +}; + +} // namespace auth +} // namespace firebase + +#endif // FIREBASE_AUTH_SRC_INCLUDE_FIREBASE_AUTH_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/auth/credential.h b/packages/firebase_core/firebase_core/firebase_core/firebase/auth/credential.h new file mode 100644 index 000000000000..a179d199b67a --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/auth/credential.h @@ -0,0 +1,633 @@ +/* + * Copyright 2016 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_AUTH_SRC_INCLUDE_FIREBASE_AUTH_CREDENTIAL_H_ +#define FIREBASE_AUTH_SRC_INCLUDE_FIREBASE_AUTH_CREDENTIAL_H_ + +#include + +#include + +#include "firebase/auth/types.h" +#include "firebase/internal/common.h" + +namespace firebase { + +// Predeclarations. +class App; + +/// @cond FIREBASE_APP_INTERNAL +template +class Future; +/// @endcond + +namespace auth { + +// Predeclarations. +class Auth; +class User; + +// Opaque internal types. +struct AuthData; +class ForceResendingTokenData; +struct PhoneAuthProviderData; +struct PhoneListenerData; + +/// @brief Authentication credentials for an authentication provider. +/// +/// An authentication provider is a service that allows you to authenticate +/// a user. Firebase provides email/password authentication, but there are also +/// external authentication providers such as Facebook. +class Credential { +#ifndef SWIG + /// @cond FIREBASE_APP_INTERNAL + friend class EmailAuthProvider; + friend class FacebookAuthProvider; + friend class GameCenterAuthProvider; + friend class GitHubAuthProvider; + friend class GoogleAuthProvider; + friend class JniAuthPhoneListener; + friend class MicrosoftAuthProvider; + friend class OAuthProvider; + friend class PhoneAuthProvider; + friend class PlayGamesAuthProvider; + friend class TwitterAuthProvider; + friend class YahooAuthProvider; + friend class ServiceUpdatedCredentialProvider; + /// @endcond +#endif // !SWIG + + private: + /// Should only be created by `Provider` classes. + /// + /// @see EmailAuthProvider::GetCredential() + /// @see FacebookAuthProvider::GetCredential() + /// @see GoogleAuthProvider::GetCredential() + explicit Credential(void* impl) : impl_(impl), error_code_(kAuthErrorNone) {} + + public: + Credential() : impl_(nullptr), error_code_(kAuthErrorNone) {} + ~Credential(); + + /// Copy constructor. + Credential(const Credential& rhs); + + /// Copy a Credential. + Credential& operator=(const Credential& rhs); + + /// Gets the name of the Identification Provider (IDP) for the credential. + /// + /// + /// @xmlonly + /// + /// Gets the name of the Identification Provider (IDP) for the credential. + /// + /// @endxmlonly + /// + std::string provider() const; + + /// Get whether this credential is valid. A credential can be + /// invalid in an error condition, e.g. empty username/password. + /// + /// @returns True if the credential is valid, false otherwise. + bool is_valid() const; + + protected: + /// @cond FIREBASE_APP_INTERNAL + friend class Auth; + friend class User; + + /// Platform-specific implementation. + /// For example, FIRAuthCredential* on iOS. + void* impl_; + + // If not kAuthErrorNone, then use this error code and string to override + // whatever error we would normally return when trying to sign-in with this + // credential. + AuthError error_code_; + std::string error_message_; + /// @endcond +}; + +/// @brief Use email and password to authenticate. +/// +/// Allows developers to use the email and password credentials as they could +/// other auth providers. For example, this can be used to change passwords, +/// log in, etc. +class EmailAuthProvider { + public: + /// Generate a credential from the given email and password. + /// + /// @param email E-mail to generate the credential from. + /// @param password Password to use for the new credential. + /// + /// @returns New Credential. + static Credential GetCredential(const char* email, const char* password); + + /// The string used to identify this provider. + static const char* const kProviderId; +}; + +/// @brief Use an access token provided by Facebook to authenticate. +class FacebookAuthProvider { + public: + /// Generate a credential from the given Facebook token. + /// + /// @param access_token Facebook token to generate the credential from. + /// + /// @returns New Credential. + static Credential GetCredential(const char* access_token); + + /// The string used to identify this provider. + static const char* const kProviderId; +}; + +/// @brief GameCenter (Apple) auth provider +class GameCenterAuthProvider { + public: + /// Generate a credential from GameCenter for the current user. + /// + /// @return a Future that will be fulfilled with the resulting credential. + static Future GetCredential(); + + /// Get the result of the most recent GetCredential() call. + /// + /// @return an object which can be used to retrieve the Credential. + static Future GetCredentialLastResult(); + + /// Tests to see if the current user is signed in to GameCenter. + /// + /// @return true if the user is signed in, false otherwise. + static bool IsPlayerAuthenticated(); + + /// The string used to identify this provider. + static const char* const kProviderId; +}; + +/// @brief Use an access token provided by GitHub to authenticate. +class GitHubAuthProvider { + public: + /// Generate a credential from the given GitHub token. + /// + /// @param token The GitHub OAuth access token. + /// + /// @returns New Credential. + static Credential GetCredential(const char* token); + + /// The string used to identify this provider. + static const char* const kProviderId; +}; + +/// @brief Use an ID token and access token provided by Google to authenticate. +class GoogleAuthProvider { + public: + /// Generate a credential from the given Google ID token and/or access token. + /// + /// @param id_token Google Sign-In ID token. + /// @param access_token Google Sign-In access token. + /// + /// @returns New Credential. + static Credential GetCredential(const char* id_token, + const char* access_token); + + /// The string used to identify this provider. + static const char* const kProviderId; +}; + +/// @brief Use an access token provided by Microsoft to authenticate. +class MicrosoftAuthProvider { + public: + /// The string used to identify this provider. + static const char* const kProviderId; +}; + +/// @brief OAuth2.0+UserInfo auth provider (OIDC compliant and non-compliant). +class OAuthProvider { + public: + /// Generate a credential for an OAuth2 provider. + /// + /// @param provider_id Name of the OAuth2 provider + /// TODO(jsanmiya) add examples. + /// @param id_token The authentication token (OIDC only). + /// @param access_token TODO(jsanmiya) add explanation (currently missing + /// from Android and iOS implementations). + static Credential GetCredential(const char* provider_id, const char* id_token, + const char* access_token); + + /// Generate a credential for an OAuth2 provider. + /// + /// @param provider_id Name of the OAuth2 provider. + /// @param id_token The authentication token (OIDC only). + /// @param raw_nonce The raw nonce associated with the Auth credential being + /// created. + /// @param access_token The access token associated with the Auth credential + /// to be created, if available. This value may be null. + static Credential GetCredential(const char* provider_id, const char* id_token, + const char* raw_nonce, + const char* access_token); +}; + +/// @brief Use phone number text messages to authenticate. +/// +/// Allows developers to use the phone number and SMS verification codes +/// to authenticate a user on a mobile device. +/// +/// This class is not supported on tvOS and Desktop platforms. +/// +/// The verification flow results in a Credential that can be used to, +/// * Sign in to an existing phone number account/sign up with a new +/// phone number +/// * Link a phone number to a current user. This provider will be added to +/// the user. +/// * Update a phone number on an existing user. +/// * Re-authenticate an existing user. This may be needed when a sensitive +/// operation requires the user to be recently logged in. +/// +/// Possible verification flows: +/// (1) User manually enters verification code. +/// @if cpp_examples +/// - App calls @ref VerifyPhoneNumber. +/// - Web verification page is displayed to user where they may need to +/// solve a CAPTCHA. [iOS only]. +/// - Auth server sends the verification code via SMS to the provided +/// phone number. App receives verification id via Listener::OnCodeSent(). +/// - User receives SMS and enters verification code in app's GUI. +/// - App uses user's verification code to call +/// @ref PhoneAuthProvider::GetCredential. +/// @endif +/// +/// @if swig_examples +/// - App calls @ref VerifyPhoneNumber. +/// - Web verification page is displayed to user where they may need to +/// solve a CAPTCHA. [iOS only]. +/// - Auth server sends the verification code via SMS to the provided +/// phone number. App receives verification id via @ref CodeSent. +/// - User receives SMS and enters verification code in app's GUI. +/// - App uses user's verification code to call +/// @ref PhoneAuthProvider::GetCredential. +/// @endif +/// +/// +/// (2) SMS is automatically retrieved (Android only). +/// - App calls @ref VerifyPhoneNumber with `timeout_ms` > 0. +/// - Auth server sends the verification code via SMS to the provided +/// phone number. +/// - SMS arrives and is automatically retrieved by the operating system. +/// Credential is automatically created and passed to the app via +/// @if cpp_examples +/// Listener::OnVerificationCompleted(). +/// @endif +/// +/// @if swig_examples +/// @ref VerificationCompleted. +/// @endif +/// +/// +/// (3) Phone number is instantly verified (Android only). +/// - App calls @ref VerifyPhoneNumber. +/// - The operating system validates the phone number without having to +/// send an SMS. Credential is automatically created and passed to +/// the app via +/// @if cpp_examples +/// Listener::OnVerificationCompleted(). +/// @endif +/// +/// @if swig_examples +/// @ref VerificationCompleted. +/// @endif +/// +/// +/// @if cpp_examples +/// All three flows can be handled with the example code below. +/// The flow is complete when PhoneVerifier::credential() returns non-NULL. +/// +/// @code{.cpp} +/// class PhoneVerifier : public PhoneAuthProvider::Listener { +/// public: +/// PhoneVerifier(const char* phone_number, +/// PhoneAuthProvider* phone_auth_provider) +/// : display_message_("Sending SMS with verification code"), +/// display_verification_code_input_box_(false), +/// display_resend_sms_button_(false), +/// phone_auth_provider_(phone_auth_provider), +/// phone_number_(phone_number) { +/// SendSms(); +/// } +/// +/// ~PhoneVerifier() override {} +/// +/// void OnVerificationCompleted(Credential credential) override { +/// // Grab `mutex_` for the scope of `lock`. Callbacks can be called on +/// // other threads, so this mutex ensures data access is atomic. +/// MutexLock lock(mutex_); +/// credential_ = credential; +/// } +/// +/// void OnVerificationFailed(const std::string& error) override { +/// MutexLock lock(mutex_); +/// display_message_ = "Verification failed with error: " + error; +/// } +/// +/// void OnCodeSent(const std::string& verification_id, +/// const PhoneAuthProvider::ForceResendingToken& +/// force_resending_token) override { +/// MutexLock lock(mutex_); +/// verification_id_ = verification_id; +/// force_resending_token_ = force_resending_token; +/// +/// display_verification_code_input_box_ = true; +/// display_message_ = "Waiting for SMS"; +/// } +/// +/// void OnCodeAutoRetrievalTimeOut( +/// const std::string& verification_id) override { +/// MutexLock lock(mutex_); +/// display_resend_sms_button_ = true; +/// } +/// +/// // Draw the verification GUI on screen and process input events. +/// void Draw() { +/// MutexLock lock(mutex_); +/// +/// // Draw an informative message describing what's currently happening. +/// ShowTextBox(display_message_.c_str()); +/// +/// // Once the time out expires, display a button to resend the SMS. +/// // If the button is pressed, call VerifyPhoneNumber again using the +/// // force_resending_token_. +/// if (display_resend_sms_button_ && !verification_id_.empty()) { +/// const bool resend_sms = ShowTextButton("Resend SMS"); +/// if (resend_sms) { +/// SendSms(); +/// } +/// } +/// +/// // Once the SMS has been sent, allow the user to enter the SMS +/// // verification code into a text box. When the user has completed +/// // entering it, call GetCredential() to complete the flow. +/// if (display_verification_code_input_box_) { +/// const std::string verification_code = +/// ShowInputBox("Verification code"); +/// if (!verification_code.empty()) { +/// credential_ = phone_auth_provider_->GetCredential( +/// verification_id_.c_str(), verification_code.c_str()); +/// } +/// } +/// } +/// +/// // The phone number verification flow is complete when this returns +/// // non-NULL. +/// Credential* credential() { +/// MutexLock lock(mutex_); +/// return credential_.is_valid() ? &credential_ : nullptr; +/// } +/// +/// private: +/// void SendSms() { +/// static const uint32_t kAutoVerifyTimeOut = 2000; +/// MutexLock lock(mutex_); +/// phone_auth_provider_->VerifyPhoneNumber( +/// phone_number_.c_str(), kAutoVerifyTimeOut, &force_resending_token_, +/// this); +/// display_resend_sms_button_ = false; +/// } +/// +/// // GUI-related variables. +/// std::string display_message_; +/// bool display_verification_code_input_box_; +/// bool display_resend_sms_button_; +/// +/// // Phone flow related variables. +/// PhoneAuthProvider* phone_auth_provider_; +/// std::string phone_number_; +/// std::string verification_id_; +/// PhoneAuthProvider::ForceResendingToken force_resending_token_; +/// Credential credential_; +/// +/// // Callbacks can be called on other threads, so guard them with a mutex. +/// Mutex mutex_; +/// }; +/// @endcode +/// @endif +class PhoneAuthProvider { + public: + /// @brief Token to maintain current phone number verification session. + /// Acquired via @ref Listener::OnCodeSent. Used in @ref VerifyPhoneNumber. + class ForceResendingToken { + public: + /// This token will be invalid until it is assigned a value sent via + /// @ref Listener::OnCodeSent. It can still be passed into + /// @ref VerifyPhoneNumber, but it will be ignored. + ForceResendingToken(); + + /// Make `this` token refer to the same phone session as `rhs`. + ForceResendingToken(const ForceResendingToken& rhs); + + /// Releases internal resources when destructing. + ~ForceResendingToken(); + + /// Make `this` token refer to the same phone session as `rhs`. + ForceResendingToken& operator=(const ForceResendingToken& rhs); + + /// Return true if `rhs` is refers to the same phone number session as + /// `this`. + bool operator==(const ForceResendingToken& rhs) const; + + /// Return true if `rhs` is refers to a different phone number session as + /// `this`. + bool operator!=(const ForceResendingToken& rhs) const; + + private: + friend class JniAuthPhoneListener; + friend class PhoneAuthProvider; + ForceResendingTokenData* data_; + }; + + /// @brief Receive callbacks from @ref VerifyPhoneNumber events. + /// + /// Please see @ref PhoneAuthProvider for a sample implementation. + class Listener { + public: + Listener(); + virtual ~Listener(); + + /// @brief Phone number auto-verification succeeded. + /// + /// Called when, + /// - auto-sms-retrieval has succeeded--flow (2) in @ref PhoneAuthProvider + /// - instant validation has succeeded--flow (3) in @ref PhoneAuthProvider + /// + /// @note This callback is never called on iOS, since iOS does not have + /// auto-validation. It is always called immediately in the stub desktop + /// implementation, however, since it fakes immediate success. + /// + /// @param[in] credential The completed credential from the phone number + /// verification flow. + virtual void OnVerificationCompleted(Credential credential) = 0; + + /// @brief Phone number verification failed with an error. + /// + /// Called when and error occurred doing phone number authentication. + /// For example, + /// - quota exceeded + /// - unknown phone number format + /// + /// @param[in] error A description of the failure. + virtual void OnVerificationFailed(const std::string& error) = 0; + + /// @brief SMS message with verification code sent to phone number. + /// + /// Called immediately after Auth server sends a verification SMS. + /// Once receiving this, you can allow users to manually input the + /// verification code (even if you're also performing auto-verification). + /// For user manual input case, get the SMS verification code from the user + /// and then call @ref GetCredential with the user's code. + /// + /// @param[in] verification_id Pass to @ref GetCredential along with the + /// user-input verification code to complete the phone number verification + /// flow. + /// @param[in] force_resending_token If the user requests that another SMS + /// message be sent, use this when you recall @ref VerifyPhoneNumber. + virtual void OnCodeSent(const std::string& verification_id, + const ForceResendingToken& force_resending_token); + + /// @brief The timeout specified in @ref VerifyPhoneNumber has expired. + /// + /// Called once `auto_verify_time_out_ms` has passed. + /// If using auto SMS retrieval, you can choose to block the UI (do not + /// allow manual input of the verification code) until timeout is hit. + /// + /// @note This callback is called immediately on iOS, since iOS does not + /// have auto-validation. + /// + /// @param[in] verification_id Identify the transaction that has timed out. + virtual void OnCodeAutoRetrievalTimeOut(const std::string& verification_id); + + private: + friend class PhoneAuthProvider; + + /// Back-pointer to the data of the PhoneAuthProvider that + /// @ref VerifyPhoneNumber was called with. Used internally. + PhoneListenerData* data_; + }; + + /// Maximum value of `auto_verify_time_out_ms` in @ref VerifyPhoneNumber. + /// Larger values will be clamped. + /// + /// @deprecated This value is no longer used to clamp + /// `auto_verify_time_out_ms` in VerifyPhoneNumber. The range is + /// determined by the underlying SDK, ex. PhoneAuthOptions.Build + /// in Android SDK + static const uint32_t kMaxTimeoutMs; + + /// Start the phone number authentication operation. + /// + /// @param[in] phone_number The phone number identifier supplied by the user. + /// Its format is normalized on the server, so it can be in any format + /// here. + /// @param[in] auto_verify_time_out_ms The time out for SMS auto retrieval, in + /// miliseconds. Currently SMS auto retrieval is only supported on Android. + /// If 0, do not do SMS auto retrieval. + /// If positive, try to auto-retrieve the SMS verification code. + /// When the time out is exceeded, listener->OnCodeAutoRetrievalTimeOut() + /// is called. + /// @param[in] force_resending_token If NULL, assume this is a new phone + /// number to verify. If not-NULL, bypass the verification session deduping + /// and force resending a new SMS. + /// This token is received in @ref Listener::OnCodeSent. + /// This should only be used when the user presses a Resend SMS button. + /// @param[in,out] listener Class that receives notification whenever an SMS + /// verification event occurs. See sample code at top of class. + void VerifyPhoneNumber(const char* phone_number, + uint32_t auto_verify_time_out_ms, + const ForceResendingToken* force_resending_token, + Listener* listener); + + /// Generate a credential for the given phone number. + /// + /// @param[in] verification_id The id returned when sending the verification + /// code. Sent to the caller via @ref Listener::OnCodeSent. + /// @param[in] verification_code The verification code supplied by the user, + /// most likely by a GUI where the user manually enters the code + /// received in the SMS sent by @ref VerifyPhoneNumber. + /// + /// @returns New Credential. + Credential GetCredential(const char* verification_id, + const char* verification_code); + + /// Return the PhoneAuthProvider for the specified `auth`. + /// + /// @param[in] auth The Auth session for which we want to get a + /// PhoneAuthProvider. + static PhoneAuthProvider& GetInstance(Auth* auth); + + /// The string used to identify this provider. + static const char* const kProviderId; + + private: + friend struct AuthData; + friend class JniAuthPhoneListener; + + // Use @ref GetInstance to access the PhoneAuthProvider. + PhoneAuthProvider(); + + // The PhoneAuthProvider is owned by the Auth class. + ~PhoneAuthProvider(); + + PhoneAuthProviderData* data_; +}; + +/// @brief Use a server auth code provided by Google Play Games to authenticate. +class PlayGamesAuthProvider { + public: + /// Generate a credential from the given Server Auth Code. + /// + /// @param server_auth_code Play Games Sign in Server Auth Code. + /// + /// @return New Credential. + static Credential GetCredential(const char* server_auth_code); + + /// The string used to identify this provider. + static const char* const kProviderId; +}; + +/// @brief Use a token and secret provided by Twitter to authenticate. +class TwitterAuthProvider { + public: + /// Generate a credential from the given Twitter token and password. + /// + /// @param token The Twitter OAuth token. + /// @param secret The Twitter OAuth secret. + /// + /// @return New Credential. + static Credential GetCredential(const char* token, const char* secret); + + /// The string used to identify this provider. + static const char* const kProviderId; +}; + +/// @brief Use an access token provided by Yahoo to authenticate. +class YahooAuthProvider { + public: + /// The string used to identify this provider. + static const char* const kProviderId; +}; + +} // namespace auth +} // namespace firebase + +#endif // FIREBASE_AUTH_SRC_INCLUDE_FIREBASE_AUTH_CREDENTIAL_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/auth/types.h b/packages/firebase_core/firebase_core/firebase_core/firebase/auth/types.h new file mode 100644 index 000000000000..3f141ad3692c --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/auth/types.h @@ -0,0 +1,473 @@ +/* + * Copyright 2016 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_AUTH_SRC_INCLUDE_FIREBASE_AUTH_TYPES_H_ +#define FIREBASE_AUTH_SRC_INCLUDE_FIREBASE_AUTH_TYPES_H_ + +#include +#include +#include + +namespace firebase { +namespace auth { + +/// All possible error codes from asynchronous calls. +/// For error details, +/// @if cpp_examples +/// call Future::ErrorMessage(). +/// @endif +/// +/// @if swig_examples +/// use the FirebaseException.Message property. +/// @endif +/// +enum AuthError { + /// Success. + kAuthErrorNone = 0, + + /// Function will be implemented in a later revision of the API. + kAuthErrorUnimplemented = -1, + + /// This indicates an internal error. + /// Common error code for all API Methods. + kAuthErrorFailure = 1, + + /// Indicates a validation error with the custom token. + /// This error originates from "bring your own auth" methods. + kAuthErrorInvalidCustomToken, + + /// Indicates the service account and the API key belong to different + /// projects. + /// Caused by "Bring your own auth" methods. + kAuthErrorCustomTokenMismatch, + + /// Indicates the IDP token or requestUri is invalid. + /// Caused by "Sign in with credential" methods. + kAuthErrorInvalidCredential, + + /// Indicates the user’s account is disabled on the server. + /// Caused by "Sign in with credential" methods. + kAuthErrorUserDisabled, + + /// Indicates an account already exists with the same email address but using + /// different sign-in credentials. Account linking is required. + /// Caused by "Sign in with credential" methods. + kAuthErrorAccountExistsWithDifferentCredentials, + + /// Indicates the administrator disabled sign in with the specified identity + /// provider. + /// Caused by "Set account info" methods. + kAuthErrorOperationNotAllowed, + + /// Indicates the email used to attempt a sign up is already in use. + /// Caused by "Set account info" methods. + kAuthErrorEmailAlreadyInUse, + + /// Indicates the user has attemped to change email or password more than 5 + /// minutes after signing in, and will need to refresh the credentials. + /// Caused by "Set account info" methods. + kAuthErrorRequiresRecentLogin, + + /// Indicates an attempt to link with a credential that has already been + /// linked with a different Firebase account. + /// Caused by "Set account info" methods. + kAuthErrorCredentialAlreadyInUse, + + /// Indicates an invalid email address. + /// Caused by "Sign in with password" methods. + kAuthErrorInvalidEmail, + + /// Indicates the user attempted sign in with a wrong password. + /// Caused by "Sign in with password" methods. + kAuthErrorWrongPassword, + + /// Indicates that too many requests were made to a server method. + /// Common error code for all API methods. + kAuthErrorTooManyRequests, + + /// Indicates the user account was not found. + /// Send password request email error code. + /// Common error code for all API methods. + kAuthErrorUserNotFound, + + /// Indicates an attempt to link a provider to which the account is already + /// linked. + /// Caused by "Link credential" methods. + kAuthErrorProviderAlreadyLinked, + + /// Indicates an attempt to unlink a provider that is not linked. + /// Caused by "Link credential" methods. + kAuthErrorNoSuchProvider, + + /// Indicates user's saved auth credential is invalid, the user needs to sign + /// in again. + /// Caused by requests with an STS id token. + kAuthErrorInvalidUserToken, + + /// Indicates the saved token has expired. + /// For example, the user may have changed account password on another device. + /// The user needs to sign in again on the device that made this request. + /// Caused by requests with an STS id token. + kAuthErrorUserTokenExpired, + + /// Indicates a network error occurred (such as a timeout, interrupted + /// connection, or unreachable host). These types of errors are often + /// recoverable with a retry. + /// Common error code for all API Methods. + kAuthErrorNetworkRequestFailed, + + /// Indicates an invalid API key was supplied in the request. + /// For Android these should no longer occur (as of 2016 v3). + /// Common error code for all API Methods. + kAuthErrorInvalidApiKey, + + /// Indicates the App is not authorized to use Firebase Authentication with + /// the provided API Key. + /// Common error code for all API Methods. + /// On Android this error should no longer occur (as of 2016 v3). + /// Common error code for all API Methods. + kAuthErrorAppNotAuthorized, + + /// Indicates that an attempt was made to reauthenticate with a user which is + /// not the current user. + kAuthErrorUserMismatch, + + /// Indicates an attempt to set a password that is considered too weak. + kAuthErrorWeakPassword, + + /// Internal api usage error code when there is no signed-in user + /// and getAccessToken is called. + /// + /// @note This error is only reported on Android. + kAuthErrorNoSignedInUser, + + /// This can happen when certain methods on App are performed, when the auth + /// API is not loaded. + /// + /// @note This error is only reported on Android. + kAuthErrorApiNotAvailable, + + /// Indicates the out-of-band authentication code is expired. + kAuthErrorExpiredActionCode, + + /// Indicates the out-of-band authentication code is invalid. + kAuthErrorInvalidActionCode, + + /// Indicates that there are invalid parameters in the payload during a + /// "send password reset email" attempt. + kAuthErrorInvalidMessagePayload, + + /// Indicates that an invalid phone number was provided. + /// This is caused when the user is entering a phone number for verification. + kAuthErrorInvalidPhoneNumber, + + /// Indicates that a phone number was not provided during phone number + /// verification. + /// + /// @note This error is iOS-specific. + kAuthErrorMissingPhoneNumber, + + /// Indicates that the recipient email is invalid. + kAuthErrorInvalidRecipientEmail, + + /// Indicates that the sender email is invalid during a "send password reset + /// email" attempt. + kAuthErrorInvalidSender, + + /// Indicates that an invalid verification code was used in the + /// verifyPhoneNumber request. + kAuthErrorInvalidVerificationCode, + + /// Indicates that an invalid verification ID was used in the + /// verifyPhoneNumber request. + kAuthErrorInvalidVerificationId, + + /// Indicates that the phone auth credential was created with an empty + /// verification code. + kAuthErrorMissingVerificationCode, + + /// Indicates that the phone auth credential was created with an empty + /// verification ID. + kAuthErrorMissingVerificationId, + + /// Indicates that an email address was expected but one was not provided. + kAuthErrorMissingEmail, + + /// Represents the error code for when an application attempts to create an + /// email/password account with an empty/null password field. + /// + /// @note This error is only reported on Android. + kAuthErrorMissingPassword, + + /// Indicates that the project's quota for this operation (SMS messages, + /// sign-ins, account creation) has been exceeded. Try again later. + kAuthErrorQuotaExceeded, + + /// Thrown when one or more of the credentials passed to a method fail to + /// identify and/or authenticate the user subject of that operation. Inspect + /// the error message to find out the specific cause. + /// @note This error is only reported on Android. + kAuthErrorRetryPhoneAuth, + + /// Indicates that the SMS code has expired. + kAuthErrorSessionExpired, + + /// Indicates that the app could not be verified by Firebase during phone + /// number authentication. + /// + /// @note This error is iOS-specific. + kAuthErrorAppNotVerified, + + /// Indicates a general failure during the app verification flow. + /// + /// @note This error is iOS-specific. + kAuthErrorAppVerificationFailed, + + /// Indicates that the reCAPTCHA token is not valid. + /// + /// @note This error is iOS and tvOS-specific. + kAuthErrorCaptchaCheckFailed, + + /// Indicates that an invalid APNS device token was used in the verifyClient + /// request. + /// + /// @note This error is iOS and tvOS-specific. + kAuthErrorInvalidAppCredential, + + /// Indicates that the APNS device token is missing in the verifyClient + /// request. + /// + /// @note This error is iOS and tvOS-specific. + kAuthErrorMissingAppCredential, + + /// Indicates that the clientID used to invoke a web flow is invalid. + /// + /// @note This error is iOS and tvOS-specific. + kAuthErrorInvalidClientId, + + /// Indicates that the domain specified in the continue URI is not valid. + /// + /// @note This error is iOS and tvOS-specific. + kAuthErrorInvalidContinueUri, + + /// Indicates that a continue URI was not provided in a request to the backend + /// which requires one. + kAuthErrorMissingContinueUri, + + /// Indicates an error occurred while attempting to access the keychain. + /// Common error code for all API Methods. + /// + /// @note This error is iOS and tvOS-specific. + kAuthErrorKeychainError, + + /// Indicates that the APNs device token could not be obtained. The app may + /// not have set up remote notification correctly, or may have failed to + /// forward the APNs device token to FIRAuth if app delegate swizzling is + /// disabled. + /// + /// @note This error is iOS and tvOS-specific. + kAuthErrorMissingAppToken, + + /// Indicates that the iOS bundle ID is missing when an iOS App Store ID is + /// provided. + /// + /// @note This error is iOS and tvOS-specific. + kAuthErrorMissingIosBundleId, + + /// Indicates that the app fails to forward remote notification to FIRAuth. + /// + /// @note This error is iOS and tvOS-specific. + kAuthErrorNotificationNotForwarded, + + /// Indicates that the domain specified in the continue URL is not white- + /// listed in the Firebase console. + /// + /// @note This error is iOS and tvOS-specific. + kAuthErrorUnauthorizedDomain, + + /// Indicates that an attempt was made to present a new web context while one + /// was already being presented. + kAuthErrorWebContextAlreadyPresented, + + /// Indicates that the URL presentation was cancelled prematurely by the user. + kAuthErrorWebContextCancelled, + + /// Indicates that Dynamic Links in the Firebase Console is not activated. + kAuthErrorDynamicLinkNotActivated, + + /// Indicates that the operation was cancelled. + kAuthErrorCancelled, + + /// Indicates that the provider id given for the web operation is invalid. + kAuthErrorInvalidProviderId, + + /// Indicates that an internal error occurred during a web operation. + kAuthErrorWebInternalError, + + /// Indicates that 3rd party cookies or data are disabled, or that there was + /// a problem with the browser. + kAuthErrorWebStorateUnsupported, + + /// Indicates that the provided tenant ID does not match the Auth instance's + /// tenant ID. + kAuthErrorTenantIdMismatch, + + /// Indicates that a request was made to the backend with an associated tenant + /// ID for an operation that does not support multi-tenancy. + kAuthErrorUnsupportedTenantOperation, + + /// Indicates that an FDL domain used for an out of band code flow is either + /// not configured or is unauthorized for the current project. + kAuthErrorInvalidLinkDomain, + + /// Indicates that credential related request data is invalid. This can occur + /// when there is a project number mismatch (sessionInfo, spatula header, + /// temporary proof), + /// an incorrect temporary proof phone number, or during game center sign in + /// when the user is + /// already signed into a different game center account. + kAuthErrorRejectedCredential, + + /// Indicates that the phone number provided in the MFA sign in flow to be + /// verified does not correspond to a phone second factor for the user. + kAuthErrorPhoneNumberNotFound, + + /// Indicates that a request was made to the backend with an invalid tenant + /// ID. + kAuthErrorInvalidTenantId, + + /// Indicates that a request was made to the backend without a valid client + /// identifier. + kAuthErrorMissingClientIdentifier, + + /// Indicates that a second factor challenge request was made without proof of + /// a successful first factor sign-in. + kAuthErrorMissingMultiFactorSession, + + /// Indicates that a second factor challenge request was made where a second + /// factor identifier was not provided. + kAuthErrorMissingMultiFactorInfo, + + /// Indicates that a second factor challenge request was made containing an + /// invalid proof of first factor sign-in. + kAuthErrorInvalidMultiFactorSession, + + /// Indicates that the user does not have a second factor matching the + /// provided identifier. + kAuthErrorMultiFactorInfoNotFound, + + /// Indicates that a request was made that is restricted to administrators + /// only. + kAuthErrorAdminRestrictedOperation, + + /// Indicates that the user's email must be verified to perform that request. + kAuthErrorUnverifiedEmail, + + /// Indicates that the user is trying to enroll a second factor that already + /// exists on their account. + kAuthErrorSecondFactorAlreadyEnrolled, + + /// Indicates that the user has reached the maximum number of allowed second + /// factors and is attempting to enroll another one. + kAuthErrorMaximumSecondFactorCountExceeded, + + /// Indicates that a user either attempted to enroll in 2FA with an + /// unsupported first factor or is enrolled and attempts a first factor sign + /// in that is not supported for 2FA users. + kAuthErrorUnsupportedFirstFactor, + + /// Indicates that a second factor users attempted to change their email with + /// updateEmail instead of verifyBeforeUpdateEmail. + kAuthErrorEmailChangeNeedsVerification, + +#ifdef INTERNAL_EXPERIMENTAL + /// Indicates that the provided event handler is null or invalid. + kAuthErrorInvalidEventHandler, + + /// Indicates that the federated provider is busy with a previous + /// authorization request. Try again when the previous authorization request + /// completes. + kAuthErrorFederatedProviderAreadyInUse, + + /// Indicates that one or more fields of the provided AuthenticatedUserData + /// are invalid. + kAuthErrorInvalidAuthenticatedUserData, + + /// Indicates that an error occurred during a Federated Auth UI Flow when the + /// user was prompted to enter their credentials. + kAuthErrorFederatedSignInUserInteractionFailure, + + /// Indicates that a request was made with a missing or invalid nonce. + /// This can happen if the hash of the provided raw nonce did not match the + /// hashed nonce in the OIDC ID token payload. + kAuthErrorMissingOrInvalidNonce, + + /// Indicates that the user did not authorize the application during Generic + /// IDP sign-in. + kAuthErrorUserCancelled, + + /// Indicates that a request was made to an unsupported backend endpoint in + /// passthrough mode. + kAuthErrorUnsupportedPassthroughOperation, + + /// Indicates that a token refresh was requested, but neither a refresh token + /// nor a custom token provider is available. + kAuthErrorTokenRefreshUnavailable, + +#endif // INTERNAL_EXEPERIMENTAL +}; + +/// @brief Contains information required to authenticate with a third party +/// provider. +struct FederatedProviderData { + /// @brief contains the id of the provider to be used during sign-in, link, or + /// reauthentication requests. + std::string provider_id; +}; + +/// @brief Contains information to identify an OAuth povider. +struct FederatedOAuthProviderData : FederatedProviderData { + /// Initailizes an empty provider data structure. + FederatedOAuthProviderData() {} + + /// Initializes the provider data structure with a provider id. + explicit FederatedOAuthProviderData(const std::string& provider) { + this->provider_id = provider; + } + +#ifndef SWIG + /// @brief Initializes the provider data structure with the specified provider + /// id, scopes and custom parameters. + FederatedOAuthProviderData( + const std::string& provider, std::vector scopes, + std::map custom_parameters) { + this->provider_id = provider; + this->scopes = scopes; + this->custom_parameters = custom_parameters; + } +#endif + + /// OAuth parmeters which specify which rights of access are being requested. + std::vector scopes; + + /// OAuth parameters which are provided to the federated provider service. + std::map custom_parameters; +}; + +} // namespace auth +} // namespace firebase + +#endif // FIREBASE_AUTH_SRC_INCLUDE_FIREBASE_AUTH_TYPES_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/auth/user.h b/packages/firebase_core/firebase_core/firebase_core/firebase/auth/user.h new file mode 100644 index 000000000000..ddd1ba890687 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/auth/user.h @@ -0,0 +1,501 @@ +/* + * Copyright 2016 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_AUTH_SRC_INCLUDE_FIREBASE_AUTH_USER_H_ +#define FIREBASE_AUTH_SRC_INCLUDE_FIREBASE_AUTH_USER_H_ + +#include +#include + +#include "firebase/auth/credential.h" +#include "firebase/auth/types.h" +#include "firebase/future.h" +#include "firebase/internal/common.h" +#include "firebase/variant.h" + +namespace firebase { +namespace auth { + +// Predeclarations. +class Auth; +struct AuthData; + +class FederatedAuthProvider; + +/// @brief Interface implemented by each identity provider. +class UserInfoInterface { + public: + virtual ~UserInfoInterface(); + + /// Gets the unique Firebase user ID for the user. + /// + /// @note The user's ID, unique to the Firebase project. + /// Do NOT use this value to authenticate with your backend server, if you + /// have one. + /// @if cpp_examples + /// Use User::GetToken() instead. + /// @endif + /// + /// @if swig_examples + /// Use User.Token instead. + /// @endif + /// @xmlonly + /// + /// Gets the unique Firebase user ID for the user. + /// + /// @note The user's ID, unique to the Firebase project. + /// Do NOT use this value to authenticate with your backend server, if you + /// have one. Use User.Token instead. + /// + /// @endxmlonly + /// + virtual std::string uid() const = 0; + + /// Gets email associated with the user, if any. + /// + /// @xmlonly + /// + /// Gets email associated with the user, if any. + /// + /// @endxmlonly + /// + virtual std::string email() const = 0; + + /// Gets the display name associated with the user, if any. + /// + /// @xmlonly + /// + /// Gets the display name associated with the user, if any. + /// + /// @endxmlonly + /// + virtual std::string display_name() const = 0; + + /// Gets the photo url associated with the user, if any. + /// + /// @xmlonly + /// + /// Gets the photo url associated with the user, if any. + /// + /// @endxmlonly + /// + virtual std::string photo_url() const = 0; + + /// Gets the provider ID for the user (For example, "Facebook"). + /// + /// @xmlonly + /// + /// Gets the provider ID for the user (For example, \"Facebook\"). + /// + /// @endxmlonly + /// + virtual std::string provider_id() const = 0; + + /// Gets the phone number for the user, in E.164 format. + virtual std::string phone_number() const = 0; +}; + +/// @brief Additional user data returned from an identity provider. +struct AdditionalUserInfo { + /// The provider identifier. + std::string provider_id; + + /// The name of the user. + std::string user_name; + + /// Additional identity-provider specific information. + /// Most likely a hierarchical key-value mapping, like a parsed JSON file. + /// Note we use map instead of unordered_map to support older compilers. + std::map profile; + + /// On a nonce-based credential link failure where the user has already linked + /// to the provider, the Firebase auth service may provide an updated + /// Credential. If is_valid returns true on this credential, then it may be + /// passed to a new firebase::auth::Auth::SignInWithCredential request to sign + /// the user in with the provider. + Credential updated_credential; +}; + +/// @brief Metadata corresponding to a Firebase user. +struct UserMetadata { + UserMetadata() : last_sign_in_timestamp(0), creation_timestamp(0) {} + + /// The last sign in UTC timestamp in milliseconds. + /// See https://en.wikipedia.org/wiki/Unix_time for details of UTC. + uint64_t last_sign_in_timestamp; + + /// The Firebase user creation UTC timestamp in milliseconds. + uint64_t creation_timestamp; +}; + +/// @brief Result of operations that can affect authentication state. +struct SignInResult { + SignInResult() : user(NULL) {} + + /// The currently signed-in @ref User, or NULL if there isn't any (i.e. the + /// user is signed out). + User* user; + + /// Identity-provider specific information for the user, if the provider is + /// one of Facebook, GitHub, Google, or Twitter. + AdditionalUserInfo info; + + /// Metadata associated with the Firebase user. + UserMetadata meta; +}; + +/// @brief Firebase user account object. +/// +/// This class allows you to manipulate the profile of a user, link to and +/// unlink from authentication providers, and refresh authentication tokens. +class User : public UserInfoInterface { + public: + /// Parameters to the UpdateUserProfile() function. + /// + /// For fields you don't want to update, pass NULL. + /// For fields you want to reset, pass "". + struct UserProfile { + /// Construct a UserProfile with no display name or photo URL. + UserProfile() : display_name(NULL), photo_url(NULL) {} + + /// User display name. + const char* display_name; + + /// User photo URI. + const char* photo_url; + }; + + ~User(); + + /// The Java Web Token (JWT) that can be used to identify the user to + /// the backend. + /// + /// If a current ID token is still believed to be valid (i.e. it has not yet + /// expired), that token will be returned immediately. + /// A developer may set the optional force_refresh flag to get a new ID token, + /// whether or not the existing token has expired. For example, a developer + /// may use this when they have discovered that the token is invalid for some + /// other reason. + Future GetToken(bool force_refresh); + +#if defined(INTERNAL_EXPERIMENTAL) || defined(SWIG) + /// A "thread safer" version of GetToken. + /// If called by two threads simultaneously, GetToken can return the same + /// pending Future twice. This creates problems if both threads try to set + /// the OnCompletion callback, unaware that there's another copy. + /// GetTokenThreadSafe returns a proxy to the Future if it's still pending, + /// allowing each proxy to have their own callback. + Future GetTokenThreadSafe(bool force_refresh); +#endif // defined(INTERNAL_EXPERIMENTAL) || defined(SWIG) + + /// Get results of the most recent call to @ref GetToken. + Future GetTokenLastResult() const; + + /// Gets the third party profile data associated with this user returned by + /// the authentication server, if any. + /// + /// @xmlonly + /// + /// Gets the third party profile data associated with this user returned by + /// the authentication server, if any. + /// + /// @endxmlonly + /// + const std::vector& provider_data() const; + + /// Sets the email address for the user. + /// + /// May fail if there is already an email/password-based account for the same + /// email address. + Future UpdateEmail(const char* email); + + /// Get results of the most recent call to @ref UpdateEmail. + Future UpdateEmailLastResult() const; + + /// Attempts to change the password for the current user. + /// + /// For an account linked to an Identity Provider (IDP) with no password, + /// this will result in the account becoming an email/password-based account + /// while maintaining the IDP link. May fail if the password is invalid, + /// if there is a conflicting email/password-based account, or if the token + /// has expired. + /// To retrieve fresh tokens, + /// @if cpp_examples + /// call @ref Reauthenticate. + /// @endif + /// + /// @if swig_examples + /// call @ref ReauthenticateAsync. + /// @endif + /// + Future UpdatePassword(const char* password); + + /// Get results of the most recent call to @ref UpdatePassword. + Future UpdatePasswordLastResult() const; + + /// Convenience function for @ref ReauthenticateAndRetrieveData that discards + /// the returned AdditionalUserInfo data. + Future Reauthenticate(const Credential& credential); + + /// Get results of the most recent call to @ref Reauthenticate. + Future ReauthenticateLastResult() const; + + /// Reauthenticate using a credential. + /// + /// @if cpp_examples + /// Some APIs (for example, @ref UpdatePassword, @ref Delete) require that + /// the token used to invoke them be from a recent login attempt. + /// This API takes an existing credential for the user and retrieves fresh + /// tokens, ensuring that the operation can proceed. Developers can call + /// this method prior to calling @ref UpdatePassword() to ensure success. + /// @endif + /// + /// @if swig_examples + /// Some APIs (for example, @ref UpdatePasswordAsync, @ref DeleteAsync) + /// require that the token used to invoke them be from a recent login attempt. + /// This API takes an existing credential for the user and retrieves fresh + /// tokens, ensuring that the operation can proceed. Developers can call + /// this method prior to calling @ref UpdatePasswordAsync() to ensure success. + /// @endif + /// + /// + /// Data from the Identity Provider used to sign-in is returned in the + /// AdditionalUserInfo inside the returned SignInResult. + /// + /// Returns an error if the existing credential is not for this user + /// or if sign-in with that credential failed. + /// @note: The current user may be signed out if this operation fails on + /// Android and desktop platforms. + Future ReauthenticateAndRetrieveData( + const Credential& credential); + + /// Get results of the most recent call to @ref ReauthenticateAndRetrieveData. + Future ReauthenticateAndRetrieveDataLastResult() const; + + /// @brief Re-authenticates the user with a federated auth provider. + /// + /// @param[in] provider Contains information on the auth provider to + /// authenticate with. + /// @return A Future with the result of the re-authentication + /// request. + /// @note: This operation is supported only on iOS, tvOS and Android + /// platforms. On other platforms this method will return a Future with a + /// preset error code: kAuthErrorUnimplemented. + Future ReauthenticateWithProvider( + FederatedAuthProvider* provider) const; + + /// Initiates email verification for the user. + Future SendEmailVerification(); + + /// Get results of the most recent call to @ref SendEmailVerification. + Future SendEmailVerificationLastResult() const; + + /// Updates a subset of user profile information. + Future UpdateUserProfile(const UserProfile& profile); + + /// Get results of the most recent call to @ref UpdateUserProfile. + Future UpdateUserProfileLastResult() const; + + /// Convenience function for @ref ReauthenticateAndRetrieveData that discards + /// the returned @ref AdditionalUserInfo in @ref SignInResult. + Future LinkWithCredential(const Credential& credential); + + /// Get results of the most recent call to @ref LinkWithCredential. + Future LinkWithCredentialLastResult() const; + + /// Links the user with the given 3rd party credentials. + /// + /// For example, a Facebook login access token, a Twitter token/token-secret + /// pair. + /// Status will be an error if the token is invalid, expired, or otherwise + /// not accepted by the server as well as if the given 3rd party + /// user id is already linked with another user account or if the current user + /// is already linked with another id from the same provider. + /// + /// Data from the Identity Provider used to sign-in is returned in the + /// @ref AdditionalUserInfo inside @ref SignInResult. + Future LinkAndRetrieveDataWithCredential( + const Credential& credential); + + /// Get results of the most recent call to + /// @ref LinkAndRetrieveDataWithCredential. + Future LinkAndRetrieveDataWithCredentialLastResult() const; + + /// Links this user with a federated auth provider. + /// + /// @param[in] provider Contains information on the auth provider to link + /// with. + /// @return A Future with the user data result of the link + /// request. + /// + /// @note: This operation is supported only on iOS, tvOS and Android + /// platforms. On other platforms this method will return a Future with a + /// preset error code: kAuthErrorUnimplemented. + Future LinkWithProvider(FederatedAuthProvider* provider) const; + + /// Unlinks the current user from the provider specified. + /// Status will be an error if the user is not linked to the given provider. + Future Unlink(const char* provider); + + /// Get results of the most recent call to @ref Unlink. + Future UnlinkLastResult() const; + + /// Updates the currently linked phone number on the user. + /// This is useful when a user wants to change their phone number. It is a + /// shortcut to calling Unlink(phone_credential.provider().c_str()) and then + /// LinkWithCredential(phone_credential). + /// `credential` must have been created with @ref PhoneAuthProvider. + Future UpdatePhoneNumberCredential(const Credential& credential); + + /// Get results of the most recent call to @ref UpdatePhoneNumberCredential. + Future UpdatePhoneNumberCredentialLastResult() const; + + /// Refreshes the data for this user. + /// + /// For example, the attached providers, email address, display name, etc. + Future Reload(); + + /// Get results of the most recent call to @ref Reload. + Future ReloadLastResult() const; + + /// Deletes the user account. + Future Delete(); + + /// Get results of the most recent call to @ref Delete. + Future DeleteLastResult() const; + + /// Gets the metadata for this user account. + UserMetadata metadata() const; + + /// Returns true if the email address associated with this user has been + /// verified. + /// + /// @xmlonly + /// + /// True if the email address associated with this user has been verified. + /// + /// @endxmlonly + /// + bool is_email_verified() const; + + /// Returns true if user signed in anonymously. + /// + /// @xmlonly + /// + /// True if user signed in anonymously. + /// + /// @endxmlonly + /// + bool is_anonymous() const; + + /// Gets the unique Firebase user ID for the user. + /// + /// @note The user's ID, unique to the Firebase project. + /// Do NOT use this value to authenticate with your backend server, if you + /// have one. + /// @if cpp_examples + /// Use User::GetToken() instead. + /// @endif + /// + /// @if swig_examples + /// Use User.Token instead. + /// @endif + /// @xmlonly + /// + /// Gets the unique Firebase user ID for the user. + /// + /// @note The user's ID, unique to the Firebase project. + /// Do NOT use this value to authenticate with your backend server, if you + /// have one. Use User.Token instead. + /// + /// @endxmlonly + /// + virtual std::string uid() const; + + /// Gets email associated with the user, if any. + /// + /// @xmlonly + /// + /// Gets email associated with the user, if any. + /// + /// @endxmlonly + /// + virtual std::string email() const; + + /// Gets the display name associated with the user, if any. + /// + /// @xmlonly + /// + /// Gets the display name associated with the user, if any. + /// + /// @endxmlonly + /// + virtual std::string display_name() const; + + /// Gets the photo url associated with the user, if any. + /// + /// @xmlonly + /// + /// Gets the photo url associated with the user, if any. + /// + /// @endxmlonly + /// + virtual std::string photo_url() const; + + /// Gets the provider ID for the user (For example, "Facebook"). + /// + /// @xmlonly + /// + /// Gets the provider ID for the user (For example, \"Facebook\"). + /// + /// @endxmlonly + /// + virtual std::string provider_id() const; + + /// Gets the phone number for the user, in E.164 format. + virtual std::string phone_number() const; + + private: + /// @cond FIREBASE_APP_INTERNAL + friend struct AuthData; + // Only exists in AuthData. Access via @ref Auth::CurrentUser(). + explicit User(AuthData* auth_data) : auth_data_(auth_data) {} + + // Disable copy constructor. + User(const User&) = delete; + // Disable copy operator. + User& operator=(const User&) = delete; + /// @endcond + +#if defined(INTERNAL_EXPERIMENTAL) + // Doxygen should not make docs for this function. + /// @cond FIREBASE_APP_INTERNAL + friend class IdTokenRefreshThread; + friend class IdTokenRefreshListener; + friend class Auth; + Future GetTokenInternal(const bool force_refresh, + const int future_identifier); + /// @endcond +#endif // defined(INTERNAL_EXPERIMENTAL) + + // Use the pimpl mechanism to hide data details in the cpp files. + AuthData* auth_data_; +}; + +} // namespace auth +} // namespace firebase + +#endif // FIREBASE_AUTH_SRC_INCLUDE_FIREBASE_AUTH_USER_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/database.h b/packages/firebase_core/firebase_core/firebase_core/firebase/database.h new file mode 100644 index 000000000000..d0dc904c107b --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/database.h @@ -0,0 +1,199 @@ +// Copyright 2016 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_H_ +#define FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_H_ + +#include "firebase/app.h" +#include "firebase/database/common.h" +#include "firebase/database/data_snapshot.h" +#include "firebase/database/database_reference.h" +#include "firebase/database/disconnection.h" +#include "firebase/database/listener.h" +#include "firebase/database/mutable_data.h" +#include "firebase/database/query.h" +#include "firebase/database/transaction.h" +#include "firebase/internal/common.h" +#include "firebase/log.h" + +namespace firebase { + +/// Namespace for the Firebase Realtime Database C++ SDK. +namespace database { + +namespace internal { +class DatabaseInternal; +} // namespace internal + +class DatabaseReference; + +#ifndef SWIG +/// @brief Entry point for the Firebase Realtime Database C++ SDK. +/// +/// To use the SDK, call firebase::database::Database::GetInstance() to obtain +/// an instance of Database, then use GetReference() to obtain references to +/// child paths within the database. From there you can set data via +/// Query::SetValue(), get data via Query::GetValue(), attach listeners, and +/// more. +#endif // SWIG +class Database { + public: + /// @brief Get an instance of Database corresponding to the given App. + /// + /// Firebase Realtime Database uses firebase::App to communicate with Firebase + /// Authentication to authenticate users to the Database server backend. + /// + /// If you call GetInstance() multiple times with the same App, you will get + /// the same instance of Database. + /// + /// @param[in] app Your instance of firebase::App. Firebase Realtime Database + /// will use this to communicate with Firebase Authentication. + /// @param[out] init_result_out Optional: If provided, write the init result + /// here. Will be set to kInitResultSuccess if initialization succeeded, or + /// kInitResultFailedMissingDependency on Android if Google Play services is + /// not available on the current device. + /// + /// @returns An instance of Database corresponding to the given App. + static Database* GetInstance(::firebase::App* app, + InitResult* init_result_out = nullptr); + + /// @brief Gets an instance of FirebaseDatabase for the specified URL. + /// + /// If you call GetInstance() multiple times with the same App and URL, you + /// will get the same instance of Database. + /// + /// @param[in] app Your instance of firebase::App. Firebase Realtime Database + /// will use this to communicate with Firebase Authentication. + /// @param[in] url The URL of your Firebase Realtime Database. This overrides + /// any url specified in the App options. + /// @param[out] init_result_out Optional: If provided, write the init result + /// here. Will be set to kInitResultSuccess if initialization succeeded, or + /// kInitResultFailedMissingDependency on Android if Google Play services is + /// not available on the current device. + /// + /// @returns An instance of Database corresponding to the given App and URL. + static Database* GetInstance(::firebase::App* app, const char* url, + InitResult* init_result_out = nullptr); + + /// @brief Destructor for the Database object. + /// + /// When deleted, this instance will be removed from the cache of Database + /// objects. If you call GetInstance() in the future with the same App, a new + /// Database instance will be created. + ~Database(); + + /// @brief Get the firebase::App that this Database was created with. + /// + /// @returns The firebase::App this Database was created with. + App* app() const; + + /// @brief Get the URL that this Database was created with. + /// + /// @returns The URL this Database was created with, or an empty string if + /// this Database was created with default parameters. This string will remain + /// valid in memory for the lifetime of this Database. + const char* url() const; + + /// @brief Get a DatabaseReference to the root of the database. + /// + /// @returns A DatabaseReference to the root of the database. + DatabaseReference GetReference() const; + /// @brief Get a DatabaseReference for the specified path. + /// + /// @returns A DatabaseReference to the specified path in the database. + /// If you specified an invalid path, the reference's + /// DatabaseReference::IsValid() will return false. + DatabaseReference GetReference(const char* path) const; + /// @brief Get a DatabaseReference for the provided URL, which must belong to + /// the database URL this instance is already connected to. + /// + /// @returns A DatabaseReference to the specified path in the database. + /// If you specified an invalid path, the reference's + /// DatabaseReference::IsValid() will return false. + DatabaseReference GetReferenceFromUrl(const char* url) const; + + /// @brief Shuts down the connection to the Firebase Realtime Database + /// backend until GoOnline() is called. + void GoOffline(); + + /// @brief Resumes the connection to the Firebase Realtime Database backend + /// after a previous GoOffline() call. + void GoOnline(); + + /// @brief Purge all pending writes to the Firebase Realtime Database server. + /// + /// The Firebase Realtime Database client automatically queues writes and + /// sends them to the server at the earliest opportunity, depending on network + /// connectivity. In some cases (e.g. offline usage) there may be a large + /// number of writes waiting to be sent. Calling this method will purge all + /// outstanding writes so they are abandoned. All writes will be purged, + /// including transactions and onDisconnect() writes. The writes will be + /// rolled back locally, perhaps triggering events for affected event + /// listeners, and the client will not (re-)send them to the Firebase backend. + void PurgeOutstandingWrites(); + + /// @brief Sets whether pending write data will persist between application + /// exits. + /// + /// The Firebase Database client will cache synchronized data and keep track + /// of all writes you've initiated while your application is running. It + /// seamlessly handles intermittent network connections and re-sends write + /// operations when the network connection is restored. However by default + /// your write operations and cached data are only stored in-memory and will + /// be lost when your app restarts. By setting this value to `true`, the data + /// will be persisted to on-device (disk) storage and will thus be available + /// again when the app is restarted (even when there is no network + /// connectivity at that time). + /// + /// @note SetPersistenceEnabled should be called before creating any instances + /// of DatabaseReference, and only needs to be called once per application. + /// + /// @param[in] enabled Set this to true to persist write data to on-device + /// (disk) storage, or false to discard pending writes when the app exists. + void set_persistence_enabled(bool enabled); + + /// Set the log verbosity of this Database instance. + /// + /// The log filtering is cumulative with Firebase App. That is, this library's + /// log messages will only be displayed if they are not filtered out by this + /// library's log level setting and by Firebase App's log level setting. + /// + /// @note On Android this can only be set before any operations have been + /// performed with the object. + /// + /// @param[in] log_level Log level, by default this is set to kLogLevelInfo. + void set_log_level(LogLevel log_level); + + /// Get the log verbosity of this Database instance. + /// + /// @return Get the currently configured logging verbosity. + LogLevel log_level() const; + + private: + friend Database* GetDatabaseInstance(::firebase::App* app, const char* url, + InitResult* init_result_out); + Database(::firebase::App* app, internal::DatabaseInternal* internal); + Database(const Database& src); + Database& operator=(const Database& src); + + // Delete the internal_ data. + void DeleteInternal(); + + internal::DatabaseInternal* internal_; +}; + +} // namespace database +} // namespace firebase + +#endif // FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/database/common.h b/packages/firebase_core/firebase_core/firebase_core/firebase/database/common.h new file mode 100644 index 000000000000..298972784631 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/database/common.h @@ -0,0 +1,83 @@ +// Copyright 2016 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_COMMON_H_ +#define FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_COMMON_H_ + +#include "firebase/variant.h" + +namespace firebase { +namespace database { + +/// Error code returned by Firebase Realtime Database C++ functions. +enum Error { + /// The operation was a success, no error occurred. + kErrorNone = 0, + /// The operation had to be aborted due to a network disconnect. + kErrorDisconnected, + /// The supplied auth token has expired. + kErrorExpiredToken, + /// The specified authentication token is invalid. + kErrorInvalidToken, + /// The transaction had too many retries. + kErrorMaxRetries, + /// The operation could not be performed due to a network error. + kErrorNetworkError, + /// The server indicated that this operation failed. + kErrorOperationFailed, + /// The transaction was overridden by a subsequent set. + kErrorOverriddenBySet, + /// This client does not have permission to perform this operation. + kErrorPermissionDenied, + /// The service is unavailable. + kErrorUnavailable, + /// An unknown error occurred. + kErrorUnknownError, + /// The write was canceled locally. + kErrorWriteCanceled, + /// You specified an invalid Variant type for a field. For example, + /// a DatabaseReference's Priority and the keys of a Map must be of + /// scalar type (MutableString, StaticString, Int64, Double). + kErrorInvalidVariantType, + /// An operation that conflicts with this one is already in progress. For + /// example, calling SetValue and SetValueAndPriority on a DatabaseReference + /// is not allowed. + kErrorConflictingOperationInProgress, + /// The transaction was aborted, because the user's DoTransaction function + /// returned kTransactionResultAbort instead of kTransactionResultSuccess. + kErrorTransactionAbortedByUser, +}; + +/// @brief Get the human-readable error message corresponding to an error code. +/// +/// @param[in] error Error code to get the error message for. +/// +/// @returns Statically-allocated string describing the error. +extern const char* GetErrorMessage(Error error); + +/// @brief Get a server-populated value corresponding to the current +/// timestamp. +/// +/// When inserting values into the database, you can use the special value +/// firebase::database::ServerTimestamp() to have the server auto-populate the +/// current timestamp, which is represented as millieconds since the Unix epoch, +/// into the field. +/// +/// @returns A special value that tells the server to use the current timestamp. +const Variant& ServerTimestamp(); + +} // namespace database +} // namespace firebase + +#endif // FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_COMMON_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/database/data_snapshot.h b/packages/firebase_core/firebase_core/firebase_core/firebase/database/data_snapshot.h new file mode 100644 index 000000000000..cb83292a792b --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/database/data_snapshot.h @@ -0,0 +1,205 @@ +// Copyright 2016 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_DATA_SNAPSHOT_H_ +#define FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_DATA_SNAPSHOT_H_ + +#include + +#include + +#include "firebase/internal/common.h" +#include "firebase/variant.h" + +namespace firebase { +namespace database { +namespace internal { +class Callbacks; +class ChildEventRegistration; +class DataSnapshotInternal; +class DatabaseInternal; +class DatabaseInternalTestMatcherTest; +class DatabaseReferenceInternal; +class QueryInternal; +class Repo; +class ValueEventRegistration; +} // namespace internal + +class Database; +class DatabaseReference; + +#ifndef SWIG +/// A DataSnapshot instance contains data from a Firebase Database location. Any +/// time you read Database data, you receive the data as a DataSnapshot. These +/// are efficiently-generated and cannot be changed. To modify data, +/// use DatabaseReference::SetValue() or DatabaseReference::RunTransaction(). +#endif // SWIG +class DataSnapshot { + public: + /// @brief Default constructor. + /// + /// This DataSnapshot contains nothing and is considered invalid (i.e. + /// is_valid() == false). Use this to construct an empty DataSnapshot that you + /// will later populate with data from a database callback. + DataSnapshot() : internal_(nullptr) {} + +#ifdef INTERNAL_EXPERIMENTAL + explicit DataSnapshot(internal::DataSnapshotInternal* internal); +#endif + + /// @brief Copy constructor. DataSnapshots are immutable, so they can be + /// efficiently copied. + /// + /// @param[in] snapshot DataSnapshot to copy. + DataSnapshot(const DataSnapshot& snapshot); + + /// @brief Copy assignment operator. DataSnapshots are immutable, so they can + /// be efficiently copied. + /// + /// @param[in] snapshot DataSnapshot to copy. + /// + /// @returns Reference to the destination DataSnapshot. + DataSnapshot& operator=(const DataSnapshot& snapshot); + +#if defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) + /// @brief Move constructor. DataSnapshots are immutable, so they can be + /// efficiently moved. + /// + /// @param[in] snapshot DataSnapshot to move into this one. + DataSnapshot(DataSnapshot&& snapshot); + + /// @brief Move assignment operator. DataSnapshots are immutable, so they can + /// be efficiently moved. + /// + /// @param[in] snapshot DataSnapshot to move into this one. + /// + /// @returns Reference to this destination DataSnapshot. + DataSnapshot& operator=(DataSnapshot&& snapshot); +#endif // defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) + + /// Destructor. + ~DataSnapshot(); + + /// @brief Returns true if the data is non-empty. + bool exists() const; + + /// @brief Get a DataSnapshot for the location at the specified relative path. + /// + /// @param[in] path Path relative to this snapshot's location. + /// It only needs to be valid during this call. + /// + /// @returns A DataSnapshot corresponding to specified child location. + DataSnapshot Child(const char* path) const; + + /// @brief Get a DataSnapshot for the location at the specified relative path. + /// + /// @param[in] path Path relative to this snapshot's location. + /// + /// @returns A DataSnapshot corresponding to specified child location. + DataSnapshot Child(const std::string& path) const; + + /// @brief Get all the immediate children of this location. + /// + /// @returns The immediate children of this snapshot. + std::vector children() const; + + /// @brief Get the number of children of this location. + /// + /// @returns The number of immediate children of this snapshot. + size_t children_count() const; + + /// @brief Does this DataSnapshot have any children at all? + /// + /// @returns True if the snapshot has any children, false otherwise. + bool has_children() const; + + /// @brief Get the key name of the source location of this snapshot. + /// + /// @note The returned pointer is only guaranteed to be valid while the + /// DataSnapshot is still in memory. + /// + /// @returns Key name of the source location of this snapshot. + const char* key() const; + + /// @brief Get the key name of the source location of this snapshot. + /// + /// @returns Key name of the source location of this snapshot. + std::string key_string() const; + + /// @brief Get the value of the data contained in this snapshot. + /// + /// @returns The value of the data contained in this location. + Variant value() const; + + /// @brief Get the priority of the data contained in this snapshot. + /// + /// @returns The value of this location's Priority relative to its siblings. + Variant priority() const; + + /// @brief Obtain a DatabaseReference to the source location for this + /// snapshot. + /// + /// @returns A DatabaseReference corresponding to same location as + /// this snapshot. + DatabaseReference GetReference() const; + + /// @brief Does this DataSnapshot have data at a particular location? + /// + /// @param[in] path Path relative to this snapshot's location. + /// The pointer only needs to be valid during this call. + /// + /// @returns True if the snapshot has data at the specified location, false if + /// not. + bool HasChild(const char* path) const; + + /// @brief Does this DataSnapshot have data at a particular location? + /// + /// @param[in] path Path relative to this snapshot's location. + /// + /// @returns True if the snapshot has data at the specified location, false if + /// not. + bool HasChild(const std::string& path) const; + + /// @brief Returns true if this snapshot is valid, false if it is not + /// valid. An invalid snapshot could be returned by a transaction where an + /// error has occurred. + /// + /// @returns true if this snapshot is valid, false if this snapshot is + /// invalid. + bool is_valid() const; + + private: + /// @cond FIREBASE_APP_INTERNAL + friend class internal::Callbacks; + friend class internal::ChildEventRegistration; + friend class internal::DataSnapshotInternal; + friend class internal::DatabaseInternal; + friend class internal::DatabaseInternalTestMatcherTest; + friend class internal::DatabaseReferenceInternal; + friend class internal::QueryInternal; + friend class internal::Repo; + friend class internal::ValueEventRegistration; + /// @endcond + +#ifndef INTERNAL_EXPERIMENTAL + explicit DataSnapshot(internal::DataSnapshotInternal* internal); +#endif + + internal::DataSnapshotInternal* internal_; +}; + +} // namespace database +} // namespace firebase + +#endif // FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_DATA_SNAPSHOT_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/database/database_reference.h b/packages/firebase_core/firebase_core/firebase_core/firebase/database/database_reference.h new file mode 100644 index 000000000000..3e746541a1d5 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/database/database_reference.h @@ -0,0 +1,477 @@ +// Copyright 2016 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_DATABASE_REFERENCE_H_ +#define FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_DATABASE_REFERENCE_H_ + +#include +#include + +#include "firebase/database/disconnection.h" +#include "firebase/database/query.h" +#include "firebase/database/transaction.h" +#include "firebase/future.h" +#include "firebase/internal/common.h" +#include "firebase/variant.h" + +namespace firebase { +namespace database { +namespace internal { +class DatabaseInternal; +class DatabaseReferenceInternal; +class Repo; +} // namespace internal + +class DataSnapshot; + +#ifndef SWIG +/// DatabaseReference represents a particular location in your Database and can +/// be used for reading or writing data to that Database location. +/// +/// This class is the starting point for all Database operations. After you've +/// initialized it with a URL, you can use it to read data, write data, and to +/// create new DatabaseReference instances. +#endif // SWIG +class DatabaseReference : public Query { + public: + /// @brief Default constructor. This creates an invalid DatabaseReference. + /// Attempting to perform any operations on this reference will fail unless a + /// valid DatabaseReference has been assigned to it. + DatabaseReference() : Query(), internal_(nullptr) {} + + /// @brief Required virtual destructor. + virtual ~DatabaseReference(); + + /// @brief Copy constructor. It's totally okay (and efficient) to copy + /// DatabaseReference instances, as they simply point to the same location in + /// the database. + /// + /// @param[in] reference DatabaseReference to copy from. + DatabaseReference(const DatabaseReference& reference); + + /// @brief Copy assignment operator. It's totally okay (and efficient) to copy + /// DatabaseReference instances, as they simply point to the same location in + /// the database. + /// + /// @param[in] reference DatabaseReference to copy from. + /// + /// @returns Reference to the destination DatabaseReference. + DatabaseReference& operator=(const DatabaseReference& reference); + +#if defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) + /// @brief Move constructor. Moving is an efficient operation for + /// DatabaseReference instances. + /// + /// @param[in] reference DatabaseReference to move data from. + DatabaseReference(DatabaseReference&& reference); + + /// @brief Move assignment operator. Moving is an efficient operation for + /// DatabaseReference instances. + /// + /// @param[in] reference DatabaseReference to move data from. + /// + /// @returns Reference to the destination DatabaseReference. + DatabaseReference& operator=(DatabaseReference&& reference); +#endif // defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) + + /// @brief Gets the database to which we refer. + /// + /// The pointer will remain valid indefinitely. + /// + /// @returns Firebase Database instance that this DatabaseReference refers to. + Database* database() const; + + /// @brief Gets the string key of this database location. + /// + /// The pointer is only valid while the DatabaseReference remains in memory. + /// + /// @returns String key of this database location, which will remain valid in + /// memory until the DatabaseReference itself goes away. + const char* key() const; + + /// @brief Gets the string key of this database location. + /// + /// @returns String key of this database location. + std::string key_string() const; + + /// @brief Returns true if this reference refers to the root of the database. + /// + /// @returns true if this reference refers to the root of the database, false + /// otherwise. + bool is_root() const; + + /// @brief Returns true if this reference is valid, false if it is not + /// valid. DatabaseReferences constructed with the default constructor + /// are considered invalid. An invalid reference could be returned by + /// Database::GetReference() or Database::GetReferenceFromUrl() if you specify + /// an incorrect location, or calling Query::GetReference() on an invalid + /// query. + /// + /// @returns true if this reference is valid, false if this reference is + /// invalid. + bool is_valid() const override; + + /// @brief Gets the parent of this location, or get this location again if + /// IsRoot(). + /// + /// @returns Parent of this location in the database, unless this location is + /// the root, in which case it returns this same location again. + DatabaseReference GetParent() const; + + /// @brief Gets the root of the database. + /// + /// @returns Root of the database. + DatabaseReference GetRoot() const; + + /// @brief Gets a reference to a location relative to this one. + /// + /// @param[in] path Path relative to this snapshot's location. + /// The pointer only needs to be valid during this call. + /// + /// @returns Child relative to this location. + DatabaseReference Child(const char* path) const; + + /// @brief Gets a reference to a location relative to this one. + /// + /// @param[in] path Path relative to this snapshot's location. + /// + /// @returns Child relative to this location. + DatabaseReference Child(const std::string& path) const; + + /// @brief Automatically generates a child location, create a reference to it, + /// and returns that reference to it. + /// + /// @returns A newly created child, with a unique key. + DatabaseReference PushChild() const; + + /// @brief Removes the value at this location from the database. + /// + /// This is an asynchronous operation which takes time to execute, and uses + /// firebase::Future to return its result. + /// + /// @returns A Future result, which will complete when the operation either + /// succeeds or fails. When the Future is completed, if its Error is + /// kErrorNone, the operation succeeded. + /// + /// @note Only one RemoveValue() should be running on a given database + /// location at the same time. If you need to run multiple operations at once, + /// use RunTransaction(). + Future RemoveValue(); + + /// @brief Gets the result of the most recent call to RemoveValue(); + /// + /// @returns Result of the most recent call to RemoveValue(). + Future RemoveValueLastResult(); + + /// @brief Run a user-supplied callback function (passing in a context), + /// possibly multiple times, to perform an atomic transaction on the database. + /// + /// @see firebase::database::DoTransactionWithContext for more information. + /// + /// @param[in] transaction_function The user-supplied function that will be + /// called, possibly multiple times, to perform the database transaction. + /// @param[in] context User-supplied context that will be passed to the + /// transaction function. + /// @param[in] trigger_local_events If true, events will be triggered for + /// intermediate state changes during the transaction. If false, only the + /// final state will cause events to be triggered. + /// + /// @returns A Future result, which will complete when the transaction either + /// succeeds or fails. When the Future is completed, if its Error is + /// kErrorNone, the operation succeeded and the transaction was committed, and + /// the new value of the data will be returned in the DataSnapshot result. If + /// the Error is kErrorTransactionAbortedByUser, the transaction was aborted + /// because the transaction function returned kTransactionResultAbort, and the + /// old value will be returned in DataSnapshot. Otherwise, if some other error + /// occurred, Error and ErrorMessage will be set and DataSnapshot will be + /// invalid. + /// + /// @note Only one RunTransaction() should be running on a given database + /// location at the same time. + Future RunTransaction( + DoTransactionWithContext transaction_function, void* context, + bool trigger_local_events = true); + +#if defined(FIREBASE_USE_STD_FUNCTION) || defined(DOXYGEN) + /// @brief Run a user-supplied callback, possibly multiple times, to perform + /// an atomic transaction on the database. + /// + /// @see firebase::database::DoTransactionFunction for more information. + /// + /// @param[in] transaction_function The user-supplied function or lambda that + /// will be called, possibly multiple times, to perform the database + /// transaction. + /// @param[in] trigger_local_events If true, events will be triggered for + /// intermediate state changes during the transaction. If false, only the + /// final state will cause events to be triggered. + /// + /// @returns A Future result, which will complete when the transaction either + /// succeeds or fails. When the Future is completed, if its Error is + /// kErrorNone, the operation succeeded and the transaction was committed, and + /// the new value of the data will be returned in the DataSnapshot result. If + /// the Error is kErrorTransactionAbortedByUser, the transaction was aborted + /// because the transaction function returned kTransactionResultAbort, and the + /// old value will be returned in DataSnapshot. Otherwise, if some other error + /// occurred, Error and ErrorMessage will be set and DataSnapshot will be + /// invalid. + /// + /// @note Only one RunTransaction() should be running on a given database + /// location at the same time. + /// + /// @note This version (that accepts an std::function) is not available when + /// using stlport on Android. If you don't wish to use std::function, use the + /// overloaded method that accepts a simple function pointer with a context. + Future RunTransaction( + DoTransactionFunction transaction_function, + bool trigger_local_events = true); +#endif // defined(FIREBASE_USE_STD_FUNCTION) || defined(DOXYGEN) + +#if !defined(FIREBASE_USE_STD_FUNCTION) || defined(DOXYGEN) + /// @brief Run a user-supplied callback function, possibly multiple times, to + /// perform an atomic transaction on the database. + /// + /// @see firebase::database::DoTransaction for more information. + /// + /// @param[in] transaction_function The user-supplied function that will be + /// called, possibly multiple times, to perform the database transaction. + /// @param[in] trigger_local_events If true, events will be triggered for + /// intermediate state changes during the transaction. If false, only the + /// final state will cause events to be triggered. + /// + /// @returns A Future result, which will complete when the transaction either + /// succeeds or fails. When the Future is completed, if its Error is + /// kErrorNone, the operation succeeded and the transaction was committed, and + /// the new value of the data will be returned in the DataSnapshot result. If + /// the Error is kErrorTransactionAbortedByUser, the transaction was aborted + /// because the transaction function returned kTransactionResultAbort, and the + /// old value will be returned in DataSnapshot. Otherwise, if some other error + /// occurred, Error and ErrorMessage will be set and DataSnapshot will be + /// invalid. + /// + /// @note Only one RunTransaction() should be running on a given database + /// location at the same time. + /// + /// @note This version (that accepts a simple function pointer) is only + /// available when using stlport and std::function is not available. + Future RunTransaction(DoTransaction transaction_function, + bool trigger_local_events = true); +#endif // !defined(FIREBASE_USE_STD_FUNCTION) || defined(DOXYGEN) + + /// @brief Get the result of the most recent call to RunTransaction(). + /// + /// @returns Results of the most recent call to RunTransaction(). + Future RunTransactionLastResult(); + + /// @brief Sets the priority of this field, which controls its sort + /// order relative to its siblings. + /// + /// In Firebase, children are sorted in the following order: + /// 1. First, children with no priority. + /// 2. Then, children with numerical priority, sorted numerically in + /// ascending order. + /// 3. Then, remaining children, sorted lexicographically in ascending order + /// of their text priority. + /// + /// Children with the same priority (including no priority) are sorted by + /// key: + /// A. First, children with keys that can be parsed as 32-bit integers, + /// sorted in ascending numerical order of their keys. + /// B. Then, remaining children, sorted in ascending lexicographical order + /// of their keys. + /// + /// This is an asynchronous operation which takes time to execute, and uses + /// firebase::Future to return its result. + /// + /// @param[in] priority Sort priority for this child relative to its siblings. + /// The Variant types accepted are Null, Int64, Double, and String. Other + /// types will return kErrorInvalidVariantType. + /// + /// @returns A Future result, which will complete when the operation either + /// succeeds or fails. When the Future is completed, if its Error is + /// kErrorNone, the operation succeeded. + /// + /// @note Only one SetPriority() should be running on a given database + /// location + /// at the same time. If you need to run multiple operations at once, use + /// RunTransaction(). + Future SetPriority(Variant priority); + + /// @brief Gets the result of the most recent call to SetPriority(). + /// + /// @returns Result of the most recent call to SetPriority(). + Future SetPriorityLastResult(); + + /// @brief Sets the data at this location to the given value. + /// + /// This is an asynchronous operation which takes time to execute, and uses + /// firebase::Future to return its result. + /// + /// @param[in] value The value to set this location to. The Variant's type + /// corresponds to the types accepted by the database JSON: + /// Null: Deletes this location from the database. + /// Int64: Inserts an integer value into this location. + /// Double: Inserts a floating point value into this location. + /// String: Inserts a string into this location. + /// (Accepts both Mutable and Static strings) + /// Vector: Inserts a JSON array into this location. The elements can be any + /// Variant type, including Vector and Map. + /// Map: Inserts a JSON associative array into this location. The keys must + /// be of type String (or Int64/Double which are converted to String). + /// The values can be any Variant type, including Vector and Map. + /// + /// @returns A Future result, which will complete when the operation either + /// succeeds or fails. When the Future is completed, if its Error is + /// kErrorNone, the operation succeeded. + /// + /// @note Only one SetValue() should be running on a given database location + /// at the same time. If you need to run multiple operations at once, use + /// RunTransaction(). + Future SetValue(Variant value); + + /// @brief Gets the result of the most recent call to SetValue(). + /// + /// @returns Result of the most recent call to SetValue(). + Future SetValueLastResult(); + + /// @brief Sets both the data and priority of this location. See SetValue() + /// and SetPriority() for context on the parameters. + /// + /// This is an asynchronous operation which takes time to execute, and uses + /// firebase::Future to return its result. + /// + /// @param[in] value The value to set this location to. See SetValue() for + /// information on the types accepted. + /// @param[in] priority The priority to set this location to. See + /// SetPriority() for information on the types accepted. + /// + /// @returns A Future result, which will complete when the operation either + /// succeeds or fails. When the Future is completed, if its Error is + /// kErrorNone, the operation succeeded. + /// + /// @note Only one SetValueAndPriority() should be running on a given database + /// location at the same time. SetValueAndPriority() can't be used on the same + /// location at the same time as either SetValue() or SetPriority(), and will + /// return kErrorConflictingOperationInProgress if you try. If you need to run + /// multiple operations at once, use RunTransaction(). + Future SetValueAndPriority(Variant value, Variant priority); + + /// @brief Get the result of the most recent call to SetValueAndPriority(). + /// + /// @returns Result of the most recent call to SetValueAndPriority(). + Future SetValueAndPriorityLastResult(); + + /// @brief Updates the specified child keys to the given values. + /// + /// @param[in] values A variant of type Map. The keys are the paths to update + /// and must be of type String (or Int64/Double which are converted to + /// String). The values can be any Variant type. A value of Variant type Null + /// will delete the child. + /// + /// @returns A Future result, which will complete when the operation either + /// succeeds or fails. When the Future is completed, if its Error is + /// kErrorNone, the operation succeeded. + /// + /// @note This method will return kErrorConflictingOperationInProgress if it + /// is run at the same time as SetValue(), SetValueAndPriority(), or + /// RemoveValue() in the same location. + Future UpdateChildren(Variant values); + + /// @brief Updates the specified child keys to the given values. + /// + /// This is an asynchronous operation which takes time to execute, and uses + /// firebase::Future to return its result. + /// + /// @param[in] values The paths to update, and their new child values. A value + /// of type Null will delete that particular child. + /// + /// @returns A Future result, which will complete when the operation either + /// succeeds or fails. When the Future is completed, if its Error is + /// kErrorNone, the operation succeeded. + inline Future UpdateChildren( + const std::map& values) { + return UpdateChildren(Variant(values)); + } + + /// @brief Gets the result of the most recent call to either version of + /// UpdateChildren(). + /// + /// @returns Result of the most recent call to UpdateChildren(). + Future UpdateChildrenLastResult(); + + /// @brief Get the absolute URL of this reference. + /// + /// @returns The absolute URL of the location this reference refers to. + std::string url() const; + + /// @brief Get the disconnect handler, which controls what actions the server + /// will perform to this location's data when this client disconnects. + /// + /// @returns Disconnection handler for this location. You can use this to + /// queue up operations on the server to be performed when the client + /// disconnects. + DisconnectionHandler* OnDisconnect(); + + /// @brief Manually disconnect Firebase Realtime Database from the server, and + /// disable automatic reconnection. This will affect all other instances of + /// DatabaseReference as well. + void GoOffline(); + + /// @brief Manually reestablish connection to the Firebase Realtime Database + /// server and enable automatic reconnection. This will affect all other + /// instances of DatabaseReference as well. + void GoOnline(); + + protected: + /// @cond FIREBASE_APP_INTERNAL + explicit DatabaseReference(internal::DatabaseReferenceInternal* internal); + /// @endcond + + private: + /// @cond FIREBASE_APP_INTERNAL + + // Remove the "Query" cleanup registration (which the base class constructor + // already registered) and replace it with a "DatabaseReference" registration. + // + // This is necessary so that if the instance needs to be cleaned up, the + // correct pointer type will be used to access it. + void SwitchCleanupRegistrationToDatabaseReference(); + + // Remove the "DatabaseReference" cleanup registration and replace it with a + // "Query" one. ~Query() will unregister that one. + void SwitchCleanupRegistrationBackToQuery(); + + friend class DataSnapshot; + friend class Query; + friend class internal::DatabaseInternal; + friend class internal::Repo; + friend bool operator==(const DatabaseReference& lhs, + const DatabaseReference& rhs); + /// @endcond + + internal::DatabaseReferenceInternal* internal_; +}; + +/// @brief Compares two DatabaseReference instances. +/// +/// @param[in] lhs A DatabaseReference. +/// @param[in] rhs A DatabaseReference to compare against. +/// +/// @returns True if the DatabaseReference instances have the same URL. False +/// otherwise. +bool operator==(const DatabaseReference& lhs, const DatabaseReference& rhs); + +} // namespace database +} // namespace firebase + +#endif // FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_DATABASE_REFERENCE_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/database/disconnection.h b/packages/firebase_core/firebase_core/firebase_core/firebase/database/disconnection.h new file mode 100644 index 000000000000..b21fa472e629 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/database/disconnection.h @@ -0,0 +1,156 @@ +// Copyright 2016 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_DISCONNECTION_H_ +#define FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_DISCONNECTION_H_ + +#include "firebase/future.h" +#include "firebase/internal/common.h" +#include "firebase/variant.h" + +namespace firebase { +namespace database { +namespace internal { +class DatabaseReferenceInternal; +class DisconnectionHandlerInternal; +} // namespace internal + +/// Allows you to register server-side actions to occur when the client +/// disconnects. Each method you call (with the exception of Cancel) will queue +/// up an action on the data that will be performed by the server in the event +/// the client disconnects. To reset this queue, call Cancel(). +/// +/// A DisconnectionHandler is associated with a specific location in the +/// database, as they are obtained by calling DatabaseReference::OnDisconnect(). +class DisconnectionHandler { + public: + ~DisconnectionHandler(); + + /// @brief Cancel any Disconnection operations that are queued up by this + /// handler. When the Future returns, if its Error is kErrorNone, the queue + /// has been cleared on the server. + /// + /// @returns A Future result, which will complete when the operation either + /// succeeds or fails. When the Future is completed, if its Error is + /// kErrorNone, the operation succeeded. + Future Cancel(); + /// @brief Get the result of the most recent call to Cancel(). + /// + /// @returns Result of the most recent call to Cancel(). + Future CancelLastResult(); + + /// @brief Remove the value at the current location when the client + /// disconnects. When the Future returns, if its Error is kErrorNone, the + /// RemoveValue operation has been successfully queued up on the server. + /// + /// @returns A Future result, which will complete when the operation either + /// succeeds or fails. When the Future is completed, if its Error is + /// kErrorNone, the operation succeeded. + Future RemoveValue(); + /// @brief Get the result of the most recent call to RemoveValue(). + /// + /// @returns Result of the most recent call to RemoveValue(). + Future RemoveValueLastResult(); + + /// @brief Set the value of the data at the current location when the client + /// disconnects. When the Future returns, if its Error is kErrorNone, the + /// SetValue operation has been successfully queued up on the server. + /// + /// @param[in] value The value to set this location to when the client + /// disconnects. For information on how the Variant types are used, + /// see firebase::database::DatabaseReference::SetValue(). + /// + /// @returns A Future result, which will complete when the operation either + /// succeeds or fails. When the Future is completed, if its Error is + /// kErrorNone, the operation succeeded. + Future SetValue(Variant value); + /// Get the result of the most recent call to SetValue(). + /// + /// @returns Result of the most recent call to SetValue(). + Future SetValueLastResult(); + + /// @brief Set the value and priority of the data at the current location when + /// the client disconnects. When the Future returns, if its Error is + /// kErrorNone, the SetValue operation has been successfully queued up on the + /// server. + /// + /// @param[in] value The value to set this location to when the client + /// disconnects. For information on how the Variant types are used, + /// see firebase::database::DatabaseReference::SetValue(). + /// @param[in] priority The priority to set this location to when the client + /// disconnects. The Variant types accepted are Null, Int64, Double, and + /// String. For information about how priority is used, see + /// firebase::database::DatabaseReference::SetPriority(). + /// + /// @returns A Future result, which will complete when the operation either + /// succeeds or fails. When the Future is completed, if its Error is + /// kErrorNone, the operation succeeded. + Future SetValueAndPriority(Variant value, Variant priority); + /// @brief Get the result of the most recent call to SetValueAndPriority(). + /// + /// @returns Result of the most recent call to SetValueAndPriority(). + Future SetValueAndPriorityLastResult(); + + /// @brief Updates the specified child keys to the given values when the + /// client disconnects. When the Future returns, if its Error is kErrorNone, + /// the UpdateChildren operation has been successfully queued up by the + /// server. + /// + /// @param[in] values A variant of type Map. The keys are the paths to update + /// and must be of type String (or Int64/Double which are converted to + /// String). The values can be any Variant type. A value of Variant type Null + /// will delete the child. + /// + /// @returns A Future result, which will complete when the operation either + /// succeeds or fails. When the Future is completed, if its Error is + /// kErrorNone, the operation succeeded. + Future UpdateChildren(Variant values); + /// @brief Updates the specified child keys to the given values when the + /// client disconnects. When the Future returns, if its Error is kErrorNone, + /// the UpdateChildren operation has been successfully queued up by the + /// server. + /// + /// @param[in] values The paths to update, and their new child values. A value + /// of type Null will delete that particular child. + /// + /// @returns A Future result, which will complete when the operation either + /// succeeds or fails. When the Future is completed, if its Error is + /// kErrorNone, the operation succeeded. + Future UpdateChildren(const std::map& values) { + return UpdateChildren(Variant(values)); + } + /// @brief Gets the result of the most recent call to either version of + /// UpdateChildren(). + /// + /// @returns Result of the most recent call to UpdateChildren(). + Future UpdateChildrenLastResult(); + + private: + /// @cond FIREBASE_APP_INTERNAL + friend class internal::DatabaseReferenceInternal; + friend class internal::DisconnectionHandlerInternal; + /// @endcond + + /// Call DatabaseReference::OnDisconnect() to get an instance of this class. + explicit DisconnectionHandler( + internal::DisconnectionHandlerInternal* internal); + + /// You can only get the DisconnectHandler for a given reference. + internal::DisconnectionHandlerInternal* internal_; +}; + +} // namespace database +} // namespace firebase + +#endif // FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_DISCONNECTION_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/database/listener.h b/packages/firebase_core/firebase_core/firebase_core/firebase/database/listener.h new file mode 100644 index 000000000000..fe13d9299003 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/database/listener.h @@ -0,0 +1,112 @@ +// Copyright 2016 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_LISTENER_H_ +#define FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_LISTENER_H_ + +#include "firebase/database/common.h" + +namespace firebase { +namespace database { + +class DataSnapshot; + +/// Value listener interface. Subclasses of this listener class can be +/// used to receive events about data changes at a location. Attach +/// the listener to a location using +/// DatabaseReference::AddValueListener() or +/// Query::AddValueListener(), and OnValueChanged() will be called +/// once immediately, and again when the value changes. +class ValueListener { + public: + virtual ~ValueListener(); + + /// This method will be called with a snapshot of the data at this + /// location each time that data changes. + /// + /// @param[in] snapshot The current data at the location. + virtual void OnValueChanged(const DataSnapshot& snapshot) = 0; + + /// @brief This method will be triggered in the event that this listener + /// either failed at the server, or is removed as a result of the security and + /// Firebase rules. + /// + /// @param[in] error A code corresponding to the error that occurred. + /// @param[in] error_message A description of the error that occurred. + virtual void OnCancelled(const Error& error, const char* error_message) = 0; +}; + +/// Child listener interface. Subclasses of this listener class can be +/// used to receive events about changes in the child locations of a +/// firebase::database::Query or +/// firebase::database::DatabaseReference. Attach the listener to a +/// location with Query::AddChildListener() or +/// DatabaseReference::AddChildListener() and the appropriate method +/// will be triggered when changes occur. +class ChildListener { + public: + virtual ~ChildListener(); + + /// @brief This method is triggered when a new child is added to the location + /// to which this listener was added. + /// + /// @param[in] snapshot An immutable snapshot of the data at the new data at + /// the child location. + /// @param[in] previous_sibling_key The key name of sibling location ordered + /// before the child. This will be nullptr for the first child node of a + /// location. + virtual void OnChildAdded(const DataSnapshot& snapshot, + const char* previous_sibling_key) = 0; + /// @brief This method is triggered when the data at a child location has + /// changed. + /// + /// @param[in] snapshot An immutable snapshot of the data at the new data at + /// the child location. + /// @param[in] previous_sibling_key The key name of sibling location ordered + /// before the child. This will be nullptr for the first child node of a + /// location. + virtual void OnChildChanged(const DataSnapshot& snapshot, + const char* previous_sibling_key) = 0; + /// @brief This method is triggered when a child location's priority changes. + /// See DatabaseReference::SetPriority() for more information on priorities + /// and + /// ordering data. + /// + /// @param[in] snapshot An immutable snapshot of the data at the new data at + /// the child location. + /// @param[in] previous_sibling_key The key name of sibling location ordered + /// before the child. This will be nullptr for the first child node of a + /// location. + virtual void OnChildMoved(const DataSnapshot& snapshot, + const char* previous_sibling_key) = 0; + /// @brief This method is triggered when a child is removed from the location + /// to which this listener was added. + /// + /// @param[in] snapshot An immutable snapshot of the data at the new data at + /// the child location. + virtual void OnChildRemoved(const DataSnapshot& snapshot) = 0; + + /// @brief This method will be triggered in the event that this listener + /// either failed at the server, or is removed as a result of the security and + /// Firebase rules. + /// + /// @param[in] error A code corresponding to the error that occurred. + /// @param[in] error_message A description of the error that occurred. + virtual void OnCancelled(const Error& error, const char* error_message) = 0; +}; + +} // namespace database +} // namespace firebase + +#endif // FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_LISTENER_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/database/mutable_data.h b/packages/firebase_core/firebase_core/firebase_core/firebase/database/mutable_data.h new file mode 100644 index 000000000000..cedfa159cca6 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/database/mutable_data.h @@ -0,0 +1,165 @@ +// Copyright 2016 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_MUTABLE_DATA_H_ +#define FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_MUTABLE_DATA_H_ + +#include "firebase/internal/common.h" +#include "firebase/variant.h" + +namespace firebase { +namespace database { +namespace internal { +class DatabaseInternal; +class DatabaseReferenceInternal; +class MutableDataInternal; +class Repo; +} // namespace internal + +#ifndef SWIG +/// Instances of this class encapsulate the data and priority at a location. It +/// is used in transactions, and it is intended to be inspected and then updated +/// to the desired data at that location. +#endif // SWIG +class MutableData { + public: +#if defined(FIREBASE_USE_MOVE_OPERATORS) + /// Move constructor + /// Move is more efficient than copy and delete. + MutableData(MutableData&& rhs); + + // MutableData may be moved. + MutableData& operator=(MutableData&& rhs); +#endif // defined(FIREBASE_USE_MOVE_OPERATORS) + + /// Destructor. + ~MutableData(); + + /// @brief Used to obtain a MutableData instance that encapsulates + /// the data and priority at the given relative path. + /// + /// Note that changes made to a child MutableData instance will be visible + /// to the parent and vice versa. + /// + /// @param[in] path Path relative to this snapshot's location. + /// The pointer only needs to be valid during this call. + /// + /// @returns MutableData for the Child relative to this location. The memory + /// will be freed when the Transaction is finished. + MutableData Child(const char* path); + + /// @brief Used to obtain a MutableData instance that encapsulates + /// the data and priority at the given relative path. + /// + /// @param[in] path Path relative to this snapshot's location. + /// + /// @returns MutableData for the Child relative to this location. The memory + /// will be freed when the Transaction is finished. + MutableData Child(const std::string& path); + + /// @brief Get all the immediate children of this location. + /// + /// @returns The immediate children of this location. + std::vector children(); + + /// @brief Get the number of children of this location. + /// + /// @returns The number of immediate children of this location. + size_t children_count(); + + /// @brief Get the key name of the source location of this data. + /// + /// @note The returned pointer is only guaranteed to be valid during the + /// transaction. + /// + /// @returns Key name of the source location of this data. + const char* key() const; + + /// @brief Get the key name of the source location of this data. + /// + /// @returns Key name of the source location of this data. + std::string key_string() const; + + /// @brief Get the value of the data contained at this location. + /// + /// @returns The value of the data contained at this location. + Variant value() const; + + /// @brief Get the priority of the data contained at this snapshot. + /// + /// @returns The value of this location's Priority relative to its siblings. + Variant priority(); + + /// @brief Does this MutableData have data at a particular location? + /// + /// @param[in] path Path relative to this data's location. + /// The pointer only needs to be valid during this call. + /// + /// @returns True if there is data at the specified location, false if not. + bool HasChild(const char* path) const; + + /// @brief Does this MutableData have data at a particular location? + /// + /// @param[in] path Path relative to this data's location. + /// @returns True if there is data at the specified location, false if not. + bool HasChild(const std::string& path) const; + + /// @brief Sets the data at this location to the given value. + /// + /// @param[in] value The value to set this location to. The Variant's type + /// corresponds to the types accepted by the database JSON: + /// Null: Deletes this location from the database. + /// Int64: Inserts an integer value into this location. + /// Double: Inserts a floating point value into this location. + /// String: Inserts a string into this location. + /// (Accepts both Mutable and Static strings) + /// Vector: Inserts a JSON array into this location. The elements can be any + /// Variant type, including Vector and Map. + /// Map: Inserts a JSON associative array into this location. The keys must + /// be of type String (or Int64/Double which are converted to String). + /// The values can be any Variant type, including Vector and Map. + void set_value(const Variant& value); + + /// @brief Sets the priority of this field, which controls its sort + /// order relative to its siblings. + /// + /// @see firebase::database::DatabaseReference::SetPriority() for information + /// on how Priority affects the ordering of a node's children. + /// + /// @param[in] priority Sort priority for this child relative to its siblings. + /// The Variant types accepted are Null, Int64, Double, and String. Other + /// types will return kErrorInvalidVariantType. + void set_priority(const Variant& priority); + + private: + /// @cond FIREBASE_APP_INTERNAL + friend class internal::DatabaseReferenceInternal; + friend class internal::DatabaseInternal; + friend class internal::MutableDataInternal; + friend class internal::Repo; + friend MutableData GetInvalidMutableData(); + /// @endcond + + explicit MutableData(internal::MutableDataInternal* internal); + + MutableData(const MutableData& rhs) = delete; + MutableData& operator=(const MutableData& rhs) = delete; + + internal::MutableDataInternal* internal_; +}; + +} // namespace database +} // namespace firebase + +#endif // FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_MUTABLE_DATA_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/database/query.h b/packages/firebase_core/firebase_core/firebase_core/firebase/database/query.h new file mode 100644 index 000000000000..c60707a7ee65 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/database/query.h @@ -0,0 +1,358 @@ +// Copyright 2016 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_QUERY_H_ +#define FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_QUERY_H_ + +#include + +#include "firebase/database/listener.h" +#include "firebase/future.h" +#include "firebase/internal/common.h" + +namespace firebase { +namespace database { +namespace internal { +class QueryInternal; +} // namespace internal + +class DatabaseReference; + +#ifndef SWIG +/// The Query class is used for reading data. Listeners can be attached, which +/// will be triggered when the data changes. +#endif // SWIG +class Query { + public: + /// Default constructor. This creates an invalid Query. Attempting to perform + /// any operations on this reference will fail unless a valid Query has been + /// assigned to it. + Query() : internal_(nullptr) {} + + /// Copy constructor. Queries can be copied. Copies exist independently of + /// each other. + Query(const Query& query); + + /// Copy assignment operator. Queries can be copied. Copies exist + /// independently of each other. + Query& operator=(const Query& query); + +#if defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) + /// Move constructor. + Query(Query&& query); + /// Move assignment operator. + Query& operator=(Query&& query); +#endif // defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) + + /// @brief Required virtual destructor. + virtual ~Query(); + + /// @brief Gets the value of the query for the given location a single time. + /// + /// This is an asynchronous operation which takes time to execute, and uses + /// firebase::Future to return its result. + /// + /// @returns A Future result, which will complete when the operation either + /// succeeds or fails. On this Future's completion, if its Error is + /// kErrorNone, the operation succeeded, and the DataSnapshot contains the + /// data in this location. + Future GetValue(); + /// @brief Gets the result of the most recent call to GetValue(). + /// + /// @returns Result of the most recent call to GetValue(). + Future GetValueLastResult(); + + /// @brief Adds a listener that will be called immediately and then again any + /// time the data changes. + /// + /// @param[in] listener A ValueListener instance, which must remain in memory + /// until you remove the listener from the Query. + void AddValueListener(ValueListener* listener); + + /// @brief Removes a listener that was previously added with + /// AddValueListener(). + /// + /// @param[in] listener A ValueListener instance to remove from the + /// Query. After it is removed, you can delete it or attach it to a new + /// location. + /// + /// @note You can remove a ValueListener from a different Query than you added + /// it to, as long as the two Query instances are equivalent. + void RemoveValueListener(ValueListener* listener); + + /// @brief Removes all value listeners that were added with + /// AddValueListener(). + /// + /// @note You can remove ValueListeners from a different Query than you added + /// them to, as long as the two Query instances are equivalent. + void RemoveAllValueListeners(); + + /// @brief Adds a listener that will be called any time a child is added, + /// removed, modified, or reordered. + /// + /// @param[in] listener A ChildListener instance, which must remain in memory + /// until you remove the listener from the Query. + void AddChildListener(ChildListener* listener); + + /// @brief Removes a listener that was previously added with + /// AddChildListener(). + /// + /// @param[in] listener A ChildListener instance to remove from the + /// Query. After it is removed, you can delete it or attach it to a new + /// location. + /// + /// @note You can remove a ChildListener from a different Query than you added + /// it to, as long as the two Query instances are equivalent. + void RemoveChildListener(ChildListener* listener); + + /// @brief Removes all child listeners that were added by AddChildListener(). + /// + /// @note You can remove ChildListeners from a different Query than you added + /// them to, as long as the two Query instances are equivalent. + void RemoveAllChildListeners(); + + /// @brief Gets a DatabaseReference corresponding to the given location. + /// + /// @returns A DatabaseReference corresponding to the same location as the + /// Query, but without any of the ordering or filtering parameters. + DatabaseReference GetReference() const; + + /// @brief Sets whether this location's data should be kept in sync even if + /// there are no active Listeners. + /// + /// By calling SetKeepSynchronized(true) on a given database location, the + /// data for that location will automatically be downloaded and kept in sync, + /// even when no listeners are attached for that location. Additionally, while + /// a location is kept synced, it will not be evicted from the persistent disk + /// cache. + /// + /// @param[in] keep_sync If true, set this location to be synchronized. If + /// false, set it to not be synchronized. + void SetKeepSynchronized(bool keep_sync); + + // The OrderBy* functions are used for two purposes: + // 1. Order the data when getting the list of children. + // 2. When filtering the data using the StartAt* and EndAt* functions further + // below, use the specified ordering. + + /// @brief Gets a query in which child nodes are ordered by the values of the + /// specified path. Any previous OrderBy directive will be replaced in the + /// returned Query. + /// + /// @param[in] path Path to a child node. The value of this node will be used + /// for sorting this query. The pointer you pass in need not remain valid + /// after the call completes. + /// + /// @returns A Query in this same location, with the children are sorted by + /// the value of their own child specified here. + Query OrderByChild(const char* path); + /// @brief Gets a query in which child nodes are ordered by the values of the + /// specified path. Any previous OrderBy directive will be replaced in the + /// returned Query. + /// + /// @param[in] path Path to a child node. The value of this node will be used + /// for sorting this query. + /// + /// @returns A Query in this same location, with the children are sorted by + /// the value of their own child specified here. + Query OrderByChild(const std::string& path); + /// @brief Gets a query in which child nodes are ordered by their keys. Any + /// previous OrderBy directive will be replaced in the returned Query. + /// + /// @returns A Query in this same location, with the children are sorted by + /// their key. + Query OrderByKey(); + /// @brief Gets a query in which child nodes are ordered by their priority. + /// Any previous OrderBy directive will be replaced in the returned Query. + /// + /// @returns A Query in this same location, with the children are sorted by + /// their priority. + Query OrderByPriority(); + /// @brief Create a query in which nodes are ordered by their value. + /// + /// @returns A Query in this same location, with the children are sorted by + /// their value. + Query OrderByValue(); + + // The StartAt, EndAt, and EqualTo functions are used to limit which child + // nodes are returned when iterating through the current location. + + /// @brief Get a Query constrained to nodes with the given sort value or + /// higher. + /// + /// This method is used to generate a reference to a limited view of the data + /// at this location. The Query returned will only refer to child nodes with a + /// value greater than or equal to the given value, using the given OrderBy + /// directive (or priority as the default). + /// + /// @param[in] order_value The lowest sort value the Query should include. + /// + /// @returns A Query in this same location, filtering out child nodes that + /// have a lower sort value than the sort value specified. + Query StartAt(Variant order_value); + /// @brief Get a Query constrained to nodes with the given sort value or + /// higher, and the given key or higher. + /// + /// This method is used to generate a reference to a limited view of the data + /// at this location. The Query returned will only refer to child nodes with a + /// value greater than or equal to the given value, using the given OrderBy + /// directive (or priority as default), and additionally only child nodes with + /// a key greater than or equal to the given key. + /// + /// Known issue This currently does not work properly on all platforms. + /// Please use StartAt(Variant order_value) instead. + /// + /// @param[in] order_value The lowest sort value the Query should include. + /// @param[in] child_key The lowest key the Query should include. + /// + /// @returns A Query in this same location, filtering out child nodes that + /// have a lower sort value than the sort value specified, or a lower key than + /// the key specified. + Query StartAt(Variant order_value, const char* child_key); + + /// @brief Get a Query constrained to nodes with the given sort value or + /// lower. + /// + /// This method is used to generate a reference to a limited view of the data + /// at this location. The Query returned will only refer to child nodes with a + /// value less than or equal to the given value, using the given OrderBy + /// directive (or priority as default). + /// + /// @param[in] order_value The highest sort value the Query should refer + /// to. + /// + /// @returns A Query in this same location, filtering out child nodes that + /// have a higher sort value or key than the sort value or key specified. + Query EndAt(Variant order_value); + /// @brief Get a Query constrained to nodes with the given sort value or + /// lower, and the given key or lower. + /// + /// This method is used to generate a reference to a limited view of + /// the data at this location. The Query returned will only refer to child + /// nodes with a value less than or equal to the given value, using the given + /// OrderBy directive (or priority as default), and additionally only child + /// nodes with a key less than or equal to the given key. + /// + /// Known issue This currently does not work properly on all platforms. + /// Please use EndAt(Variant order_value) instead. + /// + /// @param[in] order_value The highest sort value the Query should include. + /// @param[in] child_key The highest key the Query should include. + /// + /// @returns A Query in this same location, filtering out child nodes that + /// have a higher sort value than the sort value specified, or a higher key + /// than the key specified. + Query EndAt(Variant order_value, const char* child_key); + + /// @brief Get a Query constrained to nodes with the exact given sort value. + /// + /// This method is used to create a query constrained to only return child + /// nodes with the given value, using the given OrderBy directive (or priority + /// as default). + /// + /// @param[in] order_value The exact sort value the Query should include. + /// + /// @returns A Query in this same location, filtering out child nodes that + /// have a different sort value than the sort value specified. + Query EqualTo(Variant order_value); + + /// @brief Get a Query constrained to nodes with the exact given sort value, + /// and the exact given key. + /// + /// This method is used to create a query constrained to only return the child + /// node with the given value, using the given OrderBy directive (or priority + /// as default), and the given key. Note that there is at most one such child + /// as child key names are unique. + /// + /// Known issue This currently does not work properly on iOS, tvOS and + /// desktop. Please use EqualTo(Variant order_value) instead. + /// + /// @param[in] order_value The exact sort value the Query should include. + /// @param[in] child_key The exact key the Query should include. + /// + /// @returns A Query in this same location, filtering out child nodes that + /// have a different sort value than the sort value specified, and containing + /// at most one child with the exact key specified. + Query EqualTo(Variant order_value, const char* child_key); + + // The LimitTo* functions are used to limit how many child nodes are returned + // when iterating through the current location. + + /// @brief Gets a Query limited to only the first results. + /// + /// Limits the query to reference only the first N child nodes, using the + /// given OrderBy directive (or priority as default). + /// + /// @param[in] limit Number of children to limit the Query to. + /// + /// @returns A Query in this same location, limited to the specified number of + /// children (taken from the beginning of the sorted list). + Query LimitToFirst(size_t limit); + /// @brief Gets a Query limited to only the last results. + /// + /// @param[in] limit Number of children to limit the Query to. + /// + /// @returns A Query in this same location, limited to the specified number of + /// children (taken from the end of the sorted list). + Query LimitToLast(size_t limit); + + /// @brief Returns true if this query is valid, false if it is not valid. An + /// invalid query could be returned by, say, attempting to OrderBy two + /// different items, or calling OrderByChild() with an empty path, or by + /// constructing a Query with the default constructor. If a Query + /// is invalid, attempting to add more constraints will also result in an + /// invalid Query. + /// + /// @returns true if this query is valid, false if this query is + /// invalid. + virtual bool is_valid() const; + + protected: + /// @cond FIREBASE_APP_INTERNAL + explicit Query(internal::QueryInternal* internal); + void SetInternal(internal::QueryInternal* internal); + void RegisterCleanup(); + void UnregisterCleanup(); + /// @endcond + + private: + /// @cond FIREBASE_APP_INTERNAL + friend bool operator==(const Query& lhs, const Query& rhs); + /// @endcond + + internal::QueryInternal* internal_; +}; + +/// @brief Compares two Query instances. +/// +/// Two Query instances on the same database, in the same location, with the +/// same parameters (OrderBy*, StartAt, EndAt, EqualTo, Limit*) are considered +/// equivalent. +/// +/// Equivalent Queries have a shared pool of ValueListeners and +/// ChildListeners. When listeners are added or removed from one Query +/// instance, it affects all equivalent Query instances. +/// +/// @param[in] lhs The Query to compare against. +/// @param[in] rhs The Query to compare against. +/// +/// @returns True if the Query instances have the same database, the same +/// path, and the same parameters, determined by StartAt(), EndAt(), +/// EqualTo(), and the OrderBy and LimitTo methods. False otherwise. +bool operator==(const Query& lhs, const Query& rhs); + +} // namespace database +} // namespace firebase + +#endif // FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_QUERY_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/database/transaction.h b/packages/firebase_core/firebase_core/firebase_core/firebase/database/transaction.h new file mode 100644 index 000000000000..cb2dd33c59e2 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/database/transaction.h @@ -0,0 +1,102 @@ +// Copyright 2016 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_TRANSACTION_H_ +#define FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_TRANSACTION_H_ + +#include "firebase/database/common.h" +#include "firebase/database/data_snapshot.h" +#include "firebase/database/mutable_data.h" +#include "firebase/internal/common.h" +#include "firebase/variant.h" + +#if defined(FIREBASE_USE_STD_FUNCTION) +#include +#endif // defined(FIREBASE_USE_STD_FUNCTION) + +namespace firebase { +namespace database { + +/// Specifies whether the transaction succeeded or not. +enum TransactionResult { + /// The transaction was successful, the MutableData was updated. + kTransactionResultSuccess, + /// The transaction did not succeed. Any changes to the MutableData + /// will be discarded. + kTransactionResultAbort, +}; + +/// Your own transaction handler, which the Firebase Realtime Database library +/// may call multiple times to apply changes to the data, and should return +/// success or failure depending on whether it succeeds. + +/// @note This version of the callback is no longer supported (unless you are +/// building for Android with stlport). You should use either one of +/// DoTransactionWithContext (a simple function pointer that accepts context +/// data) or DoTransactionFunction (based on std::function). +/// +/// @see DoTransactionWithContext for more information. +typedef TransactionResult (*DoTransaction)(MutableData* data); + +/// Your own transaction handler, which the Firebase Realtime Database library +/// may call multiple times to apply changes to the data, and should return +/// success or failure depending on whether it succeeds. The context you +/// specified to RunTransaction will be passed into this call. +/// +/// This function will be called, _possibly multiple times_, with the current +/// data at this location. The function is responsible for inspecting that data +/// and modifying it as desired, then returning a TransactionResult specifying +/// either that the MutableData was modified to a desired new state, or that the +/// transaction should be aborted. Whenever this function is called, the +/// MutableData passed in must be modified from scratch. +/// +/// Since this function may be called repeatedly for the same transaction, be +/// extremely careful of any side effects that may be triggered by this +/// function. In addition, this function is called from within the Firebase +/// Realtime Database library's run loop, so care is also required when +/// accessing data that may be in use by other threads in your application. +/// +/// Best practices for this function are to ONLY rely on the data passed in. +/// +/// @param[in] data Mutable data, which the callback can edit. +/// @param[in] context Context pointer, passed verbatim to the callback. +/// +/// @returns The callback should return kTransactionResultSuccess if the data +/// was modified, or kTransactionResultAbort if it was unable to modify the +/// data. If the callback returns kTransactionResultAbort, the RunTransaction() +/// call will return the kErrorTransactionAbortedByUser error code. +/// +/// @note If you want a callback to be triggered when the transaction is +/// finished, you can use the Future value returned by the method +/// running the transaction, and call Future::OnCompletion() to register a +/// callback to be called when the transaction either succeeds or fails. +/// +/// @see DoTransaction for more information. +typedef TransactionResult (*DoTransactionWithContext)(MutableData* data, + void* context); + +#if defined(FIREBASE_USE_STD_FUNCTION) || defined(DOXYGEN) +/// Your own transaction handler function or lambda, which the Firebase Realtime +/// Database library may call multiple times to apply changes to the data, and +/// should return success or failure depending on whether it succeeds. +/// +/// @see DoTransactionWithContext for more information. +typedef std::function + DoTransactionFunction; +#endif // defined(FIREBASE_USE_STD_FUNCTION) || defined(DOXYGEN) + +} // namespace database +} // namespace firebase + +#endif // FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_TRANSACTION_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/dynamic_links.h b/packages/firebase_core/firebase_core/firebase_core/firebase/dynamic_links.h new file mode 100644 index 000000000000..7a96de679f62 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/dynamic_links.h @@ -0,0 +1,117 @@ +// Copyright 2017 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef FIREBASE_DYNAMIC_LINKS_SRC_INCLUDE_FIREBASE_DYNAMIC_LINKS_H_ +#define FIREBASE_DYNAMIC_LINKS_SRC_INCLUDE_FIREBASE_DYNAMIC_LINKS_H_ + +#include + +#include "firebase/app.h" +#include "firebase/internal/common.h" + +#if !defined(DOXYGEN) && !defined(SWIG) +FIREBASE_APP_REGISTER_CALLBACKS_REFERENCE(dynamic_links) +#endif // !defined(DOXYGEN) && !defined(SWIG) + +namespace firebase { + +/// @brief Firebase Dynamic Links API. +/// +/// Firebase Dynamic Links is a cross-platform solution for generating and +/// receiving links, whether or not the app is already installed. +namespace dynamic_links { + +#ifndef SWIG +/// @brief Error code used by Futures returned by this API. +enum ErrorCode { + kErrorCodeSuccess = 0, + kErrorCodeFailed, +}; +#endif // SWIG + +/// @brief Enum describing the strength of a dynamic links match. +/// +/// This version is local to dynamic links; there is a similar enum in invites +/// and another internal version in app. +enum LinkMatchStrength { + /// No match has been achieved + kLinkMatchStrengthNoMatch = 0, + + /// The match between the Dynamic Link and device is not perfect. You should + /// not reveal any personal information related to the Dynamic Link. + kLinkMatchStrengthWeakMatch, + + /// The match between the Dynamic Link and this device has a high confidence, + /// but there is a small possibility of error. + kLinkMatchStrengthStrongMatch, + + /// The match between the Dynamic Link and the device is exact. You may + /// safely reveal any personal information related to this Dynamic Link. + kLinkMatchStrengthPerfectMatch +}; + +/// @brief The received Dynamic Link. +struct DynamicLink { + /// The URL that was passed to the app. + std::string url; + /// The match strength of the dynamic link. + LinkMatchStrength match_strength; +}; + +/// @brief Base class used to receive Dynamic Links. +class Listener { + public: + virtual ~Listener(); + + /// Called on the client when a dynamic link arrives. + /// + /// @param[in] dynamic_link The data describing the Dynamic Link. + virtual void OnDynamicLinkReceived(const DynamicLink* dynamic_link) = 0; +}; + +/// @brief Initialize Firebase Dynamic Links. +/// +/// After Initialize is called, the implementation may call functions on the +/// Listener provided at any time. +/// +/// @param[in] app The Firebase App object for this application. +/// @param[in] listener A Listener object that receives Dynamic Links. +/// +/// @return kInitResultSuccess if initialization succeeded, or +/// kInitResultFailedMissingDependency on Android if Google Play services is +/// not available on the current device. +InitResult Initialize(const App& app, Listener* listener); + +/// @brief Terminate Firebase Dynamic Links. +void Terminate(); + +/// @brief Set the listener for receiving Dynamic Links. +/// +/// @param[in] listener A Listener object that receives Dynamic Links. +/// +/// @return Pointer to the previously set listener. +Listener* SetListener(Listener* listener); + +/// Fetch any pending dynamic links. Each pending link will trigger a call to +/// the registered Listener class. +/// +/// This function is implicitly called on initialization. On iOS this is called +/// automatically when the app gains focus, but on Android this needs to be +/// called manually. +void Fetch(); + +} // namespace dynamic_links +} // namespace firebase + +#endif // FIREBASE_DYNAMIC_LINKS_SRC_INCLUDE_FIREBASE_DYNAMIC_LINKS_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/dynamic_links/components.h b/packages/firebase_core/firebase_core/firebase_core/firebase/dynamic_links/components.h new file mode 100644 index 000000000000..7a8e8fa1a44b --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/dynamic_links/components.h @@ -0,0 +1,336 @@ +// Copyright 2017 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef FIREBASE_DYNAMIC_LINKS_SRC_INCLUDE_FIREBASE_DYNAMIC_LINKS_COMPONENTS_H_ +#define FIREBASE_DYNAMIC_LINKS_SRC_INCLUDE_FIREBASE_DYNAMIC_LINKS_COMPONENTS_H_ + +#include +#include +#include + +#include "firebase/future.h" + +namespace firebase { + +namespace dynamic_links { + +/// @brief Google Analytics Parameters. +/// +/// Note that the strings used by the struct are not copied, as so must +/// either be statically allocated, or must persist in memory until the +/// DynamicLinkComponents that uses them goes out of scope. +struct GoogleAnalyticsParameters { + /// Constructs an empty set of Google Analytics parameters. + GoogleAnalyticsParameters() + : source(nullptr), + medium(nullptr), + campaign(nullptr), + term(nullptr), + content(nullptr) {} + + /// The campaign source; used to identify a search engine, newsletter, + /// or other source. + const char* source; + /// The campaign medium; used to identify a medium such as email or + /// cost-per-click (cpc). + const char* medium; + /// The campaign name; The individual campaign name, slogan, promo code, etc. + /// for a product. + const char* campaign; + /// The campaign term; used with paid search to supply the keywords for ads. + const char* term; + /// The campaign content; used for A/B testing and content-targeted ads to + /// differentiate ads or links that point to the same URL. + const char* content; +}; + +/// @brief iOS Parameters. +/// +/// Note that the strings used by the struct are not copied, as so must +/// either be statically allocated, or must persist in memory until the +/// DynamicLinkComponents that uses them goes out of scope. +struct IOSParameters { + /// Constructs a set of IOS parameters with the given bundle id. + /// + /// @param bundle_id_ The parameters ID of the iOS app to use to open the + /// link. + IOSParameters(const char* bundle_id_) + : bundle_id(bundle_id_), + fallback_url(nullptr), + custom_scheme(nullptr), + ipad_fallback_url(nullptr), + ipad_bundle_id(nullptr), + app_store_id(nullptr), + minimum_version(nullptr) {} + + /// Constructs an empty set of IOS parameters. + IOSParameters() + : bundle_id(nullptr), + fallback_url(nullptr), + custom_scheme(nullptr), + ipad_fallback_url(nullptr), + ipad_bundle_id(nullptr), + app_store_id(nullptr), + minimum_version(nullptr) {} + + /// The parameters ID of the iOS app to use to open the link. The app must be + /// connected to your project from the Overview page of the Firebase console. + /// Note this field is required. + const char* bundle_id; + /// The link to open on iOS if the app is not installed. + /// + /// Specify this to do something other than install your app from the + /// App Store when the app isn't installed, such as open the mobile + /// web version of the content, or display a promotional page for your app. + const char* fallback_url; + /// The app's custom URL scheme, if defined to be something other than your + /// app's parameters ID. + const char* custom_scheme; + /// The link to open on iPad if the app is not installed. + /// + /// Overrides fallback_url when on iPad. + const char* ipad_fallback_url; + /// The iPad parameters ID of the app. + const char* ipad_bundle_id; + /// The App Store ID, used to send users to the App Store when the app isn't + /// installed. + const char* app_store_id; + /// The minimum version of your app that can open the link. + const char* minimum_version; +}; + +/// @brief iTunes Connect App Analytics Parameters. +/// +/// Note that the strings used by the struct are not copied, as so must +/// either be statically allocated, or must persist in memory until the +/// DynamicLinkComponents that uses them goes out of scope. +struct ITunesConnectAnalyticsParameters { + /// Constructs an empty set of ITunes Connect Analytics parameters. + ITunesConnectAnalyticsParameters() + : provider_token(nullptr), + affiliate_token(nullptr), + campaign_token(nullptr) {} + + /// The provider token that enables analytics for Dynamic Links from + /// within iTunes Connect. + const char* provider_token; + /// The affiliate token used to create affiliate-coded links. + const char* affiliate_token; + /// The campaign token that developers can add to any link in order to + /// track sales from a specific marketing campaign. + const char* campaign_token; +}; + +/// @brief Android Parameters. +/// +/// Note that the strings used by the struct are not copied, as so must +/// either be statically allocated, or must persist in memory until the +/// DynamicLinkComponents that uses them goes out of scope. +struct AndroidParameters { + /// Constructs a set of Android parameters with the given package name. + /// + /// The package name of the Android app to use to open the link. + AndroidParameters(const char* package_name_) + : package_name(package_name_), + fallback_url(nullptr), + minimum_version(0) {} + + /// Constructs an empty set of Android parameters. + AndroidParameters() + : package_name(nullptr), fallback_url(nullptr), minimum_version(0) {} + + /// The package name of the Android app to use to open the link. The app + /// must be connected to your project from the Overview page of the Firebase + /// console. + /// Note this field is required. + const char* package_name; + /// The link to open when the app isn't installed. + /// + /// Specify this to do something other than install your app from the + /// Play Store when the app isn't installed, such as open the mobile web + /// version of the content, or display a promotional page for your app. + const char* fallback_url; + /// The versionCode of the minimum version of your app that can open the link. + int minimum_version; +}; + +/// @brief Social meta-tag Parameters. +/// +/// Note that the strings used by the struct are not copied, as so must +/// either be statically allocated, or must persist in memory until the +/// DynamicLinkComponents that uses them goes out of scope. +struct SocialMetaTagParameters { + /// Constructs an empty set of Social meta-tag parameters. + SocialMetaTagParameters() + : title(nullptr), description(nullptr), image_url(nullptr) {} + + /// The title to use when the Dynamic Link is shared in a social post. + const char* title; + /// The description to use when the Dynamic Link is shared in a social post. + const char* description; + /// The URL to an image related to this link. + const char* image_url; +}; + +/// @brief The desired path length for shortened Dynamic Link URLs. +enum PathLength { + /// Uses the server-default for the path length. + /// See https://goo.gl/8yDAqC for more information. + kPathLengthDefault = 0, + /// Typical short link for non-sensitive links. + kPathLengthShort, + /// Short link that uses a very long path to make it more difficult to + /// guess. Useful for sensitive links. + kPathLengthUnguessable, +}; + +/// @brief Additional options for Dynamic Link creation. +struct DynamicLinkOptions { + /// Constructs an empty set of Dynamic Link options. + DynamicLinkOptions() : path_length(kPathLengthDefault) {} + + /// The desired path length for shortened Dynamic Link URLs. + PathLength path_length; +}; + +/// @brief The returned value from creating a Dynamic Link. +struct GeneratedDynamicLink { + /// The Dynamic Link value. + std::string url; + /// Information about potential warnings on link creation. + /// + /// Usually presence of warnings means parameter format errors, parameter + /// value errors, or missing parameters. + std::vector warnings; + /// If non-empty, the cause of the Dynamic Link generation failure. + std::string error; +}; + +/// @brief The information needed to generate a Dynamic Link. +/// +/// Note that the strings used by the struct are not copied, as so must +/// either be statically allocated, or must persist in memory until this +/// struct goes out of scope. +struct DynamicLinkComponents { + /// The link your app will open. + /// You can specify any URL your app can handle, such as a link to your + /// app's content, or a URL that initiates some + /// app-specific logic such as crediting the user with a coupon, or + /// displaying a specific welcome screen. This link must be a well-formatted + /// URL, be properly URL-encoded, and use the HTTP or HTTPS scheme. + /// Note, this field is required. + const char* link; + /// The domain (of the form "https://xyz.app.goo.gl") to use for this Dynamic + /// Link. You can find this value in the Dynamic Links section of the Firebase + /// console. + /// + /// If you have set up custom domains on your project, set this to your + /// project's custom domain as listed in the Firebase console. + /// + /// Only https:// links are supported. + /// + /// Note, this field is required. + const char* domain_uri_prefix; + /// The Google Analytics parameters. + GoogleAnalyticsParameters* google_analytics_parameters; + /// The iOS parameters. + IOSParameters* ios_parameters; + /// The iTunes Connect App Analytics parameters. + ITunesConnectAnalyticsParameters* itunes_connect_analytics_parameters; + /// The Android parameters. + AndroidParameters* android_parameters; + /// The social meta-tag parameters. + SocialMetaTagParameters* social_meta_tag_parameters; + + /// Default constructor, initializes all fields to null. + DynamicLinkComponents() + : link(nullptr), + domain_uri_prefix(nullptr), + google_analytics_parameters(nullptr), + ios_parameters(nullptr), + itunes_connect_analytics_parameters(nullptr), + android_parameters(nullptr), + social_meta_tag_parameters(nullptr) {} + + /// Constructor that initializes with the given link and domain. + /// + /// @param link_ The link your app will open. + /// @param domain_uri_prefix_ The domain (of the form + /// "https://xyz.app.goo.gl") to use for this Dynamic Link. You can find this + /// value in the Dynamic Links section of the Firebase console. If you have + /// set up custom domains on your project, set this to your project's custom + /// domain as listed in the Firebase console. Note: If you do not specify + /// "https://" as the URI scheme, it will be added. + DynamicLinkComponents(const char* link_, const char* domain_uri_prefix_) + : link(link_), + domain_uri_prefix(domain_uri_prefix_), + google_analytics_parameters(nullptr), + ios_parameters(nullptr), + itunes_connect_analytics_parameters(nullptr), + android_parameters(nullptr), + social_meta_tag_parameters(nullptr) { + // For backwards compatibility with dynamic_link_domain, if + // domain_uri_prefix doesn't start with "https://", add it. + static const char kHttpsPrefix[] = "https://"; + static const size_t kHttpsPrefixLength = sizeof(kHttpsPrefix) - 1; + if (strncmp(domain_uri_prefix, kHttpsPrefix, kHttpsPrefixLength) != 0) { + domain_uri_prefix_with_scheme = + std::string(kHttpsPrefix) + domain_uri_prefix; + domain_uri_prefix = domain_uri_prefix_with_scheme.c_str(); + } + } + +#ifndef INTERNAL_EXPERIMENTAL + + private: +#endif // INTERNAL_EXPERIMENTAL + std::string domain_uri_prefix_with_scheme; +}; + +/// Creates a long Dynamic Link from the given parameters. +GeneratedDynamicLink GetLongLink(const DynamicLinkComponents& components); + +/// Creates a shortened Dynamic Link from the given parameters. +/// @param components: Settings used to configure the behavior for the link. +Future GetShortLink( + const DynamicLinkComponents& components); + +/// Creates a shortened Dynamic Link from the given parameters. +/// @param components: Settings used to configure the behavior for the link. +/// @param options: Additional options for Dynamic Link shortening, indicating +/// whether or not to produce an unguessable or shortest possible link. +/// No references to the options object will be retained after the call. +Future GetShortLink( + const DynamicLinkComponents& components, const DynamicLinkOptions& options); + +/// Creates a shortened Dynamic Link from a given long Dynamic Link. +/// @param long_dynamic_link A link previously generated from GetLongLink. +Future GetShortLink(const char* long_dynamic_link); + +/// Creates a shortened Dynamic Link from a given long Dynamic Link. +/// @param long_dynamic_link: A link previously generated from GetLongLink. +/// @param options: Additional options for Dynamic Link shortening, indicating +/// whether or not to produce an unguessable or shortest possible link. +/// No references to the options object will be retained after the call. +Future GetShortLink(const char* long_dynamic_link, + const DynamicLinkOptions& options); + +/// Get the (possibly still pending) results of the most recent GetShortUrl +/// call. +Future GetShortLinkLastResult(); + +} // namespace dynamic_links +} // namespace firebase + +#endif // FIREBASE_DYNAMIC_LINKS_SRC_INCLUDE_FIREBASE_DYNAMIC_LINKS_COMPONENTS_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore.h new file mode 100644 index 000000000000..c35de11b4d1a --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore.h @@ -0,0 +1,458 @@ +/* + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_H_ +#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_H_ + +#include +#include + +#include "firebase/internal/common.h" + +#include "firebase/app.h" +#include "firebase/future.h" +#include "firebase/log.h" +// Include *all* the public headers to make sure including just "firestore.h" is +// sufficient for users. +#include "firebase/firestore/collection_reference.h" +#include "firebase/firestore/document_change.h" +#include "firebase/firestore/document_reference.h" +#include "firebase/firestore/document_snapshot.h" +#include "firebase/firestore/field_path.h" +#include "firebase/firestore/field_value.h" +#include "firebase/firestore/firestore_errors.h" +#include "firebase/firestore/geo_point.h" +#include "firebase/firestore/listener_registration.h" +#include "firebase/firestore/load_bundle_task_progress.h" +#include "firebase/firestore/map_field_value.h" +#include "firebase/firestore/metadata_changes.h" +#include "firebase/firestore/query.h" +#include "firebase/firestore/query_snapshot.h" +#include "firebase/firestore/set_options.h" +#include "firebase/firestore/settings.h" +#include "firebase/firestore/snapshot_metadata.h" +#include "firebase/firestore/source.h" +#include "firebase/firestore/timestamp.h" +#include "firebase/firestore/transaction.h" +#include "firebase/firestore/transaction_options.h" +#include "firebase/firestore/write_batch.h" + +namespace firebase { +/** + * @brief Cloud Firestore API. + * + * Cloud Firestore is a flexible, scalable database for mobile, web, and server + * development from Firebase and Google Cloud Platform. + */ +namespace firestore { + +class FirestoreInternal; + +namespace csharp { + +class ApiHeaders; +class TransactionManager; + +} // namespace csharp + +/** + * @brief Entry point for the Firebase Firestore C++ SDK. + * + * To use the SDK, call firebase::firestore::Firestore::GetInstance() to obtain + * an instance of Firestore, then use Collection() or Document() to obtain + * references to child paths within the database. From there, you can set data + * via CollectionReference::Add() and DocumentReference::Set(), or get data via + * CollectionReference::Get() and DocumentReference::Get(), attach listeners, + * and more. + * + * @note Firestore classes are not meant to be subclassed except for use in test + * mocks. Subclassing is not supported in production code and new SDK releases + * may break code that does so. + */ +class Firestore { + public: + /** + * @brief Returns an instance of Firestore corresponding to the given App. + * + * Firebase Firestore uses firebase::App to communicate with Firebase + * Authentication to authenticate users to the Firestore server backend. + * + * If you call GetInstance() multiple times with the same App, you will get + * the same instance of Firestore. + * + * @param[in] app Your instance of firebase::App. Firebase Firestore will use + * this to communicate with Firebase Authentication. + * @param[out] init_result_out If provided, the initialization result will be + * written here. Will be set to firebase::kInitResultSuccess if initialization + * succeeded, or firebase::kInitResultFailedMissingDependency on Android if + * Google Play services is not available on the current device. + * + * @return An instance of Firestore corresponding to the given App. + */ + static Firestore* GetInstance(::firebase::App* app, + InitResult* init_result_out = nullptr); + + /** + * @brief Returns an instance of Firestore corresponding to the default App. + * + * Firebase Firestore uses the default App to communicate with Firebase + * Authentication to authenticate users to the Firestore server backend. + * + * If you call GetInstance() multiple times, you will get the same instance. + * + * @param[out] init_result_out If provided, the initialization result will be + * written here. Will be set to firebase::kInitResultSuccess if initialization + * succeeded, or firebase::kInitResultFailedMissingDependency on Android if + * Google Play services is not available on the current device. + * + * @return An instance of Firestore corresponding to the default App. + */ + static Firestore* GetInstance(InitResult* init_result_out = nullptr); + + /** + * @brief Destructor for the Firestore object. + * + * When deleted, this instance will be removed from the cache of Firestore + * objects. If you call GetInstance() in the future with the same App, a new + * Firestore instance will be created. + */ + virtual ~Firestore(); + + /** + * Deleted copy constructor; Firestore must be created with + * Firestore::GetInstance(). + */ + Firestore(const Firestore& src) = delete; + + /** + * Deleted copy assignment operator; Firestore must be created with + * Firestore::GetInstance(). + */ + Firestore& operator=(const Firestore& src) = delete; + + /** + * @brief Returns the firebase::App that this Firestore was created with. + * + * @return The firebase::App this Firestore was created with. + */ + virtual const App* app() const; + + /** + * @brief Returns the firebase::App that this Firestore was created with. + * + * @return The firebase::App this Firestore was created with. + */ + virtual App* app(); + + /** + * @brief Returns a CollectionReference instance that refers to the + * collection at the specified path within the database. + * + * @param[in] collection_path A slash-separated path to a collection. + * + * @return The CollectionReference instance. + */ + virtual CollectionReference Collection(const char* collection_path) const; + + /** + * @brief Returns a CollectionReference instance that refers to the + * collection at the specified path within the database. + * + * @param[in] collection_path A slash-separated path to a collection. + * + * @return The CollectionReference instance. + */ + virtual CollectionReference Collection( + const std::string& collection_path) const; + + /** + * @brief Returns a DocumentReference instance that refers to the document at + * the specified path within the database. + * + * @param[in] document_path A slash-separated path to a document. + * @return The DocumentReference instance. + */ + virtual DocumentReference Document(const char* document_path) const; + + /** + * @brief Returns a DocumentReference instance that refers to the document at + * the specified path within the database. + * + * @param[in] document_path A slash-separated path to a document. + * + * @return The DocumentReference instance. + */ + virtual DocumentReference Document(const std::string& document_path) const; + + /** + * @brief Returns a Query instance that includes all documents in the + * database that are contained in a collection or subcollection with the + * given collection_id. + * + * @param[in] collection_id Identifies the collections to query over. Every + * collection or subcollection with this ID as the last segment of its path + * will be included. Cannot contain a slash. + * + * @return The Query instance. + */ + virtual Query CollectionGroup(const char* collection_id) const; + + /** + * @brief Returns a Query instance that includes all documents in the + * database that are contained in a collection or subcollection with the + * given collection_id. + * + * @param[in] collection_id Identifies the collections to query over. Every + * collection or subcollection with this ID as the last segment of its path + * will be included. Cannot contain a slash. + * + * @return The Query instance. + */ + virtual Query CollectionGroup(const std::string& collection_id) const; + + /** Returns the settings used by this Firestore object. */ + virtual Settings settings() const; + + /** Sets any custom settings used to configure this Firestore object. */ + virtual void set_settings(Settings settings); + + /** + * Creates a write batch, used for performing multiple writes as a single + * atomic operation. + * + * Unlike transactions, write batches are persisted offline and therefore are + * preferable when you don't need to condition your writes on read data. + * + * @return The created WriteBatch object. + */ + virtual WriteBatch batch() const; + + /** + * Executes the given update and then attempts to commit the changes applied + * within the transaction. If any document read within the transaction has + * changed, the update function will be retried. If it fails to commit after + * 5 attempts, the transaction will fail. + * + * @param update function or lambda to execute within the transaction context. + * The string reference parameter can be used to set the error message. + * + * @return A Future that will be resolved when the transaction finishes. + */ + virtual Future RunTransaction( + std::function update); + + /** + * Executes the given update and then attempts to commit the changes applied + * within the transaction. If any document read within the transaction has + * changed, the update function will be retried. If it fails to commit after + * the `max_attempts` specified in the given `TransactionOptions`, the + * transaction will fail. + * + * @param options The transaction options for controlling execution. + * @param update function or lambda to execute within the transaction context. + * The string reference parameter can be used to set the error message. + * + * @return A Future that will be resolved when the transaction finishes. + */ + virtual Future RunTransaction( + TransactionOptions options, + std::function update); + + /** + * Sets the log verbosity of all Firestore instances. + * + * The default verbosity level is `kLogLevelInfo`. + * + * @param[in] log_level The desired verbosity. + */ + static void set_log_level(LogLevel log_level); + + /** + * Disables network access for this instance. While the network is disabled, + * any snapshot listeners or Get() calls will return results from cache, and + * any write operations will be queued until network usage is re-enabled via a + * call to EnableNetwork(). + * + * If the network was already disabled, calling `DisableNetwork()` again is + * a no-op. + */ + virtual Future DisableNetwork(); + + /** + * Re-enables network usage for this instance after a prior call to + * DisableNetwork(). + * + * If the network is currently enabled, calling `EnableNetwork()` is a no-op. + */ + virtual Future EnableNetwork(); + + /** + * Terminates this `Firestore` instance. + * + * After calling `Terminate()`, only the `ClearPersistence()` method may be + * used. Calling any other methods will result in an error. + * + * To restart after termination, simply create a new instance of `Firestore` + * with `Firestore::GetInstance()`. + * + * `Terminate()` does not cancel any pending writes and any tasks that are + * awaiting a response from the server will not be resolved. The next time you + * start this instance, it will resume attempting to send these writes to the + * server. + * + * Note: under normal circumstances, calling `Terminate()` is not required. + * This method is useful only when you want to force this instance to release + * all of its resources or in combination with `ClearPersistence()` to ensure + * that all local state is destroyed between test runs. + * + * @return A `Future` that is resolved when the instance has been successfully + * terminated. + */ + virtual Future Terminate(); + + /** + * Waits until all currently pending writes for the active user have been + * acknowledged by the backend. + * + * The returned future is resolved immediately without error if there are no + * outstanding writes. Otherwise, the future is resolved when all previously + * issued writes (including those written in a previous app session) have been + * acknowledged by the backend. The future does not wait for writes that were + * added after the method is called. If you wish to wait for additional + * writes, you have to call `WaitForPendingWrites` again. + * + * Any outstanding `WaitForPendingWrites` futures are resolved with an + * error during user change. + */ + virtual Future WaitForPendingWrites(); + + /** + * Clears the persistent storage. This includes pending writes and cached + * documents. + * + * Must be called while the Firestore instance is not started (after the app + * is shut down or when the app is first initialized). On startup, this method + * must be called before other methods (other than `settings()` and + * `set_settings()`). If the Firestore instance is still running, the function + * will complete with an error code of `FailedPrecondition`. + * + * Note: `ClearPersistence()` is primarily intended to help write + * reliable tests that use Firestore. It uses the most efficient mechanism + * possible for dropping existing data but does not attempt to securely + * overwrite or otherwise make cached data unrecoverable. For applications + * that are sensitive to the disclosure of cache data in between user sessions + * we strongly recommend not to enable persistence in the first place. + */ + virtual Future ClearPersistence(); + + /** + * Attaches a listener for a snapshots-in-sync event. Server-generated + * updates and local changes can affect multiple snapshot listeners. + * The snapshots-in-sync event indicates that all listeners affected by + * a given change have fired. + * + * NOTE: The snapshots-in-sync event only indicates that listeners are + * in sync with each other, but does not relate to whether those + * snapshots are in sync with the server. Use `SnapshotMetadata` in the + * individual listeners to determine if a snapshot is from the cache or + * the server. + * + * @param callback A callback to be called every time all snapshot + * listeners are in sync with each other. + * @return A `ListenerRegistration` object that can be used to remove the + * listener. + */ + virtual ListenerRegistration AddSnapshotsInSyncListener( + std::function callback); + + /** + * Loads a Firestore bundle into the local cache. + * + * @param bundle A string containing the bundle to be loaded. + * @return A `Future` that is resolved when the loading is either completed + * or aborted due to an error. + */ + virtual Future LoadBundle(const std::string& bundle); + + /** + * Loads a Firestore bundle into the local cache, with the provided callback + * executed for progress updates. + * + * @param bundle A string containing the bundle to be loaded. + * @param progress_callback A callback that is called with progress + * updates, and completion or error updates. + * @return A `Future` that is resolved when the loading is either completed + * or aborted due to an error. + */ + virtual Future LoadBundle( + const std::string& bundle, + std::function progress_callback); + + /** + * Reads a Firestore `Query` from the local cache, identified by the given + * name. + * + * Named queries are packaged into bundles on the server side (along with the + * resulting documents) and loaded into local cache using `LoadBundle`. Once + * in the local cache, you can use this method to extract a query by name. + * + * If a query cannot be found, the returned future will complete with its + * `error()` set to a non-zero error code. + * + * @param query_name The name of the query to read from saved bundles. + */ + virtual Future NamedQuery(const std::string& query_name); + + protected: + /** + * Default constructor, to be used only for mocking `Firestore`. + */ + Firestore() = default; + + private: + friend class FieldValueInternal; + friend class FirestoreInternal; + friend class Wrapper; + friend struct ConverterImpl; + friend class FirestoreIntegrationTest; + friend class IncludesTest; + template + friend struct CleanupFn; + + friend class csharp::ApiHeaders; + friend class csharp::TransactionManager; + + explicit Firestore(::firebase::App* app); + explicit Firestore(FirestoreInternal* internal); + + static Firestore* CreateFirestore(::firebase::App* app, + FirestoreInternal* internal, + InitResult* init_result_out); + static Firestore* AddFirestoreToCache(Firestore* firestore, + InitResult* init_result_out); + + static void SetClientLanguage(const std::string& language_token); + + // Delete the internal_ data. + void DeleteInternal(); + + mutable FirestoreInternal* internal_ = nullptr; +}; + +} // namespace firestore +} // namespace firebase + +#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/collection_reference.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/collection_reference.h new file mode 100644 index 000000000000..3d9d4de2ee7f --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/collection_reference.h @@ -0,0 +1,183 @@ +/* + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_COLLECTION_REFERENCE_H_ +#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_COLLECTION_REFERENCE_H_ + +#include + +#include "firebase/firestore/map_field_value.h" +#include "firebase/firestore/query.h" + +namespace firebase { + +/// @cond FIREBASE_APP_INTERNAL +template +class Future; +/// @endcond + +namespace firestore { + +class CollectionReferenceInternal; +class DocumentReference; + +/** + * @brief A CollectionReference can be used for adding documents, getting + * document references, and querying for documents (using the methods inherited + * from `Query`). + * + * @note Firestore classes are not meant to be subclassed except for use in test + * mocks. Subclassing is not supported in production code and new SDK releases + * may break code that does so. + */ +class CollectionReference : public Query { + public: + /** + * @brief Creates an invalid CollectionReference that has to be reassigned + * before it can be used. + * + * Calling any member function on an invalid CollectionReference will be + * a no-op. If the function returns a value, it will return a zero, empty, or + * invalid value, depending on the type of the value. + */ + CollectionReference(); + + /** + * @brief Copy constructor. + * + * `CollectionReference` can be efficiently copied because it simply refers to + * a location in the database. + * + * @param[in] other `CollectionReference` to copy from. + */ + CollectionReference(const CollectionReference& other); + + /** + * @brief Move constructor. + * + * Moving is more efficient than copying for a `CollectionReference`. After + * being moved from, a `CollectionReference` is equivalent to its + * default-constructed state. + * + * @param[in] other `CollectionReference` to move data from. + */ + CollectionReference(CollectionReference&& other); + + /** + * @brief Copy assignment operator. + * + * `CollectionReference` can be efficiently copied because it simply refers to + * a location in the database. + * + * @param[in] other `CollectionReference` to copy from. + * + * @return Reference to the destination `CollectionReference`. + */ + CollectionReference& operator=(const CollectionReference& other); + + /** + * @brief Move assignment operator. + * + * Moving is more efficient than copying for a `CollectionReference`. After + * being moved from, a `CollectionReference` is equivalent to its + * default-constructed state. + * + * @param[in] other `CollectionReference` to move data from. + * + * @return Reference to the destination `CollectionReference`. + */ + CollectionReference& operator=(CollectionReference&& other); + + /** + * @brief Gets the ID of the referenced collection. + * + * @return The ID as a std::string. + */ + virtual const std::string& id() const; + + /** + * @brief Returns the path of this collection (relative to the root of the + * database) as a slash-separated string. + * + * @return The path as a std::string. + */ + virtual std::string path() const; + + /** + * @brief Gets a DocumentReference to the document that contains this + * collection. + * + * @return The DocumentReference that contains this collection if this is a + * subcollection. If this is a root collection, returns an invalid + * DocumentReference (`DocumentReference::is_valid()` will return false). + */ + virtual DocumentReference Parent() const; + + /** + * @brief Returns a DocumentReference that points to a new document with an + * auto-generated ID within this collection. + * + * @return A DocumentReference pointing to the new document. + */ + virtual DocumentReference Document() const; + + /** + * @brief Gets a DocumentReference instance that refers to the document at the + * specified path within this collection. + * + * @param[in] document_path A slash-separated relative path to a document. + * The pointer only needs to be valid during this call. + * + * @return The DocumentReference instance. + */ + virtual DocumentReference Document(const char* document_path) const; + + /** + * @brief Gets a DocumentReference instance that refers to the document at the + * specified path within this collection. + * + * @param[in] document_path A slash-separated relative path to a document. + * + * @return The DocumentReference instance. + */ + virtual DocumentReference Document(const std::string& document_path) const; + + /** + * @brief Adds a new document to this collection with the specified data, + * assigning it a document ID automatically. + * + * @param data A map containing the data for the new document. + * + * @return A Future that will be resolved with the DocumentReference of the + * newly created document. + */ + virtual Future Add(const MapFieldValue& data); + + private: + friend class DocumentReference; + friend class DocumentReferenceInternal; + friend class FirestoreInternal; + friend struct ConverterImpl; + + explicit CollectionReference(CollectionReferenceInternal* internal); + + CollectionReferenceInternal* internal() const; +}; + +} // namespace firestore +} // namespace firebase + +#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_COLLECTION_REFERENCE_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/document_change.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/document_change.h new file mode 100644 index 000000000000..fbef011d290f --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/document_change.h @@ -0,0 +1,203 @@ +/* + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_DOCUMENT_CHANGE_H_ +#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_DOCUMENT_CHANGE_H_ + +#include + +namespace firebase { +namespace firestore { + +class DocumentChangeInternal; +class DocumentSnapshot; + +/** + * @brief A DocumentChange represents a change to the documents matching + * a query. + * + * DocumentChange contains the document affected and the type of change that + * occurred (added, modified, or removed). + * + * @note Firestore classes are not meant to be subclassed except for use in test + * mocks. Subclassing is not supported in production code and new SDK releases + * may break code that does so. + */ +class DocumentChange { + public: + /** + * An enumeration of snapshot diff types. + */ + enum class Type { + /** + * Indicates a new document was added to the set of documents matching the + * query. + */ + kAdded, + + /** + * Indicates a document within the query was modified. + */ + kModified, + + /** + * Indicates a document within the query was removed (either deleted or no + * longer matches the query). + */ + kRemoved, + }; + + /** + * The sentinel index used as a return value to indicate no matches. + */ +#if defined(ANDROID) + // Older NDK (r16b) fails to define this properly. Fix this when support for + // the older NDK is removed. + static const std::size_t npos; +#else + static constexpr std::size_t npos = static_cast(-1); +#endif // defined(ANDROID) + + /** + * @brief Creates an invalid DocumentChange that has to be reassigned before + * it can be used. + * + * Calling any member function on an invalid DocumentChange will be a no-op. + * If the function returns a value, it will return a zero, empty, or invalid + * value, depending on the type of the value. + */ + DocumentChange(); + + /** + * @brief Copy constructor. + * + * `DocumentChange` is immutable and can be efficiently copied (no deep copy + * is performed). + * + * @param[in] other `DocumentChange` to copy from. + */ + DocumentChange(const DocumentChange& other); + + /** + * @brief Move constructor. + * + * Moving is more efficient than copying for a `DocumentChange`. After being + * moved from, a `DocumentChange` is equivalent to its default-constructed + * state. + * + * @param[in] other `DocumentChange` to move data from. + */ + DocumentChange(DocumentChange&& other); + + virtual ~DocumentChange(); + + /** + * @brief Copy assignment operator. + * + * `DocumentChange` is immutable and can be efficiently copied (no deep copy + * is performed). + * + * @param[in] other `DocumentChange` to copy from. + * + * @return Reference to the destination `DocumentChange`. + */ + DocumentChange& operator=(const DocumentChange& other); + + /** + * @brief Move assignment operator. + * + * Moving is more efficient than copying for a `DocumentChange`. After being + * moved from, a `DocumentChange` is equivalent to its default-constructed + * state. + * + * @param[in] other `DocumentChange` to move data from. + * + * @return Reference to the destination `DocumentChange`. + */ + DocumentChange& operator=(DocumentChange&& other); + + /** + * Returns the type of change that occurred (added, modified, or removed). + */ + virtual Type type() const; + + /** + * @brief The document affected by this change. + * + * Returns the newly added or modified document if this DocumentChange is for + * an updated document. Returns the deleted document if this document change + * represents a removal. + */ + virtual DocumentSnapshot document() const; + + /** + * The index of the changed document in the result set immediately prior to + * this DocumentChange (that is, supposing that all prior DocumentChange + * objects have been applied). Returns DocumentChange::npos for 'added' + * events. + */ + virtual std::size_t old_index() const; + + /** + * The index of the changed document in the result set immediately after this + * DocumentChange (that is, supposing that all prior DocumentChange objects + * and the current DocumentChange object have been applied). Returns + * DocumentChange::npos for 'removed' events. + */ + virtual std::size_t new_index() const; + + /** + * @brief Returns true if this `DocumentChange` is valid, false if it is + * not valid. An invalid `DocumentChange` could be the result of: + * - Creating a `DocumentChange` using the default constructor. + * - Moving from the `DocumentChange`. + * - Deleting your Firestore instance, which will invalidate all the + * `DocumentChange` instances associated with it. + * + * @return true if this `DocumentChange` is valid, false if this + * `DocumentChange` is invalid. + */ + bool is_valid() const { return internal_ != nullptr; } + + private: + std::size_t Hash() const; + + friend bool operator==(const DocumentChange& lhs, const DocumentChange& rhs); + friend std::size_t DocumentChangeHash(const DocumentChange& change); + + friend class FirestoreInternal; + friend class Wrapper; + friend struct ConverterImpl; + template + friend struct CleanupFn; + + explicit DocumentChange(DocumentChangeInternal* internal); + + mutable DocumentChangeInternal* internal_ = nullptr; +}; + +/** Checks `lhs` and `rhs` for equality. */ +bool operator==(const DocumentChange& lhs, const DocumentChange& rhs); + +/** Checks `lhs` and `rhs` for inequality. */ +inline bool operator!=(const DocumentChange& lhs, const DocumentChange& rhs) { + return !(lhs == rhs); +} + +} // namespace firestore +} // namespace firebase + +#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_DOCUMENT_CHANGE_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/document_reference.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/document_reference.h new file mode 100644 index 000000000000..d0f82cf42d73 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/document_reference.h @@ -0,0 +1,351 @@ +/* + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_DOCUMENT_REFERENCE_H_ +#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_DOCUMENT_REFERENCE_H_ + +#include +#include +#include + +#include "firebase/internal/common.h" + +#include "firebase/firestore/firestore_errors.h" +#include "firebase/firestore/map_field_value.h" +#include "firebase/firestore/metadata_changes.h" +#include "firebase/firestore/set_options.h" +#include "firebase/firestore/source.h" + +namespace firebase { + +/// @cond FIREBASE_APP_INTERNAL +template +class Future; +/// @endcond + +namespace firestore { + +class CollectionReference; +class DocumentReferenceInternal; +class DocumentSnapshot; +template +class EventListener; +class Firestore; +class ListenerRegistration; + +/** + * @brief A DocumentReference refers to a document location in a Firestore + * database and can be used to write, read, or listen to the location. + * + * There may or may not exist a document at the referenced location. + * A DocumentReference can also be used to create a CollectionReference to + * a subcollection. + * + * Create a DocumentReference via `Firestore::Document(const std::string& + * path)`. + * + * @note Firestore classes are not meant to be subclassed except for use in test + * mocks. Subclassing is not supported in production code and new SDK releases + * may break code that does so. + */ +class DocumentReference { + public: + /** + * @brief Creates an invalid DocumentReference that has to be reassigned + * before it can be used. + * + * Calling any member function on an invalid DocumentReference will be + * a no-op. If the function returns a value, it will return a zero, empty, or + * invalid value, depending on the type of the value. + */ + DocumentReference(); + + /** + * @brief Copy constructor. + * + * `DocumentReference` can be efficiently copied because it simply refers to + * a location in the database. + * + * @param[in] other `DocumentReference` to copy from. + */ + DocumentReference(const DocumentReference& other); + + /** + * @brief Move constructor. + * + * Moving is more efficient than copying for a `DocumentReference`. After + * being moved from, a `DocumentReference` is equivalent to its + * default-constructed state. + * + * @param[in] other `DocumentReference` to move data from. + */ + DocumentReference(DocumentReference&& other); + + virtual ~DocumentReference(); + + /** + * @brief Copy assignment operator. + * + * `DocumentReference` can be efficiently copied because it simply refers to + * a location in the database. + * + * @param[in] other `DocumentReference` to copy from. + * + * @return Reference to the destination `DocumentReference`. + */ + DocumentReference& operator=(const DocumentReference& other); + + /** + * @brief Move assignment operator. + * + * Moving is more efficient than copying for a `DocumentReference`. After + * being moved from, a `DocumentReference` is equivalent to its + * default-constructed state. + * + * @param[in] other `DocumentReference` to move data from. + * + * @return Reference to the destination `DocumentReference`. + */ + DocumentReference& operator=(DocumentReference&& other); + + /** + * @brief Returns the Firestore instance associated with this document + * reference. + * + * The pointer will remain valid indefinitely. + * + * @return Firebase Firestore instance that this DocumentReference refers to. + */ + virtual const Firestore* firestore() const; + + /** + * @brief Returns the Firestore instance associated with this document + * reference. + * + * The pointer will remain valid indefinitely. + * + * @return Firebase Firestore instance that this DocumentReference refers to. + */ + virtual Firestore* firestore(); + + /** + * @brief Returns the string ID of this document location. + * + * @return String ID of this document location. + */ + virtual const std::string& id() const; + + /** + * @brief Returns the path of this document (relative to the root of the + * database) as a slash-separated string. + * + * @return String path of this document location. + */ + virtual std::string path() const; + + /** + * @brief Returns a CollectionReference to the collection that contains this + * document. + */ + virtual CollectionReference Parent() const; + + /** + * @brief Returns a CollectionReference instance that refers to the + * subcollection at the specified path relative to this document. + * + * @param[in] collection_path A slash-separated relative path to a + * subcollection. The pointer only needs to be valid during this call. + * + * @return The CollectionReference instance. + */ + virtual CollectionReference Collection(const char* collection_path) const; + + /** + * @brief Returns a CollectionReference instance that refers to the + * subcollection at the specified path relative to this document. + * + * @param[in] collection_path A slash-separated relative path to a + * subcollection. + * + * @return The CollectionReference instance. + */ + virtual CollectionReference Collection( + const std::string& collection_path) const; + + /** + * @brief Reads the document referenced by this DocumentReference. + * + * By default, Get() attempts to provide up-to-date data when possible by + * waiting for data from the server, but it may return cached data or fail if + * you are offline and the server cannot be reached. This behavior can be + * altered via the Source parameter. + * + * @param[in] source A value to configure the get behavior (optional). + * + * @return A Future that will be resolved with the contents of the Document at + * this DocumentReference. + */ + virtual Future Get(Source source = Source::kDefault) const; + + /** + * @brief Writes to the document referred to by this DocumentReference. + * + * If the document does not yet exist, it will be created. If you pass + * SetOptions, the provided data can be merged into an existing document. + * + * @param[in] data A map of the fields and values to write to the document. + * @param[in] options An object to configure the Set() behavior (optional). + * + * @return A Future that will be resolved when the write finishes. + */ + virtual Future Set(const MapFieldValue& data, + const SetOptions& options = SetOptions()); + + /** + * @brief Updates fields in the document referred to by this + * DocumentReference. + * + * If no document exists yet, the update will fail. + * + * @param[in] data A map of field / value pairs to update. Fields can contain + * dots to reference nested fields within the document. + * + * @return A Future that will be resolved when the client is online and the + * commit has completed against the server. The future will not resolve when + * the device is offline, though local changes will be visible immediately. + */ + virtual Future Update(const MapFieldValue& data); + + /** + * @brief Updates fields in the document referred to by this + * DocumentReference. + * + * If no document exists yet, the update will fail. + * + * @param[in] data A map from FieldPath to FieldValue to update. + * + * @return A Future that will be resolved when the client is online and the + * commit has completed against the server. The future will not resolve when + * the device is offline, though local changes will be visible immediately. + */ + virtual Future Update(const MapFieldPathValue& data); + + /** + * @brief Removes the document referred to by this DocumentReference. + * + * @return A Future that will be resolved when the delete completes. + */ + virtual Future Delete(); + + /** + * @brief Starts listening to the document referenced by this + * DocumentReference. + * + * @param[in] callback The std::function to call. When this function is + * called, snapshot value is valid if and only if error is Error::kErrorOk. + * The std::string is an error message; the value may be empty if an error + * message is not available. + * + * @return A registration object that can be used to remove the listener. + */ + virtual ListenerRegistration AddSnapshotListener( + std::function + callback); + + /** + * @brief Starts listening to the document referenced by this + * DocumentReference. + * + * @param[in] metadata_changes Indicates whether metadata-only changes (that + * is, only DocumentSnapshot::metadata() changed) should trigger snapshot + * events. + * @param[in] callback The std::function to call. When this function is + * called, snapshot value is valid if and only if error is Error::kErrorOk. + * The std::string is an error message; the value may be empty if an error + * message is not available. + * + * @return A registration object that can be used to remove the listener. + */ + virtual ListenerRegistration AddSnapshotListener( + MetadataChanges metadata_changes, + std::function + callback); + + /** + * @brief Returns true if this `DocumentReference` is valid, false if it is + * not valid. An invalid `DocumentReference` could be the result of: + * - Creating a `DocumentReference` using the default constructor. + * - Moving from the `DocumentReference`. + * - Calling `CollectionReference::Parent()` on a `CollectionReference` that + * is not a subcollection. + * - Deleting your Firestore instance, which will invalidate all the + * `DocumentReference` instances associated with it. + * + * @return true if this `DocumentReference` is valid, false if this + * `DocumentReference` is invalid. + */ + bool is_valid() const { return internal_ != nullptr; } + + /** + * Returns a string representation of this `DocumentReference` for + * logging/debugging purposes. + * + * @note the exact string representation is unspecified and subject to + * change; don't rely on the format of the string. + */ + std::string ToString() const; + + /** + * Outputs the string representation of this `DocumentReference` to the given + * stream. + * + * @see `ToString()` for comments on the representation format. + */ + friend std::ostream& operator<<(std::ostream& out, + const DocumentReference& reference); + + private: + friend bool operator==(const DocumentReference& lhs, + const DocumentReference& rhs); + + friend class CollectionReferenceInternal; + friend class DocumentSnapshotInternal; + friend class FieldValueInternal; + friend class FirestoreInternal; + friend class TransactionInternal; + friend class WriteBatchInternal; + friend struct ConverterImpl; + template + friend struct CleanupFn; + + explicit DocumentReference(DocumentReferenceInternal* internal); + + mutable DocumentReferenceInternal* internal_ = nullptr; +}; + +/** Checks `lhs` and `rhs` for equality. */ +bool operator==(const DocumentReference& lhs, const DocumentReference& rhs); + +/** Checks `lhs` and `rhs` for inequality. */ +inline bool operator!=(const DocumentReference& lhs, + const DocumentReference& rhs) { + return !(lhs == rhs); +} + +} // namespace firestore +} // namespace firebase + +#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_DOCUMENT_REFERENCE_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/document_snapshot.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/document_snapshot.h new file mode 100644 index 000000000000..7617eb5d1412 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/document_snapshot.h @@ -0,0 +1,297 @@ +/* + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_DOCUMENT_SNAPSHOT_H_ +#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_DOCUMENT_SNAPSHOT_H_ + +#include +#include + +#include "firebase/firestore/map_field_value.h" +#include "firebase/firestore/snapshot_metadata.h" + +namespace firebase { +namespace firestore { + +class DocumentReference; +class DocumentSnapshotInternal; +class FieldPath; +class FieldValue; +class Firestore; + +/** + * @brief A DocumentSnapshot contains data read from a document in your + * Firestore database. + * + * The data can be extracted with the GetData() method, or by using + * Get() to access a specific field. For a DocumentSnapshot that points to + * a non-existing document, any data access will cause a failed assertion. You + * can use the exists() method to explicitly verify a document's existence. + * + * @note Firestore classes are not meant to be subclassed except for use in test + * mocks. Subclassing is not supported in production code and new SDK releases + * may break code that does so. + */ +class DocumentSnapshot { + public: + /** + * Controls the return value for server timestamps that have not yet been set + * to their final value. + */ + enum class ServerTimestampBehavior { + /** + * Return Null for server timestamps that have not yet been set to their + * final value. + */ + kNone = 0, + + /** + * Return local estimates for server timestamps that have not yet been set + * to their final value. This estimate will likely differ from the final + * value and may cause these pending values to change once the server result + * becomes available. + */ + kEstimate, + + /** + * Return the previous value for server timestamps that have not yet been + * set to their final value. + */ + kPrevious, + + /** The default behavior, which is equivalent to specifying kNone. */ + // + // Note, SWIG renaming mechanism doesn't properly handle initializing an + // enum constant with another enum constant (e.g., in expression `kFoo = + // kBar` only `kFoo` will be renamed, leaving `kBar` as is, leading to + // compilation errors). + // + kDefault = 0, + }; + + /** + * @brief Creates an invalid DocumentSnapshot that has to be reassigned before + * it can be used. + * + * Calling any member function on an invalid DocumentSnapshot will be a no-op. + * If the function returns a value, it will return a zero, empty, or invalid + * value, depending on the type of the value. + */ + DocumentSnapshot(); + + /** + * @brief Copy constructor. + * + * `DocumentSnapshot` is immutable and can be efficiently copied (no deep copy + * is performed). + * + * @param[in] other `DocumentSnapshot` to copy from. + */ + DocumentSnapshot(const DocumentSnapshot& other); + + /** + * @brief Move constructor. + * + * Moving is more efficient than copying for a `DocumentSnapshot`. After being + * moved from, a `DocumentSnapshot` is equivalent to its default-constructed + * state. + * + * @param[in] other `DocumentSnapshot` to move data from. + */ + DocumentSnapshot(DocumentSnapshot&& other); + + virtual ~DocumentSnapshot(); + + /** + * @brief Copy assignment operator. + * + * `DocumentSnapshot` is immutable and can be efficiently copied (no deep copy + * is performed). + * + * @param[in] other `DocumentSnapshot` to copy from. + * + * @return Reference to the destination `DocumentSnapshot`. + */ + DocumentSnapshot& operator=(const DocumentSnapshot& other); + + /** + * @brief Move assignment operator. + * + * Moving is more efficient than copying for a `DocumentSnapshot`. After being + * moved from, a `DocumentSnapshot` is equivalent to its default-constructed + * state. + * + * @param[in] other `DocumentSnapshot` to move data from. + * + * @return Reference to the destination `DocumentSnapshot`. + */ + DocumentSnapshot& operator=(DocumentSnapshot&& other); + + /** + * @brief Returns the string ID of the document for which this + * DocumentSnapshot contains data. + * + * @return String ID of this document location. + */ + virtual const std::string& id() const; + + /** + * @brief Returns the document location for which this DocumentSnapshot + * contains data. + * + * @return DocumentReference of this document location. + */ + virtual DocumentReference reference() const; + + /** + * @brief Returns the metadata about this snapshot concerning its source and + * if it has local modifications. + * + * @return SnapshotMetadata about this snapshot. + */ + virtual SnapshotMetadata metadata() const; + + /** + * @brief Explicitly verify a document's existence. + * + * @return True if the document exists in this snapshot. + */ + virtual bool exists() const; + + /** + * @brief Retrieves all fields in the document as a map of FieldValues. + * + * @param stb Configures how server timestamps that have not yet + * been set to their final value are returned from the snapshot (optional). + * + * @return A map containing all fields in the document, or an empty map if the + * document doesn't exist. + */ + virtual MapFieldValue GetData( + ServerTimestampBehavior stb = ServerTimestampBehavior::kDefault) const; + + /** + * @brief Retrieves a specific field from the document. + * + * @param field String ID of the field to retrieve. The pointer only needs to + * be valid during this call. + * @param stb Configures how server timestamps that have not yet been set to + * their final value are returned from the snapshot (optional). + * + * @return The value contained in the field. If the field does not exist in + * the document, then a `FieldValue` instance with `is_valid() == false` will + * be returned. + */ + virtual FieldValue Get( + const char* field, + ServerTimestampBehavior stb = ServerTimestampBehavior::kDefault) const; + + /** + * @brief Retrieves a specific field from the document. + * + * @param field String ID of the field to retrieve. + * @param stb Configures how server timestamps that have not yet been set to + * their final value are returned from the snapshot (optional). + * + * @return The value contained in the field. If the field does not exist in + * the document, then a `FieldValue` instance with `is_valid() == false` will + * be returned. + */ + virtual FieldValue Get( + const std::string& field, + ServerTimestampBehavior stb = ServerTimestampBehavior::kDefault) const; + + /** + * @brief Retrieves a specific field from the document. + * + * @param field Path of the field to retrieve. + * @param stb Configures how server timestamps that have not yet been set to + * their final value are returned from the snapshot (optional). + * + * @return The value contained in the field. If the field does not exist in + * the document, then a `FieldValue` instance with `is_valid() == false` will + * be returned. + */ + virtual FieldValue Get( + const FieldPath& field, + ServerTimestampBehavior stb = ServerTimestampBehavior::kDefault) const; + + /** + * @brief Returns true if this `DocumentSnapshot` is valid, false if it is + * not valid. An invalid `DocumentSnapshot` could be the result of: + * - Creating a `DocumentSnapshot` with the default constructor. + * - Moving from the `DocumentSnapshot`. + * - Deleting your Firestore instance, which will invalidate all the + * `DocumentSnapshot` instances associated with it. + * + * @return true if this `DocumentSnapshot` is valid, false if this + * `DocumentSnapshot` is invalid. + */ + bool is_valid() const { return internal_ != nullptr; } + + /** + * Returns a string representation of this `DocumentSnapshot` for + * logging/debugging purposes. + * + * @note the exact string representation is unspecified and subject to + * change; don't rely on the format of the string. + */ + std::string ToString() const; + + /** + * Outputs the string representation of this `DocumentSnapshot` to the given + * stream. + * + * @see `ToString()` for comments on the representation format. + */ + friend std::ostream& operator<<(std::ostream& out, + const DocumentSnapshot& document); + + private: + std::size_t Hash() const; + + friend bool operator==(const DocumentSnapshot& lhs, + const DocumentSnapshot& rhs); + friend std::size_t DocumentSnapshotHash(const DocumentSnapshot& snapshot); + + friend class DocumentChangeInternal; + friend class EventListenerInternal; + friend class FirestoreInternal; + friend class QueryInternal; + friend class TransactionInternal; + friend class Wrapper; + friend struct ConverterImpl; + template + friend struct CleanupFn; + + explicit DocumentSnapshot(DocumentSnapshotInternal* internal); + + mutable DocumentSnapshotInternal* internal_ = nullptr; +}; + +/** Checks `lhs` and `rhs` for equality. */ +bool operator==(const DocumentSnapshot& lhs, const DocumentSnapshot& rhs); + +/** Checks `lhs` and `rhs` for inequality. */ +inline bool operator!=(const DocumentSnapshot& lhs, + const DocumentSnapshot& rhs) { + return !(lhs == rhs); +} + +} // namespace firestore +} // namespace firebase + +#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_DOCUMENT_SNAPSHOT_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/field_path.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/field_path.h new file mode 100644 index 000000000000..d09dec641140 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/field_path.h @@ -0,0 +1,205 @@ +/* + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_FIELD_PATH_H_ +#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_FIELD_PATH_H_ + +#include +#include +#include +#include + +namespace firebase { +namespace firestore { + +#if !defined(__ANDROID__) + +namespace model { +class FieldPath; +} // namespace model + +#else + +class FieldPathPortable; + +#endif // !defined(__ANDROID__) + +/** + * @brief A FieldPath refers to a field in a document. + * + * The path may consist of a single field name (referring to a top level field + * in the document) or a list of field names (referring to a nested field in the + * document). + */ +class FieldPath final { + public: + /** + * @brief Creates an invalid FieldPath that has to be reassigned before it can + * be used. + * + * Calling any member function on an invalid FieldPath will be a no-op. If the + * function returns a value, it will return a zero, empty, or invalid value, + * depending on the type of the value. + */ + FieldPath(); + + /** + * Creates a FieldPath from the provided field names. If more than one field + * name is provided, the path will point to a nested field in a document. + * + * @param field_names A list of field names. + */ + FieldPath(std::initializer_list field_names); + + /** + * Creates a FieldPath from the provided field names. If more than one field + * name is provided, the path will point to a nested field in a document. + * + * @param field_names A vector of field names. + */ + FieldPath(const std::vector& field_names); + + /** + * @brief Copy constructor. + * + * This performs a deep copy, creating an independent instance. + * + * @param[in] other `FieldPath` to copy from. + */ + FieldPath(const FieldPath& other); + + /** + * @brief Move constructor. + * + * Moving is more efficient than copying for `FieldPath`. After being moved + * from, `FieldPath` is in a valid but unspecified state. + * + * @param[in] other `FieldPath` to move data from. + */ + FieldPath(FieldPath&& other) noexcept; + + ~FieldPath(); + + /** + * @brief Copy assignment operator. + * + * This performs a deep copy, creating an independent instance. + * + * @param[in] other `FieldPath` to copy from. + * + * @return Reference to the destination `FieldPath`. + */ + FieldPath& operator=(const FieldPath& other); + + /** + * @brief Move assignment operator. + * + * Moving is more efficient than copying for `FieldPath`. After being moved + * from, `FieldPath` is in a valid but unspecified state. + * + * @param[in] other `FieldPath` to move data from. + * + * @return Reference to the destination `FieldPath`. + */ + FieldPath& operator=(FieldPath&& other) noexcept; + + /** + * A special sentinel FieldPath to refer to the ID of a document. It can be + * used in queries to sort or filter by the document ID. + */ + static FieldPath DocumentId(); + + /** + * @brief Returns true if this `FieldPath` is valid, false if it is not valid. + * An invalid `FieldPath` could be the result of: + * - Creating a `FieldPath` using the default constructor. + * - Moving from the `FieldPath`. + * + * @return true if this `FieldPath` is valid, false if this `FieldPath` is + * invalid. + */ + bool is_valid() const { return internal_ != nullptr; } + + /** + * Returns a string representation of this `FieldPath` for + * logging/debugging purposes. + * + * @note the exact string representation is unspecified and subject to + * change; don't rely on the format of the string. + */ + std::string ToString() const; + + /** + * Outputs the string representation of this `FieldPath` to the given + * stream. + * + * @see `ToString()` for comments on the representation format. + */ + friend std::ostream& operator<<(std::ostream& out, const FieldPath& path); + + private: + // The type of the internal object that implements the public interface. +#if !defined(SWIG) +#if !defined(__ANDROID__) + using FieldPathInternal = ::firebase::firestore::model::FieldPath; +#else + using FieldPathInternal = ::firebase::firestore::FieldPathPortable; +#endif // !defined(__ANDROID__) +#endif // !defined(SWIG) + + friend bool operator==(const FieldPath& lhs, const FieldPath& rhs); + friend bool operator!=(const FieldPath& lhs, const FieldPath& rhs); + friend struct std::hash; + + friend class DocumentSnapshot; // For access to `FromDotSeparatedString` + friend class Query; + friend class QueryInternal; + friend class SetOptions; // For access to `FromDotSeparatedString` + friend class FieldPathConverter; + friend struct ConverterImpl; + + explicit FieldPath(FieldPathInternal* internal); + + static FieldPathInternal* InternalFromSegments( + std::vector field_names); + + static FieldPath FromDotSeparatedString(const std::string& path); + + FieldPathInternal* internal_ = nullptr; +}; + +} // namespace firestore +} // namespace firebase + +#if !defined(SWIG) +namespace std { +/** + * A convenient specialization of std::hash for FieldPath. + */ +template <> +struct hash { + /** + * Calculates the hash of the argument. + * + * Note: specialization of `std::hash` is provided for convenience only. The + * implementation is subject to change. + */ + size_t operator()(const firebase::firestore::FieldPath& field_path) const; +}; +} // namespace std +#endif // !defined(SWIG) + +#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_FIELD_PATH_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/field_value.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/field_value.h new file mode 100644 index 000000000000..e66814104ed7 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/field_value.h @@ -0,0 +1,436 @@ +/* + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_FIELD_VALUE_H_ +#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_FIELD_VALUE_H_ + +#include +#include +#include +#include +#include + +#include "firebase/firestore/map_field_value.h" +#include "firebase/internal/type_traits.h" + +namespace firebase { + +class Timestamp; + +namespace firestore { + +class DocumentReference; +class FieldValueInternal; +class GeoPoint; + +/** + * @brief A field value represents variant datatypes as stored by Firestore. + * + * FieldValue can be used when reading a particular field with + * DocumentSnapshot::Get() or fields with DocumentSnapshot::GetData(). When + * writing document fields with DocumentReference::Set() or + * DocumentReference::Update(), it can also represent sentinel values in + * addition to real data values. + * + * For a non-sentinel instance, you can check whether it is of a particular type + * with is_foo() and get the value with foo_value(), where foo can be one of + * null, boolean, integer, double, timestamp, string, blob, reference, + * geo_point, array or map. If the instance is not of type foo, the call to + * foo_value() will fail (and cause a crash). + */ +class FieldValue final { + // Helper aliases for `Increment` member functions. + // Qualifying `is_integer` is to prevent ambiguity with the + // `FieldValue::is_integer` member function. + // Note: normally, `enable_if::type` would be included in the alias, but such + // a declaration breaks SWIG (presumably, SWIG cannot handle `typename` within + // an alias template). + template + using EnableIfIntegral = enable_if<::firebase::is_integer::value, int>; + template + using EnableIfFloatingPoint = enable_if::value, int>; + + public: + /** + * The enumeration of all valid runtime types of FieldValue. + */ + enum class Type { + kNull, + kBoolean, + kInteger, + kDouble, + kTimestamp, + kString, + kBlob, + kReference, + kGeoPoint, + kArray, + kMap, + // Below are sentinel types. Sentinel types can be passed to Firestore + // methods as arguments, but are never returned from Firestore. + kDelete, + kServerTimestamp, + kArrayUnion, + kArrayRemove, + kIncrementInteger, + kIncrementDouble, + }; + + /** + * @brief Creates an invalid FieldValue that has to be reassigned before it + * can be used. + * + * Calling any member function on an invalid FieldValue will be a no-op. If + * the function returns a value, it will return a zero, empty, or invalid + * value, depending on the type of the value. + */ + FieldValue(); + + /** + * @brief Copy constructor. + * + * `FieldValue` is immutable and can be efficiently copied (no deep copy is + * performed). + * + * @param[in] other `FieldValue` to copy from. + */ + FieldValue(const FieldValue& other); + + /** + * @brief Move constructor. + * + * Moving is more efficient than copying for a `FieldValue`. After being moved + * from, a `FieldValue` is equivalent to its default-constructed state. + * + * @param[in] other `FieldValue` to move data from. + */ + FieldValue(FieldValue&& other) noexcept; + + ~FieldValue(); + + /** + * @brief Copy assignment operator. + * + * `FieldValue` is immutable and can be efficiently copied (no deep copy is + * performed). + * + * @param[in] other `FieldValue` to copy from. + * + * @return Reference to the destination `FieldValue`. + */ + FieldValue& operator=(const FieldValue& other); + + /** + * @brief Move assignment operator. + * + * Moving is more efficient than copying for a `FieldValue`. After being moved + * from, a `FieldValue` is equivalent to its default-constructed state. + * + * @param[in] other `FieldValue` to move data from. + * + * @return Reference to the destination `FieldValue`. + */ + FieldValue& operator=(FieldValue&& other) noexcept; + + /** + * @brief Constructs a FieldValue containing the given boolean value. + */ + static FieldValue Boolean(bool value); + + /** + * @brief Constructs a FieldValue containing the given 64-bit integer value. + */ + static FieldValue Integer(int64_t value); + + /** + * @brief Constructs a FieldValue containing the given double-precision + * floating point value. + */ + static FieldValue Double(double value); + + /** + * @brief Constructs a FieldValue containing the given Timestamp value. + */ + static FieldValue Timestamp(Timestamp value); + + /** + * @brief Constructs a FieldValue containing the given std::string value. + */ + static FieldValue String(std::string value); + + /** + * @brief Constructs a FieldValue containing the given blob value of given + * size. `value` is copied into the returned FieldValue. + */ + static FieldValue Blob(const uint8_t* value, size_t size); + + /** + * @brief Constructs a FieldValue containing the given reference value. + */ + static FieldValue Reference(DocumentReference value); + + /** + * @brief Constructs a FieldValue containing the given GeoPoint value. + */ + static FieldValue GeoPoint(GeoPoint value); + + /** + * @brief Constructs a FieldValue containing the given FieldValue vector + * value. + */ + static FieldValue Array(std::vector value); + + /** + * @brief Constructs a FieldValue containing the given FieldValue map value. + */ + static FieldValue Map(MapFieldValue value); + + /** @brief Gets the current type contained in this FieldValue. */ + Type type() const; + + /** @brief Gets whether this FieldValue is currently null. */ + bool is_null() const { return type() == Type::kNull; } + + /** @brief Gets whether this FieldValue contains a boolean value. */ + bool is_boolean() const { return type() == Type::kBoolean; } + + /** @brief Gets whether this FieldValue contains an integer value. */ + bool is_integer() const { return type() == Type::kInteger; } + + /** @brief Gets whether this FieldValue contains a double value. */ + bool is_double() const { return type() == Type::kDouble; } + + /** @brief Gets whether this FieldValue contains a timestamp. */ + bool is_timestamp() const { return type() == Type::kTimestamp; } + + /** @brief Gets whether this FieldValue contains a string. */ + bool is_string() const { return type() == Type::kString; } + + /** @brief Gets whether this FieldValue contains a blob. */ + bool is_blob() const { return type() == Type::kBlob; } + + /** + * @brief Gets whether this FieldValue contains a reference to a document in + * the same Firestore. + */ + bool is_reference() const { return type() == Type::kReference; } + + /** @brief Gets whether this FieldValue contains a GeoPoint. */ + bool is_geo_point() const { return type() == Type::kGeoPoint; } + + /** @brief Gets whether this FieldValue contains an array of FieldValues. */ + bool is_array() const { return type() == Type::kArray; } + + /** @brief Gets whether this FieldValue contains a map of std::string to + * FieldValue. */ + bool is_map() const { return type() == Type::kMap; } + + /** @brief Gets the boolean value contained in this FieldValue. */ + bool boolean_value() const; + + /** @brief Gets the integer value contained in this FieldValue. */ + int64_t integer_value() const; + + /** @brief Gets the double value contained in this FieldValue. */ + double double_value() const; + + /** @brief Gets the timestamp value contained in this FieldValue. */ + class Timestamp timestamp_value() const; + + /** @brief Gets the string value contained in this FieldValue. */ + std::string string_value() const; + + /** @brief Gets the blob value contained in this FieldValue. */ + const uint8_t* blob_value() const; + + /** @brief Gets the blob size contained in this FieldValue. */ + size_t blob_size() const; + + /** @brief Gets the DocumentReference contained in this FieldValue. */ + DocumentReference reference_value() const; + + /** @brief Gets the GeoPoint value contained in this FieldValue. */ + class GeoPoint geo_point_value() const; + + /** @brief Gets the vector of FieldValues contained in this FieldValue. */ + std::vector array_value() const; + + /** + * @brief Gets the map of string to FieldValue contained in this FieldValue. + */ + MapFieldValue map_value() const; + + /** + * @brief Returns `true` if this `FieldValue` is valid, `false` if it is not + * valid. An invalid `FieldValue` could be the result of: + * - Creating a `FieldValue` using the default constructor. + * - Moving from the `FieldValue`. + * - Calling `DocumentSnapshot::Get(field)` for a field that does not exist + * in the document. + * + * @return `true` if this `FieldValue` is valid, `false` if this `FieldValue` + * is invalid. + */ + bool is_valid() const { return internal_ != nullptr; } + + /** @brief Constructs a null. */ + static FieldValue Null(); + + /** + * @brief Returns a sentinel for use with Update() to mark a field for + * deletion. + */ + static FieldValue Delete(); + + /** + * Returns a sentinel that can be used with Set() or Update() to include + * a server-generated timestamp in the written data. + */ + static FieldValue ServerTimestamp(); + + /** + * Returns a special value that can be used with Set() or Update() that tells + * the server to union the given elements with any array value that already + * exists on the server. Each specified element that doesn't already exist in + * the array will be added to the end. If the field being modified is not + * already an array, it will be overwritten with an array containing exactly + * the specified elements. + * + * @param elements The elements to union into the array. + * @return The FieldValue sentinel for use in a call to Set() or Update(). + */ + static FieldValue ArrayUnion(std::vector elements); + + /** + * Returns a special value that can be used with Set() or Update() that tells + * the server to remove the given elements from any array value that already + * exists on the server. All instances of each element specified will be + * removed from the array. If the field being modified is not already an + * array, it will be overwritten with an empty array. + * + * @param elements The elements to remove from the array. + * @return The FieldValue sentinel for use in a call to Set() or Update(). + */ + static FieldValue ArrayRemove(std::vector elements); + + /** + * Returns a special value that can be used with `Set()` or `Update()` that + * tells the server to increment the field's current value by the given + * integer value. + * + * If the current field value is an integer, possible integer overflows are + * resolved to `LONG_MAX` or `LONG_MIN`. If the current field value is a + * double, both values will be interpreted as doubles and the arithmetic will + * follow IEEE 754 semantics. + * + * If field is not an integer or a double, or if the field does not yet exist, + * the transformation will set the field to the given value. + * + * @param by_value The integer value to increment by. Should be an integer + * type not larger than `int64_t`. + * @return The FieldValue sentinel for use in a call to `Set()` or `Update().` + */ + template ::type = 0> + static FieldValue Increment(T by_value) { + // Note: Doxygen will run into trouble if this function's definition is + // moved outside the class body. + static_assert( + (std::numeric_limits::max)() <= + (std::numeric_limits::max)(), + "The integer type you provided is larger than can fit in an int64_t. " + "If you are sure the value will not be truncated, please explicitly " + "cast to int64_t before passing it to FieldValue::Increment()."); + return IntegerIncrement(static_cast(by_value)); + } + + /** + * Returns a special value that can be used with `Set()` or `Update()` that + * tells the server to increment the field's current value by the given + * floating point value. + * + * If the current field value is an integer, possible integer overflows are + * resolved to `LONG_MAX` or `LONG_MIN`. If the current field value is a + * double, both values will be interpreted as doubles and the arithmetic will + * follow IEEE 754 semantics. + * + * If field is not an integer or a double, or if the field does not yet exist, + * the transformation will set the field to the given value. + * + * @param by_value The double value to increment by. Should be a floating + * point type no larger than `double`. + * @return The FieldValue sentinel for use in a call to `Set()` or `Update().` + */ + template ::type = 0> + static FieldValue Increment(T by_value) { + // Note: Doxygen will run into trouble if this function's definition is + // moved outside the class body. + static_assert( + (std::numeric_limits::max)() <= (std::numeric_limits::max)(), + "The floating point type you provided is larger than can fit in a " + "double. If you are sure the value will not be truncated, please " + "explicitly cast to double before passing it to " + "FieldValue::Increment()."); + return DoubleIncrement(static_cast(by_value)); + } + + /** + * Returns a string representation of this `FieldValue` for logging/debugging + * purposes. + * + * @note the exact string representation is unspecified and subject to + * change; don't rely on the format of the string. + */ + std::string ToString() const; + + /** + * Outputs the string representation of this `FieldValue` to the given stream. + * + * @see `ToString()` for comments on the representation format. + */ + friend std::ostream& operator<<(std::ostream& out, const FieldValue& value); + + private: + friend class DocumentReferenceInternal; + friend class DocumentSnapshotInternal; + friend class FieldValueInternal; + friend class FirestoreInternal; + friend class QueryInternal; + friend class TransactionInternal; + friend class Wrapper; + friend class WriteBatchInternal; + friend struct ConverterImpl; + friend bool operator==(const FieldValue& lhs, const FieldValue& rhs); + + explicit FieldValue(FieldValueInternal* internal); + + static FieldValue IntegerIncrement(int64_t by_value); + static FieldValue DoubleIncrement(double by_value); + + FieldValueInternal* internal_ = nullptr; +}; + +/** Checks `lhs` and `rhs` for equality. */ +bool operator==(const FieldValue& lhs, const FieldValue& rhs); + +/** Checks `lhs` and `rhs` for inequality. */ +inline bool operator!=(const FieldValue& lhs, const FieldValue& rhs) { + return !(lhs == rhs); +} + +} // namespace firestore +} // namespace firebase + +#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_FIELD_VALUE_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/firestore_errors.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/firestore_errors.h new file mode 100644 index 000000000000..6af214a08df1 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/firestore_errors.h @@ -0,0 +1,116 @@ +/* + * Copyright 2018 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIRESTORE_CORE_INCLUDE_FIREBASE_FIRESTORE_FIRESTORE_ERRORS_H_ +#define FIRESTORE_CORE_INCLUDE_FIREBASE_FIRESTORE_FIRESTORE_ERRORS_H_ + +namespace firebase { +namespace firestore { + +/** + * Error codes used by Cloud Firestore. + * + * The codes are in sync across Firestore SDKs on various platforms. + */ +enum Error { + /** The operation completed successfully. */ + // Note: NSError objects will never have a code with this value. + kErrorOk = 0, + + kErrorNone = 0, + + /** The operation was cancelled (typically by the caller). */ + kErrorCancelled = 1, + + /** Unknown error or an error from a different error domain. */ + kErrorUnknown = 2, + + /** + * Client specified an invalid argument. Note that this differs from + * FailedPrecondition. InvalidArgument indicates arguments that are + * problematic regardless of the state of the system (e.g., an invalid field + * name). + */ + kErrorInvalidArgument = 3, + + /** + * Deadline expired before operation could complete. For operations that + * change the state of the system, this error may be returned even if the + * operation has completed successfully. For example, a successful response + * from a server could have been delayed long enough for the deadline to + * expire. + */ + kErrorDeadlineExceeded = 4, + + /** Some requested document was not found. */ + kErrorNotFound = 5, + + /** Some document that we attempted to create already exists. */ + kErrorAlreadyExists = 6, + + /** The caller does not have permission to execute the specified operation. */ + kErrorPermissionDenied = 7, + + /** + * Some resource has been exhausted, perhaps a per-user quota, or perhaps the + * entire file system is out of space. + */ + kErrorResourceExhausted = 8, + + /** + * Operation was rejected because the system is not in a state required for + * the operation's execution. + */ + kErrorFailedPrecondition = 9, + + /** + * The operation was aborted, typically due to a concurrency issue like + * transaction aborts, etc. + */ + kErrorAborted = 10, + + /** Operation was attempted past the valid range. */ + kErrorOutOfRange = 11, + + /** Operation is not implemented or not supported/enabled. */ + kErrorUnimplemented = 12, + + /** + * Internal errors. Means some invariants expected by underlying system has + * been broken. If you see one of these errors, something is very broken. + */ + kErrorInternal = 13, + + /** + * The service is currently unavailable. This is a most likely a transient + * condition and may be corrected by retrying with a backoff. + */ + kErrorUnavailable = 14, + + /** Unrecoverable data loss or corruption. */ + kErrorDataLoss = 15, + + /** + * The request does not have valid authentication credentials for the + * operation. + */ + kErrorUnauthenticated = 16 +}; + +} // namespace firestore +} // namespace firebase + +#endif // FIRESTORE_CORE_INCLUDE_FIREBASE_FIRESTORE_FIRESTORE_ERRORS_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/firestore_version.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/firestore_version.h new file mode 100644 index 000000000000..627ead9e3ae7 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/firestore_version.h @@ -0,0 +1,29 @@ +/* + * Copyright 2018 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIRESTORE_CORE_INCLUDE_FIREBASE_FIRESTORE_FIRESTORE_VERSION_H_ +#define FIRESTORE_CORE_INCLUDE_FIREBASE_FIRESTORE_FIRESTORE_VERSION_H_ + +namespace firebase { +namespace firestore { + +/** Version string for the Firebase Firestore SDK. */ +extern const char* const kFirestoreVersionString; + +} // namespace firestore +} // namespace firebase + +#endif // FIRESTORE_CORE_INCLUDE_FIREBASE_FIRESTORE_FIRESTORE_VERSION_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/geo_point.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/geo_point.h new file mode 100644 index 000000000000..ac56e74a4515 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/geo_point.h @@ -0,0 +1,120 @@ +/* + * Copyright 2018 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIRESTORE_CORE_INCLUDE_FIREBASE_FIRESTORE_GEO_POINT_H_ +#define FIRESTORE_CORE_INCLUDE_FIREBASE_FIRESTORE_GEO_POINT_H_ + +#include +#include + +namespace firebase { +namespace firestore { + +/** + * An immutable object representing a geographical point in Firestore. The point + * is represented as a latitude/longitude pair. + * + * Latitude values are in the range of [-90, 90]. + * Longitude values are in the range of [-180, 180]. + */ +class GeoPoint { + public: + /** Creates a `GeoPoint` with both latitude and longitude set to 0. */ + GeoPoint() = default; + + /** + * Creates a `GeoPoint` from the provided latitude and longitude values. + * + * @param latitude The latitude as number of degrees between -90 and 90. + * @param longitude The longitude as number of degrees between -180 and 180. + */ + GeoPoint(double latitude, double longitude); + + /** Copy constructor, `GeoPoint` is trivially copyable. */ + GeoPoint(const GeoPoint& other) = default; + + /** Move constructor, equivalent to copying. */ + GeoPoint(GeoPoint&& other) = default; + + /** Copy assignment operator, `GeoPoint` is trivially copyable. */ + GeoPoint& operator=(const GeoPoint& other) = default; + + /** Move assignment operator, equivalent to copying. */ + GeoPoint& operator=(GeoPoint&& other) = default; + + /** Returns the latitude value of this `GeoPoint`. */ + double latitude() const { + return latitude_; + } + + /** Returns the latitude value of this `GeoPoint`. */ + double longitude() const { + return longitude_; + } + + /** + * Returns a string representation of this `GeoPoint` for logging/debugging + * purposes. + * + * @note: the exact string representation is unspecified and subject to + * change; don't rely on the format of the string. + */ + std::string ToString() const; + + /** + * Outputs the string representation of this `GeoPoint` to the given stream. + * + * @see `ToString()` for comments on the representation format. + */ + friend std::ostream& operator<<(std::ostream& out, const GeoPoint& geo_point); + + private: + double latitude_ = 0.0; + double longitude_ = 0.0; +}; + +/** Checks whether `lhs` and `rhs` are in ascending order. */ +bool operator<(const GeoPoint& lhs, const GeoPoint& rhs); + +/** Checks whether `lhs` and `rhs` are in descending order. */ +inline bool operator>(const GeoPoint& lhs, const GeoPoint& rhs) { + return rhs < lhs; +} + +/** Checks whether `lhs` and `rhs` are in non-ascending order. */ +inline bool operator>=(const GeoPoint& lhs, const GeoPoint& rhs) { + return !(lhs < rhs); +} + +/** Checks whether `lhs` and `rhs` are in non-descending order. */ +inline bool operator<=(const GeoPoint& lhs, const GeoPoint& rhs) { + return !(lhs > rhs); +} + +/** Checks `lhs` and `rhs` for inequality. */ +inline bool operator!=(const GeoPoint& lhs, const GeoPoint& rhs) { + return lhs < rhs || lhs > rhs; +} + +/** Checks `lhs` and `rhs` for equality. */ +inline bool operator==(const GeoPoint& lhs, const GeoPoint& rhs) { + return !(lhs != rhs); +} + +} // namespace firestore +} // namespace firebase + +#endif // FIRESTORE_CORE_INCLUDE_FIREBASE_FIRESTORE_GEO_POINT_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/listener_registration.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/listener_registration.h new file mode 100644 index 000000000000..20487943347f --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/listener_registration.h @@ -0,0 +1,130 @@ +/* + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_LISTENER_REGISTRATION_H_ +#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_LISTENER_REGISTRATION_H_ + +namespace firebase { +namespace firestore { + +class FirestoreInternal; +class ListenerRegistrationInternal; + +/** Represents a listener that can be removed by calling Remove(). */ +class ListenerRegistration { + public: + /** + * @brief Creates an invalid ListenerRegistration that has to be reassigned + * before it can be used. + * + * Calling Remove() on an invalid ListenerRegistration is a no-op. + */ + ListenerRegistration(); + + /** + * @brief Copy constructor. + * + * `ListenerRegistration` can be efficiently copied because it simply refers + * to the same underlying listener. If there is more than one copy of + * a `ListenerRegistration`, after calling `Remove` on one of them, the + * listener is removed, and calling `Remove` on any other copies will be + * a no-op. + * + * @param[in] other `ListenerRegistration` to copy from. + */ + ListenerRegistration(const ListenerRegistration& other); + + /** + * @brief Move constructor. + * + * Moving is more efficient than copying for a `ListenerRegistration`. After + * being moved from, a `ListenerRegistration` is equivalent to its + * default-constructed state. + * + * @param[in] other `ListenerRegistration` to move data from. + */ + ListenerRegistration(ListenerRegistration&& other); + + virtual ~ListenerRegistration(); + + /** + * @brief Copy assignment operator. + * + * `ListenerRegistration` can be efficiently copied because it simply refers + * to the same underlying listener. If there is more than one copy of + * a `ListenerRegistration`, after calling `Remove` on one of them, the + * listener is removed, and calling `Remove` on any other copies will be + * a no-op. + * + * @param[in] other `ListenerRegistration` to copy from. + * + * @return Reference to the destination `ListenerRegistration`. + */ + ListenerRegistration& operator=(const ListenerRegistration& other); + + /** + * @brief Move assignment operator. + * + * Moving is more efficient than copying for a `ListenerRegistration`. After + * being moved from, a `ListenerRegistration` is equivalent to its + * default-constructed state. + * + * @param[in] other `ListenerRegistration` to move data from. + * + * @return Reference to the destination `ListenerRegistration`. + */ + ListenerRegistration& operator=(ListenerRegistration&& other); + + /** + * Removes the listener being tracked by this ListenerRegistration. After the + * initial call, subsequent calls have no effect. + */ + virtual void Remove(); + + /** + * @brief Returns true if this `ListenerRegistration` is valid, false if it is + * not valid. An invalid `ListenerRegistration` could be the result of: + * - Creating a `ListenerRegistration` using the default constructor. + * - Moving from the `ListenerRegistration`. + * - Deleting your Firestore instance, which will invalidate all the + * `ListenerRegistration` instances associated with it. + * + * @return true if this `ListenerRegistration` is valid, false if this + * `ListenerRegistration` is invalid. + */ + bool is_valid() const { return internal_ != nullptr; } + + private: + friend class DocumentReferenceInternal; + friend class FirestoreInternal; + friend class ListenerRegistrationInternal; + friend class QueryInternal; + friend struct ConverterImpl; + template + friend struct CleanupFn; + + explicit ListenerRegistration(ListenerRegistrationInternal* internal); + + void Cleanup(); + + FirestoreInternal* firestore_ = nullptr; + mutable ListenerRegistrationInternal* internal_ = nullptr; +}; + +} // namespace firestore +} // namespace firebase + +#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_LISTENER_REGISTRATION_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/load_bundle_task_progress.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/load_bundle_task_progress.h new file mode 100644 index 000000000000..be9b235f1205 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/load_bundle_task_progress.h @@ -0,0 +1,101 @@ +/* + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_LOAD_BUNDLE_TASK_PROGRESS_H_ +#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_LOAD_BUNDLE_TASK_PROGRESS_H_ + +#include + +namespace firebase { +namespace firestore { + +class LoadBundleTaskProgressInternal; + +/** Represents a progress update or the final state from loading bundles. */ +class LoadBundleTaskProgress { + public: + /** + * Represents the state of bundle loading tasks. + * + * Both `kSuccess` and `kError` are final states: the task will abort + * or complete and there will be no more updates after they are reported. + */ + enum class State { kError, kInProgress, kSuccess }; + + LoadBundleTaskProgress() = default; + /** Construct a LoadBundleTaskProgress with specific state. **/ + LoadBundleTaskProgress(int32_t documents_loaded, + int32_t total_documents, + int64_t bytes_loaded, + int64_t total_bytes, + State state); + + /** Returns how many documents have been loaded. */ + int32_t documents_loaded() const { return documents_loaded_; } + + /** + * Returns the total number of documents in the bundle. Returns 0 if the + * bundle failed to parse. + */ + int32_t total_documents() const { return total_documents_; } + + /** Returns how many bytes have been loaded. */ + int64_t bytes_loaded() const { return bytes_loaded_; } + + /** + * Returns the total number of bytes in the bundle. Returns 0 if the bundle + * failed to parse. + */ + int64_t total_bytes() const { return total_bytes_; } + + /** Returns the current state of the loading progress. */ + State state() const { return state_; } + + private: + friend class EventListenerInternal; + friend class LoadBundleTaskProgressInternal; + friend struct ConverterImpl; + +#if defined(__ANDROID__) + explicit LoadBundleTaskProgress(LoadBundleTaskProgressInternal* internal); +#endif // defined(__ANDROID__) + + int32_t documents_loaded_ = 0; + int32_t total_documents_ = 0; + int64_t bytes_loaded_ = 0; + int64_t total_bytes_ = 0; + State state_ = State::kInProgress; +}; + +/** LoadBundleTaskProgress == comparison operator. **/ +inline bool operator==(const LoadBundleTaskProgress& lhs, + const LoadBundleTaskProgress& rhs) { + return lhs.state() == rhs.state() && + lhs.bytes_loaded() == rhs.bytes_loaded() && + lhs.documents_loaded() == rhs.documents_loaded() && + lhs.total_bytes() == rhs.total_bytes() && + lhs.total_documents() == rhs.total_documents(); +} + +/** LoadBundleTaskProgress != comparison operator. **/ +inline bool operator!=(const LoadBundleTaskProgress& lhs, + const LoadBundleTaskProgress& rhs) { + return !(lhs == rhs); +} + +} // namespace firestore +} // namespace firebase + +#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_LOAD_BUNDLE_TASK_PROGRESS_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/map_field_value.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/map_field_value.h new file mode 100644 index 000000000000..8c67c05a1088 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/map_field_value.h @@ -0,0 +1,37 @@ +/* + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_MAP_FIELD_VALUE_H_ +#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_MAP_FIELD_VALUE_H_ + +#include +#include + +namespace firebase { +namespace firestore { + +class FieldPath; +class FieldValue; + +/** @brief A map of `FieldValue`s indexed by stringified field paths. */ +using MapFieldValue = std::unordered_map; +/** @brief A map of `FieldValue`s indexed by field paths. */ +using MapFieldPathValue = std::unordered_map; + +} // namespace firestore +} // namespace firebase + +#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_MAP_FIELD_VALUE_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/metadata_changes.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/metadata_changes.h new file mode 100644 index 000000000000..13f9abe48427 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/metadata_changes.h @@ -0,0 +1,41 @@ +/* + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_METADATA_CHANGES_H_ +#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_METADATA_CHANGES_H_ + +namespace firebase { +namespace firestore { + +/** + * Indicates whether metadata-only changes (that is, + * DocumentSnapshot::metadata() or QuerySnapshot::metadata() changed) should + * trigger snapshot events. + */ +enum class MetadataChanges { + /** Snapshot events will not be triggered by metadata-only changes. */ + kExclude, + + /** + * Snapshot events will be triggered by any changes, including metadata-only + * changes. + */ + kInclude, +}; + +} // namespace firestore +} // namespace firebase +#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_METADATA_CHANGES_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/query.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/query.h new file mode 100644 index 000000000000..d2e73400cee6 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/query.h @@ -0,0 +1,683 @@ +/* + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_QUERY_H_ +#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_QUERY_H_ + +#include +#include +#include +#include +#include + +#include "firebase/internal/common.h" + +#include "firebase/firestore/firestore_errors.h" +#include "firebase/firestore/metadata_changes.h" +#include "firebase/firestore/source.h" + +namespace firebase { +/// @cond FIREBASE_APP_INTERNAL +template +class Future; +/// @endcond + +namespace firestore { + +class DocumentSnapshot; +template +class EventListener; +class FieldPath; +class FieldValue; +class ListenerRegistration; +class Firestore; +class QueryInternal; +class QuerySnapshot; + +/** + * @brief A Query which you can read or listen to. + * + * You can also construct refined Query objects by adding filters and ordering. + * + * You cannot construct a valid Query directly; use CollectionReference + * methods that return a Query instead. + * + * @note Firestore classes are not meant to be subclassed except for use in test + * mocks. Subclassing is not supported in production code and new SDK releases + * may break code that does so. + */ +class Query { + public: + /** + * An enum for the direction of a sort. + */ + enum class Direction { + kAscending, + kDescending, + }; + + /** + * @brief Creates an invalid Query that has to be reassigned before it can be + * used. + * + * Calling any member function on an invalid Query will be a no-op. If the + * function returns a value, it will return a zero, empty, or invalid value, + * depending on the type of the value. + */ + Query(); + + /** + * @brief Copy constructor. + * + * `Query` is immutable and can be efficiently copied (no deep copy is + * performed). + * + * @param[in] other `Query` to copy from. + */ + Query(const Query& other); + + /** + * @brief Move constructor. + * + * Moving is more efficient than copying for a `Query`. After being moved + * from, a `Query` is equivalent to its default-constructed state. + * + * @param[in] other `Query` to move data from. + */ + Query(Query&& other); + + virtual ~Query(); + + /** + * @brief Copy assignment operator. + * + * `Query` is immutable and can be efficiently copied (no deep copy is + * performed). + * + * @param[in] other `Query` to copy from. + * + * @return Reference to the destination `Query`. + */ + Query& operator=(const Query& other); + + /** + * @brief Move assignment operator. + * + * Moving is more efficient than copying for a `Query`. After being moved + * from, a `Query` is equivalent to its default-constructed state. + * + * @param[in] other `Query` to move data from. + * + * @return Reference to the destination `Query`. + */ + Query& operator=(Query&& other); + + /** + * @brief Returns the Firestore instance associated with this query. + * + * The pointer will remain valid indefinitely. + * + * @return Firebase Firestore instance that this Query refers to. + */ + virtual const Firestore* firestore() const; + + /** + * @brief Returns the Firestore instance associated with this query. + * + * The pointer will remain valid indefinitely. + * + * @return Firebase Firestore instance that this Query refers to. + */ + virtual Firestore* firestore(); + + /** + * @brief Creates and returns a new Query with the additional filter that + * documents must contain the specified field and the value should be equal to + * the specified value. + * + * @param[in] field The name of the field to compare. + * @param[in] value The value for comparison. + * + * @return The created Query. + */ + virtual Query WhereEqualTo(const std::string& field, + const FieldValue& value) const; + + /** + * @brief Creates and returns a new Query with the additional filter that + * documents must contain the specified field and the value should be equal to + * the specified value. + * + * @param[in] field The path of the field to compare. + * @param[in] value The value for comparison. + * + * @return The created Query. + */ + virtual Query WhereEqualTo(const FieldPath& field, + const FieldValue& value) const; + + /** + * @brief Creates and returns a new Query with the additional filter that + * documents must contain the specified field and the value does not equal the + * specified value. + * + * A Query can have only one `WhereNotEqualTo()` filter, and it cannot be + * combined with `WhereNotIn()`. + * + * @param[in] field The name of the field to compare. + * @param[in] value The value for comparison. + * + * @return The created Query. + */ + virtual Query WhereNotEqualTo(const std::string& field, + const FieldValue& value) const; + + /** + * @brief Creates and returns a new Query with the additional filter that + * documents must contain the specified field and the value does not equal the + * specified value. + * + * A Query can have only one `WhereNotEqualTo()` filter, and it cannot be + * combined with `WhereNotIn()`. + * + * @param[in] field The path of the field to compare. + * @param[in] value The value for comparison. + * + * @return The created Query. + */ + virtual Query WhereNotEqualTo(const FieldPath& field, + const FieldValue& value) const; + + /** + * @brief Creates and returns a new Query with the additional filter that + * documents must contain the specified field and the value should be less + * than the specified value. + * + * @param[in] field The name of the field to compare. + * @param[in] value The value for comparison. + * + * @return The created Query. + */ + virtual Query WhereLessThan(const std::string& field, + const FieldValue& value) const; + + /** + * @brief Creates and returns a new Query with the additional filter that + * documents must contain the specified field and the value should be less + * than the specified value. + * + * @param[in] field The path of the field to compare. + * @param[in] value The value for comparison. + * + * @return The created Query. + */ + virtual Query WhereLessThan(const FieldPath& field, + const FieldValue& value) const; + + /** + * @brief Creates and returns a new Query with the additional filter that + * documents must contain the specified field and the value should be less + * than or equal to the specified value. + * + * @param[in] field The name of the field to compare. + * @param[in] value The value for comparison. + * + * @return The created Query. + */ + virtual Query WhereLessThanOrEqualTo(const std::string& field, + const FieldValue& value) const; + + /** + * @brief Creates and returns a new Query with the additional filter that + * documents must contain the specified field and the value should be less + * than or equal to the specified value. + * + * @param[in] field The path of the field to compare. + * @param[in] value The value for comparison. + * + * @return The created Query. + */ + virtual Query WhereLessThanOrEqualTo(const FieldPath& field, + const FieldValue& value) const; + + /** + * @brief Creates and returns a new Query with the additional filter that + * documents must contain the specified field and the value should be greater + * than the specified value. + * + * @param[in] field The name of the field to compare. + * @param[in] value The value for comparison. + * + * @return The created Query. + */ + virtual Query WhereGreaterThan(const std::string& field, + const FieldValue& value) const; + + /** + * @brief Creates and returns a new Query with the additional filter that + * documents must contain the specified field and the value should be greater + * than the specified value. + * + * @param[in] field The path of the field to compare. + * @param[in] value The value for comparison. + * + * @return The created Query. + */ + virtual Query WhereGreaterThan(const FieldPath& field, + const FieldValue& value) const; + + /** + * @brief Creates and returns a new Query with the additional filter that + * documents must contain the specified field and the value should be greater + * than or equal to the specified value. + * + * @param[in] field The name of the field to compare. + * @param[in] value The value for comparison. + * + * @return The created Query. + */ + virtual Query WhereGreaterThanOrEqualTo(const std::string& field, + const FieldValue& value) const; + + /** + * @brief Creates and returns a new Query with the additional filter that + * documents must contain the specified field and the value should be greater + * than or equal to the specified value. + * + * @param[in] field The path of the field to compare. + * @param[in] value The value for comparison. + * + * @return The created Query. + */ + virtual Query WhereGreaterThanOrEqualTo(const FieldPath& field, + const FieldValue& value) const; + + /** + * @brief Creates and returns a new Query with the additional filter that + * documents must contain the specified field, the value must be an array, and + * that the array must contain the provided value. + * + * A Query can have only one `WhereArrayContains()` filter and it cannot be + * combined with `WhereArrayContainsAny()` or `WhereIn()`. + * + * @param[in] field The name of the field containing an array to search. + * @param[in] value The value that must be contained in the array. + * + * @return The created Query. + */ + virtual Query WhereArrayContains(const std::string& field, + const FieldValue& value) const; + + /** + * @brief Creates and returns a new Query with the additional filter that + * documents must contain the specified field, the value must be an array, and + * that the array must contain the provided value. + * + * A Query can have only one `WhereArrayContains()` filter and it cannot be + * combined with `WhereArrayContainsAny()` or `WhereIn()`. + * + * @param[in] field The path of the field containing an array to search. + * @param[in] value The value that must be contained in the array. + * + * @return The created Query. + */ + virtual Query WhereArrayContains(const FieldPath& field, + const FieldValue& value) const; + + /** + * @brief Creates and returns a new Query with the additional filter that + * documents must contain the specified field, the value must be an array, and + * that the array must contain at least one value from the provided list. + * + * A Query can have only one `WhereArrayContainsAny()` filter and it cannot be + * combined with `WhereArrayContains()` or `WhereIn()`. + * + * @param[in] field The name of the field containing an array to search. + * @param[in] values The list that contains the values to match. + * + * @return The created Query. + */ + virtual Query WhereArrayContainsAny( + const std::string& field, const std::vector& values) const; + + /** + * @brief Creates and returns a new Query with the additional filter that + * documents must contain the specified field, the value must be an array, and + * that the array must contain at least one value from the provided list. + * + * A Query can have only one `WhereArrayContainsAny()` filter and it cannot be + * combined with` WhereArrayContains()` or `WhereIn()`. + * + * @param[in] field The path of the field containing an array to search. + * @param[in] values The list that contains the values to match. + * + * @return The created Query. + */ + virtual Query WhereArrayContainsAny( + const FieldPath& field, const std::vector& values) const; + + /** + * @brief Creates and returns a new Query with the additional filter that + * documents must contain the specified field and the value must equal one of + * the values from the provided list. + * + * A Query can have only one `WhereIn()` filter and it cannot be + * combined with `WhereArrayContainsAny()`. + * + * @param[in] field The name of the field containing an array to search. + * @param[in] values The list that contains the values to match. + * + * @return The created Query. + */ + virtual Query WhereIn(const std::string& field, + const std::vector& values) const; + + /** + * @brief Creates and returns a new Query with the additional filter that + * documents must contain the specified field and the value must equal one of + * the values from the provided list. + * + * A Query can have only one `WhereIn()` filter and it cannot be + * combined with `WhereArrayContainsAny()`. + * + * @param[in] field The path of the field containing an array to search. + * @param[in] values The list that contains the values to match. + * + * @return The created Query. + */ + virtual Query WhereIn(const FieldPath& field, + const std::vector& values) const; + + /** + * @brief Creates and returns a new Query with the additional filter that + * documents must contain the specified field and the value must not equal any + * of the values from the provided list. + * + * One special case is that `WhereNotIn` cannot match `FieldValue::Null()` + * values. To query for documents where a field exists and is + * `FieldValue::Null()`, use `WhereNotEqualTo`, which can handle this special + * case. + * + * A `Query` can have only one `WhereNotIn()` filter, and it cannot be + * combined with `WhereArrayContains()`, `WhereArrayContainsAny()`, + * `WhereIn()`, or `WhereNotEqualTo()`. + * + * @param[in] field The name of the field containing an array to search. + * @param[in] values The list that contains the values to match. + * + * @return The created Query. + */ + virtual Query WhereNotIn(const std::string& field, + const std::vector& values) const; + + /** + * @brief Creates and returns a new Query with the additional filter that + * documents must contain the specified field and the value must not equal any + * of the values from the provided list. + * + * One special case is that `WhereNotIn` cannot match `FieldValue::Null()` + * values. To query for documents where a field exists and is + * `FieldValue::Null()`, use `WhereNotEqualTo`, which can handle this special + * case. + * + * A `Query` can have only one `WhereNotIn()` filter, and it cannot be + * combined with `WhereArrayContains()`, `WhereArrayContainsAny()`, + * `WhereIn()`, or `WhereNotEqualTo()`. + * + * @param[in] field The path of the field containing an array to search. + * @param[in] values The list that contains the values to match. + * + * @return The created Query. + */ + virtual Query WhereNotIn(const FieldPath& field, + const std::vector& values) const; + + /** + * @brief Creates and returns a new Query that's additionally sorted by the + * specified field. + * + * @param[in] field The field to sort by. + * @param[in] direction The direction to sort (optional). If not specified, + * order will be ascending. + * + * @return The created Query. + */ + virtual Query OrderBy(const std::string& field, + Direction direction = Direction::kAscending) const; + + /** + * @brief Creates and returns a new Query that's additionally sorted by the + * specified field. + * + * @param[in] field The field to sort by. + * @param[in] direction The direction to sort (optional). If not specified, + * order will be ascending. + * + * @return The created Query. + */ + virtual Query OrderBy(const FieldPath& field, + Direction direction = Direction::kAscending) const; + + /** + * @brief Creates and returns a new Query that only returns the first matching + * documents up to the specified number. + * + * @param[in] limit A non-negative integer to specify the maximum number of + * items to return. + * + * @return The created Query. + */ + virtual Query Limit(int32_t limit) const; + + /** + * @brief Creates and returns a new Query that only returns the last matching + * documents up to the specified number. + * + * @param[in] limit A non-negative integer to specify the maximum number of + * items to return. + * + * @return The created Query. + */ + virtual Query LimitToLast(int32_t limit) const; + + /** + * @brief Creates and returns a new Query that starts at the provided document + * (inclusive). The starting position is relative to the order of the query. + * The document must contain all of the fields provided in the order by of + * this query. + * + * @param[in] snapshot The snapshot of the document to start at. + * + * @return The created Query. + */ + virtual Query StartAt(const DocumentSnapshot& snapshot) const; + + /** + * @brief Creates and returns a new Query that starts at the provided fields + * relative to the order of the query. The order of the field values must + * match the order of the order by clauses of the query. + * + * @param[in] values The field values to start this query at, in order of the + * query's order by. + * + * @return The created Query. + */ + virtual Query StartAt(const std::vector& values) const; + + /** + * @brief Creates and returns a new Query that starts after the provided + * document (inclusive). The starting position is relative to the order of the + * query. The document must contain all of the fields provided in the order by + * of this query. + * + * @param[in] snapshot The snapshot of the document to start after. + * + * @return The created Query. + */ + virtual Query StartAfter(const DocumentSnapshot& snapshot) const; + + /** + * @brief Creates and returns a new Query that starts after the provided + * fields relative to the order of the query. The order of the field values + * must match the order of the order by clauses of the query. + * + * @param[in] values The field values to start this query after, in order of + * the query's order by. + * + * @return The created Query. + */ + virtual Query StartAfter(const std::vector& values) const; + + /** + * @brief Creates and returns a new Query that ends before the provided + * document (inclusive). The end position is relative to the order of the + * query. The document must contain all of the fields provided in the order by + * of this query. + * + * @param[in] snapshot The snapshot of the document to end before. + * + * @return The created Query. + */ + virtual Query EndBefore(const DocumentSnapshot& snapshot) const; + + /** + * @brief Creates and returns a new Query that ends before the provided fields + * relative to the order of the query. The order of the field values must + * match the order of the order by clauses of the query. + * + * @param[in] values The field values to end this query before, in order of + * the query's order by. + * + * @return The created Query. + */ + virtual Query EndBefore(const std::vector& values) const; + + /** + * @brief Creates and returns a new Query that ends at the provided document + * (inclusive). The end position is relative to the order of the query. The + * document must contain all of the fields provided in the order by of this + * query. + * + * @param[in] snapshot The snapshot of the document to end at. + * + * @return The created Query. + */ + virtual Query EndAt(const DocumentSnapshot& snapshot) const; + + /** + * @brief Creates and returns a new Query that ends at the provided fields + * relative to the order of the query. The order of the field values must + * match the order of the order by clauses of the query. + * + * @param[in] values The field values to end this query at, in order of the + * query's order by. + * + * @return The created Query. + */ + virtual Query EndAt(const std::vector& values) const; + + /** + * @brief Executes the query and returns the results as a QuerySnapshot. + * + * By default, Get() attempts to provide up-to-date data when possible by + * waiting for data from the server, but it may return cached data or fail if + * you are offline and the server cannot be reached. This behavior can be + * altered via the Source parameter. + * + * @param[in] source A value to configure the get behavior (optional). + * + * @return A Future that will be resolved with the results of the Query. + */ + virtual Future Get(Source source = Source::kDefault) const; + + /** + * @brief Starts listening to the QuerySnapshot events referenced by this + * query. + * + * @param[in] callback The std::function to call. When this function is + * called, snapshot value is valid if and only if error is Error::kErrorOk. + * The std::string is an error message; the value may be empty if an error + * message is not available. + * + * @return A registration object that can be used to remove the listener. + */ + virtual ListenerRegistration AddSnapshotListener( + std::function + callback); + + /** + * @brief Starts listening to the QuerySnapshot events referenced by this + * query. + * + * @param[in] metadata_changes Indicates whether metadata-only changes (that + * is, only DocumentSnapshot::metadata() changed) should trigger snapshot + * events. + * @param[in] callback The std::function to call. When this function is + * called, snapshot value is valid if and only if error is Error::kErrorOk. + * The std::string is an error message; the value may be empty if an error + * message is not available. + * + * @return A registration object that can be used to remove the listener. + */ + virtual ListenerRegistration AddSnapshotListener( + MetadataChanges metadata_changes, + std::function + callback); + + /** + * @brief Returns true if this `Query` is valid, false if it is not valid. An + * invalid `Query` could be the result of: + * - Creating a `Query` using the default constructor. + * - Moving from the `Query`. + * - Deleting your Firestore instance, which will invalidate all the `Query` + * instances associated with it. + * + * @return true if this `Query` is valid, false if this `Query` is invalid. + */ + bool is_valid() const { return internal_ != nullptr; } + + private: + size_t Hash() const; + + friend bool operator==(const Query& lhs, const Query& rhs); + friend size_t QueryHash(const Query& query); + + friend class FirestoreInternal; + friend class QueryInternal; + friend class QuerySnapshotInternal; + friend struct ConverterImpl; + template + friend struct CleanupFn; + // For access to the constructor and to `internal_`. + friend class CollectionReference; + + explicit Query(QueryInternal* internal); + + mutable QueryInternal* internal_ = nullptr; +}; + +/** Checks `lhs` and `rhs` for equality. */ +bool operator==(const Query& lhs, const Query& rhs); + +/** Checks `lhs` and `rhs` for inequality. */ +inline bool operator!=(const Query& lhs, const Query& rhs) { + return !(lhs == rhs); +} + +} // namespace firestore +} // namespace firebase + +#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_QUERY_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/query_snapshot.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/query_snapshot.h new file mode 100644 index 000000000000..2dcf7aaf5239 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/query_snapshot.h @@ -0,0 +1,194 @@ +/* + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_QUERY_SNAPSHOT_H_ +#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_QUERY_SNAPSHOT_H_ + +#include +#include + +#include "firebase/firestore/metadata_changes.h" +#include "firebase/firestore/snapshot_metadata.h" + +namespace firebase { +namespace firestore { + +class DocumentChange; +class DocumentSnapshot; +class Query; +class QuerySnapshotInternal; + +/** + * @brief A QuerySnapshot contains zero or more DocumentSnapshot objects. + * + * QuerySnapshot can be iterated using a range-based for loop, and its size can + * be inspected with empty() and size(). + * + * @note Firestore classes are not meant to be subclassed except for use in test + * mocks. Subclassing is not supported in production code and new SDK releases + * may break code that does so. + */ +class QuerySnapshot { + public: + /** + * @brief Creates an invalid QuerySnapshot that has to be reassigned before it + * can be used. + * + * Calling any member function on an invalid QuerySnapshot will be a no-op. If + * the function returns a value, it will return a zero, empty, or invalid + * value, depending on the type of the value. + */ + QuerySnapshot(); + + /** + * @brief Copy constructor. + * + * `QuerySnapshot` is immutable and can be efficiently copied (no deep copy is + * performed). + * + * @param[in] other `QuerySnapshot` to copy from. + */ + QuerySnapshot(const QuerySnapshot& other); + + /** + * @brief Move constructor. + * + * Moving is more efficient than copying for a `QuerySnapshot`. After being + * moved from, a `QuerySnapshot` is equivalent to its default-constructed + * state. + * + * @param[in] other `QuerySnapshot` to move data from. + */ + QuerySnapshot(QuerySnapshot&& other); + + virtual ~QuerySnapshot(); + + /** + * @brief Copy assignment operator. + * + * `QuerySnapshot` is immutable and can be efficiently copied (no deep copy is + * performed). + * + * @param[in] other `QuerySnapshot` to copy from. + * + * @return Reference to the destination `QuerySnapshot`. + */ + QuerySnapshot& operator=(const QuerySnapshot& other); + + /** + * @brief Move assignment operator. + * + * Moving is more efficient than copying for a `QuerySnapshot`. After being + * moved from, a `QuerySnapshot` is equivalent to its default-constructed + * state. + * + * @param[in] other `QuerySnapshot` to move data from. + * + * @return Reference to the destination `QuerySnapshot`. + */ + QuerySnapshot& operator=(QuerySnapshot&& other); + + /** + * @brief The query from which you got this QuerySnapshot. + */ + virtual Query query() const; + + /** + * @brief Metadata about this snapshot, concerning its source and if it has + * local modifications. + * + * @return The metadata for this document snapshot. + */ + virtual SnapshotMetadata metadata() const; + + /** + * @brief The list of documents that changed since the last snapshot. + * + * If it's the first snapshot, all documents will be in the list as added + * changes. Documents with changes only to their metadata will not be + * included. + * + * @param[in] metadata_changes Indicates whether metadata-only changes (that + * is, only QuerySnapshot::metadata() changed) should be included. + * + * @return The list of document changes since the last snapshot. + */ + virtual std::vector DocumentChanges( + MetadataChanges metadata_changes = MetadataChanges::kExclude) const; + + /** + * @brief The list of documents in this QuerySnapshot in order of the query. + * + * @return The list of documents. + */ + virtual std::vector documents() const; + + /** + * @brief Checks the emptiness of the QuerySnapshot. + * + * @return True if there are no documents in the QuerySnapshot. + */ + bool empty() const { return size() == 0; } + + /** + * @brief Checks the size of the QuerySnapshot. + * + * @return The number of documents in the QuerySnapshot. + */ + virtual std::size_t size() const; + + /** + * @brief Returns true if this `QuerySnapshot` is valid, false if it is not + * valid. An invalid `QuerySnapshot` could be the result of: + * - Creating a `QuerySnapshot` using the default constructor. + * - Moving from the `QuerySnapshot`. + * - Deleting your Firestore instance, which will invalidate all the + * `QuerySnapshot` instances associated with it. + * + * @return true if this `QuerySnapshot` is valid, false if this + * `QuerySnapshot` is invalid. + */ + bool is_valid() const { return internal_ != nullptr; } + + private: + std::size_t Hash() const; + + friend bool operator==(const QuerySnapshot& lhs, const QuerySnapshot& rhs); + friend std::size_t QuerySnapshotHash(const QuerySnapshot& snapshot); + + friend class EventListenerInternal; + friend class FirestoreInternal; + friend struct ConverterImpl; + template + friend struct CleanupFn; + + explicit QuerySnapshot(QuerySnapshotInternal* internal); + + mutable QuerySnapshotInternal* internal_ = nullptr; +}; + +/** Checks `lhs` and `rhs` for equality. */ +bool operator==(const QuerySnapshot& lhs, const QuerySnapshot& rhs); + +/** Checks `lhs` and `rhs` for inequality. */ +inline bool operator!=(const QuerySnapshot& lhs, const QuerySnapshot& rhs) { + return !(lhs == rhs); +} + +} // namespace firestore +} // namespace firebase + +#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_QUERY_SNAPSHOT_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/set_options.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/set_options.h new file mode 100644 index 000000000000..bf21b07a0c45 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/set_options.h @@ -0,0 +1,161 @@ +/* + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_SET_OPTIONS_H_ +#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_SET_OPTIONS_H_ + +#include +#include +#include + +#include "firebase/firestore/field_path.h" + +namespace firebase { +namespace firestore { + +/** + * @brief An options object that configures the behavior of Set() calls. + * + * By providing the SetOptions objects returned by Merge(), the Set() methods in + * DocumentReference, WriteBatch and Transaction can be configured to perform + * granular merges instead of overwriting the target documents in their + * entirety. + */ +class SetOptions final { + public: + /** The enumeration of all types of SetOptions. */ + enum class Type { + /** Overwrites the whole document. */ + kOverwrite, + + /** + * Replaces the values specified in the call parameter while leaves omitted + * fields untouched. + */ + kMergeAll, + + /** + * Replaces the values of the fields explicitly specified in the call + * parameter. + */ + kMergeSpecific, + }; + + /** + * Creates SetOptions with overwrite semantics. + */ + SetOptions() = default; + + /** + * @brief Copy constructor. + * + * This performs a deep copy, creating an independent instance. + * + * @param[in] other `SetOptions` to copy from. + */ + SetOptions(const SetOptions& other) = default; + + /** + * @brief Move constructor. + * + * Moving is more efficient than copying for `SetOptions`. After being moved + * from, `SetOptions` is in a valid but unspecified state. + * + * @param[in] other `SetOptions` to move data from. + */ + SetOptions(SetOptions&& other) = default; + + ~SetOptions(); + + /** + * @brief Copy assignment operator. + * + * This performs a deep copy, creating an independent instance. + * + * @param[in] other `SetOptions` to copy from. + * + * @return Reference to the destination `SetOptions`. + */ + SetOptions& operator=(const SetOptions& other) = default; + + /** + * @brief Move assignment operator. + * + * Moving is more efficient than copying for `SetOptions`. After being moved + * from, `SetOptions` is in a valid but unspecified state. + * + * @param[in] other `SetOptions` to move data from. + * + * @return Reference to the destination `SetOptions`. + */ + SetOptions& operator=(SetOptions&& other) = default; + + /** + * Returns an instance that can be used to change the behavior of Set() calls + * to only replace the values specified in its data argument. Fields omitted + * from the Set() call will remain untouched. + */ + static SetOptions Merge(); + + /** + * Returns an instance that can be used to change the behavior of Set() calls + * to only replace the given fields. Any field that is not specified in + * `fields` is ignored and remains untouched. + * + * It is an error to pass a SetOptions object to a Set() call that is missing + * a value for any of the fields specified here. + * + * @param fields The list of fields to merge. Fields can contain dots to + * reference nested fields within the document. + */ + static SetOptions MergeFields(const std::vector& fields); + + /** + * Returns an instance that can be used to change the behavior of Set() calls + * to only replace the given fields. Any field that is not specified in + * `fields` is ignored and remains untouched. + * + * It is an error to pass a SetOptions object to a Set() call that is missing + * a value for any of the fields specified here in its to data argument. + * + * @param fields The list of fields to merge. + */ + static SetOptions MergeFieldPaths(const std::vector& fields); + + private: + friend bool operator==(const SetOptions& lhs, const SetOptions& rhs); + friend class SetOptionsInternal; + + SetOptions(Type type, std::unordered_set fields); + + Type type_ = Type::kOverwrite; + std::unordered_set fields_; +}; + +/** Checks `lhs` and `rhs` for equality. */ +inline bool operator==(const SetOptions& lhs, const SetOptions& rhs) { + return lhs.type_ == rhs.type_ && lhs.fields_ == rhs.fields_; +} + +/** Checks `lhs` and `rhs` for inequality. */ +inline bool operator!=(const SetOptions& lhs, const SetOptions& rhs) { + return !(lhs == rhs); +} + +} // namespace firestore +} // namespace firebase + +#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_SET_OPTIONS_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/settings.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/settings.h new file mode 100644 index 000000000000..8169d9f594e8 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/settings.h @@ -0,0 +1,247 @@ +/* + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_SETTINGS_H_ +#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_SETTINGS_H_ + +#if defined(__OBJC__) +#include +#endif + +#include +#include +#include +#include + +namespace firebase { +namespace firestore { + +#if !defined(__ANDROID__) +// +// This declaration is guarded by a preprocessor macro because it causes +// problems with name lookup on Android. Android implementation of the public +// API extensively uses function calls of the form `util::Foo` which are +// expected to resolve to `::firebase::util::Foo`. As soon as namespace +// `::firebase::firestore::util` becomes visible, it shadows `::firebase::util` +// (within `::firebase::firestore`), so now all those calls fail to compile +// because they are interpreted as referring to +// `::firebase::firestore::util::Foo`, which doesn't exist. Changing existing +// code is impractical because such usages are numerous. +// +namespace util { +class Executor; +} +#endif + +class FirestoreInternal; + +/** Settings used to configure a Firestore instance. */ +class Settings final { + public: + /** + * Constant to use with `set_cache_size_bytes` to disable garbage collection. + */ + static constexpr int64_t kCacheSizeUnlimited = -1; + + /** + * @brief Creates the default settings. + */ + Settings(); + + /** + * @brief Copy constructor. + * + * This performs a deep copy, creating an independent instance. + * + * @param[in] other `Settings` to copy from. + */ + Settings(const Settings& other) = default; + + /** + * @brief Move constructor. + * + * Moving is more efficient than copying for `Settings`. After being moved + * from, `Settings` is in a valid but unspecified state. + * + * @param[in] other `Settings` to move data from. + */ + Settings(Settings&& other) = default; + + /** + * @brief Copy assignment operator. + * + * This performs a deep copy, creating an independent instance. + * + * @param[in] other `Settings` to copy from. + * + * @return Reference to the destination `Settings`. + */ + Settings& operator=(const Settings& other) = default; + + /** + * @brief Move assignment operator. + * + * Moving is more efficient than copying for `Settings`. After being moved + * from, `Settings` is in a valid but unspecified state. + * + * @param[in] other `Settings` to move data from. + * + * @return Reference to the destination `Settings`. + */ + Settings& operator=(Settings&& other) = default; + + /** + * Gets the host of the Firestore backend to connect to. + */ + const std::string& host() const { return host_; } + + /** + * Returns whether to use SSL when communicating. + */ + bool is_ssl_enabled() const { return ssl_enabled_; } + + /** + * Returns whether to enable local persistent storage. + */ + bool is_persistence_enabled() const { return persistence_enabled_; } + + /** Returns cache size for on-disk data. */ + int64_t cache_size_bytes() const { return cache_size_bytes_; } + + /** + * Sets the host of the Firestore backend. The default is + * "firestore.googleapis.com". + * + * @param host The host string. + */ + void set_host(std::string host); + + /** + * Enables or disables SSL for communication. + * + * @param enabled Set true to enable SSL for communication. + */ + void set_ssl_enabled(bool enabled); + + /** + * Enables or disables local persistent storage. + * + * @param enabled Set true to enable local persistent storage. + */ + void set_persistence_enabled(bool enabled); + + /** + * Sets an approximate cache size threshold for the on-disk data. If the cache + * grows beyond this size, Cloud Firestore will start removing data that + * hasn't been recently used. The size is not a guarantee that the cache will + * stay below that size, only that if the cache exceeds the given size, + * cleanup will be attempted. + * + * By default, collection is enabled with a cache size of 100 MB. The minimum + * value is 1 MB. + */ + void set_cache_size_bytes(int64_t value); + +#if defined(__OBJC__) || defined(DOXYGEN) + /** + * Returns a dispatch queue that Firestore will use to execute callbacks. + * + * The returned dispatch queue is used for all completion handlers and event + * handlers. + * + * If no dispatch queue is explictly set by calling `set_dispatch_queue()` + * then a dedicated "callback queue" will be used; namely, the main thread + * will not be used for callbacks unless expliclty set to do so by a call to + * `set_dispatch_queue()`. + * + * @note This method is only available when `__OBJC__` is defined, such as + * when compiling for iOS or tvOS. + * + * @see `set_dispatch_queue(dispatch_queue_t)` for information on how to + * explicitly set the dispatch queue to use. + */ + dispatch_queue_t dispatch_queue() const; + + /** + * Sets the dispatch queue that Firestore will use to execute callbacks. + * + * The specified dispatch queue will be used for all completion handlers and + * event handlers. + * + * @param queue The dispatch queue to use. + * + * @note This method is only available when `__OBJC__` is defined, such as + * when compiling for iOS or tvOS. + * + * @see `dispatch_queue()` for the "get" counterpart to this method. + */ + void set_dispatch_queue(dispatch_queue_t queue); +#endif // defined(__OBJC__) || defined(DOXYGEN) + + /** + * Returns a string representation of these `Settings` for + * logging/debugging purposes. + * + * @note the exact string representation is unspecified and subject to + * change; don't rely on the format of the string. + */ + std::string ToString() const; + + /** + * Outputs the string representation of these `Settings` to the given + * stream. + * + * @see `ToString()` for comments on the representation format. + */ + friend std::ostream& operator<<(std::ostream& out, const Settings& settings); + + private: + static constexpr int64_t kDefaultCacheSizeBytes = 100 * 1024 * 1024; + + std::string host_; + bool ssl_enabled_ = true; + bool persistence_enabled_ = true; + int64_t cache_size_bytes_ = kDefaultCacheSizeBytes; + + // + // TODO(varconst): fix Android problems and make these declarations + // unconditional. + // +#if !defined(__ANDROID__) + friend class FirestoreInternal; + std::unique_ptr CreateExecutor() const; + + std::shared_ptr executor_; +#endif +}; + +/** Checks `lhs` and `rhs` for equality. */ +inline bool operator==(const Settings& lhs, const Settings& rhs) { + return lhs.host() == rhs.host() && + lhs.is_ssl_enabled() == rhs.is_ssl_enabled() && + lhs.is_persistence_enabled() == rhs.is_persistence_enabled() && + lhs.cache_size_bytes() == rhs.cache_size_bytes(); +} + +/** Checks `lhs` and `rhs` for inequality. */ +inline bool operator!=(const Settings& lhs, const Settings& rhs) { + return !(lhs == rhs); +} + +} // namespace firestore +} // namespace firebase + +#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_SETTINGS_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/snapshot_metadata.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/snapshot_metadata.h new file mode 100644 index 000000000000..ce7f3f2b8607 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/snapshot_metadata.h @@ -0,0 +1,159 @@ +/* + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_SNAPSHOT_METADATA_H_ +#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_SNAPSHOT_METADATA_H_ + +#include +#include + +namespace firebase { +namespace firestore { + +/** Metadata about a snapshot, describing the state of the snapshot. */ +class SnapshotMetadata final { + public: + /** + * Constructs a SnapshotMetadata that has all of its boolean members set to + * false. + */ + SnapshotMetadata() = default; + + /** + * Constructs a SnapshotMetadata by providing boolean parameters that describe + * the state of the snapshot. + * + * @param has_pending_writes Whether there is any pending write on the + * snapshot. + * @param is_from_cache Whether the snapshot is from cache instead of backend. + */ + SnapshotMetadata(bool has_pending_writes, bool is_from_cache) + : has_pending_writes_(has_pending_writes), + is_from_cache_(is_from_cache) {} + + /** + * @brief Copy constructor. + * + * This performs a deep copy, creating an independent instance. + * + * @note This class is currently trivially copyable, but it is not guaranteed + * to stay that way, and code relying on this might be broken by a future + * release. + * + * @param[in] other `SnapshotMetadata` to copy from. + */ + SnapshotMetadata(const SnapshotMetadata& other) = default; + + /** + * @brief Move constructor, equivalent to copying. + * + * After being moved from, `SnapshotMetadata` is in a valid but unspecified + * state. + * + * @param[in] other `SnapshotMetadata` to move data from. + */ + SnapshotMetadata(SnapshotMetadata&& other) = default; + + /** + * @brief Copy assignment operator. + * + * This performs a deep copy, creating an independent instance. + * + * @note This class is currently trivially copyable, but it is not guaranteed + * to stay that way, and code relying on this might be broken by a future + * release. + * + * @param[in] other `SnapshotMetadata` to copy from. + * + * @return Reference to the destination `SnapshotMetadata`. + */ + SnapshotMetadata& operator=(const SnapshotMetadata& other) = default; + + /** + * @brief Move assignment operator, equivalent to copying. + * + * After being moved from, `SnapshotMetadata` is in a valid but unspecified + * state. + * + * @param[in] other `SnapshotMetadata` to move data from. + * + * @return Reference to the destination `SnapshotMetadata`. + */ + SnapshotMetadata& operator=(SnapshotMetadata&& other) = default; + + /** + * Returns whether the snapshot contains the result of local writes. + * + * @return true if the snapshot contains the result of local writes (for + * example, Set() or Update() calls) that have not yet been committed to the + * backend. If your listener has opted into metadata updates (via + * MetadataChanges::kInclude) you will receive another snapshot with + * has_pending_writes() equal to false once the writes have been committed to + * the backend. + */ + bool has_pending_writes() const { return has_pending_writes_; } + + /** + * Returns whether the snapshot was created from cached data. + * + * @return true if the snapshot was created from cached data rather than + * guaranteed up-to-date server data. If your listener has opted into metadata + * updates (via MetadataChanges::kInclude) you will receive another snapshot + * with is_from_cache() equal to false once the client has received up-to-date + * data from the backend. + */ + bool is_from_cache() const { return is_from_cache_; } + + /** + * Returns a string representation of this `SnapshotMetadata` for + * logging/debugging purposes. + * + * @note the exact string representation is unspecified and subject to + * change; don't rely on the format of the string. + */ + std::string ToString() const; + + /** + * Outputs the string representation of this `SnapshotMetadata` to the given + * stream. + * + * @see `ToString()` for comments on the representation format. + */ + friend std::ostream& operator<<(std::ostream& out, + const SnapshotMetadata& metadata); + + private: + bool has_pending_writes_ = false; + bool is_from_cache_ = false; +}; + +/** Checks `lhs` and `rhs` for equality. */ +inline bool operator==(const SnapshotMetadata& lhs, + const SnapshotMetadata& rhs) { + return lhs.has_pending_writes() == rhs.has_pending_writes() && + lhs.is_from_cache() == rhs.is_from_cache(); +} + +/** Checks `lhs` and `rhs` for inequality. */ +inline bool operator!=(const SnapshotMetadata& lhs, + const SnapshotMetadata& rhs) { + return !(lhs == rhs); +} + +} // namespace firestore +} // namespace firebase + +#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_SNAPSHOT_METADATA_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/source.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/source.h new file mode 100644 index 000000000000..743106d9e578 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/source.h @@ -0,0 +1,59 @@ +/* + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_SOURCE_H_ +#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_SOURCE_H_ + +namespace firebase { +namespace firestore { + +/** + * @brief Configures the behavior of DocumentReference::Get() and Query::Get(). + * + * By providing a Source value, these methods can be configured to fetch results + * only from the server, only from the local cache, or attempt to fetch results + * from the server and fall back to the cache (which is the default). + */ +enum class Source { + /** + * Causes Firestore to try to retrieve an up-to-date (server-retrieved) + * snapshot, but fall back to returning cached data if the server can't be + * reached. + */ + kDefault, + + /** + * Causes Firestore to avoid the cache, generating an error if the server + * cannot be reached. Note that the cache will still be updated if the server + * request succeeds. Also note that latency-compensation still takes effect, + * so any pending write operations will be visible in the returned data + * (merged into the server-provided data). + */ + kServer, + + /** + * Causes Firestore to immediately return a value from the cache, ignoring the + * server completely (implying that the returned value may be stale with + * respect to the value on the server). If there is no data in the cache to + * satisfy the DocumentReference::Get() call will return an error and + * Query::Get() will return an empty QuerySnapshot with no documents. + */ + kCache, +}; + +} // namespace firestore +} // namespace firebase +#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_SOURCE_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/timestamp.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/timestamp.h new file mode 100644 index 000000000000..e806bb87c136 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/timestamp.h @@ -0,0 +1,252 @@ +/* + * Copyright 2018 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIRESTORE_CORE_INCLUDE_FIREBASE_FIRESTORE_TIMESTAMP_H_ +#define FIRESTORE_CORE_INCLUDE_FIREBASE_FIRESTORE_TIMESTAMP_H_ + +#include +#include +#include +#include + +#if !defined(_STLPORT_VERSION) +#include // NOLINT(build/c++11) +#endif // !defined(_STLPORT_VERSION) + +namespace firebase { + +/** + * A Timestamp represents a point in time independent of any time zone or + * calendar, represented as seconds and fractions of seconds at nanosecond + * resolution in UTC Epoch time. It is encoded using the Proleptic Gregorian + * Calendar which extends the Gregorian calendar backwards to year one. It is + * encoded assuming all minutes are 60 seconds long, i.e. leap seconds are + * "smeared" so that no leap second table is needed for interpretation. Range is + * from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.999999999Z. + * + * @see + * https://github.com/google/protobuf/blob/master/src/google/protobuf/timestamp.proto + */ +class Timestamp { + public: + /** + * Creates a new timestamp representing the epoch (with seconds and + * nanoseconds set to 0). + */ + Timestamp() = default; + + /** + * Creates a new timestamp. + * + * @param seconds The number of seconds of UTC time since Unix epoch + * 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to + * 9999-12-31T23:59:59Z inclusive; otherwise, assertion failure will be + * triggered. + * @param nanoseconds The non-negative fractions of a second at nanosecond + * resolution. Negative second values with fractions must still have + * non-negative nanoseconds values that count forward in time. Must be + * from 0 to 999,999,999 inclusive; otherwise, assertion failure will be + * triggered. + */ + Timestamp(int64_t seconds, int32_t nanoseconds); + + /** Copy constructor, `Timestamp` is trivially copyable. */ + Timestamp(const Timestamp& other) = default; + + /** Move constructor, equivalent to copying. */ + Timestamp(Timestamp&& other) = default; + + /** Copy assignment operator, `Timestamp` is trivially copyable. */ + Timestamp& operator=(const Timestamp& other) = default; + + /** Move assignment operator, equivalent to copying. */ + Timestamp& operator=(Timestamp&& other) = default; + + /** + * Creates a new timestamp with the current date. + * + * The precision is up to nanoseconds, depending on the system clock. + * + * @return a new timestamp representing the current date. + */ + static Timestamp Now(); + + /** + * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z. + */ + int64_t seconds() const { + return seconds_; + } + + /** + * The non-negative fractions of a second at nanosecond resolution. Negative + * second values with fractions still have non-negative nanoseconds values + * that count forward in time. + */ + int32_t nanoseconds() const { + return nanoseconds_; + } + + /** + * Converts `time_t` to a `Timestamp`. + * + * @param seconds_since_unix_epoch + * @parblock + * The number of seconds of UTC time since Unix epoch + * 1970-01-01T00:00:00Z. Can be negative to represent dates before the + * epoch. Must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z + * inclusive; otherwise, assertion failure will be triggered. + * + * Note that while the epoch of `time_t` is unspecified, it's usually Unix + * epoch. If this assumption is broken, this function will produce + * incorrect results. + * @endparblock + * + * @return a new timestamp with the given number of seconds and zero + * nanoseconds. + */ + static Timestamp FromTimeT(time_t seconds_since_unix_epoch); + +#if !defined(_STLPORT_VERSION) + /** + * Converts `std::chrono::time_point` to a `Timestamp`. + * + * @param time_point + * @parblock + * The time point with system clock's epoch, which is + * presumed to be Unix epoch 1970-01-01T00:00:00Z. Can be negative to + * represent dates before the epoch. Must be from 0001-01-01T00:00:00Z to + * 9999-12-31T23:59:59Z inclusive; otherwise, assertion failure will be + * triggered. + * + * Note that while the epoch of `std::chrono::system_clock` is + * unspecified, it's usually Unix epoch. If this assumption is broken, + * this constructor will produce incorrect results. + * @endparblock + */ + static Timestamp FromTimePoint( + std::chrono::time_point time_point); + + /** + * Converts this `Timestamp` to a `time_point`. + * + * Important: if overflow would occur, the returned value will be the maximum + * or minimum value that `Duration` can hold. Note in particular that `long + * long` is insufficient to hold the full range of `Timestamp` values with + * nanosecond precision (which is why `Duration` defaults to `microseconds`). + */ + template + std::chrono::time_point ToTimePoint() const; +#endif // !defined(_STLPORT_VERSION) + + /** + * Returns a string representation of this `Timestamp` for logging/debugging + * purposes. + * + * @note: the exact string representation is unspecified and subject to + * change; don't rely on the format of the string. + */ + std::string ToString() const; + + /** + * Outputs the string representation of this `Timestamp` to the given stream. + * + * @see `ToString()` for comments on the representation format. + */ + friend std::ostream& operator<<(std::ostream& out, + const Timestamp& timestamp); + + private: + // Checks that the number of seconds is within the supported date range, and + // that nanoseconds satisfy 0 <= ns <= 1second. + void ValidateBounds() const; + + int64_t seconds_ = 0; + int32_t nanoseconds_ = 0; +}; + +/** Checks whether `lhs` and `rhs` are in ascending order. */ +inline bool operator<(const Timestamp& lhs, const Timestamp& rhs) { + return lhs.seconds() < rhs.seconds() || + (lhs.seconds() == rhs.seconds() && + lhs.nanoseconds() < rhs.nanoseconds()); +} + +/** Checks whether `lhs` and `rhs` are in descending order. */ +inline bool operator>(const Timestamp& lhs, const Timestamp& rhs) { + return rhs < lhs; +} + +/** Checks whether `lhs` and `rhs` are in non-ascending order. */ +inline bool operator>=(const Timestamp& lhs, const Timestamp& rhs) { + return !(lhs < rhs); +} + +/** Checks whether `lhs` and `rhs` are in non-descending order. */ +inline bool operator<=(const Timestamp& lhs, const Timestamp& rhs) { + return !(lhs > rhs); +} + +/** Checks `lhs` and `rhs` for inequality. */ +inline bool operator!=(const Timestamp& lhs, const Timestamp& rhs) { + return lhs < rhs || lhs > rhs; +} + +/** Checks `lhs` and `rhs` for equality. */ +inline bool operator==(const Timestamp& lhs, const Timestamp& rhs) { + return !(lhs != rhs); +} + +#if !defined(_STLPORT_VERSION) + +// Make sure the header compiles even when included after `` without +// `NOMINMAX` defined. `push/pop_macro` pragmas are supported by Visual Studio +// as well as Clang and GCC. +#pragma push_macro("min") +#pragma push_macro("max") +#undef min +#undef max + +template +std::chrono::time_point Timestamp::ToTimePoint() const { + namespace chr = std::chrono; + using TimePoint = chr::time_point; + + // Saturate on overflow + const auto max_seconds = chr::duration_cast(Duration::max()); + if (seconds_ > 0 && max_seconds.count() <= seconds_) { + return TimePoint{Duration::max()}; + } + const auto min_seconds = chr::duration_cast(Duration::min()); + if (seconds_ < 0 && min_seconds.count() >= seconds_) { + return TimePoint{Duration::min()}; + } + + const auto seconds = chr::duration_cast(chr::seconds(seconds_)); + const auto nanoseconds = + chr::duration_cast(chr::nanoseconds(nanoseconds_)); + return TimePoint{seconds + nanoseconds}; +} + +#pragma pop_macro("max") +#pragma pop_macro("min") + +#endif // !defined(_STLPORT_VERSION) + +} // namespace firebase + +#endif // FIRESTORE_CORE_INCLUDE_FIREBASE_FIRESTORE_TIMESTAMP_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/transaction.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/transaction.h new file mode 100644 index 000000000000..af78e0a2fb70 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/transaction.h @@ -0,0 +1,143 @@ +/* + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_TRANSACTION_H_ +#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_TRANSACTION_H_ + +#include + +#include "firebase/firestore/firestore_errors.h" +#include "firebase/firestore/map_field_value.h" +#include "firebase/firestore/set_options.h" + +namespace firebase { +namespace firestore { + +class DocumentReference; +class DocumentSnapshot; +class TransactionInternal; + +/** + * @brief Transaction provides methods to read and write data within + * a transaction. + * + * You cannot create a `Transaction` directly; use `Firestore::RunTransaction()` + * function instead. + * + * @note Firestore classes are not meant to be subclassed except for use in test + * mocks. Subclassing is not supported in production code and new SDK releases + * may break code that does so. + */ +class Transaction { + public: + /** Destructor. */ + virtual ~Transaction(); + + /** + * @brief Deleted copy constructor. + * + * A `Transaction` object is only valid for the duration of the callback you + * pass to `Firestore::RunTransaction()` and cannot be copied. + */ + Transaction(const Transaction& other) = delete; + + /** + * @brief Deleted copy assignment operator. + * + * A `Transaction` object is only valid for the duration of the callback you + * pass to `Firestore::RunTransaction()` and cannot be copied. + */ + Transaction& operator=(const Transaction& other) = delete; + + /** + * @brief Writes to the document referred to by the provided reference. + * + * If the document does not yet exist, it will be created. If you pass + * SetOptions, the provided data can be merged into an existing document. + * + * @param[in] document The DocumentReference to overwrite. + * @param[in] data A map of the fields and values to write to the document. + * @param[in] options An object to configure the Set() behavior (optional). + */ + virtual void Set(const DocumentReference& document, + const MapFieldValue& data, + const SetOptions& options = SetOptions()); + + /** + * Updates fields in the document referred to by the provided reference. If no + * document exists yet, the update will fail. + * + * @param[in] document The DocumentReference to update. + * @param[in] data A map of field / value pairs to update. Fields can contain + * dots to reference nested fields within the document. + */ + virtual void Update(const DocumentReference& document, + const MapFieldValue& data); + + /** + * Updates fields in the document referred to by the provided reference. If no + * document exists yet, the update will fail. + * + * @param[in] document The DocumentReference to update. + * @param[in] data A map from FieldPath to FieldValue to update. + */ + virtual void Update(const DocumentReference& document, + const MapFieldPathValue& data); + + /** + * Deletes the document referred to by the provided reference. + * + * @param[in] document The DocumentReference to delete. + */ + virtual void Delete(const DocumentReference& document); + + /** + * Reads the document referred by the provided reference. + * + * @param[in] document The DocumentReference to read. + * @param[out] error_code An out parameter to capture an error, if one + * occurred. + * @param[out] error_message An out parameter to capture error message, if + * any. + * @return The contents of the document at this DocumentReference or invalid + * DocumentSnapshot if there is any error. + */ + virtual DocumentSnapshot Get(const DocumentReference& document, + Error* error_code, + std::string* error_message); + + protected: + /** + * Default constructor, to be used only for mocking a `Transaction`. + */ + Transaction() = default; + + private: + friend class FirestoreInternal; + friend class TransactionInternal; + friend struct ConverterImpl; + template + friend struct CleanupFn; + + explicit Transaction(TransactionInternal* internal); + + mutable TransactionInternal* internal_ = nullptr; +}; + +} // namespace firestore +} // namespace firebase + +#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_TRANSACTION_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/transaction_options.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/transaction_options.h new file mode 100644 index 000000000000..9433578879b3 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/transaction_options.h @@ -0,0 +1,137 @@ +/* + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_TRANSACTION_OPTIONS_H_ +#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_TRANSACTION_OPTIONS_H_ + +#include +#include +#include + +namespace firebase { +namespace firestore { + +/** + * Options to customize transaction behavior for `Firestore.runTransaction()`. + */ +class TransactionOptions final { + public: + /** + * @brief Creates the default `TransactionOptions`. + */ + TransactionOptions() = default; + + /** + * @brief Copy constructor. + * + * This performs a deep copy, creating an independent instance. + * + * @param[in] other `TransactionOptions` to copy from. + */ + TransactionOptions(const TransactionOptions& other) = default; + + /** + * @brief Move constructor. + * + * Moving is not any more efficient than copying for `TransactionOptions` + * because this class is trivially copyable; however, future additions to this + * class may make it not trivially copyable, at which point moving would be + * more efficient than copying. After being moved from, `TransactionOptions` + * is in a valid but unspecified state. + * + * @param[in] other `TransactionOptions` to move data from. + */ + TransactionOptions(TransactionOptions&& other) = default; + + /** + * @brief Copy assignment operator. + * + * This performs a deep copy, creating an independent instance. + * + * @param[in] other `TransactionOptions` to copy from. + * + * @return Reference to the destination `TransactionOptions`. + */ + TransactionOptions& operator=(const TransactionOptions& other) = default; + + /** + * @brief Move assignment operator. + * + * Moving is not any more efficient than copying for `TransactionOptions` + * because this class is trivially copyable; however, future additions to this + * class may make it not trivially copyable, at which point moving would be + * more efficient than copying. After being moved from, `TransactionOptions` + * is in a valid but unspecified state. + * + * @param[in] other `TransactionOptions` to move data from. + * + * @return Reference to the destination `TransactionOptions`. + */ + TransactionOptions& operator=(TransactionOptions&& other) = default; + + /** + * @brief Gets the maximum number of attempts to commit, after which the + * transaction fails. + * + * The default value is 5. + */ + int32_t max_attempts() const { return max_attempts_; } + + /** + * @brief Sets the maximum number of attempts to commit, after which the + * transaction fails. + * + * The default value is 5. + * + * @param[in] max_attempts The maximum number of attempts; must be greater + * than zero. + */ + void set_max_attempts(int32_t max_attempts); + + /** + * Returns a string representation of this `TransactionOptions` object for + * logging/debugging purposes. + * + * @note the exact string representation is unspecified and subject to + * change; don't rely on the format of the string. + */ + std::string ToString() const; + + /** + * Outputs the string representation of this `TransactionOptions` object to + * the given stream. + * + * @see `ToString()` for comments on the representation format. + */ + friend std::ostream& operator<<(std::ostream&, const TransactionOptions&); + + private: + int32_t max_attempts_ = 5; +}; + +/** Compares two `TransactionOptions` objects for equality. */ +bool operator==(const TransactionOptions&, const TransactionOptions&); + +/** Compares two `TransactionOptions` objects for inequality. */ +inline bool operator!=(const TransactionOptions& lhs, + const TransactionOptions& rhs) { + return !(lhs == rhs); +} + +} // namespace firestore +} // namespace firebase + +#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_TRANSACTION_OPTIONS_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/write_batch.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/write_batch.h new file mode 100644 index 000000000000..1e92cd693516 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/write_batch.h @@ -0,0 +1,188 @@ +/* + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_WRITE_BATCH_H_ +#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_WRITE_BATCH_H_ + +#include "firebase/firestore/map_field_value.h" +#include "firebase/firestore/set_options.h" + +namespace firebase { + +/// @cond FIREBASE_APP_INTERNAL +template +class Future; +/// @endcond + +namespace firestore { + +class DocumentReference; +class WriteBatchInternal; + +/** + * @brief A write batch is used to perform multiple writes as a single atomic + * unit. + * + * A WriteBatch object provides methods for adding writes to the write batch. + * None of the writes will be committed (or visible locally) until Commit() is + * called. + * + * Unlike transactions, write batches are persisted offline and therefore are + * preferable when you don't need to condition your writes on read data. + * + * @note Firestore classes are not meant to be subclassed except for use in test + * mocks. Subclassing is not supported in production code and new SDK releases + * may break code that does so. + */ +class WriteBatch { + public: + /** + * @brief Creates an invalid WriteBatch that has to be reassigned before it + * can be used. + * + * Calling any member function on an invalid WriteBatch will be a no-op. If + * the function returns a value, it will return a zero, empty, or invalid + * value, depending on the type of the value. + */ + WriteBatch(); + + /** + * @brief Copy constructor. + * + * This performs a deep copy, creating an independent instance. + * + * @param[in] other `WriteBatch` to copy from. + */ + WriteBatch(const WriteBatch& other); + + /** + * @brief Move constructor. + * + * Moving is more efficient than copying for a `WriteBatch`. After being moved + * from, a `WriteBatch` is equivalent to its default-constructed state. + * + * @param[in] other `WriteBatch` to move data from. + */ + WriteBatch(WriteBatch&& other); + + virtual ~WriteBatch(); + + /** + * @brief Copy assignment operator. + * + * This performs a deep copy, creating an independent instance. + * + * @param[in] other `WriteBatch` to copy from. + * + * @return Reference to the destination `WriteBatch`. + */ + WriteBatch& operator=(const WriteBatch& other); + + /** + * @brief Move assignment operator. + * + * Moving is more efficient than copying for a `WriteBatch`. After being moved + * from, a `WriteBatch` is equivalent to its default-constructed state. + * + * @param[in] other `WriteBatch` to move data from. + * + * @return Reference to the destination `WriteBatch`. + */ + WriteBatch& operator=(WriteBatch&& other); + + /** + * @brief Writes to the document referred to by the provided reference. + * + * If the document does not yet exist, it will be created. If you pass + * SetOptions, the provided data can be merged into an existing document. + * + * @param document The DocumentReference to write to. + * @param data A map of the fields and values to write to the document. + * @param[in] options An object to configure the Set() behavior (optional). + * + * @return This WriteBatch instance. Used for chaining method calls. + */ + virtual WriteBatch& Set(const DocumentReference& document, + const MapFieldValue& data, + const SetOptions& options = SetOptions()); + + /** + * Updates fields in the document referred to by the provided reference. If no + * document exists yet, the update will fail. + * + * @param document The DocumentReference to update. + * @param data A map of field / value pairs to update. Fields can contain dots + * to reference nested fields within the document. + * @return This WriteBatch instance. Used for chaining method calls. + */ + virtual WriteBatch& Update(const DocumentReference& document, + const MapFieldValue& data); + + /** + * Updates fields in the document referred to by the provided reference. If no + * document exists yet, the update will fail. + * + * @param document The DocumentReference to update. + * @param data A map from FieldPath to FieldValue to update. + * @return This WriteBatch instance. Used for chaining method calls. + */ + virtual WriteBatch& Update(const DocumentReference& document, + const MapFieldPathValue& data); + + /** + * Deletes the document referred to by the provided reference. + * + * @param document The DocumentReference to delete. + * @return This WriteBatch instance. Used for chaining method calls. + */ + virtual WriteBatch& Delete(const DocumentReference& document); + + /** + * Commits all of the writes in this write batch as a single atomic unit. + * + * @return A Future that will be resolved when the write finishes. + */ + virtual Future Commit(); + + /** + * @brief Returns true if this `WriteBatch` is valid, false if it is not + * valid. An invalid `WriteBatch` could be the result of: + * - Creating a `WriteBatch` using the default constructor. + * - Moving from the `WriteBatch`. + * - Deleting your Firestore instance, which will invalidate all the + * `WriteBatch` instances associated with it. + * + * @return true if this `WriteBatch` is valid, false if this `WriteBatch` is + * invalid. + */ + bool is_valid() const { return internal_ != nullptr; } + + private: + friend class FirestoreInternal; + friend class WriteBatchInternal; + friend struct ConverterImpl; + template + friend struct CleanupFn; + + explicit WriteBatch(WriteBatchInternal* internal); + + mutable WriteBatchInternal* internal_ = nullptr; +}; + +} // namespace firestore +} // namespace firebase + +#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_WRITE_BATCH_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/functions.h b/packages/firebase_core/firebase_core/firebase_core/firebase/functions.h new file mode 100644 index 000000000000..500a05cc7ae9 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/functions.h @@ -0,0 +1,115 @@ +// Copyright 2017 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef FIREBASE_FUNCTIONS_SRC_INCLUDE_FIREBASE_FUNCTIONS_H_ +#define FIREBASE_FUNCTIONS_SRC_INCLUDE_FIREBASE_FUNCTIONS_H_ + +#include + +#include "firebase/app.h" +#include "firebase/functions/callable_reference.h" +#include "firebase/functions/callable_result.h" +#include "firebase/functions/common.h" + +namespace firebase { + +/// Namespace for the Firebase C++ SDK for Cloud Functions. +namespace functions { + +/// @cond FIREBASE_APP_INTERNAL +namespace internal { +class FunctionsInternal; +} // namespace internal +/// @endcond + +class FunctionsReference; + +#ifndef SWIG +/// @brief Entry point for the Firebase C++ SDK for Cloud Functions. +/// +/// To use the SDK, call firebase::functions::Functions::GetInstance() to +/// obtain an instance of Functions, then use GetHttpsCallable() to obtain +/// references to callable functions. From there you can call them with +/// CallableReference::Call(). +#endif // SWIG +class Functions { + public: + /// @brief Destructor. You may delete an instance of Functions when + /// you are finished using it, to shut down the Functions library. + ~Functions(); + + /// @brief Get an instance of Functions corresponding to the given App. + /// + /// Cloud Functions uses firebase::App to communicate with Firebase + /// Authentication to authenticate users to the server backend. + /// + /// @param[in] app An instance of firebase::App. Cloud Functions will use + /// this to communicate with Firebase Authentication. + /// @param[out] init_result_out Optional: If provided, write the init result + /// here. Will be set to kInitResultSuccess if initialization succeeded, or + /// kInitResultFailedMissingDependency on Android if Google Play services is + /// not available on the current device. + /// + /// @returns An instance of Functions corresponding to the given App. + static Functions* GetInstance(::firebase::App* app, + InitResult* init_result_out = nullptr); + + /// @brief Get an instance of Functions corresponding to the given App. + /// + /// Cloud Functions uses firebase::App to communicate with Firebase + /// Authentication to authenticate users to the server backend. + /// + /// @param[in] app An instance of firebase::App. Cloud Functions will use + /// this to communicate with Firebase Authentication. + /// @param[in] region The region to call functions in. + /// @param[out] init_result_out Optional: If provided, write the init result + /// here. Will be set to kInitResultSuccess if initialization succeeded, or + /// kInitResultFailedMissingDependency on Android if Google Play services is + /// not available on the current device. + /// + /// @returns An instance of Functions corresponding to the given App. + static Functions* GetInstance(::firebase::App* app, const char* region, + InitResult* init_result_out = nullptr); + + /// @brief Get the firebase::App that this Functions was created with. + /// + /// @returns The firebase::App this Functions was created with. + ::firebase::App* app(); + + /// @brief Get a FunctionsReference for the specified path. + HttpsCallableReference GetHttpsCallable(const char* name) const; + + /// @brief Get a FunctionsReference for the specified URL. + HttpsCallableReference GetHttpsCallableFromURL(const char* url) const; + + /// @brief Sets an origin for a Cloud Functions emulator to use. + void UseFunctionsEmulator(const char* origin); + + private: + /// @cond FIREBASE_APP_INTERNAL + Functions(::firebase::App* app, const char* region); + Functions(const Functions& src); + Functions& operator=(const Functions& src); + + // Delete the internal_ data. + void DeleteInternal(); + + internal::FunctionsInternal* internal_; + /// @endcond +}; + +} // namespace functions +} // namespace firebase + +#endif // FIREBASE_FUNCTIONS_SRC_INCLUDE_FIREBASE_FUNCTIONS_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/functions/callable_reference.h b/packages/firebase_core/firebase_core/firebase_core/firebase/functions/callable_reference.h new file mode 100644 index 000000000000..9641c23564df --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/functions/callable_reference.h @@ -0,0 +1,124 @@ +// Copyright 2017 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef FIREBASE_FUNCTIONS_SRC_INCLUDE_FIREBASE_FUNCTIONS_CALLABLE_REFERENCE_H_ +#define FIREBASE_FUNCTIONS_SRC_INCLUDE_FIREBASE_FUNCTIONS_CALLABLE_REFERENCE_H_ + +#include +#include + +#include "firebase/future.h" +#include "firebase/internal/common.h" + +namespace firebase { +class Variant; + +namespace functions { +class Functions; +class HttpsCallableResult; + +/// @cond FIREBASE_APP_INTERNAL +namespace internal { +class HttpsCallableReferenceInternal; +} // namespace internal +/// @endcond + +#ifndef SWIG +/// Represents a reference to a Cloud Functions object. +/// Developers can call HTTPS Callable Functions. +#endif // SWIG +class HttpsCallableReference { + public: + /// @brief Default constructor. This creates an invalid + /// HttpsCallableReference. Attempting to perform any operations on this + /// reference will fail unless a valid HttpsCallableReference has been + /// assigned to it. + HttpsCallableReference() : internal_(nullptr) {} + + ~HttpsCallableReference(); + + /// @brief Copy constructor. It's totally okay (and efficient) to copy + /// HttpsCallableReference instances, as they simply point to the same + /// location. + /// + /// @param[in] reference HttpsCallableReference to copy from. + HttpsCallableReference(const HttpsCallableReference& reference); + + /// @brief Copy assignment operator. It's totally okay (and efficient) to copy + /// HttpsCallableReference instances, as they simply point to the same + /// location. + /// + /// @param[in] reference HttpsCallableReference to copy from. + /// + /// @returns Reference to the destination HttpsCallableReference. + HttpsCallableReference& operator=(const HttpsCallableReference& reference); + +#if defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) + /// @brief Move constructor. Moving is an efficient operation for + /// HttpsCallableReference instances. + /// + /// @param[in] other HttpsCallableReference to move data from. + HttpsCallableReference(HttpsCallableReference&& other); + + /// @brief Move assignment operator. Moving is an efficient operation for + /// HttpsCallableReference instances. + /// + /// @param[in] other HttpsCallableReference to move data from. + /// + /// @returns Reference to the destination HttpsCallableReference. + HttpsCallableReference& operator=(HttpsCallableReference&& other); +#endif // defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) + + /// @brief Gets the firebase::functions::Functions instance to which we refer. + /// + /// The pointer will remain valid indefinitely. + /// + /// @returns The firebase::functions::Functions instance that this + /// HttpsCallableReference refers to. + Functions* functions(); + + /// @brief Calls the function. + /// + /// @returns The result of the call; + Future Call(); + + /// @brief Calls the function. + /// + /// @param[in] data The params to pass to the function. + /// @returns The result of the call; + Future Call(const Variant& data); + + /// @brief Returns true if this HttpsCallableReference is valid, false if it + /// is not valid. An invalid HttpsCallableReference indicates that the + /// reference is uninitialized (created with the default constructor) or that + /// there was an error retrieving the reference. + /// + /// @returns true if this HttpsCallableReference is valid, false if this + /// HttpsCallableReference is invalid. + bool is_valid() const; + + private: + /// @cond FIREBASE_APP_INTERNAL + friend class Functions; + + HttpsCallableReference(internal::HttpsCallableReferenceInternal* internal); + + internal::HttpsCallableReferenceInternal* internal_; + /// @endcond +}; + +} // namespace functions +} // namespace firebase + +#endif // FIREBASE_FUNCTIONS_SRC_INCLUDE_FIREBASE_FUNCTIONS_CALLABLE_REFERENCE_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/functions/callable_result.h b/packages/firebase_core/firebase_core/firebase_core/firebase/functions/callable_result.h new file mode 100644 index 000000000000..5186377ae828 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/functions/callable_result.h @@ -0,0 +1,96 @@ +// Copyright 2018 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef FIREBASE_FUNCTIONS_SRC_INCLUDE_FIREBASE_FUNCTIONS_CALLABLE_RESULT_H_ +#define FIREBASE_FUNCTIONS_SRC_INCLUDE_FIREBASE_FUNCTIONS_CALLABLE_RESULT_H_ + +#include "firebase/functions/common.h" +#include "firebase/variant.h" + +namespace firebase { +namespace functions { + +/// @cond FIREBASE_APP_INTERNAL +namespace internal { +class HttpsCallableReferenceInternal; +} +/// @endcond + +/// An HttpsCallableResult contains the result of calling an HttpsCallable. +class HttpsCallableResult { + public: + /// @brief Creates an HttpsCallableResult with null data. + HttpsCallableResult() {} + + ~HttpsCallableResult() {} + + /// @brief Copy constructor. Copying is as efficient as copying a Variant. + /// + /// @param[in] other HttpsCallableResult to copy data from. + HttpsCallableResult(const HttpsCallableResult& other) : data_(other.data_) {} + + /// @brief Assignment operator. Copying is as efficient as copying a Variant. + /// + /// @param[in] other HttpsCallableResult to copy data from. + /// + /// @returns Reference to the destination HttpsCallableResult. + HttpsCallableResult& operator=(const HttpsCallableResult& other) { + data_ = other.data_; + return *this; + } + +#if defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) + /// @brief Move constructor. Moving is an efficient operation for + /// HttpsCallableResult instances. + /// + /// @param[in] other HttpsCallableResult to move data from. + HttpsCallableResult(HttpsCallableResult&& other) { + data_ = std::move(other.data_); + } + + /// @brief Move assignment operator. Moving is an efficient operation for + /// HttpsCallableResult instances. + /// + /// @param[in] other HttpsCallableResult to move data from. + /// + /// @returns Reference to the destination HttpsCallableResult. + HttpsCallableResult& operator=(HttpsCallableResult&& other) { + data_ = std::move(other.data_); + return *this; + } + +#endif // defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) + + /// @brief Returns the data that is the result of a Call. + /// + /// @returns The variant containing the data. + const Variant& data() const { return data_; } + + private: + /// @cond FIREBASE_APP_INTERNAL + // Only functions are allowed to construct results. + friend class ::firebase::functions::internal::HttpsCallableReferenceInternal; + HttpsCallableResult(const Variant& data) : data_(data) {} +#if defined(FIREBASE_USE_MOVE_OPERATORS) + HttpsCallableResult(Variant&& data) : data_(std::move(data)) {} +#endif // defined(FIREBASE_USE_MOVE_OPERATORS) + + Variant data_; + /// @endcond +}; + +} // namespace functions +} // namespace firebase + +#endif // FIREBASE_FUNCTIONS_SRC_INCLUDE_FIREBASE_FUNCTIONS_CALLABLE_RESULT_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/functions/common.h b/packages/firebase_core/firebase_core/firebase_core/firebase/functions/common.h new file mode 100644 index 000000000000..143dc8257618 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/functions/common.h @@ -0,0 +1,202 @@ +// Copyright 2017 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef FIREBASE_FUNCTIONS_SRC_INCLUDE_FIREBASE_FUNCTIONS_COMMON_H_ +#define FIREBASE_FUNCTIONS_SRC_INCLUDE_FIREBASE_FUNCTIONS_COMMON_H_ + +#include "firebase/variant.h" + +namespace firebase { +namespace functions { + +/// Error code returned by Cloud Functions C++ functions. +/// Standard gRPC error codes, as defined in: +/// https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto +enum Error { +#ifdef INTERNAL_EXPERIMENTAL +// LINT.IfChange +#endif // INTERNAL_EXPERIMENTAL + + // Not an error; returned on success + // + // HTTP Mapping: 200 OK + kErrorNone = 0, + + // The operation was cancelled, typically by the caller. + // + // HTTP Mapping: 499 Client Closed Request + kErrorCancelled = 1, + + // Unknown error. For example, this error may be returned when + // a `Status` value received from another address space belongs to + // an error space that is not known in this address space. Also + // errors raised by APIs that do not return enough error information + // may be converted to this error. + // + // HTTP Mapping: 500 Internal Server Error + kErrorUnknown = 2, + + // The client specified an invalid argument. Note that this differs + // from `FAILED_PRECONDITION`. `INVALID_ARGUMENT` indicates arguments + // that are problematic regardless of the state of the system + // (e.g., a malformed file name). + // + // HTTP Mapping: 400 Bad Request + kErrorInvalidArgument = 3, + + // The deadline expired before the operation could complete. For operations + // that change the state of the system, this error may be returned + // even if the operation has completed successfully. For example, a + // successful response from a server could have been delayed long + // enough for the deadline to expire. + // + // HTTP Mapping: 504 Gateway Timeout + kErrorDeadlineExceeded = 4, + + // Some requested entity (e.g., file or directory) was not found. + // + // Note to server developers: if a request is denied for an entire class + // of users, such as gradual feature rollout or undocumented whitelist, + // `NOT_FOUND` may be used. If a request is denied for some users within + // a class of users, such as user-based access control, `PERMISSION_DENIED` + // must be used. + // + // HTTP Mapping: 404 Not Found + kErrorNotFound = 5, + + // The entity that a client attempted to create (e.g., file or directory) + // already exists. + // + // HTTP Mapping: 409 Conflict + kErrorAlreadyExists = 6, + + // The caller does not have permission to execute the specified + // operation. `PERMISSION_DENIED` must not be used for rejections + // caused by exhausting some resource (use `RESOURCE_EXHAUSTED` + // instead for those errors). `PERMISSION_DENIED` must not be + // used if the caller can not be identified (use `UNAUTHENTICATED` + // instead for those errors). This error code does not imply the + // request is valid or the requested entity exists or satisfies + // other pre-conditions. + // + // HTTP Mapping: 403 Forbidden + kErrorPermissionDenied = 7, + + // The request does not have valid authentication credentials for the + // operation. + // + // HTTP Mapping: 401 Unauthorized + kErrorUnauthenticated = 16, + + // Some resource has been exhausted, perhaps a per-user quota, or + // perhaps the entire file system is out of space. + // + // HTTP Mapping: 429 Too Many Requests + kErrorResourceExhausted = 8, + + // The operation was rejected because the system is not in a state + // required for the operation's execution. For example, the directory + // to be deleted is non-empty, an rmdir operation is applied to + // a non-directory, etc. + // + // Service implementors can use the following guidelines to decide + // between `FAILED_PRECONDITION`, `ABORTED`, and `UNAVAILABLE`: + // (a) Use `UNAVAILABLE` if the client can retry just the failing call. + // (b) Use `ABORTED` if the client should retry at a higher level + // (e.g., when a client-specified test-and-set fails, indicating the + // client should restart a read-modify-write sequence). + // (c) Use `FAILED_PRECONDITION` if the client should not retry until + // the system state has been explicitly fixed. E.g., if an "rmdir" + // fails because the directory is non-empty, `FAILED_PRECONDITION` + // should be returned since the client should not retry unless + // the files are deleted from the directory. + // + // HTTP Mapping: 400 Bad Request + kErrorFailedPrecondition = 9, + + // The operation was aborted, typically due to a concurrency issue such as + // a sequencer check failure or transaction abort. + // + // See the guidelines above for deciding between `FAILED_PRECONDITION`, + // `ABORTED`, and `UNAVAILABLE`. + // + // HTTP Mapping: 409 Conflict + kErrorAborted = 10, + + // The operation was attempted past the valid range. E.g., seeking or + // reading past end-of-file. + // + // Unlike `INVALID_ARGUMENT`, this error indicates a problem that may + // be fixed if the system state changes. For example, a 32-bit file + // system will generate `INVALID_ARGUMENT` if asked to read at an + // offset that is not in the range [0,2^32-1], but it will generate + // `OUT_OF_RANGE` if asked to read from an offset past the current + // file size. + // + // There is a fair bit of overlap between `FAILED_PRECONDITION` and + // `OUT_OF_RANGE`. We recommend using `OUT_OF_RANGE` (the more specific + // error) when it applies so that callers who are iterating through + // a space can easily look for an `OUT_OF_RANGE` error to detect when + // they are done. + // + // HTTP Mapping: 400 Bad Request + kErrorOutOfRange = 11, + + // The operation is not implemented or is not supported/enabled in this + // service. + // + // HTTP Mapping: 501 Not Implemented + kErrorUnimplemented = 12, + + // Internal errors. This means that some invariants expected by the + // underlying system have been broken. This error code is reserved + // for serious errors. + // + // HTTP Mapping: 500 Internal Server Error + kErrorInternal = 13, + + // The service is currently unavailable. This is most likely a + // transient condition, which can be corrected by retrying with + // a backoff. + // + // See the guidelines above for deciding between `FAILED_PRECONDITION`, + // `ABORTED`, and `UNAVAILABLE`. + // + // HTTP Mapping: 503 Service Unavailable + kErrorUnavailable = 14, + + // Unrecoverable data loss or corruption. + // + // HTTP Mapping: 500 Internal Server Error + kErrorDataLoss = 15, + +}; + +#ifdef INTERNAL_EXPERIMENTAL +/// @cond FIREBASE_APP_INTERNAL +namespace internal { + +// Get the human-readable error message corresponding to an error code. +// +// Returns a statically-allocated string describing the error code you pass in. +const char* GetErrorMessage(Error error); + +} // namespace internal +/// @endcond +#endif // INTERNAL_EXPERIMENTAL + +} // namespace functions +} // namespace firebase + +#endif // FIREBASE_FUNCTIONS_SRC_INCLUDE_FIREBASE_FUNCTIONS_COMMON_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/future.h b/packages/firebase_core/firebase_core/firebase_core/firebase/future.h new file mode 100644 index 000000000000..0d09fc079a32 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/future.h @@ -0,0 +1,533 @@ +/* + * Copyright 2016 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_APP_SRC_INCLUDE_FIREBASE_FUTURE_H_ +#define FIREBASE_APP_SRC_INCLUDE_FIREBASE_FUTURE_H_ + +#include +#include + +#include + +#include "firebase/internal/common.h" +#include "firebase/internal/mutex.h" + +#ifdef FIREBASE_USE_STD_FUNCTION +#include +#endif + +namespace firebase { + +// Predeclarations. +/// @cond FIREBASE_APP_INTERNAL +namespace detail { +class FutureApiInterface; +class CompletionCallbackHandle; +} // namespace detail +/// @endcond + +/// Asynchronous call status. +enum FutureStatus { + /// Results are ready. + kFutureStatusComplete, + + /// Result is still being processed. + kFutureStatusPending, + + /// No result is pending. + /// FutureBase::Release() or move operator was called. + kFutureStatusInvalid +}; + +/// Handle that the API uses to identify an asynchronous call. +/// The exact interpretation of the handle is up to the API. +typedef uintptr_t FutureHandleId; + +/// Class that provides more context to FutureHandleId, which allows the +/// underlying API to track handles, perform reference counting, etc. +class FutureHandle { + public: + /// @cond FIREBASE_APP_INTERNAL + FutureHandle(); + explicit FutureHandle(FutureHandleId id) : FutureHandle(id, nullptr) {} + FutureHandle(FutureHandleId id, detail::FutureApiInterface* api); + ~FutureHandle(); + + // Copy constructor and assignment operator. + FutureHandle(const FutureHandle& rhs); + FutureHandle& operator=(const FutureHandle& rhs); + +#if defined(FIREBASE_USE_MOVE_OPERATORS) + // Move constructor and assignment operator. + FutureHandle(FutureHandle&& rhs) noexcept; + FutureHandle& operator=(FutureHandle&& rhs) noexcept; +#endif // defined(FIREBASE_USE_MOVE_OPERATORS) + + // Comparison operators. + bool operator!=(const FutureHandle& rhs) const { return !(*this == rhs); } + bool operator==(const FutureHandle& rhs) const { + // Only compare IDs, since the API is irrelevant (comparison will only occur + // within the context of a single API anyway). + return id() == rhs.id(); + } + + FutureHandleId id() const { return id_; } + detail::FutureApiInterface* api() const { return api_; } + + // Detach from the FutureApi. This handle will no longer increment the + // Future's reference count. This is mainly used for testing, so that you can + // still look up the Future based on its handle's ID without affecting the + // reference count yourself. + void Detach(); + + // Called by CleanupNotifier when the API is being deleted. At this point we + // can ignore all of the reference counts since all Future data is about to be + // deleted anyway. + void Cleanup() { api_ = nullptr; } + + private: + FutureHandleId id_; + detail::FutureApiInterface* api_; + /// @endcond +}; + +/// @brief Type-independent return type of asynchronous calls. +/// +/// @see Future for code samples. +/// +/// @cond FIREBASE_APP_INTERNAL +/// Notes: +/// - Futures have pointers back to the API, but the API does not maintain +/// pointers to its Futures. Therefore, all Futures must be destroyed +/// *before* the API is destroyed. +/// - Futures can be moved or copied. Call results are reference counted, +/// and are destroyed when they are no longer referenced by any Futures. +/// - The actual `Status`, `Error`, and `Result` values are kept inside the +/// API. This makes synchronization and data management easier. +/// +/// WARNING: This class should remain POD (plain old data). It should not have +/// virtual methods. Nor should the derived Future class add any +/// data. Internally, we static_cast FutureBase to Future, +/// so the underlying data should remain the same. +/// @endcond +class FutureBase { + public: + /// Function pointer for a completion callback. When we call this, we will + /// send the completed future, along with the user data that you specified + /// when you set up the callback. + typedef void (*CompletionCallback)(const FutureBase& result_data, + void* user_data); + +#if defined(INTERNAL_EXPERIMENTAL) + /// Handle, representing a completion callback, that can be passed to + /// RemoveOnCompletion. + using CompletionCallbackHandle = detail::CompletionCallbackHandle; +#endif + + /// Construct an untyped future. + FutureBase(); + + /// @cond FIREBASE_APP_INTERNAL + + /// Construct an untyped future using the specified API and handle. + /// + /// @param api API class used to provide the future implementation. + /// @param handle Handle to the future. + FutureBase(detail::FutureApiInterface* api, const FutureHandle& handle); + + /// @endcond + + ~FutureBase(); + + /// Copy constructor and operator. + /// Increment the reference count when creating a copy of the future. + FutureBase(const FutureBase& rhs); + + /// Copy an untyped future. + FutureBase& operator=(const FutureBase& rhs); + +#if defined(FIREBASE_USE_MOVE_OPERATORS) + /// Move constructor and operator. + /// Move is more efficient than copy and delete because we don't touch the + /// reference counting in the API. + FutureBase(FutureBase&& rhs) noexcept; + + /// Copy an untyped future. + FutureBase& operator=(FutureBase&& rhs) noexcept; +#endif // defined(FIREBASE_USE_MOVE_OPERATORS) + + /// Explicitly release the internal resources for a future. + /// Future will become invalid. + void Release(); + + /// Completion status of the asynchronous call. + FutureStatus status() const; + + /// When status() is firebase::kFutureStatusComplete, returns the API-defined + /// error code. Otherwise, return value is undefined. + int error() const; + + /// When status() is firebase::kFutureStatusComplete, returns the API-defined + /// error message, as human-readable text, or an empty string if the API does + /// not provide a human readable description of the error. + /// + /// @note The returned pointer is only valid for the lifetime of the Future + /// or its copies. + const char* error_message() const; + + /// Result of the asynchronous call, or nullptr if the result is still + /// pending. Cast is required since GetFutureResult() returns void*. + const void* result_void() const; + +#if defined(INTERNAL_EXPERIMENTAL) + /// Special timeout value indicating an infinite timeout. + /// + /// Passing this value to FutureBase::Wait() or Future::Await() will cause + /// those methods to wait until the future is complete. + /// + /// @Warning It is inadvisable to use this from code that could be called + /// from an event loop. + static const int kWaitTimeoutInfinite; + + /// Block (i.e. suspend the current thread) until either the future is + /// completed or the specified timeout period (in milliseconds) has elapsed. + /// If `timeout_milliseconds` is `kWaitTimeoutInfinite`, then the timeout + /// period is treated as being infinite, i.e. this will block until the + /// future is completed. + /// + /// @return True if the future completed, or + /// false if the timeout period elapsed before the future completed. + bool Wait(int timeout_milliseconds) const; +#endif // defined(INTERNAL_EXPERIMENTAL) + + /// Register a single callback that will be called at most once, when the + /// future is completed. + /// + /// If you call any OnCompletion() method more than once on the same future, + /// only the most recent callback you registered with OnCompletion() will be + /// called. +#if defined(INTERNAL_EXPERIMENTAL) + /// However completions registered with AddCompletion() will still be + /// called even if there is a subsequent call to OnCompletion(). + /// + /// When the future completes, first the most recent callback registered with + /// OnCompletion(), if any, will be called; then all callbacks registered with + /// AddCompletion() will be called, in the order that they were registered. +#endif + /// + /// When your callback is called, the user_data that you supplied here will be + /// passed back as the second parameter. + /// + /// @param[in] callback Function pointer to your callback. + /// @param[in] user_data Optional user data. We will pass this back to your + /// callback. + void OnCompletion(CompletionCallback callback, void* user_data) const; + +#if defined(FIREBASE_USE_STD_FUNCTION) || defined(DOXYGEN) + /// Register a single callback that will be called at most once, when the + /// future is completed. + /// + /// If you call any OnCompletion() method more than once on the same future, + /// only the most recent callback you registered with OnCompletion() will be + /// called. +#if defined(INTERNAL_EXPERIMENTAL) + /// However completions registered with AddCompletion() will still be + /// called even if there is a subsequent call to OnCompletion(). + /// + /// When the future completes, first the most recent callback registered with + /// OnCompletion(), if any, will be called; then all callbacks registered with + /// AddCompletion() will be called, in the order that they were registered. +#endif + /// + /// @param[in] callback Function or lambda to call. + /// + /// @note This method is not available when using STLPort on Android, as + /// `std::function` is not supported on STLPort. + void OnCompletion(std::function callback) const; +#endif // defined(FIREBASE_USE_STD_FUNCTION) || defined(DOXYGEN) + +#if defined(INTERNAL_EXPERIMENTAL) + /// Like OnCompletion, but allows adding multiple callbacks. + /// + /// If you call AddCompletion() more than once, all of the completions that + /// you register will be called, when the future is completed. However, any + /// callbacks which were subsequently removed by calling RemoveOnCompletion + /// will not be called. + /// + /// When the future completes, first the most recent callback registered with + /// OnCompletion(), if any, will be called; then all callbacks registered with + /// AddCompletion() will be called, in the order that they were registered. + /// + /// @param[in] callback Function pointer to your callback. + /// @param[in] user_data Optional user data. We will pass this back to your + /// callback. + /// @return A handle that can be passed to RemoveOnCompletion. + CompletionCallbackHandle AddOnCompletion(CompletionCallback callback, + void* user_data) const; + +#if defined(FIREBASE_USE_STD_FUNCTION) || defined(DOXYGEN) + /// Like OnCompletion, but allows adding multiple callbacks. + /// + /// If you call AddCompletion() more than once, all of the completions that + /// you register will be called, when the future is completed. However, any + /// callbacks which were subsequently removed by calling RemoveOnCompletion + /// will not be called. + /// + /// When the future completes, first the most recent callback registered with + /// OnCompletion(), if any, will be called; then all callbacks registered with + /// AddCompletion() will be called, in the order that they were registered. + /// + /// @param[in] callback Function or lambda to call. + /// @return A handle that can be passed to RemoveOnCompletion. + /// + /// @note This method is not available when using STLPort on Android, as + /// `std::function` is not supported on STLPort. + CompletionCallbackHandle AddOnCompletion( + std::function callback) const; + +#endif // defined(FIREBASE_USE_STD_FUNCTION) || defined(DOXYGEN) + + /// Unregisters a callback that was previously registered with + /// AddOnCompletion. + /// + /// @param[in] completion_handle The return value of a previous call to + /// AddOnCompletion. + void RemoveOnCompletion(CompletionCallbackHandle completion_handle) const; +#endif // defined(INTERNAL_EXPERIMENTAL) + + /// Returns true if the two Futures reference the same result. + bool operator==(const FutureBase& rhs) const { + MutexLock lock(mutex_); + return api_ == rhs.api_ && handle_ == rhs.handle_; + } + + /// Returns true if the two Futures reference different results. + bool operator!=(const FutureBase& rhs) const { return !operator==(rhs); } + +#if defined(INTERNAL_EXPERIMENTAL) + /// Returns the API-specific handle. Should only be called by the API. + FutureHandle GetHandle() const { + MutexLock lock(mutex_); + return handle_; + } +#endif // defined(INTERNAL_EXPERIMENTAL) + + protected: + /// @cond FIREBASE_APP_INTERNAL + + mutable Mutex mutex_; + + /// Backpointer to the issuing API class. + /// Set to nullptr when Future is invalidated. + detail::FutureApiInterface* api_; + + /// API-specified handle type. + FutureHandle handle_; + + /// @endcond +}; + +/// @brief Type-specific version of FutureBase. +/// +/// The Firebase C++ SDK uses this class to return results from asynchronous +/// operations. All Firebase C++ functions and method calls that operate +/// asynchronously return a Future, and provide a "LastResult" function to +/// retrieve the most recent Future result. +/// +/// @code +/// // You can retrieve the Future from the function call directly, like this: +/// Future< SampleResultType > future = firebase::SampleAsyncOperation(); +/// +/// // Or you can retrieve it later, like this: +/// firebase::SampleAsyncOperation(); +/// // [...] +/// Future< SampleResultType > future = +/// firebase::SampleAsyncOperationLastResult(); +/// @endcode +/// +/// When you have a Future from an asynchronous operation, it will eventually +/// complete. Once it is complete, you can check for errors (a nonzero error() +/// means an error occurred) and get the result data if no error occurred by +/// calling result(). +/// +/// There are two ways to find out that a Future has completed. You can poll +/// its status(), or set an OnCompletion() callback: +/// +/// @code +/// // Check whether the status is kFutureStatusComplete. +/// if (future.status() == firebase::kFutureStatusComplete) { +/// if (future.error() == 0) { +/// DoSomethingWithResultData(future.result()); +/// } +/// else { +/// LogMessage("Error %d: %s", future.error(), future.error_message()); +/// } +/// } +/// +/// // Or, set an OnCompletion callback, which accepts a C++11 lambda or +/// // function pointer. You can pass your own user data to the callback. In +/// // most cases, the callback will be running in a different thread, so take +/// // care to make sure your code is thread-safe. +/// future.OnCompletion([](const Future< SampleResultType >& completed_future, +/// void* user_data) { +/// // We are probably in a different thread right now. +/// if (completed_future.error() == 0) { +/// DoSomethingWithResultData(completed_future.result()); +/// } +/// else { +/// LogMessage("Error %d: %s", +/// completed_future.error(), +/// completed_future.error_message()); +/// } +/// }, user_data); +/// @endcode +/// +/// @tparam ResultType The type of this Future's result. +// +// WARNING: This class should not have virtual methods or data members. +// See the warning in FutureBase for further details. +template +class Future : public FutureBase { + public: + /// Function pointer for a completion callback. When we call this, we will + /// send the completed future, along with the user data that you specified + /// when you set up the callback. + typedef void (*TypedCompletionCallback)(const Future& result_data, + void* user_data); + + /// Construct a future. + Future() {} + + /// @cond FIREBASE_APP_INTERNAL + + /// Construct a future using the specified API and handle. + /// + /// @param api API class used to provide the future implementation. + /// @param handle Handle to the future. + Future(detail::FutureApiInterface* api, const FutureHandle& handle) + : FutureBase(api, handle) {} + + /// @endcond + + /// Result of the asynchronous call, or nullptr if the result is still + /// pending. Allows the API to provide a type-specific interface. + /// + const ResultType* result() const { + return static_cast(result_void()); + } + +#if defined(INTERNAL_EXPERIMENTAL) + /// Waits (blocks) until either the future is completed, or the specified + /// timeout period (in milliseconds) has elapsed, then returns the result of + /// the asynchronous call. + /// + /// This is a convenience method that calls Wait() and then returns result(). + /// + /// If `timeout_milliseconds` is `kWaitTimeoutInfinite`, then the timeout + /// period is treated as being infinite, i.e. this will block until the + /// future is completed. + const ResultType* Await(int timeout_milliseconds) const { + Wait(timeout_milliseconds); + return result(); + } +#endif // defined(INTERNAL_EXPERIMENTAL) + + /// Register a single callback that will be called at most once, when the + /// future is completed. + /// + /// If you call any OnCompletion() method more than once on the same future, + /// only the most recent callback you registered will be called. + /// + /// When your callback is called, the user_data that you supplied here will be + /// passed back as the second parameter. + /// + /// @param[in] callback Function pointer to your callback. + /// @param[in] user_data Optional user data. We will pass this back to your + /// callback. + /// + /// @note This is the same callback as FutureBase::OnCompletion(), so you + /// can't expect to set both and have both run; again, only the most recently + /// registered one will run. + inline void OnCompletion(TypedCompletionCallback callback, + void* user_data) const; + +#if defined(FIREBASE_USE_STD_FUNCTION) || defined(DOXYGEN) + /// Register a single callback that will be called at most once, when the + /// future is completed. + /// + /// If you call any OnCompletion() method more than once on the same future, + /// only the most recent callback you registered will be called. + /// + /// @param[in] callback Function or lambda to call. + /// + /// @note This method is not available when using STLPort on Android, as + /// `std::function` is not supported on STLPort. + /// + /// @note This is the same callback as FutureBase::OnCompletion(), so you + /// can't expect to set both and have both run; again, only the most recently + /// registered one will run. + inline void OnCompletion( + std::function&)> callback) const; +#endif // defined(FIREBASE_USE_STD_FUNCTION) || defined(DOXYGEN) + +#if defined(INTERNAL_EXPERIMENTAL) + /// Like OnCompletion, but allows adding multiple callbacks. + /// + /// If you call AddCompletion() more than once, all of the completions that + /// you register will be called, when the future is completed. However, any + /// callbacks which were subsequently removed by calling RemoveOnCompletion + /// will not be called. + /// + /// When the future completes, first the most recent callback registered with + /// OnCompletion(), if any, will be called; then all callbacks registered with + /// AddCompletion() will be called, in the order that they were registered. + /// + /// @param[in] callback Function pointer to your callback. + /// @param[in] user_data Optional user data. We will pass this back to your + /// callback. + /// @return A handle that can be passed to RemoveOnCompletion. + inline CompletionCallbackHandle AddOnCompletion( + TypedCompletionCallback callback, void* user_data) const; + +#if defined(FIREBASE_USE_STD_FUNCTION) || defined(DOXYGEN) + /// Like OnCompletion, but allows adding multiple callbacks. + /// + /// If you call AddCompletion() more than once, all of the completions that + /// you register will be called, when the future is completed. However, any + /// callbacks which were subsequently removed by calling RemoveOnCompletion + /// will not be called. + /// + /// When the future completes, first the most recent callback registered with + /// OnCompletion(), if any, will be called; then all callbacks registered with + /// AddCompletion() will be called, in the order that they were registered. + /// + /// @param[in] callback Function or lambda to call. + /// @return A handle that can be passed to RemoveOnCompletion. + /// + /// @note This method is not available when using STLPort on Android, as + /// `std::function` is not supported on STLPort. + inline CompletionCallbackHandle AddOnCompletion( + std::function&)> callback) const; +#endif // defined(FIREBASE_USE_STD_FUNCTION) || defined(DOXYGEN) +#endif // defined(INTERNAL_EXPERIMENTAL) +}; + +} // namespace firebase + +// Include the inline implementation. +#include "firebase/internal/future_impl.h" + +#endif // FIREBASE_APP_SRC_INCLUDE_FIREBASE_FUTURE_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/gma.h b/packages/firebase_core/firebase_core/firebase_core/firebase/gma.h new file mode 100644 index 000000000000..b7da2cf569b9 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/gma.h @@ -0,0 +1,207 @@ +/* + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_GMA_SRC_INCLUDE_FIREBASE_GMA_H_ +#define FIREBASE_GMA_SRC_INCLUDE_FIREBASE_GMA_H_ + +#include "firebase/internal/platform.h" + +#if FIREBASE_PLATFORM_ANDROID +#include +#endif // FIREBASE_PLATFORM_ANDROID + +#include + +#include "firebase/app.h" +#include "firebase/gma/ad_view.h" +#include "firebase/gma/interstitial_ad.h" +#include "firebase/gma/rewarded_ad.h" +#include "firebase/gma/types.h" +#include "firebase/internal/common.h" + +#if !defined(DOXYGEN) && !defined(SWIG) +FIREBASE_APP_REGISTER_CALLBACKS_REFERENCE(gma) +#endif // !defined(DOXYGEN) && !defined(SWIG) + +namespace firebase { +// In the GMA docs, link to firebase::Future in the Firebase C++ docs. +#if defined(DOXYGEN_ADMOB) +/// @brief The Google Mobile Ads C++ SDK uses this class to return results from +/// asynchronous operations. All C++ functions and method calls that operate +/// asynchronously return a %Future, and provide a "LastResult" +/// function to retrieve the most recent %Future result. +/// +/// The Google Mobile Ads C++ SDK uses this class from the Firebase C++ SDK to +/// return results from asynchronous operations. For more information, see the +/// Firebase +/// C++ SDK documentation. +template +class Future { + // Empty class (used for documentation only). +}; +#endif // defined(DOXYGEN_ADMOB) + +/// @brief API for Google Mobile Ads with Firebase. +/// +/// The GMA API allows you to load and display mobile ads using the Google +/// Mobile Ads SDK. Each ad format has its own header file. +namespace gma { + +/// Initializes Google Mobile Ads (GMA) via Firebase. +/// +/// @param[in] app The Firebase app for which to initialize mobile ads. +/// +/// @param[out] init_result_out Optional: If provided, write the basic init +/// result here. kInitResultSuccess if initialization succeeded, or +/// kInitResultFailedMissingDependency on Android if Google Play services is not +/// available on the current device and the Google Mobile Ads SDK requires +/// Google Play services (for example, when using 'play-services-ads-lite'). +/// Note that this does not include the adapter initialization status, which is +/// returned in the Future. +/// +/// @return If init_result_out is kInitResultSuccess, this Future will contain +/// the initialization status of each adapter once initialization is complete. +/// Otherwise, the returned Future will have kFutureStatusInvalid. +Future Initialize( + const ::firebase::App& app, InitResult* init_result_out = nullptr); + +#if FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) +/// Initializes Google Mobile Ads (GMA) without Firebase for Android. +/// +/// The arguments to @ref Initialize are platform-specific so the caller must do +/// something like this: +/// @code +/// #if defined(__ANDROID__) +/// firebase::gma::Initialize(jni_env, activity); +/// #else +/// firebase::gma::Initialize(); +/// #endif +/// @endcode +/// +/// @param[in] jni_env JNIEnv pointer. +/// @param[in] activity Activity used to start the application. +/// @param[out] init_result_out Optional: If provided, write the basic init +/// result here. kInitResultSuccess if initialization succeeded, or +/// kInitResultFailedMissingDependency on Android if Google Play services is not +/// available on the current device and the Google Mobile Ads SDK requires +/// Google Play services (for example, when using 'play-services-ads-lite'). +/// Note that this does not include the adapter initialization status, which is +/// returned in the Future. +/// +/// @return If init_result_out is kInitResultSuccess, this Future will contain +/// the initialization status of each adapter once initialization is complete. +/// Otherwise, the returned Future will have kFutureStatusInvalid. +Future Initialize( + JNIEnv* jni_env, jobject activity, InitResult* init_result_out = nullptr); + +#endif // defined(__ANDROID__) || defined(DOXYGEN) +#if !FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) +/// Initializes Google Mobile Ads (GMA) without Firebase for iOS. +/// +/// @param[out] init_result_out Optional: If provided, write the basic init +/// result here. kInitResultSuccess if initialization succeeded, or +/// kInitResultFailedMissingDependency on Android if Google Play services is not +/// available on the current device and the Google Mobile Ads SDK requires +/// Google Play services (for example, when using 'play-services-ads-lite'). +/// Note that this does not include the adapter initialization status, which is +/// returned in the Future. +/// +/// @return If init_result_out is kInitResultSuccess, this Future +/// will contain the initialization status of each adapter once initialization +/// is complete. Otherwise, the returned Future will have +/// kFutureStatusInvalid. +Future Initialize( + InitResult* init_result_out = nullptr); +#endif // !defined(__ANDROID__) || defined(DOXYGEN) + +/// Get the Future returned by a previous call to +/// @ref firebase::gma::Initialize(). +Future InitializeLastResult(); + +/// Get the current adapter initialization status. You can poll this method to +/// check which adapters have been initialized. +AdapterInitializationStatus GetInitializationStatus(); + +/// Disables automated SDK crash reporting on iOS. If not called, the SDK +/// records the original exception handler if available and registers a new +/// exception handler. The new exception handler only reports SDK related +/// exceptions and calls the recorded original exception handler. +/// +/// This method has no effect on Android. +void DisableSDKCrashReporting(); + +/// Disables mediation adapter initialization on iOS during initialization of +/// the GMA SDK. Calling this method may negatively impact your ad +/// performance and should only be called if you will not use GMA SDK +/// controlled mediation during this app session. This method must be called +/// before initializing the GMA SDK or loading ads and has no effect once the +/// SDK has been initialized. +/// +/// This method has no effect on Android. +void DisableMediationInitialization(); + +/// Sets the global @ref RequestConfiguration that will be used for +/// every @ref AdRequest during the app's session. +/// +/// @param[in] request_configuration The request configuration that should be +/// applied to all ad requests. +void SetRequestConfiguration(const RequestConfiguration& request_configuration); + +/// Gets the global RequestConfiguration. +/// +/// @return the currently active @ref RequestConfiguration that's being +/// used for every ad request. +/// @note: on iOS, the +/// @ref RequestConfiguration::tag_for_child_directed_treatment and +/// @ref RequestConfiguration::tag_for_under_age_of_consent fields will be set +/// to RequestConfiguration.kChildDirectedTreatmentUnspecified, and +/// RequestConfiguration.kUnderAgeOfConsentUnspecified, respectfully. +RequestConfiguration GetRequestConfiguration(); + +/// Opens the ad inspector UI. +/// +/// @param[in] parent The platform-specific UI element that will host the +/// ad inspector. For iOS this should be the window's +/// UIViewController. For Android this is the +/// Activity Context which the GMA SDK is running in. +/// @param[in] listener The listener will be invoked when the user closes +/// the ad inspector UI. @ref firebase::gma::Initialize(). must be called +/// prior to this function. +void OpenAdInspector(AdParent parent, AdInspectorClosedListener* listener); + +/// Controls whether the Google Mobile Ads SDK Same App Key is enabled. +/// +/// This function must be invoked after GMA has been initialized. The value set +/// persists across app sessions. The key is enabled by default. +/// +/// This operation is supported on iOS only. This is a no-op on Android +/// systems. +/// +/// @param[in] is_enabled whether the Google Mobile Ads SDK Same App Key is +/// enabled. +void SetIsSameAppKeyEnabled(bool is_enabled); + +/// @brief Terminate GMA. +/// +/// Frees resources associated with GMA that were allocated during +/// @ref firebase::gma::Initialize(). +void Terminate(); + +} // namespace gma +} // namespace firebase + +#endif // FIREBASE_GMA_SRC_INCLUDE_FIREBASE_GMA_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/gma/ad_view.h b/packages/firebase_core/firebase_core/firebase_core/firebase/gma/ad_view.h new file mode 100644 index 000000000000..16916a21665f --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/gma/ad_view.h @@ -0,0 +1,267 @@ +/* + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_GMA_SRC_INCLUDE_FIREBASE_GMA_AD_VIEW_H_ +#define FIREBASE_GMA_SRC_INCLUDE_FIREBASE_GMA_AD_VIEW_H_ + +#include "firebase/future.h" +#include "firebase/gma/types.h" +#include "firebase/internal/common.h" + +namespace firebase { +namespace gma { + +namespace internal { +// Forward declaration for platform-specific data, implemented in each library. +class AdViewInternal; +} // namespace internal + +class AdViewBoundingBoxListener; +struct BoundingBox; + +/// @brief Loads and displays Google Mobile Ads AdView ads. +/// +/// Each AdView object corresponds to a single GMA ad placement of a specified +/// size. There are methods to load an ad, move it, show it and hide it, and +/// retrieve the bounds of the ad onscreen. +/// +/// AdView objects provide information about their current state through +/// Futures. Methods like @ref Initialize, @ref LoadAd, and @ref Hide each have +/// a corresponding @ref Future from which the result of the last call can be +/// determined. The two variants of @ref SetPosition share a single result +/// @ref Future, since they're essentially the same action. +/// +/// For example, you could initialize, load, and show an AdView while +/// checking the result of the previous action at each step as follows: +/// +/// @code +/// namespace gma = ::firebase::gma; +/// gma::AdView* ad_view = new gma::AdView(); +/// ad_view->Initialize(ad_parent, "YOUR_AD_UNIT_ID", desired_ad_size) +/// @endcode +/// +/// Then, later: +/// +/// @code +/// if (ad_view->InitializeLastResult().status() == +/// ::firebase::kFutureStatusComplete && +/// ad_view->InitializeLastResult().error() == +/// firebase::gma::kAdErrorCodeNone) { +/// ad_view->LoadAd(your_ad_request); +/// } +/// @endcode +class AdView { + public: + /// The possible screen positions for a @ref AdView, configured via + /// @ref SetPosition. + enum Position { + /// The position isn't one of the predefined screen locations. + kPositionUndefined = -1, + /// Top of the screen, horizontally centered. + kPositionTop = 0, + /// Bottom of the screen, horizontally centered. + kPositionBottom, + /// Top-left corner of the screen. + kPositionTopLeft, + /// Top-right corner of the screen. + kPositionTopRight, + /// Bottom-left corner of the screen. + kPositionBottomLeft, + /// Bottom-right corner of the screen. + kPositionBottomRight, + }; + + /// Creates an uninitialized @ref AdView object. + /// @ref Initialize must be called before the object is used. + AdView(); + + ~AdView(); + + /// Initializes the @ref AdView object. + /// @param[in] parent The platform-specific UI element that will host the ad. + /// @param[in] ad_unit_id The ad unit ID to use when requesting ads. + /// @param[in] size The desired ad size for the ad. + Future Initialize(AdParent parent, const char* ad_unit_id, + const AdSize& size); + + /// Returns a @ref Future that has the status of the last call to + /// @ref Initialize. + Future InitializeLastResult() const; + + /// Begins an asynchronous request for an ad. If successful, the ad will + /// automatically be displayed in the AdView. + /// @param[in] request An AdRequest struct with information about the request + /// to be made (such as targeting info). + Future LoadAd(const AdRequest& request); + + /// Returns a @ref Future containing the status of the last call to + /// @ref LoadAd. + Future LoadAdLastResult() const; + + /// Retrieves the @ref AdView's current onscreen size and location. + /// + /// @return The current size and location. Values are in pixels, and location + /// coordinates originate from the top-left corner of the screen. + BoundingBox bounding_box() const; + + /// Sets an AdListener for this ad view. + /// + /// @param[in] listener An AdListener object which will be invoked + /// when lifecycle events occur on this AdView. + void SetAdListener(AdListener* listener); + + /// Sets a listener to be invoked when the Ad's bounding box + /// changes size or location. + /// + /// @param[in] listener A AdViewBoundingBoxListener object which will be + /// invoked when the ad changes size, shape, or position. + void SetBoundingBoxListener(AdViewBoundingBoxListener* listener); + + /// Sets a listener to be invoked when this ad is estimated to have earned + /// money. + /// + /// @param[in] listener A PaidEventListener object to be invoked when a + /// paid event occurs on the ad. + void SetPaidEventListener(PaidEventListener* listener); + + /// Moves the @ref AdView so that its top-left corner is located at + /// (x, y). Coordinates are in pixels from the top-left corner of the screen. + /// + /// When built for Android, the library will not display an ad on top of or + /// beneath an Activity's status bar. If a call to SetPostion + /// would result in an overlap, the @ref AdView is placed just below the + /// status bar, so no overlap occurs. + /// @param[in] x The desired horizontal coordinate. + /// @param[in] y The desired vertical coordinate. + /// + /// @return a @ref Future which will be completed when this move operation + /// completes. + Future SetPosition(int x, int y); + + /// Moves the @ref AdView so that it's located at the given predefined + /// position. + /// + /// @param[in] position The predefined position to which to move the + /// @ref AdView. + /// + /// @return a @ref Future which will be completed when this move operation + /// completes. + Future SetPosition(Position position); + + /// Returns a @ref Future containing the status of the last call to either + /// version of @ref SetPosition. + Future SetPositionLastResult() const; + + /// Hides the AdView. + Future Hide(); + + /// Returns a @ref Future containing the status of the last call to + /// @ref Hide. + Future HideLastResult() const; + + /// Shows the @ref AdView. + Future Show(); + + /// Returns a @ref Future containing the status of the last call to + /// @ref Show. + Future ShowLastResult() const; + + /// Pauses the @ref AdView. Should be called whenever the C++ engine + /// pauses or the application loses focus. + Future Pause(); + + /// Returns a @ref Future containing the status of the last call to + /// @ref Pause. + Future PauseLastResult() const; + + /// Resumes the @ref AdView after pausing. + Future Resume(); + + /// Returns a @ref Future containing the status of the last call to + /// @ref Resume. + Future ResumeLastResult() const; + + /// Cleans up and deallocates any resources used by the @ref AdView. + /// You must call this asynchronous operation before this object's destructor + /// is invoked or risk leaking device resources. + Future Destroy(); + + /// Returns a @ref Future containing the status of the last call to + /// @ref Destroy. + Future DestroyLastResult() const; + + /// Returns the AdSize of the AdView. + /// + /// @return An @ref AdSize object representing the size of the ad. If this + /// view has not been initialized then the AdSize will be 0,0. + AdSize ad_size() const; + + protected: + /// Pointer to a listener for AdListener events. + AdListener* ad_listener_; + + /// Pointer to a listener for BoundingBox events. + AdViewBoundingBoxListener* ad_view_bounding_box_listener_; + + /// Pointer to a listener for paid events. + PaidEventListener* paid_event_listener_; + + private: + // An internal, platform-specific implementation object that this class uses + // to interact with the Google Mobile Ads SDKs for iOS and Android. + internal::AdViewInternal* internal_; +}; + +/// A listener class that developers can extend and pass to an @ref AdView +/// object's @ref AdView::SetBoundingBoxListener method to be notified of +/// changes to the size of the Ad's bounding box. +class AdViewBoundingBoxListener { + public: + virtual ~AdViewBoundingBoxListener(); + + /// This method is called when the @ref AdView object's bounding box + /// changes. + /// + /// @param[in] ad_view The view whose bounding box changed. + /// @param[in] box The new bounding box. + virtual void OnBoundingBoxChanged(AdView* ad_view, BoundingBox box) = 0; +}; + +/// @brief The screen location and dimensions of an AdView once it has been +/// initialized. +struct BoundingBox { + /// Default constructor which initializes all member variables to 0. + BoundingBox() + : height(0), width(0), x(0), y(0), position(AdView::kPositionUndefined) {} + + /// Height of the ad in pixels. + int height; + /// Width of the ad in pixels. + int width; + /// Horizontal position of the ad in pixels from the left. + int x; + /// Vertical position of the ad in pixels from the top. + int y; + + /// The position of the AdView if one has been set as the target position, or + /// kPositionUndefined otherwise. + AdView::Position position; +}; + +} // namespace gma +} // namespace firebase + +#endif // FIREBASE_GMA_SRC_INCLUDE_FIREBASE_GMA_AD_VIEW_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/gma/interstitial_ad.h b/packages/firebase_core/firebase_core/firebase_core/firebase/gma/interstitial_ad.h new file mode 100644 index 000000000000..4680537178c8 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/gma/interstitial_ad.h @@ -0,0 +1,128 @@ +/* + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_GMA_SRC_INCLUDE_FIREBASE_GMA_INTERSTITIAL_AD_H_ +#define FIREBASE_GMA_SRC_INCLUDE_FIREBASE_GMA_INTERSTITIAL_AD_H_ + +#include "firebase/future.h" +#include "firebase/gma/types.h" +#include "firebase/internal/common.h" + +namespace firebase { +namespace gma { + +namespace internal { +// Forward declaration for platform-specific data, implemented in each library. +class InterstitialAdInternal; +} // namespace internal + +/// @brief Loads and displays Google Mobile Ads interstitial ads. +/// +/// @ref InterstitialAd is a single-use object that can load and show a +/// single GMA interstitial ad. +/// +/// InterstitialAd objects provide information about their current state +/// through Futures. @ref Initialize, @ref LoadAd, and @ref Show each have a +/// corresponding @ref Future from which you can determine result of the +/// previous call. +/// +/// Here's how one might initialize, load, and show an interstitial ad while +/// checking against the result of the previous action at each step: +/// +/// @code +/// namespace gma = ::firebase::gma; +/// gma::InterstitialAd* interstitial = new gma::InterstitialAd(); +/// interstitial->Initialize(ad_parent); +/// @endcode +/// +/// Then, later: +/// +/// @code +/// if (interstitial->InitializeLastResult().status() == +/// ::firebase::kFutureStatusComplete && +/// interstitial->InitializeLastResult().error() == +/// firebase::gma::kAdErrorCodeNone) { +/// interstitial->LoadAd( "YOUR_AD_UNIT_ID", my_ad_request); +/// } +/// @endcode +/// +/// And after that: +/// +/// @code +/// if (interstitial->LoadAdLastResult().status() == +/// ::firebase::kFutureStatusComplete && +/// interstitial->LoadAdLastResult().error() == +/// firebase::gma::kAdErrorCodeNone)) { +/// interstitial->Show(); +/// } +/// @endcode +class InterstitialAd { + public: + /// Creates an uninitialized @ref InterstitialAd object. + /// @ref Initialize must be called before the object is used. + InterstitialAd(); + + ~InterstitialAd(); + + /// Initialize the @ref InterstitialAd object. + /// @param[in] parent The platform-specific UI element that will host the ad. + Future Initialize(AdParent parent); + + /// Returns a @ref Future containing the status of the last call to + /// @ref Initialize. + Future InitializeLastResult() const; + + /// Begins an asynchronous request for an ad. + /// + /// @param[in] ad_unit_id The ad unit ID to use in loading the ad. + /// @param[in] request An AdRequest struct with information about the request + /// to be made (such as targeting info). + Future LoadAd(const char* ad_unit_id, const AdRequest& request); + + /// Returns a @ref Future containing the status of the last call to + /// @ref LoadAd. + Future LoadAdLastResult() const; + + /// Shows the @ref InterstitialAd. This should not be called unless an ad has + /// already been loaded. + Future Show(); + + /// Returns a @ref Future containing the status of the last call to + /// @ref Show. + Future ShowLastResult() const; + + /// Sets the @ref FullScreenContentListener for this @ref InterstitialAd. + /// + /// @param[in] listener A valid @ref FullScreenContentListener to receive + /// callbacks. + void SetFullScreenContentListener(FullScreenContentListener* listener); + + /// Registers a callback to be invoked when this ad is estimated to have + /// earned money + /// + /// @param[in] listener A valid @ref PaidEventListener to receive callbacks. + void SetPaidEventListener(PaidEventListener* listener); + + private: + // An internal, platform-specific implementation object that this class uses + // to interact with the Google Mobile Ads SDKs for iOS and Android. + internal::InterstitialAdInternal* internal_; +}; + +} // namespace gma +} // namespace firebase + +#endif // FIREBASE_GMA_SRC_INCLUDE_FIREBASE_GMA_INTERSTITIAL_AD_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/gma/rewarded_ad.h b/packages/firebase_core/firebase_core/firebase_core/firebase/gma/rewarded_ad.h new file mode 100644 index 000000000000..a3c5431486d4 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/gma/rewarded_ad.h @@ -0,0 +1,152 @@ +/* + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_GMA_SRC_INCLUDE_FIREBASE_GMA_REWARDED_AD_H_ +#define FIREBASE_GMA_SRC_INCLUDE_FIREBASE_GMA_REWARDED_AD_H_ + +#include + +#include "firebase/future.h" +#include "firebase/gma/types.h" +#include "firebase/internal/common.h" + +namespace firebase { +namespace gma { + +namespace internal { +// Forward declaration for platform-specific data, implemented in each library. +class RewardedAdInternal; +} // namespace internal + +/// @brief Loads and displays Google Mobile Ads rewarded ads. +/// +/// @ref RewardedAd is a single-use object that can load and show a +/// single GMA rewarded ad. +/// +/// RewardedAd objects provide information about their current state +/// through Futures. @ref Initialize, @ref LoadAd, and @ref Show each have a +/// corresponding @ref Future from which you can determine result of the +/// previous call. +/// +/// Here's how one might initialize, load, and show an rewarded ad while +/// checking against the result of the previous action at each step: +/// +/// @code +/// namespace gma = ::firebase::gma; +/// gma::RewardedAd* rewarded = new gma::RewardedAd(); +/// rewarded->Initialize(ad_parent); +/// @endcode +/// +/// Then, later: +/// +/// @code +/// if (rewarded->InitializeLastResult().status() == +/// ::firebase::kFutureStatusComplete && +/// rewarded->InitializeLastResult().error() == +/// firebase::gma::kAdErrorCodeNone) { +/// rewarded->LoadAd( "YOUR_AD_UNIT_ID", my_ad_request); +/// } +/// @endcode +/// +/// And after that: +/// +/// @code +/// if (rewarded->LoadAdLastResult().status() == +/// ::firebase::kFutureStatusComplete && +/// rewarded->LoadAdLastResult().error() == +/// firebase::gma::kAdErrorCodeNone)) { +/// rewarded->Show(&my_user_earned_reward_listener); +/// } +/// @endcode +class RewardedAd { + public: + /// Options for RewardedAd server-side verification callbacks. Set options on + /// a RewardedAd object using the @ref SetServerSideVerificationOptions + /// method. + struct ServerSideVerificationOptions { + /// Custom data to be included in server-side verification callbacks. + std::string custom_data; + + /// User id to be used in server-to-server reward callbacks. + std::string user_id; + }; + + /// Creates an uninitialized @ref RewardedAd object. + /// @ref Initialize must be called before the object is used. + RewardedAd(); + + ~RewardedAd(); + + /// Initialize the @ref RewardedAd object. + /// @param[in] parent The platform-specific UI element that will host the ad. + Future Initialize(AdParent parent); + + /// Returns a @ref Future containing the status of the last call to + /// @ref Initialize. + Future InitializeLastResult() const; + + /// Begins an asynchronous request for an ad. + /// + /// @param[in] ad_unit_id The ad unit ID to use in loading the ad. + /// @param[in] request An AdRequest struct with information about the request + /// to be made (such as targeting info). + Future LoadAd(const char* ad_unit_id, const AdRequest& request); + + /// Returns a @ref Future containing the status of the last call to + /// @ref LoadAd. + Future LoadAdLastResult() const; + + /// Shows the @ref RewardedAd. This should not be called unless an ad has + /// already been loaded. + /// + /// @param[in] listener The @ref UserEarnedRewardListener to be notified when + /// user earns a reward. + Future Show(UserEarnedRewardListener* listener); + + /// Returns a @ref Future containing the status of the last call to + /// @ref Show. + Future ShowLastResult() const; + + /// Sets the @ref FullScreenContentListener for this @ref RewardedAd. + /// + /// @param[in] listener A valid @ref FullScreenContentListener to receive + /// callbacks. + void SetFullScreenContentListener(FullScreenContentListener* listener); + + /// Registers a callback to be invoked when this ad is estimated to have + /// earned money + /// + /// @param[in] listener A valid @ref PaidEventListener to receive callbacks. + void SetPaidEventListener(PaidEventListener* listener); + + /// Sets the server side verification options. + /// + /// @param[in] serverSideVerificationOptions A @ref + /// ServerSideVerificationOptions object containing custom data and a user + /// Id. + void SetServerSideVerificationOptions( + const ServerSideVerificationOptions& serverSideVerificationOptions); + + private: + // An internal, platform-specific implementation object that this class uses + // to interact with the Google Mobile Ads SDKs for iOS and Android. + internal::RewardedAdInternal* internal_; +}; + +} // namespace gma +} // namespace firebase + +#endif // FIREBASE_GMA_SRC_INCLUDE_FIREBASE_GMA_REWARDED_AD_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/gma/types.h b/packages/firebase_core/firebase_core/firebase_core/firebase/gma/types.h new file mode 100644 index 000000000000..292ee4138a68 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/gma/types.h @@ -0,0 +1,939 @@ +/* + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_GMA_SRC_INCLUDE_FIREBASE_GMA_TYPES_H_ +#define FIREBASE_GMA_SRC_INCLUDE_FIREBASE_GMA_TYPES_H_ + +#include +#include +#include +#include +#include + +#include "firebase/future.h" +#include "firebase/internal/platform.h" + +#if FIREBASE_PLATFORM_ANDROID +#include +#elif FIREBASE_PLATFORM_IOS || FIREBASE_PLATFORM_TVOS +extern "C" { +#include +} // extern "C" +#endif // FIREBASE_PLATFORM_ANDROID, FIREBASE_PLATFORM_IOS, + // FIREBASE_PLATFORM_TVOS + +namespace firebase { +namespace gma { + +struct AdErrorInternal; +struct AdapterResponseInfoInternal; +struct BoundingBox; +struct ResponseInfoInternal; + +class AdapterResponseInfo; +class AdViewBoundingBoxListener; +class GmaInternal; +class AdView; +class InterstitialAd; +class PaidEventListener; +class ResponseInfo; + +namespace internal { +class AdViewInternal; +} + +/// This is a platform specific datatype that is required to create +/// a Google Mobile Ads ad. +/// +/// The following defines the datatype on each platform: +///
    +///
  • Android: A `jobject` which references an Android Activity.
  • +///
  • iOS: An `id` which references an iOS UIView.
  • +///
+#if FIREBASE_PLATFORM_ANDROID +/// An Android Activity from Java. +typedef jobject AdParent; +#elif FIREBASE_PLATFORM_IOS || FIREBASE_PLATFORM_TVOS +/// A pointer to an iOS UIView. +typedef id AdParent; +#else +/// A void pointer for stub classes. +typedef void* AdParent; +#endif // FIREBASE_PLATFORM_ANDROID, FIREBASE_PLATFORM_IOS, + // FIREBASE_PLATFORM_TVOS + +/// Error codes returned by Future::error(). +enum AdErrorCode { + /// Call completed successfully. + kAdErrorCodeNone, + /// The ad has not been fully initialized. + kAdErrorCodeUninitialized, + /// The ad is already initialized (repeat call). + kAdErrorCodeAlreadyInitialized, + /// A call has failed because an ad is currently loading. + kAdErrorCodeLoadInProgress, + /// A call to load an ad has failed due to an internal SDK error. + kAdErrorCodeInternalError, + /// A call to load an ad has failed due to an invalid request. + kAdErrorCodeInvalidRequest, + /// A call to load an ad has failed due to a network error. + kAdErrorCodeNetworkError, + /// A call to load an ad has failed because no ad was available to serve. + kAdErrorCodeNoFill, + /// An attempt has been made to show an ad on an Android Activity that has + /// no window token (such as one that's not done initializing). + kAdErrorCodeNoWindowToken, + /// An attempt to load an Ad Network extras class for an ad request has + /// failed. + kAdErrorCodeAdNetworkClassLoadError, + /// The ad server experienced a failure processing the request. + kAdErrorCodeServerError, + /// The current device’s OS is below the minimum required version. + kAdErrorCodeOSVersionTooLow, + /// The request was unable to be loaded before being timed out. + kAdErrorCodeTimeout, + /// Will not send request because the interstitial object has already been + /// used. + kAdErrorCodeInterstitialAlreadyUsed, + /// The mediation response was invalid. + kAdErrorCodeMediationDataError, + /// Error finding or creating a mediation ad network adapter. + kAdErrorCodeMediationAdapterError, + /// Attempting to pass an invalid ad size to an adapter. + kAdErrorCodeMediationInvalidAdSize, + /// Invalid argument error. + kAdErrorCodeInvalidArgument, + /// Received invalid response. + kAdErrorCodeReceivedInvalidResponse, + /// Will not send a request because the rewarded ad object has already been + /// used. + kAdErrorCodeRewardedAdAlreadyUsed, + /// A mediation ad network adapter received an ad request, but did not fill. + /// The adapter’s error is included as an underlyingError. + kAdErrorCodeMediationNoFill, + /// Will not send request because the ad object has already been used. + kAdErrorCodeAdAlreadyUsed, + /// Will not send request because the application identifier is missing. + kAdErrorCodeApplicationIdentifierMissing, + /// Android Ad String is invalid. + kAdErrorCodeInvalidAdString, + /// The ad can not be shown when app is not in the foreground. + kAdErrorCodeAppNotInForeground, + /// A mediation adapter failed to show the ad. + kAdErrorCodeMediationShowError, + /// The ad is not ready to be shown. + kAdErrorCodeAdNotReady, + /// Ad is too large for the scene. + kAdErrorCodeAdTooLarge, + /// Attempted to present ad from a non-main thread. This is an internal + /// error which should be reported to support if encountered. + kAdErrorCodeNotMainThread, + /// A debug operation failed because the device is not in test mode. + kAdErrorCodeNotInTestMode, + /// An attempt to load the Ad Inspector failed. + kAdErrorCodeInspectorFailedToLoad, + /// The request to show the Ad Inspector failed because it's already open. + kAdErrorCodeInsepctorAlreadyOpen, + /// Fallback error for any unidentified cases. + kAdErrorCodeUnknown, +}; + +/// A listener for receiving notifications during the lifecycle of a BannerAd. +class AdListener { + public: + virtual ~AdListener(); + + /// Called when a click is recorded for an ad. + virtual void OnAdClicked() {} + + /// Called when the user is about to return to the application after clicking + /// on an ad. + virtual void OnAdClosed() {} + + /// Called when an impression is recorded for an ad. + virtual void OnAdImpression() {} + + /// Called when an ad opens an overlay that covers the screen. + virtual void OnAdOpened() {} +}; + +/// Information about why an ad operation failed. +class AdError { + public: + /// Default Constructor. + AdError(); + + /// Copy Constructor. + AdError(const AdError& ad_error); + + /// Destructor. + virtual ~AdError(); + + /// Assignment operator. + AdError& operator=(const AdError& obj); + + /// Retrieves an AdError which represents the cause of this error. + /// + /// @return a pointer to an adError which represents the cause of this + /// AdError. If there was no cause then nullptr is returned. + std::unique_ptr GetCause() const; + + /// Gets the error's code. + AdErrorCode code() const; + + /// Gets the domain of the error. + const std::string& domain() const; + + /// Gets the message describing the error. + const std::string& message() const; + + /// Gets the ResponseInfo if an error occurred during a loadAd operation. + /// The ResponseInfo will have empty fields if this AdError does not + /// represent an error stemming from a load ad operation. + const ResponseInfo& response_info() const; + + /// Returns a log friendly string version of this object. + virtual const std::string& ToString() const; + + /// A domain string which represents an undefined error domain. + /// + /// The GMA SDK returns this domain for domain() method invocations when + /// converting error information from legacy mediation adapter callbacks. + static const char* const kUndefinedDomain; + + private: + friend class AdapterResponseInfo; + friend class GmaInternal; + friend class AdView; + friend class InterstitialAd; + + /// Constructor used when building results in Ad event callbacks. + explicit AdError(const AdErrorInternal& ad_error_internal); + + // Collection of response from adapters if this Result is due to a loadAd + // operation. + ResponseInfo* response_info_; + + // An internal, platform-specific implementation object that this class uses + // to interact with the Google Mobile Ads SDKs for iOS and Android. + AdErrorInternal* internal_; +}; + +/// Information about an ad response. +class ResponseInfo { + public: + /// Constructor creates an uninitialized ResponseInfo. + ResponseInfo(); + + /// Gets the AdapterResponseInfo objects for the ad response. + /// + /// @return a vector of AdapterResponseInfo objects containing metadata for + /// each adapter included in the ad response. + const std::vector& adapter_responses() const { + return adapter_responses_; + } + + /// A class name that identifies the ad network that returned the ad. + /// Returns an empty string if the ad failed to load. + const std::string& mediation_adapter_class_name() const { + return mediation_adapter_class_name_; + } + + /// Gets the response ID string for the loaded ad. Returns an empty + /// string if the ad fails to load. + const std::string& response_id() const { return response_id_; } + + /// Gets a log friendly string version of this object. + const std::string& ToString() const { return to_string_; } + + private: + friend class AdError; + friend class GmaInternal; + + explicit ResponseInfo(const ResponseInfoInternal& internal); + + std::vector adapter_responses_; + std::string mediation_adapter_class_name_; + std::string response_id_; + std::string to_string_; +}; + +/// Information about the result of an ad operation. +class AdResult { + public: + /// Default Constructor. + AdResult(); + + /// Constructor. + explicit AdResult(const AdError& ad_error); + + /// Destructor. + virtual ~AdResult(); + + /// Returns true if the operation was successful. + bool is_successful() const; + + /// An object representing an error which occurred during an ad operation. + /// If the @ref AdResult::is_successful() returned true, then the + /// @ref AdError object returned via this method will contain no contextual + /// information. + const AdError& ad_error() const; + + /// For debugging and logging purposes, successfully loaded ads provide a + /// ResponseInfo object which contains information about the adapter which + /// loaded the ad. If the ad failed to load then the object returned from + /// this method will have default values. Information about the error + /// should be retrieved via @ref AdResult::ad_error() instead. + const ResponseInfo& response_info() const; + + private: + friend class GmaInternal; + + /// Constructor invoked upon successful ad load. This contains response + /// information from the adapter which loaded the ad. + explicit AdResult(const ResponseInfo& response_info); + + /// Denotes if the @ref AdResult represents a success or an error. + bool is_successful_; + + /// Information about the error. Will be a default-constructed @ref AdError + /// if this result represents a success. + AdError ad_error_; + + /// Information from the adapter which loaded the ad. + ResponseInfo response_info_; +}; + +/// A snapshot of a mediation adapter's initialization status. +class AdapterStatus { + public: + AdapterStatus() : is_initialized_(false), latency_(0) {} + + /// Detailed description of the status. + /// + /// This method should only be used for informational purposes, such as + /// logging. Use @ref is_initialized to make logical decisions regarding an + /// adapter's status. + const std::string& description() const { return description_; } + + /// Returns the adapter's initialization state. + bool is_initialized() const { return is_initialized_; } + + /// The adapter's initialization latency in milliseconds. + /// 0 if initialization has not yet ended. + int latency() const { return latency_; } + +#if !defined(DOXYGEN) + // Equality operator for testing. + bool operator==(const AdapterStatus& rhs) const { + return (description() == rhs.description() && + is_initialized() == rhs.is_initialized() && + latency() == rhs.latency()); + } +#endif // !defined(DOXYGEN) + + private: + friend class GmaInternal; + std::string description_; + bool is_initialized_; + int latency_; +}; + +/// An immutable snapshot of the GMA SDK’s initialization status, categorized +/// by mediation adapter. +class AdapterInitializationStatus { + public: + /// Initialization status of each known ad network, keyed by its adapter's + /// class name. + std::map GetAdapterStatusMap() const { + return adapter_status_map_; + } +#if !defined(DOXYGEN) + // Equality operator for testing. + bool operator==(const AdapterInitializationStatus& rhs) const { + return (GetAdapterStatusMap() == rhs.GetAdapterStatusMap()); + } +#endif // !defined(DOXYGEN) + + private: + friend class GmaInternal; + std::map adapter_status_map_; +}; + +/// Listener to be invoked when the Ad Inspector has been closed. +class AdInspectorClosedListener { + public: + virtual ~AdInspectorClosedListener(); + + /// Called when the user clicked the ad. The AdResult contains the status of + /// the operation, including details of the error if one occurred. + virtual void OnAdInspectorClosed(const AdResult& ad_result) = 0; +}; + +/// @brief Response information for an individual ad network contained within +/// a @ref ResponseInfo object. +class AdapterResponseInfo { + public: + /// Destructor + ~AdapterResponseInfo(); + + /// @brief Information about the result including whether an error + /// occurred, and any contextual information about that error. + /// + /// @return the error that occurred while rendering the ad. If no error + /// occurred then the AdResult's successful method will return true. + AdResult ad_result() const { return ad_result_; } + + /// Returns a string representation of a class name that identifies the ad + /// network adapter. + const std::string& adapter_class_name() const { return adapter_class_name_; } + + /// Amount of time the ad network spent loading an ad. + /// + /// @return number of milliseconds the network spent loading an ad. This value + /// is 0 if the network did not make a load attempt. + int64_t latency_in_millis() const { return latency_; } + + /// A log friendly string version of this object. + const std::string& ToString() const { return to_string_; } + + private: + friend class ResponseInfo; + + /// Constructs an Adapter Response Info Object. + explicit AdapterResponseInfo(const AdapterResponseInfoInternal& internal); + + AdResult ad_result_; + std::string adapter_class_name_; + int64_t latency_; + std::string to_string_; +}; + +/// The size of a banner ad. +class AdSize { + public: + /// Denotes the orientation of the AdSize. + enum Orientation { + /// AdSize should reflect the current orientation of the device. + kOrientationCurrent = 0, + + /// AdSize will be adaptively formatted in Landscape mode. + kOrientationLandscape, + + /// AdSize will be adaptively formatted in Portrait mode. + kOrientationPortrait + }; + + /// Denotes the type size object that the @ref AdSize represents. + enum Type { + /// The standard AdSize type of a set height and width. + kTypeStandard = 0, + + /// An adaptive size anchored to a portion of the screen. + kTypeAnchoredAdaptive, + + /// An adaptive size intended to be embedded in scrollable content. + kTypeInlineAdaptive, + }; + + /// Mobile Marketing Association (MMA) banner ad size (320x50 + /// density-independent pixels). + static const AdSize kBanner; + + /// Interactive Advertising Bureau (IAB) full banner ad size + /// (468x60 density-independent pixels). + static const AdSize kFullBanner; + + /// Taller version of kBanner. Typically 320x100. + static const AdSize kLargeBanner; + + /// Interactive Advertising Bureau (IAB) leaderboard ad size + /// (728x90 density-independent pixels). + static const AdSize kLeaderboard; + + /// Interactive Advertising Bureau (IAB) medium rectangle ad size + /// (300x250 density-independent pixels). + static const AdSize kMediumRectangle; + + /// Creates a new AdSize. + /// + /// @param[in] width The width of the ad in density-independent pixels. + /// @param[in] height The height of the ad in density-independent pixels. + AdSize(uint32_t width, uint32_t height); + + /// @brief Creates an AdSize with the given width and a Google-optimized + /// height to create a banner ad in landscape mode. + /// + /// @param[in] width The width of the ad in density-independent pixels. + /// + /// @return an AdSize with the given width and a Google-optimized height + /// to create a banner ad. The size returned will have an aspect ratio + /// similar to BANNER, suitable for anchoring near the top or bottom of + /// your app. The exact size of the ad returned can be retrieved by calling + /// @ref AdView::ad_size once the ad has been loaded. + static AdSize GetLandscapeAnchoredAdaptiveBannerAdSize(uint32_t width); + + /// @brief Creates an AdSize with the given width and a Google-optimized + /// height to create a banner ad in portrait mode. + /// + /// @param[in] width The width of the ad in density-independent pixels. + /// + /// @return an AdSize with the given width and a Google-optimized height + /// to create a banner ad. The size returned will have an aspect ratio + /// similar to BANNER, suitable for anchoring near the top or bottom + /// of your app. The exact size of the ad returned can be retrieved by + /// calling @ref AdView::ad_size once the ad has been loaded. + static AdSize GetPortraitAnchoredAdaptiveBannerAdSize(uint32_t width); + + /// @brief Creates an AdSize with the given width and a Google-optimized + /// height to create a banner ad given the current orientation. + /// + /// @param[in] width The width of the ad in density-independent pixels. + /// + /// @return an AdSize with the given width and a Google-optimized height + /// to create a banner ad. The size returned will have an aspect ratio + /// similar to AdSize, suitable for anchoring near the top or bottom of + /// your app. The exact size of the ad returned can be retrieved by calling + /// @ref AdView::ad_size once the ad has been loaded. + static AdSize GetCurrentOrientationAnchoredAdaptiveBannerAdSize( + uint32_t width); + + /// @brief This ad size is most suitable for banner ads given a maximum + /// height. + /// + /// This AdSize allows Google servers to choose an optimal ad size with + /// a height less than or equal to the max height given in + /// + /// @param[in] width The width of the ad in density-independent pixels. + /// @param[in] max_height The maximum height that a loaded ad will have. Must + /// be + /// at least 32 dp, but a maxHeight of 50 dp or higher is recommended. + /// + /// @return an AdSize with the given width and a height that is always 0. + /// The exact size of the ad returned can be retrieved by calling + /// @ref AdView::ad_size once the ad has been loaded. + static AdSize GetInlineAdaptiveBannerAdSize(int width, int max_height); + + /// @brief Creates an AdSize with the given width and the device’s + /// landscape height. + /// + /// This ad size allows Google servers to choose an optimal ad size with + /// a height less than or equal to the height of the screen in landscape + /// orientation. + /// + /// @param[in] width The width of the ad in density-independent pixels. + /// + /// @return an AdSize with the given width and a height that is always 0. + /// The exact size of the ad returned can be retrieved by calling + /// @ref AdView::ad_size once the ad has been loaded. + static AdSize GetLandscapeInlineAdaptiveBannerAdSize(int width); + + /// @brief Creates an AdSize with the given width and the device’s + /// portrait height. + /// + /// This ad size allows Google servers to choose an optimal ad size with + /// a height less than or equal to the height of the screen in portrait + /// orientation. + /// + /// @param[in] width The width of the ad in density-independent pixels. + /// + /// @return an AdSize with the given width and a height that is always 0. + /// The exact size of the ad returned can be retrieved by calling + /// @ref AdView::ad_size once the ad has been loaded. + static AdSize GetPortraitInlineAdaptiveBannerAdSize(int width); + + /// @brief A convenience method to return an inline adaptive banner ad size + /// given the current interface orientation. + /// + /// This AdSize allows Google servers to choose an optimal ad size with a + /// height less than or equal to the height of the screen in the requested + /// orientation. + /// + /// @param[in] width The width of the ad in density-independent pixels. + /// + /// @return an AdSize with the given width and a height that is always 0. + /// The exact size of the ad returned can be retrieved by calling + /// @ref AdView::ad_size once the ad has been loaded. + static AdSize GetCurrentOrientationInlineAdaptiveBannerAdSize(int width); + + /// Comparison operator. + /// + /// @return true if `rhs` refers to the same AdSize as `this`. + bool operator==(const AdSize& rhs) const; + + /// Comparison operator. + /// + /// @returns true if `rhs` refers to a different AdSize as `this`. + bool operator!=(const AdSize& rhs) const; + + /// The width of the region represented by this AdSize. Value is in + /// density-independent pixels. + uint32_t width() const { return width_; } + + /// The height of the region represented by this AdSize. Value is in + /// density-independent pixels. + uint32_t height() const { return height_; } + + /// The AdSize orientation. + Orientation orientation() const { return orientation_; } + + /// The AdSize type, either standard size or adaptive. + Type type() const { return type_; } + + private: + friend class firebase::gma::internal::AdViewInternal; + + /// Returns an Anchor Adpative AdSize Object given a width and orientation. + static AdSize GetAnchoredAdaptiveBannerAdSize(uint32_t width, + Orientation orientation); + + /// Returns true if the AdSize parameter is equivalient to this AdSize object. + bool is_equal(const AdSize& ad_size) const; + + /// Denotes the orientation for anchored adaptive AdSize objects. + Orientation orientation_; + + /// Advertisement width in platform-indepenent pixels. + uint32_t width_; + + /// Advertisement width in platform-indepenent pixels. + uint32_t height_; + + /// The type of AdSize (standard or adaptive) + Type type_; +}; + +/// Contains targeting information used to fetch an ad. +class AdRequest { + public: + /// Creates an @ref AdRequest with no custom configuration. + AdRequest(); + + /// Creates an @ref AdRequest with the optional content URL. + /// + /// When requesting an ad, apps may pass the URL of the content they are + /// serving. This enables keyword targeting to match the ad with the content. + /// + /// The URL is ignored if null or the number of characters exceeds 512. + /// + /// @param[in] content_url the url of the content being viewed. + explicit AdRequest(const char* content_url); + + ~AdRequest(); + + /// The content URL targeting information. + /// + /// @return the content URL for the @ref AdRequest. The string will be empty + /// if no content URL has been configured. + const std::string& content_url() const { return content_url_; } + + /// A Map of adapter class names to their collection of extra parameters, as + /// configured via @ref add_extra. + const std::map >& extras() + const { + return extras_; + } + + /// Keywords which will help GMA to provide targeted ads, as added by + /// @ref add_keyword. + const std::unordered_set& keywords() const { return keywords_; } + + /// Returns the set of neighboring content URLs or an empty set if no URLs + /// were set via @ref add_neighboring_content_urls(). + const std::unordered_set& neighboring_content_urls() const { + return neighboring_content_urls_; + } + + /// Add a network extra for the associated ad mediation adapter. + /// + /// Appends an extra to the corresponding list of extras for the ad mediation + /// adapter. Each ad mediation adapter can have multiple extra strings. + /// + /// @param[in] adapter_class_name the class name of the ad mediation adapter + /// for which to add the extra. + /// @param[in] extra_key a key which will be passed to the corresponding ad + /// mediation adapter. + /// @param[in] extra_value the value associated with extra_key. + void add_extra(const char* adapter_class_name, const char* extra_key, + const char* extra_value); + + /// Adds a keyword for targeting purposes. + /// + /// Multiple keywords may be added via repeated invocations of this method. + /// + /// @param[in] keyword a string that GMA will use to aid in targeting ads. + void add_keyword(const char* keyword); + + /// When requesting an ad, apps may pass the URL of the content they are + /// serving. This enables keyword targeting to match the ad with the content. + /// + /// The URL is ignored if null or the number of characters exceeds 512. + /// + /// @param[in] content_url the url of the content being viewed. + void set_content_url(const char* content_url); + + /// Adds to the list of URLs which represent web content near an ad. + /// + /// Promotes brand safety and allows displayed ads to have an app level + /// rating (MA, T, PG, etc) that is more appropriate to neighboring content. + /// + /// Subsequent invocations append to the existing list. + /// + /// @param[in] neighboring_content_urls neighboring content URLs to be + /// attached to the existing neighboring content URLs. + void add_neighboring_content_urls( + const std::vector& neighboring_content_urls); + + private: + std::string content_url_; + std::map > extras_; + std::unordered_set keywords_; + std::unordered_set neighboring_content_urls_; +}; + +/// Describes a reward credited to a user for interacting with a RewardedAd. +class AdReward { + public: + /// Creates an @ref AdReward. + AdReward(const std::string& type, int64_t amount) + : type_(type), amount_(amount) {} + + /// Returns the reward amount. + int64_t amount() const { return amount_; } + + /// Returns the type of the reward. + const std::string& type() const { return type_; } + + private: + const int64_t amount_; + const std::string type_; +}; + +/// The monetary value earned from an ad. +class AdValue { + public: + /// Allowed constants for @ref precision_type(). + enum PrecisionType { + /// An ad value with unknown precision. + kdValuePrecisionUnknown = 0, + /// An ad value estimated from aggregated data. + kAdValuePrecisionEstimated, + /// A publisher-provided ad value, such as manual CPMs in a mediation group. + kAdValuePrecisionPublisherProvided = 2, + /// The precise value paid for this ad. + kAdValuePrecisionPrecise = 3 + }; + + /// Constructor + AdValue(const char* currency_code, PrecisionType precision_type, + int64_t value_micros) + : currency_code_(currency_code), + precision_type_(precision_type), + value_micros_(value_micros) {} + + /// The value's ISO 4217 currency code. + const std::string& currency_code() const { return currency_code_; } + + /// The precision of the reported ad value. + PrecisionType precision_type() const { return precision_type_; } + + /// The ad's value in micro-units, where 1,000,000 micro-units equal one + /// unit of the currency. + int64_t value_micros() const { return value_micros_; } + + private: + const std::string currency_code_; + const PrecisionType precision_type_; + const int64_t value_micros_; +}; + +/// @brief Listener to be invoked when ads show and dismiss full screen content, +/// such as a fullscreen ad experience or an in-app browser. +class FullScreenContentListener { + public: + virtual ~FullScreenContentListener(); + + /// Called when the user clicked the ad. + virtual void OnAdClicked() {} + + /// Called when the ad dismissed full screen content. + virtual void OnAdDismissedFullScreenContent() {} + + /// Called when the ad failed to show full screen content. + /// + /// @param[in] ad_error An object containing detailed information + /// about the error. + virtual void OnAdFailedToShowFullScreenContent(const AdError& ad_error) {} + + /// Called when an impression is recorded for an ad. + virtual void OnAdImpression() {} + + /// Called when the ad showed the full screen content. + virtual void OnAdShowedFullScreenContent() {} +}; + +/// Listener to be invoked when ads have been estimated to earn money. +class PaidEventListener { + public: + virtual ~PaidEventListener(); + + /// Called when an ad is estimated to have earned money. + virtual void OnPaidEvent(const AdValue& value) {} +}; + +/// @brief Global configuration that will be used for every @ref AdRequest. +/// Set the configuration via @ref SetRequestConfiguration. +struct RequestConfiguration { + /// A maximum ad content rating, which may be configured via + /// @ref max_ad_content_rating. + enum MaxAdContentRating { + /// No content rating has been specified. + kMaxAdContentRatingUnspecified = -1, + + /// Content suitable for general audiences, including families. + kMaxAdContentRatingG, + + /// Content suitable only for mature audiences. + kMaxAdContentRatingMA, + + /// Content suitable for most audiences with parental guidance. + kMaxAdContentRatingPG, + + /// Content suitable for teen and older audiences. + kMaxAdContentRatingT + }; + + /// Specify whether you would like your app to be treated as child-directed + /// for purposes of the Children’s Online Privacy Protection Act (COPPA). + /// Values defined here may be configured via + /// @ref tag_for_child_directed_treatment. + enum TagForChildDirectedTreatment { + /// Indicates that ad requests will include no indication of how you would + /// like your app treated with respect to COPPA. + kChildDirectedTreatmentUnspecified = -1, + + /// Indicates that your app should not be treated as child-directed for + /// purposes of the Children’s Online Privacy Protection Act (COPPA). + kChildDirectedTreatmentFalse, + + /// Indicates that your app should be treated as child-directed for purposes + /// of the Children’s Online Privacy Protection Act (COPPA). + kChildDirectedTreatmentTrue + }; + + /// Configuration values to mark your app to receive treatment for users in + /// the European Economic Area (EEA) under the age of consent. Values defined + /// here should be configured via @ref tag_for_under_age_of_consent. + enum TagForUnderAgeOfConsent { + /// Indicates that the publisher has not specified whether the ad request + /// should receive treatment for users in the European Economic Area (EEA) + /// under the age of consent. + kUnderAgeOfConsentUnspecified = -1, + + /// Indicates the publisher specified that the ad request should not receive + /// treatment for users in the European Economic Area (EEA) under the age of + /// consent. + kUnderAgeOfConsentFalse, + + /// Indicates the publisher specified that the ad request should receive + /// treatment for users in the European Economic Area (EEA) under the age of + /// consent. + kUnderAgeOfConsentTrue + }; + + /// Sets a maximum ad content rating. GMA ads returned for your app will + /// have a content rating at or below that level. + MaxAdContentRating max_ad_content_rating; + + /// @brief Allows you to specify whether you would like your app + /// to be treated as child-directed for purposes of the Children’s Online + /// Privacy Protection Act (COPPA) - + /// http://business.ftc.gov/privacy-and-security/childrens-privacy. + /// + /// If you set this value to + /// RequestConfiguration.kChildDirectedTreatmentTrue, you will indicate + /// that your app should be treated as child-directed for purposes of the + /// Children’s Online Privacy Protection Act (COPPA). + /// + /// If you set this value to + /// RequestConfiguration.kChildDirectedTreatmentFalse, you will indicate + /// that your app should not be treated as child-directed for purposes of the + /// Children’s Online Privacy Protection Act (COPPA). + /// + /// If you do not set this value, or set this value to + /// RequestConfiguration.kChildDirectedTreatmentUnspecified, ad requests will + /// include no indication of how you would like your app treated with respect + /// to COPPA. + /// + /// By setting this value, you certify that this notification is accurate and + /// you are authorized to act on behalf of the owner of the app. You + /// understand that abuse of this setting may result in termination of your + /// Google account. + /// + /// @note: it may take some time for this designation to be fully implemented + /// in applicable Google services. + /// + TagForChildDirectedTreatment tag_for_child_directed_treatment; + + /// This value allows you to mark your app to receive treatment for users in + /// the European Economic Area (EEA) under the age of consent. This feature is + /// designed to help facilitate compliance with the General Data Protection + /// Regulation (GDPR). Note that you may have other legal obligations under + /// GDPR. Please review the European Union's guidance and consult with your + /// own legal counsel. Please remember that Google's tools are designed to + /// facilitate compliance and do not relieve any particular publisher of its + /// obligations under the law. + /// + /// When using this feature, a Tag For Users under the Age of Consent in + /// Europe (TFUA) parameter will be included in all ad requests. This + /// parameter disables personalized advertising, including remarketing, for + /// that specific ad request. It also disables requests to third-party ad + /// vendors, such as ad measurement pixels and third-party ad servers. + /// + /// If you set this value to RequestConfiguration.kUnderAgeOfConsentTrue, you + /// will indicate that you want your app to be handled in a manner suitable + /// for users under the age of consent. + /// + /// If you set this value to RequestConfiguration.kUnderAgeOfConsentFalse, + /// you will indicate that you don't want your app to be handled in a manner + /// suitable for users under the age of consent. + /// + /// If you do not set this value, or set this value to + /// kUnderAgeOfConsentUnspecified, your app will include no indication of how + /// you would like your app to be handled in a manner suitable for users under + /// the age of consent. + TagForUnderAgeOfConsent tag_for_under_age_of_consent; + + /// Sets a list of test device IDs corresponding to test devices which will + /// always request test ads. + std::vector test_device_ids; +}; + +/// Listener to be invoked when the user earned a reward. +class UserEarnedRewardListener { + public: + virtual ~UserEarnedRewardListener(); + /// Called when the user earned a reward. The app is responsible for + /// crediting the user with the reward. + /// + /// @param[in] reward the @ref AdReward that should be granted to the user. + virtual void OnUserEarnedReward(const AdReward& reward) {} +}; + +} // namespace gma +} // namespace firebase + +#endif // FIREBASE_GMA_SRC_INCLUDE_FIREBASE_GMA_TYPES_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/installations.h b/packages/firebase_core/firebase_core/firebase_core/firebase/installations.h new file mode 100644 index 000000000000..c9774bc37e73 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/installations.h @@ -0,0 +1,123 @@ +// Copyright 2020 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef FIREBASE_INSTALLATIONS_SRC_INCLUDE_FIREBASE_INSTALLATIONS_H_ +#define FIREBASE_INSTALLATIONS_SRC_INCLUDE_FIREBASE_INSTALLATIONS_H_ + +#include +#include + +#include "firebase/app.h" +#include "firebase/future.h" +#include "firebase/internal/common.h" + +/// @brief Namespace that encompasses all Firebase APIs. +namespace firebase { + +namespace installations { + +/// Installations error codes. +enum Error { + kErrorNone = 0, + /// An unknown error occurred. + kErrorUnknown, + /// Installations service cannot be accessed. + kErrorNoAccess, + /// Some of the parameters of the request were invalid. + kErrorInvalidConfiguration, +}; + +namespace internal { +// Implementation specific data for an Installation. +class InstallationsInternal; +} // namespace internal + +/// @brief Installations provides a unique identifier for each app instance and +/// a mechanism to authenticate and authorize actions (for example, sending an +/// FCM message). +/// +/// Provides a unique identifier for a Firebase installation. +/// Provides an auth token for a Firebase installation. +/// Provides a API to perform data deletion for a Firebase +/// installation. +class Installations { + public: + ~Installations(); + + /// @brief Get the App this object is connected to. + /// + /// @return App this object is connected to. + App* app() const { return app_; } + + /// @brief Returns the Installations object for an App creating the + /// Installations if required. + /// + /// @param[in] app The App to create an Installations object from. + /// + /// @return Installations object if successful, nullptr otherwise. + static Installations* GetInstance(App* app); + + /// @brief Returns a stable identifier that uniquely identifies the app + /// installation. + /// + /// @return Unique identifier for the app installation. + Future GetId(); + + /// @brief Get the results of the most recent call to @ref GetId. + Future GetIdLastResult(); + + /// @brief Call to delete this Firebase app installation from the Firebase + /// backend. + Future Delete(); + + /// @brief Get the results of the most recent call to @ref Delete. + Future DeleteLastResult(); + + /// @brief Returns a token that authorizes an Entity to perform an action on + /// behalf of the application identified by installations. + /// + /// This is similar to an OAuth2 token except it applies to the + /// application instance instead of a user. + /// + /// For example, to get a token that can be used to send messages to an + /// application via Firebase Cloud Messaging, set entity to the + /// sender ID, and set scope to "FCM". + /// + /// @param forceRefresh If set true, will always return a new token. + /// + /// @return Returns a valid authentication token for the Firebase + /// installation. + Future GetToken(bool forceRefresh); + + /// @brief Get the results of the most recent call to @ref GetToken. + Future GetTokenLastResult(); + + private: + explicit Installations(App* app); + + static Installations* FindInstallations(App* app); + // Installations internal initialize. + bool InitInternal(); + // Clean up Installations instance. + void DeleteInternal(); + + App* app_; + internal::InstallationsInternal* installations_internal_; +}; + +} // namespace installations + +} // namespace firebase + +#endif // FIREBASE_INSTALLATIONS_SRC_INCLUDE_FIREBASE_INSTALLATIONS_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/internal/common.h b/packages/firebase_core/firebase_core/firebase_core/firebase/internal/common.h new file mode 100644 index 000000000000..2e2878a0bd97 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/internal/common.h @@ -0,0 +1,128 @@ +/* + * Copyright 2016 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_APP_SRC_INCLUDE_FIREBASE_INTERNAL_COMMON_H_ +#define FIREBASE_APP_SRC_INCLUDE_FIREBASE_INTERNAL_COMMON_H_ + +// This file contains definitions that configure the SDK. + +// Include a STL header file, othewise _STLPORT_VERSION won't be set. +#include + +// Move operators use rvalue references, which are a C++11 extension. +// Also, Visual Studio 2010 and later actually support move operators despite +// reporting __cplusplus to be 199711L, so explicitly check for that. +// Also, stlport doesn't implement std::move(). +#if (__cplusplus >= 201103L || _MSC_VER >= 1600) && !defined(_STLPORT_VERSION) +#define FIREBASE_USE_MOVE_OPERATORS +#endif + +// stlport doesn't implement std::function. +#if !defined(_STLPORT_VERSION) +#define FIREBASE_USE_STD_FUNCTION +#endif // !defined(_STLPORT_VERSION) + +// stlport doesn't implement std::aligned_storage. +#if defined(_STLPORT_VERSION) +#include + +namespace firebase { +template +struct AlignedStorage { + struct type { + alignas(Alignment) unsigned char data[Length]; + }; +}; +} // namespace firebase +#define FIREBASE_ALIGNED_STORAGE ::firebase::AlignedStorage +#else +#include +#define FIREBASE_ALIGNED_STORAGE std::aligned_storage +#endif // defined(_STLPORT_VERSION) + +// Visual Studio 2013 does not support snprintf, so use streams instead. +#if !(defined(_MSC_VER) && _MSC_VER <= 1800) +#define FIREBASE_USE_SNPRINTF +#endif // !(defined(_MSC_VER) && _MSC_VER <= 1800) + +#if !(defined(_MSC_VER) && _MSC_VER <= 1800) +#define FIREBASE_USE_EXPLICIT_DEFAULT_METHODS +#endif // !(defined(_MSC_VER) && _MSC_VER <= 1800) + +#if !defined(DOXYGEN) && !defined(SWIG) +#if !defined(_WIN32) && !defined(__CYGWIN__) +// Prevent GCC & Clang from stripping a symbol. +#define FIREBASE_APP_KEEP_SYMBOL __attribute__((used)) +#else +// MSVC needs to reference a symbol directly in the application for it to be +// kept in the final executable. In this case, the end user's application +// must include the appropriate Firebase header (e.g firebase/analytics.h) to +// initialize the module. +#define FIREBASE_APP_KEEP_SYMBOL +#endif // !defined(_WIN32) && !defined(__CYGWIN__) + +// Module initializer's name. +// +// This can be used to explicitly include a module initializer in an application +// to prevent the object from being stripped by the linker. The symbol is +// located in the "firebase" namespace so can be referenced using: +// +// ::firebase::FIREBASE_APP_REGISTER_CALLBACKS_REFERENCE_NAME(name) +// +// Where "name" is the module name, for example "analytics". +#define FIREBASE_APP_REGISTER_CALLBACKS_INITIALIZER_NAME(module_name) \ + g_##module_name##_initializer + +// Declare a module initializer variable as a global. +#define FIREBASE_APP_REGISTER_CALLBACKS_INITIALIZER_VARIABLE(module_name) \ + namespace firebase { \ + extern void* FIREBASE_APP_REGISTER_CALLBACKS_INITIALIZER_NAME(module_name); \ + } /* namespace firebase */ + +// Generates code which references a module initializer. +// For example, FIREBASE_APP_REGISTER_REFERENCE(analytics) will register the +// module initializer for the analytics module. +#define FIREBASE_APP_REGISTER_CALLBACKS_REFERENCE(module_name) \ + FIREBASE_APP_REGISTER_CALLBACKS_INITIALIZER_VARIABLE(module_name) \ + namespace firebase { \ + static void* module_name##_ref FIREBASE_APP_KEEP_SYMBOL = \ + &FIREBASE_APP_REGISTER_CALLBACKS_INITIALIZER_NAME(module_name); \ + } /* namespace firebase */ +#endif // !defined(DOXYGEN) && !defined(SWIG) + +#if defined(SWIG) || defined(DOXYGEN) +// SWIG needs to ignore the FIREBASE_DEPRECATED tag. +#define FIREBASE_DEPRECATED +#endif // defined(SWIG) || defined(DOXYGEN) + +#ifndef FIREBASE_DEPRECATED +#ifdef __GNUC__ +#define FIREBASE_DEPRECATED __attribute__((deprecated)) +#elif defined(_MSC_VER) +#define FIREBASE_DEPRECATED __declspec(deprecated) +#else +// We don't know how to mark functions as "deprecated" with this compiler. +#define FIREBASE_DEPRECATED +#endif +#endif // FIREBASE_DEPRECATED + +// Calculates the number of elements in an array. +#define FIREBASE_ARRAYSIZE(x) (sizeof(x) / sizeof((x)[0])) + +// Guaranteed compile time strlen. +#define FIREBASE_STRLEN(s) (FIREBASE_ARRAYSIZE(s) - sizeof((s)[0])) + +#endif // FIREBASE_APP_SRC_INCLUDE_FIREBASE_INTERNAL_COMMON_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/internal/future_impl.h b/packages/firebase_core/firebase_core/firebase_core/firebase/internal/future_impl.h new file mode 100644 index 000000000000..59e7771d010b --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/internal/future_impl.h @@ -0,0 +1,359 @@ +/* + * Copyright 2016 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_APP_SRC_INCLUDE_FIREBASE_INTERNAL_FUTURE_IMPL_H_ +#define FIREBASE_APP_SRC_INCLUDE_FIREBASE_INTERNAL_FUTURE_IMPL_H_ + +/// @cond FIREBASE_APP_INTERNAL + +// You shouldn't include future_impl.h directly, since its just the inline +// implementation of the functions in future.h. Include future.h instead. +#include "firebase/future.h" + +#if defined(FIREBASE_USE_MOVE_OPERATORS) +#include +#endif // defined(FIREBASE_USE_MOVE_OPERATORS) + +namespace firebase { + +class ReferenceCountedFutureImpl; + +namespace detail { + +class CompletionCallbackHandle; + +/// Pure-virtual interface that APIs must implement to use Futures. +class FutureApiInterface { + public: + // typedef void FutureCallbackFn(const FutureBase* future); + virtual ~FutureApiInterface(); + + /// Increment the reference count on handle's asynchronous call. + /// Called when the Future is copied. + virtual void ReferenceFuture(const FutureHandle& handle) = 0; + + /// Decrement the reference count on handle's asynchronous call. + /// Called when the Future is destroyed or moved. + /// If the reference count drops to zero, the asynchronous call can be + /// forgotten. + virtual void ReleaseFuture(const FutureHandle& handle) = 0; + + /// Return the status of the asynchronous call. + virtual FutureStatus GetFutureStatus(const FutureHandle& handle) const = 0; + + /// Return the API-specific error. + /// Valid when GetFutureStatus() is kFutureStatusComplete, and undefined + /// otherwise. + virtual int GetFutureError(const FutureHandle& handle) const = 0; + + /// Return the API-specific error, in human-readable form, or "" if no message + /// has been provided. + /// Valid when GetFutureStatus() is kFutureStatusComplete, and undefined + /// otherwise. + virtual const char* GetFutureErrorMessage( + const FutureHandle& handle) const = 0; + + /// Return a pointer to the completed asynchronous result, or NULL if + /// result is still pending. + /// After an asynchronous call is marked complete, the API should not + /// modify the result (especially on a callback thread), since the threads + /// owning the Future can reference the result memory via this function. + virtual const void* GetFutureResult(const FutureHandle& handle) const = 0; + + /// Register a callback that will be called when this future's status is set + /// to Complete. If clear_existing_callbacks is true, then the new callback + /// will replace any existing callbacks, otherwise it will be added to the + /// list of callbacks. + /// + /// The future's result data will be passed back when the callback is + /// called, along with the user_data supplied here. + /// + /// After the callback has been called, if `user_data_delete_fn_ptr` is + /// non-null, then `(*user_data_delete_fn_ptr)(user_data)` will be called. + virtual CompletionCallbackHandle AddCompletionCallback( + const FutureHandle& handle, FutureBase::CompletionCallback callback, + void* user_data, void (*user_data_delete_fn)(void*), + bool clear_existing_callbacks) = 0; + + /// Unregister a callback that was previously registered with + /// `AddCompletionCallback`. + virtual void RemoveCompletionCallback( + const FutureHandle& handle, CompletionCallbackHandle callback_handle) = 0; + +#if defined(FIREBASE_USE_STD_FUNCTION) + /// Register a callback that will be called when this future's status is set + /// to Complete. + /// + /// If `clear_existing_callbacks` is true, then the new callback + /// will replace any existing callbacks, otherwise it will be added to the + /// list of callbacks. + /// + /// The future's result data will be passed back when the callback is + /// called. + /// + /// @return A handle that can be passed to `FutureBase::RemoveCompletion`. + virtual CompletionCallbackHandle AddCompletionCallbackLambda( + const FutureHandle& handle, + std::function callback, + bool clear_existing_callbacks) = 0; +#endif // defined(FIREBASE_USE_STD_FUNCTION) + + /// Register this Future instance to be cleaned up. + virtual void RegisterFutureForCleanup(FutureBase* future) = 0; + + /// Unregister this Future instance from the cleanup list. + virtual void UnregisterFutureForCleanup(FutureBase* future) = 0; +}; + +inline void RegisterForCleanup(FutureApiInterface* api, FutureBase* future) { + if (api != NULL) { // NOLINT + api->RegisterFutureForCleanup(future); + } +} + +inline void UnregisterForCleanup(FutureApiInterface* api, FutureBase* future) { + if (api != NULL) { // NOLINT + api->UnregisterFutureForCleanup(future); + } +} + +class CompletionCallbackHandle { + public: + // Construct a null CompletionCallbackHandle. + CompletionCallbackHandle() + : callback_(nullptr), + user_data_(nullptr), + user_data_delete_fn_(nullptr) {} + + private: + friend class ::firebase::FutureBase; + friend class ::firebase::ReferenceCountedFutureImpl; + CompletionCallbackHandle(FutureBase::CompletionCallback callback, + void* user_data, void (*user_data_delete_fn)(void*)) + : callback_(callback), + user_data_(user_data), + user_data_delete_fn_(user_data_delete_fn) {} + + FutureBase::CompletionCallback callback_; + void* user_data_; + void (*user_data_delete_fn_)(void*); +}; + +} // namespace detail + +template +void Future::OnCompletion(TypedCompletionCallback callback, + void* user_data) const { + FutureBase::OnCompletion(reinterpret_cast(callback), + user_data); +} + +#if defined(FIREBASE_USE_STD_FUNCTION) +template +inline void Future::OnCompletion( + std::function&)> callback) const { + FutureBase::OnCompletion( + *reinterpret_cast*>(&callback)); +} +#endif // defined(FIREBASE_USE_STD_FUNCTION) + +#if defined(INTERNAL_EXPERIMENTAL) +template +FutureBase::CompletionCallbackHandle Future::AddOnCompletion( + TypedCompletionCallback callback, void* user_data) const { + return FutureBase::AddOnCompletion( + reinterpret_cast(callback), user_data); +} + +#if defined(FIREBASE_USE_STD_FUNCTION) +template +inline FutureBase::CompletionCallbackHandle Future::AddOnCompletion( + std::function&)> callback) const { + return FutureBase::AddOnCompletion( + *reinterpret_cast*>(&callback)); +} +#endif // defined(FIREBASE_USE_STD_FUNCTION) + +#endif // defined(INTERNAL_EXPERIMENTAL) + +inline FutureBase::FutureBase() + : mutex_(Mutex::Mode::kModeNonRecursive), + api_(NULL), + handle_(0) {} // NOLINT + +inline FutureBase::FutureBase(detail::FutureApiInterface* api, + const FutureHandle& handle) + : mutex_(Mutex::Mode::kModeNonRecursive), api_(api), handle_(handle) { + api_->ReferenceFuture(handle_); + // Once the FutureBase has reference, we don't need extra handle reference. + handle_.Detach(); + detail::RegisterForCleanup(api_, this); +} + +inline FutureBase::~FutureBase() { Release(); } + +inline FutureBase::FutureBase(const FutureBase& rhs) + : mutex_(Mutex::Mode::kModeNonRecursive), + api_(NULL) // NOLINT +{ // NOLINT + *this = rhs; +} + +inline FutureBase& FutureBase::operator=(const FutureBase& rhs) { + Release(); + + detail::FutureApiInterface* new_api; + FutureHandle new_handle; + { + MutexLock lock(rhs.mutex_); + new_api = rhs.api_; + new_handle = rhs.handle_; + } + + { + MutexLock lock(mutex_); + api_ = new_api; + handle_ = new_handle; + + if (api_ != NULL) { // NOLINT + api_->ReferenceFuture(handle_); + } + detail::RegisterForCleanup(api_, this); + } + + return *this; +} + +#if defined(FIREBASE_USE_MOVE_OPERATORS) +inline FutureBase::FutureBase(FutureBase&& rhs) noexcept + : mutex_(Mutex::Mode::kModeNonRecursive), + api_(NULL) // NOLINT +{ + *this = std::move(rhs); +} + +inline FutureBase& FutureBase::operator=(FutureBase&& rhs) noexcept { + Release(); + + detail::FutureApiInterface* new_api; + FutureHandle new_handle; + { + MutexLock lock(rhs.mutex_); + detail::UnregisterForCleanup(rhs.api_, &rhs); + new_api = rhs.api_; + new_handle = rhs.handle_; + rhs.api_ = NULL; // NOLINT + } + + MutexLock lock(mutex_); + api_ = new_api; + handle_ = new_handle; + detail::RegisterForCleanup(api_, this); + return *this; +} +#endif // defined(FIREBASE_USE_MOVE_OPERATORS) + +inline void FutureBase::Release() { + MutexLock lock(mutex_); + if (api_ != NULL) { // NOLINT + detail::UnregisterForCleanup(api_, this); + api_->ReleaseFuture(handle_); + api_ = NULL; // NOLINT + } +} + +inline FutureStatus FutureBase::status() const { + MutexLock lock(mutex_); + return api_ == NULL ? // NOLINT + kFutureStatusInvalid + : api_->GetFutureStatus(handle_); +} + +inline int FutureBase::error() const { + MutexLock lock(mutex_); + return api_ == NULL ? -1 : api_->GetFutureError(handle_); // NOLINT +} + +inline const char* FutureBase::error_message() const { + MutexLock lock(mutex_); + return api_ == NULL ? NULL : api_->GetFutureErrorMessage(handle_); // NOLINT +} + +inline const void* FutureBase::result_void() const { + MutexLock lock(mutex_); + return api_ == NULL ? NULL : api_->GetFutureResult(handle_); // NOLINT +} + +inline void FutureBase::OnCompletion(CompletionCallback callback, + void* user_data) const { + MutexLock lock(mutex_); + if (api_ != NULL) { // NOLINT + api_->AddCompletionCallback(handle_, callback, user_data, nullptr, + /*clear_existing_callbacks=*/true); + } +} + +#if defined(INTERNAL_EXPERIMENTAL) +inline FutureBase::CompletionCallbackHandle FutureBase::AddOnCompletion( + CompletionCallback callback, void* user_data) const { + MutexLock lock(mutex_); + if (api_ != NULL) { // NOLINT + return api_->AddCompletionCallback(handle_, callback, user_data, nullptr, + /*clear_existing_callbacks=*/false); + } + return CompletionCallbackHandle(); +} + +inline void FutureBase::RemoveOnCompletion( + CompletionCallbackHandle completion_handle) const { + MutexLock lock(mutex_); + if (api_ != NULL) { // NOLINT + api_->RemoveCompletionCallback(handle_, completion_handle); + } +} +#endif // defined(INTERNAL_EXPERIMENTAL) + +#if defined(FIREBASE_USE_STD_FUNCTION) +inline void FutureBase::OnCompletion( + std::function callback) const { + MutexLock lock(mutex_); + if (api_ != NULL) { // NOLINT + api_->AddCompletionCallbackLambda(handle_, callback, + /*clear_existing_callbacks=*/true); + } +} + +#if defined(INTERNAL_EXPERIMENTAL) +inline FutureBase::CompletionCallbackHandle FutureBase::AddOnCompletion( + std::function callback) const { + MutexLock lock(mutex_); + if (api_ != NULL) { // NOLINT + return api_->AddCompletionCallbackLambda( + handle_, callback, + /*clear_existing_callbacks=*/false); + } + return CompletionCallbackHandle(); +} +#endif // defined(INTERNAL__EXPERIMENTAL) + +#endif // defined(FIREBASE_USE_STD_FUNCTION) + +// NOLINTNEXTLINE - allow namespace overridden +} // namespace firebase + +/// @endcond + +#endif // FIREBASE_APP_SRC_INCLUDE_FIREBASE_INTERNAL_FUTURE_IMPL_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/internal/mutex.h b/packages/firebase_core/firebase_core/firebase_core/firebase/internal/mutex.h new file mode 100644 index 000000000000..86f6a45d1b38 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/internal/mutex.h @@ -0,0 +1,100 @@ +/* + * Copyright 2016 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_APP_SRC_INCLUDE_FIREBASE_INTERNAL_MUTEX_H_ +#define FIREBASE_APP_SRC_INCLUDE_FIREBASE_INTERNAL_MUTEX_H_ + +#include "firebase/internal/platform.h" + +#if FIREBASE_PLATFORM_WINDOWS +#include +#else +#include +#endif // FIREBASE_PLATFORM_WINDOWS + +namespace firebase { + +#if !defined(DOXYGEN) + +/// @brief A simple synchronization lock. Only one thread at a time can Acquire. +class Mutex { + public: + // Bitfield that describes the mutex configuration. + enum Mode { + kModeNonRecursive = (0 << 0), + kModeRecursive = (1 << 0), + }; + + Mutex() : Mutex(kModeRecursive) {} + + explicit Mutex(Mode mode); + + ~Mutex(); + + // Acquires the lock for this mutex, blocking until it is available. + void Acquire(); + + // Releases the lock for this mutex acquired by a previous `Acquire()` call. + void Release(); + +// Returns the implementation-defined native mutex handle. +// Used by firebase::Thread implementation. +#if FIREBASE_PLATFORM_WINDOWS + HANDLE* native_handle() { return &synchronization_object_; } +#else + pthread_mutex_t* native_handle() { return &mutex_; } +#endif // FIREBASE_PLATFORM_WINDOWS + + private: + Mutex(const Mutex&) = delete; + Mutex& operator=(const Mutex&) = delete; + +#if FIREBASE_PLATFORM_WINDOWS + HANDLE synchronization_object_; + Mode mode_; +#else + pthread_mutex_t mutex_; +#endif // FIREBASE_PLATFORM_WINDOWS +}; + +/// @brief Acquire and hold a /ref Mutex, while in scope. +/// +/// Example usage: +/// \code{.cpp} +/// Mutex syncronization_mutex; +/// void MyFunctionThatRequiresSynchronization() { +/// MutexLock lock(syncronization_mutex); +/// // ... logic ... +/// } +/// \endcode +class MutexLock { + public: + explicit MutexLock(Mutex& mutex) : mutex_(&mutex) { mutex_->Acquire(); } + ~MutexLock() { mutex_->Release(); } + + private: + // Copy is disallowed. + MutexLock(const MutexLock& rhs); // NOLINT + MutexLock& operator=(const MutexLock& rhs); + + Mutex* mutex_; +}; + +#endif // !defined(DOXYGEN) + +} // namespace firebase + +#endif // FIREBASE_APP_SRC_INCLUDE_FIREBASE_INTERNAL_MUTEX_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/internal/platform.h b/packages/firebase_core/firebase_core/firebase_core/firebase/internal/platform.h new file mode 100644 index 000000000000..17d64e32d022 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/internal/platform.h @@ -0,0 +1,110 @@ +/* + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_APP_SRC_INCLUDE_FIREBASE_INTERNAL_PLATFORM_H_ +#define FIREBASE_APP_SRC_INCLUDE_FIREBASE_INTERNAL_PLATFORM_H_ + +// This header serts exactly one of these FIREBASE_PLATFORM macros to 1, and the +// rest to 0: +// +// FIREBASE_PLATFORM_ANDROID +// FIREBASE_PLATFORM_IOS +// FIREBASE_PLATFORM_TVOS +// FIREBASE_PLATFORM_OSX +// FIREBASE_PLATFORM_WINDOWS +// FIREBASE_PLATFORM_LINUX +// FIREBASE_PLATFORM_UNKNOWN +// +// You can use e.g. #if FIREBASE_PLATFORM_OSX to conditionally compile code +// after including this header. +// +// It also defines some convenience macros: +// FIREBASE_PLATFORM_DESKTOP (1 on OSX, WINDOWS, and LINUX, 0 otherwise) +// FIREBASE_PLATFORM_MOBILE (1 on IOS and ANDROID, 0 otherwise) + +#define FIREBASE_PLATFORM_ANDROID 0 +#define FIREBASE_PLATFORM_IOS 0 +#define FIREBASE_PLATFORM_TVOS 0 +#define FIREBASE_PLATFORM_OSX 0 +#define FIREBASE_PLATFORM_WINDOWS 0 +#define FIREBASE_PLATFORM_LINUX 0 +#define FIREBASE_PLATFORM_UNKNOWN 0 + +#ifdef __APPLE__ +#include "TargetConditionals.h" +#endif // __APPLE__ + +#if defined(__ANDROID__) +#undef FIREBASE_PLATFORM_ANDROID +#define FIREBASE_PLATFORM_ANDROID 1 +#elif defined(TARGET_OS_IOS) && TARGET_OS_IOS +#undef FIREBASE_PLATFORM_IOS +#define FIREBASE_PLATFORM_IOS 1 +#elif defined(TARGET_OS_TV) && TARGET_OS_TV +#undef FIREBASE_PLATFORM_TVOS +#define FIREBASE_PLATFORM_TVOS 1 +#elif defined(TARGET_OS_OSX) && TARGET_OS_OSX +#undef FIREBASE_PLATFORM_OSX +#define FIREBASE_PLATFORM_OSX 1 +#elif defined(_WIN32) +#undef FIREBASE_PLATFORM_WINDOWS +#define FIREBASE_PLATFORM_WINDOWS 1 +#elif defined(__linux__) +#undef FIREBASE_PLATFORM_LINUX +#define FIREBASE_PLATFORM_LINUX 1 +#else +#undef FIREBASE_PLATFORM_UNKNOWN +#define FIREBASE_PLATFORM_UNKNOWN 1 +#endif + +#if FIREBASE_PLATFORM_LINUX + +// Include std library header to get version defines +#include + +#if defined(__clang__) +#define FIREBASE_COMPILER_CLANG 1 +#elif defined(__GNUC__) +#define FIREBASE_COMPILER_GCC 1 +#endif + +#if defined(_LIBCPP_VERSION) +#define FIREBASE_STANDARD_LIBCPP 1 +#elif defined(__GLIBCXX__) +#define FIREBASE_STANDARD_LIBSTDCPP 1 +#endif + +#if (FIREBASE_COMPILER_CLANG && FIREBASE_STANDARD_LIBCPP) +#define FIREBASE_LINUX_BUILD_CONFIG_STRING "clang_libstdcpp" +#elif (FIREBASE_COMPILER_CLANG && FIREBASE_STANDARD_LIBSTDCPP) +#define FIREBASE_LINUX_BUILD_CONFIG_STRING "clang_libcpp" +#elif (FIREBASE_COMPILER_GCC && FIREBASE_STANDARD_LIBCPP) +#define FIREBASE_LINUX_BUILD_CONFIG_STRING "gcc_libstdcpp" +#elif (FIREBASE_COMPILER_GCC && FIREBASE_STANDARD_LIBSTDCPP) +#define FIREBASE_LINUX_BUILD_CONFIG_STRING "gcc_libcpp" +#else +#error "Unsupported compiler or standard library" +#endif + +#endif // FIREBASE_PLATFORM_LINUX + +#define FIREBASE_PLATFORM_MOBILE \ + (FIREBASE_PLATFORM_IOS || FIREBASE_PLATFORM_ANDROID) +#define FIREBASE_PLATFORM_DESKTOP \ + (FIREBASE_PLATFORM_LINUX || FIREBASE_PLATFORM_WINDOWS || \ + FIREBASE_PLATFORM_OSX) + +#endif // FIREBASE_APP_SRC_INCLUDE_FIREBASE_INTERNAL_PLATFORM_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/internal/type_traits.h b/packages/firebase_core/firebase_core/firebase_core/firebase/internal/type_traits.h new file mode 100644 index 000000000000..7c465ea27c1e --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/internal/type_traits.h @@ -0,0 +1,134 @@ +/* + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_APP_SRC_INCLUDE_FIREBASE_INTERNAL_TYPE_TRAITS_H_ +#define FIREBASE_APP_SRC_INCLUDE_FIREBASE_INTERNAL_TYPE_TRAITS_H_ + +#include +#include + +// Doxygen breaks trying to parse this file, and since it is internal logic, +// it doesn't need to be included in the generated documentation. +#ifndef DOXYGEN + +namespace firebase { + +template +struct remove_reference { + typedef T type; +}; + +template +struct remove_reference { + typedef T type; +}; + +template +struct remove_reference { + typedef T type; +}; + +template +struct is_array { + static constexpr bool value = false; +}; + +template +struct is_array { + static constexpr bool value = true; +}; + +template +struct is_array { + static constexpr bool value = true; +}; + +template +struct is_lvalue_reference { + static constexpr bool value = false; +}; + +template +struct is_lvalue_reference { + static constexpr bool value = true; +}; + +// STLPort does include header, but its contents are in `std::tr1` +// namespace. To work around this, use aliases. +// TODO(varconst): all of the reimplementations of traits above can be replaced +// with appropriate aliases. +// TODO(varconst): the traits in this file would be more conformant if they +// inherited from `std::integral_constant`. +#ifdef STLPORT +#define FIREBASE_TYPE_TRAITS_NS std::tr1 +#else +#define FIREBASE_TYPE_TRAITS_NS std +#endif + +template +using decay = FIREBASE_TYPE_TRAITS_NS::decay; + +template +using decay_t = typename decay::type; + +template +using enable_if = FIREBASE_TYPE_TRAITS_NS::enable_if; + +template +using is_floating_point = FIREBASE_TYPE_TRAITS_NS::is_floating_point; + +template +using is_integral = FIREBASE_TYPE_TRAITS_NS::is_integral; + +template +using is_same = FIREBASE_TYPE_TRAITS_NS::is_same; + +template +using integral_constant = FIREBASE_TYPE_TRAITS_NS::integral_constant; + +using true_type = FIREBASE_TYPE_TRAITS_NS::true_type; +using false_type = FIREBASE_TYPE_TRAITS_NS::false_type; + +#undef FIREBASE_TYPE_TRAITS_NS + +// `is_char::value` is true iff `T` is a character type (including `wchar_t` +// and C++11 fixed-width character types). +template +struct is_char { + static constexpr bool value = +#if __cplusplus >= 202002L + is_same::value || +#endif +#if __cplusplus >= 201103L + is_same::value || is_same::value || +#endif + is_same::value || is_same::value || + is_same::value || is_same::value; +}; + +// A subset of `std::is_integral`: excludes `bool` and character types. +template +struct is_integer { + static constexpr bool value = + is_integral::value && !is_same::value && !is_char::value; +}; + +// NOLINTNEXTLINE - allow namespace overridden +} // namespace firebase + +#endif // DOXYGEN + +#endif // FIREBASE_APP_SRC_INCLUDE_FIREBASE_INTERNAL_TYPE_TRAITS_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/log.h b/packages/firebase_core/firebase_core/firebase_core/firebase/log.h new file mode 100644 index 000000000000..3d36ce37dcb3 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/log.h @@ -0,0 +1,54 @@ +/* + * Copyright 2016 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_APP_SRC_INCLUDE_FIREBASE_LOG_H_ +#define FIREBASE_APP_SRC_INCLUDE_FIREBASE_LOG_H_ + +/// @brief Namespace that encompasses all Firebase APIs. +namespace firebase { + +/// @brief Levels used when logging messages. +enum LogLevel { + /// Verbose Log Level + kLogLevelVerbose = 0, + /// Debug Log Level + kLogLevelDebug, + /// Info Log Level + kLogLevelInfo, + /// Warning Log Level + kLogLevelWarning, + /// Error Log Level + kLogLevelError, + /// Assert Log Level + kLogLevelAssert, +}; + +/// @brief Sets the logging verbosity. +/// All log messages at or above the specific log level. +/// +/// @param[in] level Log level to display, by default this is set to +/// kLogLevelInfo. +void SetLogLevel(LogLevel level); + +/// @brief Gets the logging verbosity. +/// +/// @return Get the currently configured logging verbosity. +LogLevel GetLogLevel(); + +// NOLINTNEXTLINE - allow namespace overridden +} // namespace firebase + +#endif // FIREBASE_APP_SRC_INCLUDE_FIREBASE_LOG_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/messaging.h b/packages/firebase_core/firebase_core/firebase_core/firebase/messaging.h new file mode 100644 index 000000000000..e7c7f5776868 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/messaging.h @@ -0,0 +1,728 @@ +// Copyright 2016 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef FIREBASE_MESSAGING_SRC_INCLUDE_FIREBASE_MESSAGING_H_ +#define FIREBASE_MESSAGING_SRC_INCLUDE_FIREBASE_MESSAGING_H_ + +#include + +#include +#include +#include + +#include "firebase/app.h" +#include "firebase/future.h" +#include "firebase/internal/common.h" + +#if !defined(DOXYGEN) && !defined(SWIG) +FIREBASE_APP_REGISTER_CALLBACKS_REFERENCE(messaging) +#endif // !defined(DOXYGEN) && !defined(SWIG) + +namespace firebase { + +/// @brief Firebase Cloud Messaging API. +/// +/// Firebase Cloud Messaging allows you to send data from your server to your +/// users' devices, and receive messages from devices on the same connection +/// if you're using a XMPP server. +/// +/// The FCM service handles all aspects of queueing of messages and delivery +/// to client applications running on target devices. +namespace messaging { + +/// @brief A class to configure the behavior of Firebase Cloud Messaging. +/// +/// This class contains various configuration options that control some of +/// Firebase Cloud Messaging's behavior. +struct MessagingOptions { + /// Default constructor. + MessagingOptions() : suppress_notification_permission_prompt(false) {} + + /// If true, do not display the prompt to the user requesting permission to + /// allow notifications to this app. If the prompt is suppressed in this way, + /// the developer must manually prompt the user for permission at some point + /// in the future using `RequestPermission()`. + /// + /// If this prompt has already been accepted once in the past the prompt will + /// not be displayed again. + /// + /// This option currently only applies to iOS and tvOS. + bool suppress_notification_permission_prompt; +}; + +/// @brief Data structure for parameters that are unique to the Android +/// implementation. +struct AndroidNotificationParams { + /// The channel id that was provided when the message was sent. + std::string channel_id; +}; + +/// Used for messages that display a notification. +/// +/// On android, this requires that the app is using the Play Services client +/// library. +struct Notification { + Notification() : android(nullptr) {} + +#ifndef SWIG + /// Copy constructor. Makes a deep copy of this Message. + Notification(const Notification& other) : android(nullptr) { *this = other; } +#endif // !SWIG + +#ifndef SWIG + /// Copy assignment operator. Makes a deep copy of this Message. + Notification& operator=(const Notification& other) { + this->title = other.title; + this->body = other.body; + this->icon = other.icon; + this->sound = other.sound; + this->tag = other.tag; + this->color = other.color; + this->click_action = other.click_action; + this->body_loc_key = other.body_loc_key; + this->body_loc_args = other.body_loc_args; + this->title_loc_key = other.title_loc_key; + this->title_loc_args = other.title_loc_args; + delete this->android; + if (other.android) { + this->android = new AndroidNotificationParams(*other.android); + } else { + this->android = nullptr; + } + return *this; + } +#endif // !SWIG + + /// Destructor. + ~Notification() { delete android; } + + /// Indicates notification title. This field is not visible on tvOS, iOS + /// phones and tablets. + std::string title; + + /// Indicates notification body text. + std::string body; + + /// Indicates notification icon. Sets value to myicon for drawable resource + /// myicon. + std::string icon; + + /// Indicates a sound to play when the device receives the notification. + /// Supports default, or the filename of a sound resource bundled in the + /// app. + /// + /// Android sound files must reside in /res/raw/, while iOS and tvOS sound + /// files can be in the main bundle of the client app or in the + /// Library/Sounds folder of the app’s data container. + std::string sound; + + /// Indicates the badge on the client app home icon. iOS and tvOS only. + std::string badge; + + /// Indicates whether each notification results in a new entry in the + /// notification drawer on Android. If not set, each request creates a new + /// notification. If set, and a notification with the same tag is already + /// being shown, the new notification replaces the existing one in the + /// notification drawer. + std::string tag; + + /// Indicates color of the icon, expressed in \#rrggbb format. Android only. + std::string color; + + /// The action associated with a user click on the notification. + /// + /// On Android, if this is set, an activity with a matching intent filter is + /// launched when user clicks the notification. + /// + /// If set on iOS or tvOS, corresponds to category in APNS payload. + std::string click_action; + + /// Indicates the key to the body string for localization. + /// + /// On iOS and tvOS, this corresponds to "loc-key" in APNS payload. + /// + /// On Android, use the key in the app's string resources when populating this + /// value. + std::string body_loc_key; + + /// Indicates the string value to replace format specifiers in body string + /// for localization. + /// + /// On iOS and tvOS, this corresponds to "loc-args" in APNS payload. + /// + /// On Android, these are the format arguments for the string resource. For + /// more information, see [Formatting strings][1]. + /// + /// [1]: + /// https://developer.android.com/guide/topics/resources/string-resource.html#FormattingAndStyling + std::vector body_loc_args; + + /// Indicates the key to the title string for localization. + /// + /// On iOS and tvOS, this corresponds to "title-loc-key" in APNS payload. + /// + /// On Android, use the key in the app's string resources when populating this + /// value. + std::string title_loc_key; + + /// Indicates the string value to replace format specifiers in title string + /// for localization. + /// + /// On iOS and tvOS, this corresponds to "title-loc-args" in APNS payload. + /// + /// On Android, these are the format arguments for the string resource. For + /// more information, see [Formatting strings][1]. + /// + /// [1]: + /// https://developer.android.com/guide/topics/resources/string-resource.html#FormattingAndStyling + std::vector title_loc_args; + + /// Parameters that are unique to the Android implementation. + AndroidNotificationParams* android; +}; + +/// @brief Data structure used to send messages to, and receive messages from, +/// cloud messaging. +struct Message { + /// Initialize the message. + Message() + : time_to_live(0), + notification(nullptr), + notification_opened(false), + sent_time(0) {} + + /// Destructor. + ~Message() { delete notification; } + +#ifndef SWIG + /// Copy constructor. Makes a deep copy of this Message. + Message(const Message& other) : notification(nullptr) { *this = other; } +#endif // !SWIG + +#ifndef SWIG + /// Copy assignment operator. Makes a deep copy of this Message. + Message& operator=(const Message& other) { + this->from = other.from; + this->to = other.to; + this->collapse_key = other.collapse_key; + this->data = other.data; + this->raw_data = other.raw_data; + this->message_id = other.message_id; + this->message_type = other.message_type; + this->priority = other.priority; + this->original_priority = other.original_priority; + this->sent_time = other.sent_time; + this->time_to_live = other.time_to_live; + this->error = other.error; + this->error_description = other.error_description; + delete this->notification; + if (other.notification) { + this->notification = new Notification(*other.notification); + } else { + this->notification = nullptr; + } + this->notification_opened = other.notification_opened; + this->link = other.link; + return *this; + } +#endif // !SWIG + + /// Authenticated ID of the sender. This is a project number in most cases. + /// + /// Any value starting with google.com, goog. or gcm. are reserved. + /// + /// This field is only used for downstream messages received through + /// Listener::OnMessage(). + std::string from; + + /// This parameter specifies the recipient of a message. + /// + /// For example it can be a registration token, a topic name, an Instance ID + /// or project ID. + /// + /// PROJECT_ID@gcm.googleapis.com or Instance ID are accepted. + std::string to; + + /// This parameter identifies a group of messages (e.g., with collapse_key: + /// "Updates Available") that can be collapsed, so that only the last message + /// gets sent when delivery can be resumed. This is intended to avoid sending + /// too many of the same messages when the device comes back online or becomes + /// active. + /// + /// Note that there is no guarantee of the order in which messages get sent. + /// + /// Note: A maximum of 4 different collapse keys is allowed at any given time. + /// This means a FCM connection server can simultaneously store 4 different + /// send-to-sync messages per client app. If you exceed this number, there is + /// no guarantee which 4 collapse keys the FCM connection server will keep. + /// + /// This field is only used for downstream messages received through + /// Listener::OnMessage(). + std::string collapse_key; + + /// The metadata, including all original key/value pairs. Includes some of the + /// HTTP headers used when sending the message. `gcm`, `google` and `goog` + /// prefixes are reserved for internal use. + std::map data; + + /// Binary payload. + std::vector raw_data; + + /// Message ID. This can be specified by sender. Internally a hash of the + /// message ID and other elements will be used for storage. The ID must be + /// unique for each topic subscription - using the same ID may result in + /// overriding the original message or duplicate delivery. + std::string message_id; + + /// Equivalent with a content-type. + /// + /// Defined values: + /// - "deleted_messages" - indicates the server had too many messages and + /// dropped some, and the client should sync with his own server. + /// Current limit is 100 messages stored. + /// - "send_event" - indicates an upstream message has been pushed to the + /// FCM server. It does not guarantee the upstream destination received + /// it. + /// Parameters: "message_id" + /// - "send_error" - indicates an upstream message expired, without being + /// sent to the FCM server. + /// Parameters: "message_id" and "error" + /// + /// If this field is missing, the message is a regular message. + /// + /// This field is only used for downstream messages received through + /// Listener::OnMessage(). + std::string message_type; + + /// Sets the priority of the message. Valid values are "normal" and "high." On + /// iOS and tvOS, these correspond to APNs priority 5 and 10. + /// + /// By default, messages are sent with normal priority. Normal priority + /// optimizes the client app's battery consumption, and should be used unless + /// immediate delivery is required. For messages with normal priority, the app + /// may receive the message with unspecified delay. + /// + /// When a message is sent with high priority, it is sent immediately, and the + /// app can wake a sleeping device and open a network connection to your + /// server. + /// + /// For more information, see [Setting the priority of a message][1]. + /// + /// This field is only used for downstream messages received through + /// Listener::OnMessage(). + /// + /// [1]: + /// https://firebase.google.com/docs/cloud-messaging/concept-options#setting-the-priority-of-a-message + std::string priority; + + /// This parameter specifies 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. For more + /// information, see [Setting the lifespan of a message][1]. + /// + /// This field is only used for downstream messages received through + /// Listener::OnMessage(). + /// + /// [1]: https://firebase.google.com/docs/cloud-messaging/concept-options#ttl + int32_t time_to_live; + + /// Error code. Used in "nack" messages for CCS, and in responses from the + /// server. + /// See the CCS specification for the externally-supported list. + /// + /// This field is only used for downstream messages received through + /// Listener::OnMessage(). + std::string error; + + /// Human readable details about the error. + /// + /// This field is only used for downstream messages received through + /// Listener::OnMessage(). + std::string error_description; + + /// Optional notification to show. This only set if a notification was + /// received with this message, otherwise it is null. + /// + /// The notification is only guaranteed to be valid during the call to + /// Listener::OnMessage(). If you need to keep it around longer you will need + /// to make a copy of either the Message or Notification. Copying the Message + /// object implicitly makes a deep copy of the notification (allocated with + /// new) which is owned by the Message. + /// + /// This field is only used for downstream messages received through + /// Listener::OnMessage(). + Notification* notification; + + /// A flag indicating whether this message was opened by tapping a + /// notification in the OS system tray. If the message was received this way + /// this flag is set to true. + bool notification_opened; + + /// The link into the app from the message. + /// + /// This field is only used for downstream messages received through + /// Listener::OnMessage(). + std::string link; + + /// @cond FIREBASE_APP_INTERNAL + /// Original priority of the message. + std::string original_priority; + + /// UTC timestamp in milliseconds when the message was sent. + /// See https://en.wikipedia.org/wiki/Unix_time for details of UTC. + int64_t sent_time; + /// @endcond +}; + +/// @brief Base class used to receive messages from Firebase Cloud Messaging. +/// +/// You need to override base class methods to handle any events required by the +/// application. Methods are invoked asynchronously and may be invoked on other +/// threads. +class Listener { + public: + virtual ~Listener(); + + /// Called on the client when a message arrives. + /// + /// @param[in] message The data describing this message. + virtual void OnMessage(const Message& message) = 0; + + /// Called on the client when a registration token arrives. This function + /// will eventually be called in response to a call to + /// firebase::messaging::Initialize(...). + /// + /// @param[in] token The registration token. + virtual void OnTokenReceived(const char* token) = 0; +}; + +/// @brief Initialize Firebase Cloud Messaging. +/// +/// After Initialize is called, the implementation may call functions on the +/// Listener provided at any time. +/// +/// @param[in] app The Firebase App object for this application. +/// @param[in] listener A Listener object that listens for events from the +/// Firebase Cloud Messaging servers. +/// +/// @return kInitResultSuccess if initialization succeeded, or +/// kInitResultFailedMissingDependency on Android if Google Play services is +/// not available on the current device. +InitResult Initialize(const App& app, Listener* listener); + +/// @brief Initialize Firebase Cloud Messaging. +/// +/// After Initialize is called, the implementation may call functions on the +/// Listener provided at any time. +/// +/// @param[in] app The Firebase App object for this application. +/// @param[in] listener A Listener object that listens for events from the +/// Firebase Cloud Messaging servers. +/// @param[in] options A set of options that configure the +/// initialzation behavior of Firebase Cloud Messaging. +/// +/// @return kInitResultSuccess if initialization succeeded, or +/// kInitResultFailedMissingDependency on Android if Google Play services is +/// not available on the current device. +InitResult Initialize(const App& app, Listener* listener, + const MessagingOptions& options); + +/// @brief Terminate Firebase Cloud Messaging. +/// +/// Frees resources associated with Firebase Cloud Messaging. +/// +/// @note On Android, the services will not be shut down by this method. +void Terminate(); + +/// Determines if automatic token registration during initalization is enabled. +/// +/// @return true if auto token registration is enabled and false if disabled. +bool IsTokenRegistrationOnInitEnabled(); + +/// Enable or disable token registration during initialization of Firebase Cloud +/// Messaging. +/// +/// This token is what identifies the user to Firebase, so disabling this avoids +/// creating any new identity and automatically sending it to Firebase, unless +/// consent has been granted. +/// +/// If this setting is enabled, it triggers the token registration refresh +/// immediately. This setting is persisted across app restarts and overrides the +/// setting "firebase_messaging_auto_init_enabled" specified in your Android +/// manifest (on Android) or Info.plist (on iOS and tvOS). +/// +///

By default, token registration during initialization is enabled. +/// +/// The registration happens before you can programmatically disable it, so +/// if you need to change the default, (for example, because you want to prompt +/// the user before FCM generates/refreshes a registration token on app +/// startup), add to your application’s manifest: +/// +/// +/// @if NOT_DOXYGEN +/// +/// @else +/// @code +/// <meta-data android:name="firebase_messaging_auto_init_enabled" +/// android:value="false" /> +/// @endcode +/// @endif +/// +/// or on iOS or tvOS to your Info.plist: +/// +/// @if NOT_DOXYGEN +/// FirebaseMessagingAutoInitEnabled +/// +/// @else +/// @code +/// <key>FirebaseMessagingAutoInitEnabled</key> +/// <false/> +/// @endcode +/// @endif +/// +/// @param enable sets if a registration token should be requested on +/// initialization. +void SetTokenRegistrationOnInitEnabled(bool enable); + +#ifndef SWIG +/// @brief Set the listener for events from the Firebase Cloud Messaging +/// servers. +/// +/// A listener must be set for the application to receive messages from +/// the Firebase Cloud Messaging servers. The implementation may call functions +/// on the Listener provided at any time. +/// +/// @param[in] listener A Listener object that listens for events from the +/// Firebase Cloud Messaging servers. +/// +/// @return Pointer to the previously set listener. +Listener* SetListener(Listener* listener); +#endif // !SWIG + +/// Error code returned by Firebase Cloud Messaging C++ functions. +enum Error { + /// The operation was a success, no error occurred. + kErrorNone = 0, + /// Permission to receive notifications was not granted. + kErrorFailedToRegisterForRemoteNotifications, + /// Topic name is invalid for subscription/unsubscription. + kErrorInvalidTopicName, + /// Could not subscribe/unsubscribe because there is no registration token. + kErrorNoRegistrationToken, + /// Unknown error. + kErrorUnknown, +}; + +/// @brief Displays a prompt to the user requesting permission to display +/// notifications. +/// +/// The permission prompt only appears on iOS and tvOS. If the user has +/// already agreed to allow notifications, no prompt is displayed and the +/// returned future is completed immediately. +/// +/// @return A future that completes when the notification prompt has been +/// dismissed. +Future RequestPermission(); + +/// @brief Gets the result of the most recent call to RequestPermission(); +/// +/// @return Result of the most recent call to RequestPermission(). +Future RequestPermissionLastResult(); + +/// @brief Subscribe to receive all messages to the specified topic. +/// +/// Subscribes an app instance to a topic, enabling it to receive messages +/// sent to that topic. +/// +/// Call this function from the main thread. FCM is not thread safe. +/// +/// @param[in] topic The name of the topic to subscribe. Must match the +/// following regular expression: `[a-zA-Z0-9-_.~%]{1,900}`. +Future Subscribe(const char* topic); + +/// @brief Gets the result of the most recent call to Unsubscribe(); +/// +/// @return Result of the most recent call to Unsubscribe(). +Future SubscribeLastResult(); + +/// @brief Unsubscribe from a topic. +/// +/// Unsubscribes an app instance from a topic, stopping it from receiving +/// any further messages sent to that topic. +/// +/// Call this function from the main thread. FCM is not thread safe. +/// +/// @param[in] topic The name of the topic to unsubscribe from. Must match the +/// following regular expression: `[a-zA-Z0-9-_.~%]{1,900}`. +Future Unsubscribe(const char* topic); + +/// @brief Gets the result of the most recent call to Unsubscribe(); +/// +/// @return Result of the most recent call to Unsubscribe(). +Future UnsubscribeLastResult(); + +/// Determines whether Firebase Cloud Messaging exports message delivery metrics +/// to BigQuery. +/// +/// This function is currently only implemented on Android, and returns false +/// with no other behavior on other platforms. +/// +/// @return true if Firebase Cloud Messaging exports message delivery metrics to +/// BigQuery. +bool DeliveryMetricsExportToBigQueryEnabled(); + +/// Enables or disables Firebase Cloud Messaging message delivery metrics export +/// to BigQuery. +/// +/// By default, message delivery metrics are not exported to BigQuery. Use this +/// method to enable or disable the export at runtime. In addition, you can +/// enable the export by adding to your manifest. Note that the run-time method +/// call will override the manifest value. +/// +/// +/// +/// This function is currently only implemented on Android, and has no behavior +/// on other platforms. +/// +/// @param[in] enable Whether Firebase Cloud Messaging should export message +/// delivery metrics to BigQuery. +void SetDeliveryMetricsExportToBigQuery(bool enable); + +/// @brief This creates a Firebase Installations ID, if one does not exist, and +/// sends information about the application and the device where it's running to +/// the Firebase backend. +/// +/// @return A future with the token. +Future GetToken(); + +/// @brief Gets the result of the most recent call to GetToken(); +/// +/// @return Result of the most recent call to GetToken(). +Future GetTokenLastResult(); + +/// @brief Deletes the default token for this Firebase project. +/// +/// Note that this does not delete the Firebase Installations ID that may have +/// been created when generating the token. See Installations.Delete() for +/// deleting that. +/// +/// @return A future that completes when the token is deleted. +Future DeleteToken(); + +/// @brief Gets the result of the most recent call to DeleteToken(); +/// +/// @return Result of the most recent call to DeleteToken(). +Future DeleteTokenLastResult(); + +class PollableListenerImpl; + +/// @brief A listener that can be polled to consume pending `Message`s. +/// +/// This class is intended to be used with applications that have a main loop +/// that frequently updates, such as in the case of a game that has a main +/// loop that updates 30 to 60 times a second. Rather than respond to incoming +/// messages and tokens via the `OnMessage` virtual function, this class will +/// queue up the message internally in a thread-safe manner so that it can be +/// consumed with `PollMessage`. For example: +/// +/// ::firebase::messaging::PollableListener listener; +/// ::firebase::messaging::Initialize(app, &listener); +/// +/// while (true) { +/// std::string token; +/// if (listener.PollRegistrationToken(&token)) { +/// LogMessage("Received a registration token"); +/// } +/// +/// ::firebase::messaging::Message message; +/// while (listener.PollMessage(&message)) { +/// LogMessage("Received a new message"); +/// } +/// +/// // Remainder of application logic... +/// } +class PollableListener : public Listener { + public: + /// @brief The default constructor. + PollableListener(); + + /// @brief The required virtual destructor. + virtual ~PollableListener(); + + /// @brief An implementation of `OnMessage` which adds the incoming messages + /// to a queue, which can be consumed by calling `PollMessage`. + virtual void OnMessage(const Message& message); + + /// @brief An implementation of `OnTokenReceived` which stores the incoming + /// token so that it can be consumed by calling `PollRegistrationToken`. + virtual void OnTokenReceived(const char* token); + + /// @brief Returns the first message queued up, if any. + /// + /// If one or more messages has been received, the first message in the + /// queue will be popped and used to populate the `message` argument and the + /// function will return `true`. If there are no pending messages, `false` is + /// returned. This function should be called in a loop until all messages have + /// been consumed, like so: + /// + /// ::firebase::messaging::Message message; + /// while (listener.PollMessage(&message)) { + /// LogMessage("Received a new message"); + /// } + /// + /// @param[out] message The `Message` struct to be populated. If there were no + /// pending messages, `message` is not modified. + /// + /// @return Returns `true` if there was a pending message, `false` otherwise. + bool PollMessage(Message* message); + + /// @brief Returns the registration key, if a new one has been received. + /// + /// When a new registration token is received, it is cached internally and can + /// be retrieved by calling `PollRegistrationToken`. The cached registration + /// token will be used to populate the `token` argument, then the cache will + /// be cleared and the function will return `true`. If there is no cached + /// registration token this function retuns `false`. + /// + /// std::string token; + /// if (listener.PollRegistrationToken(&token)) { + /// LogMessage("Received a registration token"); + /// } + /// + /// @param[out] token A string to be populated with the new token if one has + /// been received. If there were no new token, the string is left unmodified. + /// + /// @return Returns `true` if there was a new token, `false` otherwise. + bool PollRegistrationToken(std::string* token) { + bool got_token; + std::string token_received = PollRegistrationToken(&got_token); + if (got_token) { + *token = token_received; + } + return got_token; + } + + private: + std::string PollRegistrationToken(bool* got_token); + + // The implementation of the `PollableListener`. + PollableListenerImpl* impl_; +}; + +} // namespace messaging +} // namespace firebase + +#endif // FIREBASE_MESSAGING_SRC_INCLUDE_FIREBASE_MESSAGING_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/remote_config.h b/packages/firebase_core/firebase_core/firebase_core/firebase/remote_config.h new file mode 100644 index 000000000000..a2bd41775775 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/remote_config.h @@ -0,0 +1,526 @@ +// Copyright 2016 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef FIREBASE_REMOTE_CONFIG_SRC_INCLUDE_FIREBASE_REMOTE_CONFIG_H_ +#define FIREBASE_REMOTE_CONFIG_SRC_INCLUDE_FIREBASE_REMOTE_CONFIG_H_ + +#include +#include +#include + +#include "firebase/app.h" +#include "firebase/future.h" +#include "firebase/internal/common.h" +#include "firebase/internal/platform.h" +#ifndef SWIG +#include "firebase/variant.h" +#endif // SWIG + +#if !defined(DOXYGEN) && !defined(SWIG) +FIREBASE_APP_REGISTER_CALLBACKS_REFERENCE(remote_config) +#endif // !defined(DOXYGEN) && !defined(SWIG) + +/// @brief Namespace that encompasses all Firebase APIs. +namespace firebase { + +#ifndef SWIG +/// @brief Firebase Remote Config API. +/// +/// Firebase Remote Config is a cloud service that lets you change the +/// appearance and behavior of your app without requiring users to download an +/// app update. +#endif // SWIG +namespace remote_config { + +/// @brief Describes the most recent fetch request status. +enum LastFetchStatus { + /// The most recent fetch was a success, and its data is ready to be + /// applied, if you have not already done so. + kLastFetchStatusSuccess, + /// The most recent fetch request failed. + kLastFetchStatusFailure, + /// The most recent fetch is still in progress. + kLastFetchStatusPending, +}; + +/// @brief Describes the most recent fetch failure. +enum FetchFailureReason { + /// The fetch has not yet failed. + kFetchFailureReasonInvalid, + /// The most recent fetch failed because it was throttled by the server. + /// (You are sending too many fetch requests in too short a time.) + kFetchFailureReasonThrottled, + /// The most recent fetch failed for an unknown reason. + kFetchFailureReasonError, +}; + +/// @brief Describes the state of the most recent Fetch() call. +/// Normally returned as a result of the GetInfo() function. +struct ConfigInfo { + /// @brief The time (in milliseconds since the epoch) that the last fetch + /// operation completed. + uint64_t fetch_time; + + /// @brief The status of the last fetch request. + LastFetchStatus last_fetch_status; + + /// @brief The reason the most recent fetch failed. + FetchFailureReason last_fetch_failure_reason; + + /// @brief The time (in milliseconds since the epoch) when the refreshing of + /// Remote Config data is throttled. + uint64_t throttled_end_time; +}; + +/// @brief Describes the source a config value was retrieved from. +enum ValueSource { + /// The value was not specified and no default was specified, so a static + /// value (0 for numeric values, an empty string for strings) was returned. + kValueSourceStaticValue, + /// The value was found in the remote data store, and returned. + kValueSourceRemoteValue, + /// The value was not specified, so the specified default value was + /// returned instead. + kValueSourceDefaultValue, +}; + +/// @brief Describes a retrieved value. +struct ValueInfo { + /// Where the config value was retrieved from (Default Config or Active + /// Config). + ValueSource source; + /// If true this indicates conversion to the requested type + /// succeeded, otherwise conversion failed so the static value for the + /// requested type was retrieved instead. + bool conversion_successful; +}; + +/// @brief Keys of API settings. +/// +/// @see SetConfigSetting +/// @see GetConfigSetting +enum ConfigSetting { + /// Set the value associated with this key to "1" to enable developer mode + /// (i.e disable throttling) and "0" to disable. + kConfigSettingDeveloperMode, +}; + +/// @brief The default cache expiration used by Fetch(), equal to 12 hours, +/// in milliseconds. +static const uint64_t kDefaultCacheExpiration = 60 * 60 * 12 * 1000; + +/// @brief The default timeout used by Fetch(), equal to 30 seconds, +/// in milliseconds. +static const uint64_t kDefaultTimeoutInMilliseconds = 30 * 1000; + +/// @brief Describes a mapping of a key to a string value. Used to set default +/// values. +struct ConfigKeyValue { + /// The lookup key string. +#ifndef SWIG + /// + /// @note Ensure this string stays valid for the duration of the + /// call to SetDefaults. +#endif // SWIG + const char* key; + /// The value string to be stored. +#ifndef SWIG + /// + /// @note Ensure this string stays valid for the duration of the + /// call to SetDefaults. +#endif // SWIG + const char* value; +}; + +#ifndef SWIG +/// @brief Describes a mapping of a key to a value of any type. Used to set +/// default values. +struct ConfigKeyValueVariant { + /// The lookup key string. + /// + /// @note Ensure this string stays valid for the duration of the + /// call to SetDefaults. + const char* key; + /// The value to be stored. The type of the Variant determines the type of + /// default data for the given key. + /// + /// @note If you use a Variant of type StaticString, ensure it stays + /// valid for the duration of the call to SetDefaults. + Variant value; +}; +#endif // SWIG + +/// @brief Configurations for Remote Config behavior. +struct ConfigSettings { + /// The timeout specifies how long the client should wait for a connection to + /// the Firebase Remote Config servers. + /// + /// @note A fetch call will fail if it takes longer than the specified timeout + /// to connect to the Remote Config servers. Default is 60 seconds. + uint64_t fetch_timeout_in_milliseconds = kDefaultTimeoutInMilliseconds; + + /// The minimum interval between successive fetch calls. + /// + /// @note Fetches less than duration seconds after the last fetch from the + /// Firebase Remote Config server would use values returned during the last + /// fetch. Default is 12 hours. + uint64_t minimum_fetch_interval_in_milliseconds = kDefaultCacheExpiration; +}; + +namespace internal { +class RemoteConfigInternal; +} // namespace internal + +#ifndef SWIG +/// @brief Entry point for the Firebase C++ SDK for Remote Config. +/// +/// To use the SDK, call firebase::remote_config::RemoteConfig::GetInstance() to +/// obtain an instance of RemoteConfig, then call operations on that instance. +/// The instance contains the complete set of FRC parameter values available to +/// your app. The instance also stores values fetched from the FRC Server until +/// they are made available for use with a call to @ref Activate(). +#endif // SWIG +class RemoteConfig { + public: + ~RemoteConfig(); + + /// @brief Returns a Future that contains ConfigInfo representing the + /// initialization status of this Firebase Remote Config instance. + /// Use this method to ensure Set/Get call not being blocked. + Future EnsureInitialized(); + + /// @brief Get the (possibly still pending) results of the most recent + /// EnsureInitialized() call. + /// + /// @return The future result from the last call to EnsureInitialized(). + Future EnsureInitializedLastResult(); + + /// Asynchronously activates the most recently fetched configs, so that the + /// fetched key value pairs take effect. + /// + /// @return A Future that contains true if fetched configs were + /// activated. The future will contain false if the configs were already + /// activated. + Future Activate(); + + /// @brief Get the (possibly still pending) results of the most recent + /// Activate() call. + /// + /// @return The future result from the last call to Activate(). + Future ActivateLastResult(); + + /// Asynchronously fetches and then activates the fetched configs. + /// + /// If the time elapsed since the last fetch from the Firebase Remote Config + /// backend is more than the default minimum fetch interval, configs are + /// fetched from the backend. + /// + /// After the fetch is complete, the configs are activated so that the fetched + /// key value pairs take effect. + /// + /// @return A Future that contains true if the current call + /// activated the fetched configs; if no configs were fetched from the backend + /// and the local fetched configs have already been activated, the future will + /// contain false. + Future FetchAndActivate(); + + /// @brief Get the (possibly still pending) results of the most recent + /// FetchAndActivate() call. + /// + /// @return The future result from the last call to FetchAndActivate(). + Future FetchAndActivateLastResult(); + + /// @brief Fetches config data from the server. + /// + /// @note This does not actually apply the data or make it accessible, + /// it merely retrieves it and caches it. To accept and access the newly + /// retrieved values, you must call @ref Activate(). + /// + /// Note that this function is asynchronous, and will normally take an + /// unspecified amount of time before completion. + /// + /// @return A Future which can be used to determine when the fetch is + /// complete. + Future Fetch(); + + /// @brief Fetches config data from the server. + /// + /// @note This does not actually apply the data or make it accessible, + /// it merely retrieves it and caches it. To accept and access the newly + /// retrieved values, you must call @ref Activate(). + /// Note that this function is asynchronous, and will normally take an + /// unspecified amount of time before completion. + /// + /// @param[in] cache_expiration_in_seconds The number of seconds to keep + /// previously fetch data available. If cached data is available that is + /// newer than cache_expiration_in_seconds, then the function returns + /// immediately and does not fetch any data. A cache_expiration_in_seconds of + /// zero will always cause a fetch. + /// + /// @return A Future which can be used to determine when the fetch is + /// complete. + Future Fetch(uint64_t cache_expiration_in_seconds); + + /// @brief Get the (possibly still pending) results of the most recent Fetch() + /// call. + /// + /// @return The future result from the last call to Fetch(). + Future FetchLastResult(); + +#if defined(__ANDROID__) + /// @brief Sets the default values, using an XML resource. + /// + /// @note This method is specific to the Android implementation. + /// + /// This completely overwrites all previous default values. + /// + /// @param[in] defaults_resource_id Id for the XML resource, which should be + /// in your applications res/xml folder. + /// + /// @return a Future which can be used to determine when the operation is + /// complete. + Future SetDefaults(int defaults_resource_id); +#endif // __ANDROID__ + +#ifndef SWIG + /// @brief Sets the default values based on a mapping of string to Variant. + /// This allows you to specify defaults of type other than string. + /// + /// The type of each Variant in the map determines the type of data for which + /// you are providing a default. For example, boolean values can be retrieved + /// with GetBool(), integer values can be retrieved with GetLong(), double + /// values can be retrieved with GetDouble(), string values can be retrieved + /// with GetString(), and binary data can be retrieved with GetData(). + /// Aggregate Variant types are not allowed. + /// + /// @see firebase::Variant for more information on how to create a Variant of + /// each type. + /// + /// @note This completely overrides all previous values. + /// + /// @param defaults Array of ConfigKeyValueVariant, representing the new set + /// of defaults to apply. If the same key is specified multiple times, the + /// value associated with the last duplicate key is applied. + /// @param number_of_defaults Number of elements in the defaults array. + /// + /// @return a Future which can be used to determine when the operation is + /// complete. + Future SetDefaults(const ConfigKeyValueVariant* defaults, + size_t number_of_defaults); +#endif // SWIG + + /// @brief Sets the default values based on a string map. + /// + /// @note This completely overrides all previous values. + /// + /// @param defaults Array of ConfigKeyValue, representing the new set of + /// defaults to apply. If the same key is specified multiple times, the + /// value associated with the last duplicate key is applied. + /// @param number_of_defaults Number of elements in the defaults array. + /// + /// @return a Future which can be used to determine when the operation is + /// complete. + Future SetDefaults(const ConfigKeyValue* defaults, + size_t number_of_defaults); + + /// @brief Get the (possibly still pending) results of the most recent + /// SetDefaults() call. + /// + /// @return The future result from the last call to SetDefaults(). + Future SetDefaultsLastResult(); + + /// @brief Asynchronously changes the settings for this Remote Config + /// instance. + /// + /// @param settings The new settings to be applied. + /// + /// @return a Future which can be used to determine when the operation is + /// complete. + Future SetConfigSettings(ConfigSettings settings); + + /// @brief Gets the current settings of the RemoteConfig object. + /// + /// @return A ConfigSettings struct. + ConfigSettings GetConfigSettings(); + + /// @brief Get the (possibly still pending) results of the most recent + /// SetConfigSettings() call. + /// + /// @return The future result from the last call to SetConfigSettings(). + Future SetConfigSettingsLastResult(); + + /// @brief Returns the value associated with a key, converted to a bool. + /// + /// Values of "1", "true", "t", "yes", "y" and "on" are interpreted (case + /// insensitive) as true and "0", "false", "f", "no", "n", "off", + /// and empty strings are interpreted (case insensitive) as + /// false. + /// + /// @param[in] key Key of the value to be retrieved. + /// + /// @return Value associated with the specified key converted to a boolean + /// value. + bool GetBoolean(const char* key); + + /// @brief Returns the value associated with a key, converted to a bool. + /// + /// Values of "1", "true", "t", "yes", "y" and "on" are interpreted (case + /// insensitive) as true and "0", "false", "f", "no", "n", "off", + /// and empty strings are interpreted (case insensitive) as + /// false. + /// + /// @param[in] key Key of the value to be retrieved. + /// @param[out] info A return value, specifying the source of the returned + /// value. + /// + /// @return Value associated with the specified key converted to a boolean + /// value. + bool GetBoolean(const char* key, ValueInfo* info); + + /// @brief Returns the value associated with a key, converted to a 64-bit + /// integer. + /// + /// @param[in] key Key of the value to be retrieved. + /// + /// @return Value associated with the specified key converted to a 64-bit + /// integer. + int64_t GetLong(const char* key); + + /// @brief Returns the value associated with a key, converted to a 64-bit + /// integer. + /// + /// @param[in] key Key of the value to be retrieved. + /// @param[out] info A return value, specifying the source of the returned + /// value. + /// + /// @return Value associated with the specified key converted to a 64-bit + /// integer. + int64_t GetLong(const char* key, ValueInfo* info); + + /// @brief Returns the value associated with a key, converted to a double. + /// + /// @param[in] key Key of the value to be retrieved. + /// + /// @return Value associated with the specified key converted to a double. + double GetDouble(const char* key); + + /// @brief Returns the value associated with a key, converted to a double. + /// + /// @param[in] key Key of the value to be retrieved. + /// @param[out] info A return value, specifying the source of the returned + /// value. + /// + /// @return Value associated with the specified key converted to a double. + double GetDouble(const char* key, ValueInfo* info); + + /// @brief Returns the value associated with a key, converted to a string. + /// + /// @param[in] key Key of the value to be retrieved. + /// + /// @return Value as a string associated with the specified key. + std::string GetString(const char* key); + + /// @brief Returns the value associated with a key, converted to a string. + /// + /// @param[in] key Key of the value to be retrieved. + /// @param[out] info A return value, specifying the source of the returned + /// value. + /// + /// @return Value as a string associated with the specified key. + std::string GetString(const char* key, ValueInfo* info); + + /// @brief Returns the value associated with a key, as a vector of raw + /// byte-data. + /// + /// @param[in] key Key of the value to be retrieved. + /// + /// @return Vector of bytes. + std::vector GetData(const char* key); + + /// @brief Returns the value associated with a key, as a vector of raw + /// byte-data. + /// + /// @param[in] key Key of the value to be retrieved. + /// @param[out] info A return value, specifying the source of the returned + /// value. + /// + /// @return Vector of bytes. + std::vector GetData(const char* key, ValueInfo* info); + + /// @brief Gets the set of keys that start with the given prefix. + /// + /// @param[in] prefix The key prefix to look for. If empty or null, this + /// method will return all keys. + /// + /// @return Set of Remote Config parameter keys that start with the specified + /// prefix. Will return an empty set if there are no keys with the given + /// prefix. + std::vector GetKeysByPrefix(const char* prefix); + + /// @brief Gets the set of all keys. + /// + /// @return Set of all Remote Config parameter keys. + std::vector GetKeys(); + + /// @brief Returns a Map of Firebase Remote Config key value pairs. + /// + /// Evaluates the values of the parameters in the following order: + /// The activated value, if the last successful @ref Activate() contained the + /// key. The default value, if the key was set with @ref SetDefaults(). + std::map GetAll(); + + /// @brief Returns information about the last fetch request, in the form + /// of a ConfigInfo struct. + /// + /// @return A ConfigInfo struct, containing fields reflecting the state + /// of the most recent fetch request. + const ConfigInfo GetInfo(); + + /// Gets the App this remote config object is connected to. + App* app() { return app_; } + + /// Returns the RemoteConfig object for an App. Creates the RemoteConfig if + /// required. + /// + /// To get the RemoteConfig object for the default app, use, + /// GetInstance(GetDefaultFirebaseApp()); + /// + /// If the library RemoteConfig fails to initialize, init_result_out will be + /// written with the result status (if a pointer is given). + /// + /// @param[in] app The App to use for the RemoteConfig object. + static RemoteConfig* GetInstance(App* app); + + private: + explicit RemoteConfig(App* app); + + // Find RemoteConfig instance using App. Return null if the instance does not + // exist. + static RemoteConfig* FindRemoteConfig(App* app); + + // Clean up RemoteConfig instance. + void DeleteInternal(); + + /// The Firebase App this remote config is connected to. + App* app_; + + bool InitInternal(); + + internal::RemoteConfigInternal* internal_; +}; + +} // namespace remote_config +} // namespace firebase + +#endif // FIREBASE_REMOTE_CONFIG_SRC_INCLUDE_FIREBASE_REMOTE_CONFIG_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/storage.h b/packages/firebase_core/firebase_core/firebase_core/firebase/storage.h new file mode 100644 index 000000000000..8d081e4c0ead --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/storage.h @@ -0,0 +1,161 @@ +// Copyright 2016 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_H_ +#define FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_H_ + +#include + +#include "firebase/app.h" +#include "firebase/internal/common.h" +#include "firebase/storage/common.h" +#include "firebase/storage/controller.h" +#include "firebase/storage/listener.h" +#include "firebase/storage/metadata.h" +#include "firebase/storage/storage_reference.h" + +#if !defined(DOXYGEN) +#ifndef SWIG +FIREBASE_APP_REGISTER_CALLBACKS_REFERENCE(storage) +#endif // SWIG +#endif // !defined(DOXYGEN) + +namespace firebase { + +/// Namespace for the Firebase C++ SDK for Cloud Storage. +namespace storage { + +namespace internal { +class StorageInternal; +class MetadataInternal; +} // namespace internal + +class StorageReference; + +#ifndef SWIG +/// @brief Entry point for the Firebase C++ SDK for Cloud Storage. +/// +/// To use the SDK, call firebase::storage::Storage::GetInstance() to +/// obtain an instance of Storage, then use GetReference() to obtain references +/// to child blobs. From there you can upload data with +/// StorageReference::PutStream(), get data via StorageReference::GetStream(). +#endif // SWIG +class Storage { + public: + /// @brief Destructor. You may delete an instance of Storage when + /// you are finished using it, to shut down the Storage library. + ~Storage(); + + /// @brief Get an instance of Storage corresponding to the given App. + /// + /// Cloud Storage uses firebase::App to communicate with Firebase + /// Authentication to authenticate users to the server backend. + /// + /// @param[in] app An instance of firebase::App. Cloud Storage will use + /// this to communicate with Firebase Authentication. + /// @param[out] init_result_out Optional: If provided, write the init result + /// here. Will be set to kInitResultSuccess if initialization succeeded, or + /// kInitResultFailedMissingDependency on Android if Google Play services is + /// not available on the current device. + /// + /// @returns An instance of Storage corresponding to the given App. + static Storage* GetInstance(::firebase::App* app, + InitResult* init_result_out = nullptr); + + /// @brief Get an instance of Storage corresponding to the given App, + /// with the given Cloud Storage URL. + /// + /// Cloud Storage uses firebase::App to communicate with Firebase + /// Authentication to authenticate users to the server backend. + /// + /// @param[in] app An instance of firebase::App. Cloud Storage will use + /// this to communicate with Firebase Authentication. + /// @param[in] url Cloud Storage URL. + /// @param[out] init_result_out Optional: If provided, write the init result + /// here. Will be set to kInitResultSuccess if initialization succeeded, or + /// kInitResultFailedMissingDependency on Android if Google Play services is + /// not available on the current device. + /// + /// @returns An instance of Storage corresponding to the given App. + static Storage* GetInstance(::firebase::App* app, const char* url, + InitResult* init_result_out = nullptr); + + /// @brief Get the firease::App that this Storage was created with. + /// + /// @returns The firebase::App this Storage was created with. + ::firebase::App* app(); + + /// @brief Get the URL that this Storage was created with. + /// + /// @returns The URL this Storage was created with, or an empty + /// string if this Storage was created with default parameters. + std::string url(); + + /// @brief Get a StorageReference to the root of the database. + StorageReference GetReference() const; + + /// @brief Get a StorageReference for the specified path. + StorageReference GetReference(const char* path) const; + /// @brief Get a StorageReference for the specified path. + StorageReference GetReference(const std::string& path) const { + return GetReference(path.c_str()); + } + + /// @brief Get a StorageReference for the provided URL. + StorageReference GetReferenceFromUrl(const char* url) const; + /// @brief Get a StorageReference for the provided URL. + StorageReference GetReferenceFromUrl(const std::string& url) const { + return GetReferenceFromUrl(url.c_str()); + } + + /// @brief Returns the maximum time in seconds to retry a download if a + /// failure occurs. + double max_download_retry_time(); + /// @brief Sets the maximum time to retry a download if a failure occurs. + /// Defaults to 600 seconds (10 minutes). + void set_max_download_retry_time(double max_transfer_retry_seconds); + + /// @brief Returns the maximum time to retry an upload if a failure occurs. + double max_upload_retry_time(); + /// @brief Sets the maximum time to retry an upload if a failure occurs. + /// Defaults to 600 seconds (10 minutes). + void set_max_upload_retry_time(double max_transfer_retry_seconds); + + /// @brief Returns the maximum time to retry operations other than upload + /// and download if a failure occurs. + double max_operation_retry_time(); + /// @brief Sets the maximum time to retry operations other than upload and + /// download if a failure occurs. Defaults to 120 seconds (2 minutes). + void set_max_operation_retry_time(double max_transfer_retry_seconds); + + private: + /// @cond FIREBASE_APP_INTERNAL + friend class Metadata; + friend class internal::MetadataInternal; + + Storage(::firebase::App* app, const char* url); + Storage(const Storage& src); + Storage& operator=(const Storage& src); + + // Destroy the internal_ object. + void DeleteInternal(); + + internal::StorageInternal* internal_; + /// @endcond +}; + +} // namespace storage +} // namespace firebase + +#endif // FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/storage/common.h b/packages/firebase_core/firebase_core/firebase_core/firebase/storage/common.h new file mode 100644 index 000000000000..567ed714920c --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/storage/common.h @@ -0,0 +1,62 @@ +// Copyright 2016 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_COMMON_H_ +#define FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_COMMON_H_ + +namespace firebase { +namespace storage { + +/// Error code returned by Cloud Storage C++ functions. +enum Error { + /// The operation was a success, no error occurred. + kErrorNone = 0, + /// An unknown error occurred. + kErrorUnknown, + /// No object exists at the desired reference. + kErrorObjectNotFound, + /// No bucket is configured for Cloud Storage. + kErrorBucketNotFound, + /// No project is configured for Cloud Storage. + kErrorProjectNotFound, + /// Quota on your Cloud Storage bucket has been exceeded. + kErrorQuotaExceeded, + /// User is unauthenticated. + kErrorUnauthenticated, + /// User is not authorized to perform the desired action. + kErrorUnauthorized, + /// The maximum time limit on an operation (upload, download, delete, etc.) + /// has been exceeded. + kErrorRetryLimitExceeded, + /// File on the client does not match the checksum of the file received by the + /// server. + kErrorNonMatchingChecksum, + /// Size of the downloaded file exceeds the amount of memory allocated for the + /// download. + kErrorDownloadSizeExceeded, + /// User cancelled the operation. + kErrorCancelled, +}; + +/// @brief Get the human-readable error message corresponding to an error code. +/// +/// @param[in] error Error code to get the error message for. +/// +/// @returns Statically-allocated string describing the error. +const char* GetErrorMessage(Error error); + +} // namespace storage +} // namespace firebase + +#endif // FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_COMMON_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/storage/controller.h b/packages/firebase_core/firebase_core/firebase_core/firebase/storage/controller.h new file mode 100644 index 000000000000..42f29aa0c73b --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/storage/controller.h @@ -0,0 +1,146 @@ +// Copyright 2016 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_CONTROLLER_H_ +#define FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_CONTROLLER_H_ + +#include "firebase/storage/storage_reference.h" + +namespace firebase { +namespace storage { + +/// @cond FIREBASE_APP_INTERNAL +namespace internal { +class ControllerInternal; +class ListenerInternal; +class RestOperation; +} // namespace internal +/// @endcond + +/// @brief Controls an ongoing operation, allowing the caller to Pause, Resume +/// or Cancel an ongoing download or upload. +/// +/// An instance of Controller can be constructed and passed to +/// StorageReference::GetBytes(), StorageReference::GetFile(), +/// StorageReference::PutBytes(), or StorageReference::PutFile() to become +/// associated with it. Each Controller can only be associated with one +/// operation at a time. +/// +/// A Controller is also passed as an argument to Listener's callbacks. The +/// Controller passed to a StorageReference operation is not the same object +/// passed to Listener callbacks (though it refers to the same operation), so +/// there are no restrictions on the lifetime of the Controller the user creates +/// (but the Controller passed into a Listener callbacks should only be used +/// from within that callback). +/// +/// This class is currently not thread safe and can only be called on the main +/// thread. +class Controller { + public: + /// @brief Default constructor. + /// + /// You may construct your own Controller to pass into various + /// StorageReference operations. + Controller(); + + /// @brief Destructor. + ~Controller(); + + /// @brief Copy constructor. + /// + /// @param[in] other Controller to copy from. + Controller(const Controller& other); + + /// @brief Copy assignment operator. + /// + /// @param[in] other Controller to copy from. + /// + /// @returns Reference to the destination Controller. + Controller& operator=(const Controller& other); + +#if defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) + /// @brief Move constructor. Moving is an efficient operation for + /// Controller instances. + /// + /// @param[in] other Controller to move from. + Controller(Controller&& other); + + /// @brief Move assignment operator. Moving is an efficient operation for + /// Controller instances. + /// + /// @param[in] other Controller to move from. + /// + /// @returns Reference to the destination Controller. + Controller& operator=(Controller&& other); +#endif // defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) + + /// @brief Pauses the operation currently in progress. + /// + /// @returns True if the operation was successfully paused, false otherwise. + bool Pause(); + + /// @brief Resumes the operation that is paused. + /// + /// @returns True if the operation was successfully resumed, false otherwise. + bool Resume(); + + /// @brief Cancels the operation currently in progress. + /// + /// @returns True if the operation was successfully canceled, false otherwise. + bool Cancel(); + + /// @brief Returns true if the operation is paused. + bool is_paused() const; + + /// @brief Returns the number of bytes transferred so far. + /// + /// @returns The number of bytes transferred so far. + int64_t bytes_transferred() const; + + /// @brief Returns the total bytes to be transferred. + /// + /// @returns The total bytes to be transferred. This will return -1 if + /// the size of the transfer is unknown. + int64_t total_byte_count() const; + + /// @brief Returns the StorageReference associated with this Controller. + /// + /// @returns The StorageReference associated with this Controller. + StorageReference GetReference() const; + + /// @brief Returns true if this Controller is valid, false if it is not + /// valid. An invalid Controller is one that is not associated with an + /// operation. + /// + /// @returns true if this Controller is valid, false if this Controller is + /// invalid. + bool is_valid() const; + + private: + /// @cond FIREBASE_APP_INTERNAL + friend class internal::StorageReferenceInternal; + friend class internal::ControllerInternal; + friend class internal::ListenerInternal; + friend class internal::RestOperation; + + Controller(internal::ControllerInternal* internal); + + internal::ControllerInternal* internal_; + /// @endcond +}; + +} // namespace storage +} // namespace firebase + +#endif // FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_CONTROLLER_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/storage/listener.h b/packages/firebase_core/firebase_core/firebase_core/firebase/storage/listener.h new file mode 100644 index 000000000000..8bd624f61537 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/storage/listener.h @@ -0,0 +1,74 @@ +// Copyright 2016 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_LISTENER_H_ +#define FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_LISTENER_H_ + +#include "firebase/storage/controller.h" + +namespace firebase { +namespace storage { + +/// @cond FIREBASE_APP_INTERNAL +namespace internal { +class ListenerInternal; +class StorageInternal; +class StorageReferenceInternal; +class RestOperation; +} // namespace internal +/// @endcond + +/// @brief Base class used to receive pause and progress events on a running +/// read or write operation. +/// +/// Subclasses of this listener class can be used to receive events about data +/// transfer progress a location. Attach the listener to a location using +/// StorageReference::GetBytes(), StorageReference::GetFile(), +/// StorageReference::PutBytes(), and StorageReference::PutFile(); then +/// OnPaused() will be called whenever the Read or Write operation is paused, +/// and OnProgress() will be called periodically as the transfer makes progress. +class Listener { + public: + /// @brief Constructor. + Listener(); + + /// @brief Virtual destructor. + virtual ~Listener(); + + /// @brief The operation was paused. + /// + /// @param[in] controller A controller that can be used to check the status + /// and make changes to the ongoing operation. + virtual void OnPaused(Controller* controller) = 0; + + /// @brief There has been progress event. + /// + /// @param[in] controller A controller that can be used to check the status + /// and make changes to the ongoing operation. + virtual void OnProgress(Controller* controller) = 0; + + private: + /// @cond FIREBASE_APP_INTERNAL + friend class internal::StorageReferenceInternal; + friend class internal::RestOperation; + + // Platform specific data. + internal::ListenerInternal* impl_; + /// @endcond +}; + +} // namespace storage +} // namespace firebase + +#endif // FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_LISTENER_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/storage/metadata.h b/packages/firebase_core/firebase_core/firebase_core/firebase/storage/metadata.h new file mode 100644 index 000000000000..8d697c1072e7 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/storage/metadata.h @@ -0,0 +1,276 @@ +// Copyright 2016 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_METADATA_H_ +#define FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_METADATA_H_ + +#include +#include +#include +#include + +#include "firebase/internal/common.h" + +namespace firebase { +namespace storage { + +namespace internal { +class MetadataInternal; +class MetadataInternalCommon; +class StorageInternal; +class StorageReferenceInternal; +} // namespace internal + +class Storage; +class StorageReference; + +/// @brief Metadata stores default attributes such as size and content type. +/// +/// Metadata for a StorageReference. You may also store custom metadata key +/// value pairs. Metadata values may be used to authorize operations using +/// declarative validation rules. +class Metadata { + public: + /// @brief Create a default Metadata that you can modify and use. + Metadata(); + +#ifdef INTERNAL_EXPERIMENTAL + Metadata(internal::MetadataInternal* internal); +#endif + + /// @brief Copy constructor. + /// + /// @param[in] other Metadata to copy from. + Metadata(const Metadata& other); + + /// @brief Copy assignment operator. + /// + /// @param[in] other Metadata to copy from. + /// + /// @returns Reference to the destination Metadata. + Metadata& operator=(const Metadata& other); + +#if defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) + /// @brief Move constructor. Moving is an efficient operation for Metadata. + /// + /// @param[in] other Metadata to move from. + Metadata(Metadata&& other); + + /// @brief Move assignment operator. Moving is an efficient operation for + /// Metadata. + /// + /// @param[in] other Metadata to move from. + /// + /// @returns Reference to the destination Metadata. + Metadata& operator=(Metadata&& other); +#endif // defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) + + ~Metadata(); + + /// @brief Return the owning Google Cloud Storage bucket for the + /// StorageReference. + /// + /// @returns The owning Google Cloud Storage bucket for the StorageReference. + const char* bucket() const; + + /// @brief Set the Cache Control setting of the StorageReference. + /// + /// @see https://tools.ietf.org/html/rfc7234#section-5.2 + void set_cache_control(const char* cache_control); + + /// @brief Set the Cache Control setting of the StorageReference. + /// + /// @see https://tools.ietf.org/html/rfc7234#section-5.2 + void set_cache_control(const std::string& cache_control) { + set_cache_control(cache_control.c_str()); + } + + /// @brief Return the Cache Control setting of the StorageReference. + /// + /// @returns The Cache Control setting of the StorageReference. + /// + /// @see https://tools.ietf.org/html/rfc7234#section-5.2 + const char* cache_control() const; + + /// @brief Set the content disposition of the StorageReference. + /// + /// @see https://tools.ietf.org/html/rfc6266 + void set_content_disposition(const char* disposition); + + /// @brief Set the content disposition of the StorageReference. + /// + /// @see https://tools.ietf.org/html/rfc6266 + void set_content_disposition(const std::string& disposition) { + set_content_disposition(disposition.c_str()); + } + + /// @brief Return the content disposition of the StorageReference. + /// + /// @returns The content disposition of the StorageReference. + /// + /// @see https://tools.ietf.org/html/rfc6266 + const char* content_disposition() const; + + /// @brief Set the content encoding for the StorageReference. + /// + /// @see https://tools.ietf.org/html/rfc2616#section-14.11 + void set_content_encoding(const char* encoding); + + /// @brief Set the content encoding for the StorageReference. + /// + /// @see https://tools.ietf.org/html/rfc2616#section-14.11 + void set_content_encoding(const std::string& encoding) { + set_content_encoding(encoding.c_str()); + } + + /// @brief Return the content encoding for the StorageReference. + /// + /// @returns The content encoding for the StorageReference. + /// + /// @see https://tools.ietf.org/html/rfc2616#section-14.11 + const char* content_encoding() const; + + /// @brief Set the content language for the StorageReference. + /// + /// @see https://tools.ietf.org/html/rfc2616#section-14.12 + void set_content_language(const char* language); + + /// @brief Set the content language for the StorageReference. + /// + /// This must be an ISO 639-1 two-letter language code. + /// E.g. "zh", "es", "en". + /// + /// @see https://www.loc.gov/standards/iso639-2/php/code_list.php + void set_content_language(const std::string& language) { + set_content_language(language.c_str()); + } + + /// @brief Return the content language for the StorageReference. + /// + /// @returns The content language for the StorageReference. + /// + /// @see https://tools.ietf.org/html/rfc2616#section-14.12 + const char* content_language() const; + + /// @brief Set the content type of the StorageReference. + /// + /// @see https://tools.ietf.org/html/rfc2616#section-14.17 + void set_content_type(const char* type); + + /// @brief Set the content type of the StorageReference. + /// + /// @see https://tools.ietf.org/html/rfc2616#section-14.17 + void set_content_type(const std::string& type) { + set_content_type(type.c_str()); + } + + /// @brief Return the content type of the StorageReference. + /// + /// @returns The content type of the StorageReference. + /// + /// @see https://tools.ietf.org/html/rfc2616#section-14.17 + const char* content_type() const; + + /// @brief Return the time the StorageReference was created in milliseconds + /// since the epoch. + /// + /// @returns The time the StorageReference was created in milliseconds since + /// the epoch. + int64_t creation_time() const; + + /// @brief Return a map of custom metadata key value pairs. + /// + /// The pointer returned is only valid during the lifetime of the Metadata + /// object that owns it. + /// + /// @returns The keys for custom metadata. + std::map* custom_metadata() const; + + // download_url() and download_urls() are deprecated and removed. + // Please use StorageReference::GetDownloadUrl() instead. + + /// @brief Return a version String indicating what version of the + /// StorageReference. + /// + /// @returns A value indicating the version of the StorageReference. + int64_t generation() const; + + /// @brief Return a version String indicating the version of this + /// StorageMetadata. + /// + /// @returns A value indicating the version of this StorageMetadata. + int64_t metadata_generation() const; + + /// @brief Return a simple name of the StorageReference object. + /// + /// @returns A simple name of the StorageReference object. + const char* name() const; + + /// @brief Return the path of the StorageReference object. + /// + /// @returns The path of the StorageReference object. + const char* path() const; + + /// @brief Return the associated StorageReference to which this Metadata + /// belongs. + /// + /// @returns The associated StorageReference to which this Metadata belongs. + /// If this Metadata is invalid or is not associated with any file, an invalid + /// StorageReference is returned. + StorageReference GetReference() const; + + /// @brief Return the stored Size in bytes of the StorageReference object. + /// + /// @returns The stored Size in bytes of the StorageReference object. + int64_t size_bytes() const; + + /// @brief Return the time the StorageReference was last updated in + /// milliseconds since the epoch. + /// + /// @return The time the StorageReference was last updated in milliseconds + /// since the epoch. + int64_t updated_time() const; + + /// @brief Returns true if this Metadata is valid, false if it is not + /// valid. An invalid Metadata is returned when a method such as + /// StorageReference::GetMetadata() completes with an error. + /// + /// @returns true if this Metadata is valid, false if this Metadata is + /// invalid. + bool is_valid() const; + + /// @brief MD5 hash of the data; encoded using base64. + /// + /// @returns MD5 hash of the data; encoded using base64. + const char* md5_hash() const; + + private: + /// @cond FIREBASE_APP_INTERNAL + friend class StorageReference; + friend class internal::MetadataInternal; + friend class internal::MetadataInternalCommon; + friend class internal::StorageReferenceInternal; + +#ifndef INTERNAL_EXPERIMENTAL + Metadata(internal::MetadataInternal* internal); +#endif + + internal::MetadataInternal* internal_; + /// @endcond +}; + +} // namespace storage +} // namespace firebase + +#endif // FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_METADATA_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/storage/storage_reference.h b/packages/firebase_core/firebase_core/firebase_core/firebase/storage/storage_reference.h new file mode 100644 index 000000000000..e5c7c2f85ae6 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/storage/storage_reference.h @@ -0,0 +1,361 @@ +// Copyright 2016 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_STORAGE_REFERENCE_H_ +#define FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_STORAGE_REFERENCE_H_ + +#include +#include + +#include "firebase/future.h" +#include "firebase/internal/common.h" +#include "firebase/storage/metadata.h" + +namespace firebase { +namespace storage { + +class Controller; +class Listener; +class Storage; + +/// @cond FIREBASE_APP_INTERNAL +namespace internal { +class ControllerInternal; +class MetadataInternal; +class StorageInternal; +class StorageReferenceInternalCommon; +class StorageReferenceInternal; +} // namespace internal +/// @endcond FIREBASE_APP_INTERNAL + +#ifndef SWIG +/// Represents a reference to a Cloud Storage object. +/// Developers can upload and download objects, get/set object metadata, and +/// delete an object at a specified path. +#endif // SWIG +class StorageReference { + public: + /// @brief Default constructor. This creates an invalid StorageReference. + /// Attempting to perform any operations on this reference will fail unless a + /// valid StorageReference has been assigned to it. + StorageReference() : internal_(nullptr) {} + + ~StorageReference(); + + /// @brief Copy constructor. It's totally okay (and efficient) to copy + /// StorageReference instances, as they simply point to the same location. + /// + /// @param[in] reference StorageReference to copy from. + StorageReference(const StorageReference& reference); + + /// @brief Copy assignment operator. It's totally okay (and efficient) to copy + /// StorageReference instances, as they simply point to the same location. + /// + /// @param[in] reference StorageReference to copy from. + /// + /// @returns Reference to the destination StorageReference. + StorageReference& operator=(const StorageReference& reference); + +#if defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) + /// @brief Move constructor. Moving is an efficient operation for + /// StorageReference instances. + /// + /// @param[in] other StorageReference to move data from. + StorageReference(StorageReference&& other); + + /// @brief Move assignment operator. Moving is an efficient operation for + /// StorageReference instances. + /// + /// @param[in] other StorageReference to move data from. + /// + /// @returns Reference to the destination StorageReference. + StorageReference& operator=(StorageReference&& other); +#endif // defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) + + /// @brief Gets the firebase::storage::Storage instance to which we refer. + /// + /// The pointer will remain valid indefinitely. + /// + /// @returns The firebase::storage::Storage instance that this + /// StorageReference refers to. + Storage* storage(); + + /// @brief Gets a reference to a location relative to this one. + /// + /// @param[in] path Path relative to this reference's location. + /// The pointer only needs to be valid during this call. + /// + /// @returns Child relative to this location. + StorageReference Child(const char* path) const; + + /// @brief Gets a reference to a location relative to this one. + /// + /// @param[in] path Path relative to this reference's location. + /// + /// @returns Child relative to this location. + StorageReference Child(const std::string& path) const { + return Child(path.c_str()); + } + + /// @brief Deletes the object at the current path. + /// + /// @returns A Future result, which will complete when the operation either + /// succeeds or fails. When the Future is completed, if its Error is + /// kErrorNone, the operation succeeded. + Future Delete(); + + /// @brief Returns the result of the most recent call to RemoveValue(); + /// + /// @returns The result of the most recent call to RemoveValue(); + Future DeleteLastResult(); + + /// @brief Return the Google Cloud Storage bucket that holds this object. + /// + /// @returns The bucket. + std::string bucket(); + + /// @brief Return the full path of the storage reference, not including + /// the Google Cloud Storage bucket. + /// + /// @returns Full path to the storage reference, not including GCS bucket. + /// For example, for the reference "gs://bucket/path/to/object.txt", the full + /// path would be "path/to/object.txt". + std::string full_path(); + + /// @brief Asynchronously downloads the object from this StorageReference. + /// + /// A byte array will be allocated large enough to hold the entire file in + /// memory. Therefore, using this method will impact memory usage of your + /// process. + /// + /// @param[in] path Path to local file on device to download into. + /// @param[in] listener A listener that will respond to events on this read + /// operation. If not nullptr, a listener that will respond to events on this + /// read operation. The caller is responsible for allocating and deallocating + /// the listener. The same listener can be used for multiple operations. + /// @param[out] controller_out Controls the write operation, providing the + /// ability to pause, resume or cancel an ongoing write operation. If not + /// nullptr, this method will output a Controller here that you can use to + /// control the write operation. + /// + /// @returns A future that returns the number of bytes read. + Future GetFile(const char* path, Listener* listener = nullptr, + Controller* controller_out = nullptr); + + /// @brief Returns the result of the most recent call to GetFile(); + /// + /// @returns The result of the most recent call to GetFile(); + Future GetFileLastResult(); + + /// @brief Asynchronously downloads the object from this StorageReference. + /// + /// A byte array will be allocated large enough to hold the entire file in + /// memory. Therefore, using this method will impact memory usage of your + /// process. + /// + /// @param[in] buffer A byte buffer to read the data into. This buffer must + /// be valid for the duration of the transfer. + /// @param[in] buffer_size The size of the byte buffer. + /// @param[in] listener A listener that will respond to events on this read + /// operation. If not nullptr, a listener that will respond to events on this + /// read operation. The caller is responsible for allocating and deallocating + /// the listener. The same listener can be used for multiple operations. + /// @param[out] controller_out Controls the write operation, providing the + /// ability to pause, resume or cancel an ongoing write operation. If not + /// nullptr, this method will output a Controller here that you can use to + /// control the write operation. + /// + /// @returns A future that returns the number of bytes read. + Future GetBytes(void* buffer, size_t buffer_size, + Listener* listener = nullptr, + Controller* controller_out = nullptr); + + /// @brief Returns the result of the most recent call to GetBytes(); + /// + /// @returns The result of the most recent call to GetBytes(); + Future GetBytesLastResult(); + + /// @brief Asynchronously retrieves a long lived download URL with a revokable + /// token. + /// + /// This can be used to share the file with others, but can be revoked by a + /// developer in the Firebase Console if desired. + /// + /// @returns A Future result, which will complete when the operation either + /// succeeds or fails. When the Future is completed, if its Error is + /// kErrorNone, the operation succeeded and the URL is returned. + Future GetDownloadUrl(); + + /// @brief Returns the result of the most recent call to GetDownloadUrl(); + /// + /// @returns The result of the most recent call to GetDownloadUrl(); + Future GetDownloadUrlLastResult(); + + /// @brief Retrieves metadata associated with an object at this + /// StorageReference. + /// + /// @returns A Future result, which will complete when the operation either + /// succeeds or fails. When the Future is completed, if its Error is + /// kErrorNone, the operation succeeded and the Metadata is returned. + Future GetMetadata(); + + /// @brief Returns the result of the most recent call to GetMetadata(); + /// + /// @returns The result of the most recent call to GetMetadata(); + Future GetMetadataLastResult(); + + /// @brief Updates the metadata associated with this StorageReference. + /// + /// @returns A Future result, which will complete when the operation either + /// succeeds or fails. When the Future is completed, if its Error is + /// kErrorNone, the operation succeeded and the Metadata is returned. + Future UpdateMetadata(const Metadata& metadata); + + /// @brief Returns the result of the most recent call to UpdateMetadata(); + /// + /// @returns The result of the most recent call to UpdateMetadata(); + Future UpdateMetadataLastResult(); + + /// @brief Returns the short name of this object. + /// + /// @returns the short name of this object. + std::string name(); + + /// @brief Returns a new instance of StorageReference pointing to the parent + /// location or null if this instance references the root location. + /// + /// @returns The parent StorageReference. + StorageReference GetParent(); + + /// @brief Asynchronously uploads data to the currently specified + /// StorageReference, without additional metadata. + /// + /// @param[in] buffer A byte buffer to write data from. This buffer must be + /// valid for the duration of the transfer. + /// @param[in] buffer_size The size of the byte buffer. + /// @param[in] listener A listener that will respond to events on this read + /// operation. If not nullptr, a listener that will respond to events on this + /// write operation. The caller is responsible for allocating and deallocating + /// the listener. The same listener can be used for multiple operations. + /// @param[out] controller_out Controls the write operation, providing the + /// ability to pause, resume or cancel an ongoing write operation. If not + /// nullptr, this method will output a Controller here that you can use to + /// control the write operation. + /// + /// @returns A future that returns the Metadata. + Future PutBytes(const void* buffer, size_t buffer_size, + Listener* listener = nullptr, + Controller* controller_out = nullptr); + + /// @brief Asynchronously uploads data to the currently specified + /// StorageReference, without additional metadata. + /// + /// @param[in] buffer A byte buffer to write data from. This buffer must be + /// valid for the duration of the transfer. + /// @param[in] buffer_size The number of bytes to write. + /// @param[in] metadata Metadata containing additional information (MIME type, + /// etc.) about the object being uploaded. + /// @param[in] listener A listener that will respond to events on this read + /// operation. If not nullptr, a listener that will respond to events on this + /// write operation. The caller is responsible for allocating and deallocating + /// the listener. The same listener can be used for multiple operations. + /// @param[out] controller_out Controls the write operation, providing the + /// ability to pause, resume or cancel an ongoing write operation. If not + /// nullptr, this method will output a Controller here that you can use to + /// control the write operation. + /// + /// @returns A future that returns the Metadata. + Future PutBytes(const void* buffer, size_t buffer_size, + const Metadata& metadata, + Listener* listener = nullptr, + Controller* controller_out = nullptr); + + /// @brief Returns the result of the most recent call to PutBytes(); + /// + /// @returns The result of the most recent call to PutBytes(); + Future PutBytesLastResult(); + + /// @brief Asynchronously uploads data to the currently specified + /// StorageReference, without additional metadata. + /// + /// @param[in] path Path to local file on device to upload to Firebase + /// Storage. + /// @param[in] listener A listener that will respond to events on this read + /// operation. If not nullptr, a listener that will respond to events on this + /// write operation. The caller is responsible for allocating and deallocating + /// the listener. The same listener can be used for multiple operations. + /// @param[out] controller_out Controls the write operation, providing the + /// ability to pause, resume or cancel an ongoing write operation. If not + /// nullptr, this method will output a Controller here that you can use to + /// control the write operation. + /// + /// @returns A future that returns the Metadata. + Future PutFile(const char* path, Listener* listener = nullptr, + Controller* controller_out = nullptr); + + /// @brief Asynchronously uploads data to the currently specified + /// StorageReference, without additional metadata. + /// + /// @param[in] path Path to local file on device to upload to Firebase + /// Storage. + /// @param[in] metadata Metadata containing additional information (MIME type, + /// etc.) about the object being uploaded. + /// @param[in] listener A listener that will respond to events on this read + /// operation. If not nullptr, a listener that will respond to events on this + /// write operation. The caller is responsible for allocating and deallocating + /// the listener. The same listener can be used for multiple operations. + /// @param[out] controller_out Controls the write operation, providing the + /// ability to pause, resume or cancel an ongoing write operation. If not + /// nullptr, this method will output a Controller here that you can use to + /// control the write operation. + /// + /// @returns A future that returns the Metadata. + Future PutFile(const char* path, const Metadata& metadata, + Listener* listener = nullptr, + Controller* controller_out = nullptr); + + /// @brief Returns the result of the most recent call to PutFile(); + /// + /// @returns The result of the most recent call to PutFile(); + Future PutFileLastResult(); + + /// @brief Returns true if this StorageReference is valid, false if it is not + /// valid. An invalid StorageReference indicates that the reference is + /// uninitialized (created with the default constructor) or that there was an + /// error retrieving the reference. + /// + /// @returns true if this StorageReference is valid, false if this + /// StorageReference is invalid. + bool is_valid() const; + + private: + /// @cond FIREBASE_APP_INTERNAL + friend class Controller; + friend class internal::ControllerInternal; + friend class Metadata; + friend class internal::MetadataInternal; + friend class Storage; + friend class internal::StorageReferenceInternal; + friend class internal::StorageReferenceInternalCommon; + + StorageReference(internal::StorageReferenceInternal* internal); + + internal::StorageReferenceInternal* internal_; + /// @endcond +}; + +} // namespace storage +} // namespace firebase + +#endif // FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_STORAGE_REFERENCE_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/util.h b/packages/firebase_core/firebase_core/firebase_core/firebase/util.h new file mode 100644 index 000000000000..4c78d45f3ac8 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/util.h @@ -0,0 +1,101 @@ +/* + * Copyright 2016 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_APP_SRC_INCLUDE_FIREBASE_UTIL_H_ +#define FIREBASE_APP_SRC_INCLUDE_FIREBASE_UTIL_H_ + +#include "firebase/app.h" +#include "firebase/future.h" + +namespace firebase { + +struct ModuleInitializerData; + +/// @brief Utility class to help with initializing Firebase modules. +/// +/// This optional class handles a basic Firebase C++ SDK code pattern: attempt +/// to initialize a Firebase module, and if the initialization fails on Android +/// due to Google Play services being unavailable, prompt the user to +/// update/enable Google Play services on their device. +/// +/// If the developer wants more advanced behavior (for example, wait to prompt +/// the user to update or enable Google Play services until later, or opt not to +/// use Firebase modules), they can still initialize each Firebase module +/// individually, and use google_play_services::MakeAvailable() directly if any +/// initializations fail. +class ModuleInitializer { + public: + /// @brief Initialization function, which should initialize a single Firebase + /// module and return the InitResult. + typedef InitResult (*InitializerFn)(App* app, void* context); + + ModuleInitializer(); + virtual ~ModuleInitializer(); + + /// @brief Initialize Firebase modules by calling one or more user-supplied + /// functions, each of which must initialize at most one library, and should + /// return the InitResult of the initialization. + /// + /// This function will run the initializers in order, checking the return + /// value of each. On Android, if the InitResult returned is + /// kInitResultFailedMissingDependency, this indicates that Google Play + /// services is not available and a Firebase module requires it. This function + /// will attempt to fix Google Play services, and will retry initializations + /// where it left off, beginning with the one that failed. + /// + /// @returns A future result. When all of the initializers are completed, the + /// Future will be completed with Error() = 0. If an initializer fails and the + /// situation cannot be fixed, the Future will be completed with Error() equal + /// to the number of initializers that did not succeed (since they are run in + /// order, this tells you which ones failed). + /// + /// @param[in] app The firebase::App that will be passed to the initializers, + /// as well as used to fix Google Play services on Android if needed. + /// + /// @param[in] context User-defined context, which will be passed to the + /// initializer functions. If you don't need this, you can use nullptr. + /// + /// @param[in] init_fns Your initialization functions to call, in an array. At + /// their simplest, these will each simply call a single Firebase module's + /// Initialize(app) and return the result, but you can perform more complex + /// logic if you prefer. + /// + /// @param[in] init_fns_count Number of initialization functions in the + /// supplied array. + /// + /// @note If a pending Initialize() is already running, this function will + /// return the existing Future rather than adding any new functions to the + /// initializer list. + Future Initialize(App* app, void* context, + const InitializerFn* init_fns, size_t init_fns_count); + + /// @brief Initialize one Firebase module by calling a single user-supplied + /// function that should initialize a Firebase module and return the + /// InitResult. @see Initialize(::firebase::App*, void*, const InitializerFn*) + /// for more information. + Future Initialize(App* app, void* context, InitializerFn init_fn); + + /// @brief Get the result of the most recent call to @see Initialize(). + Future InitializeLastResult(); + + private: + ModuleInitializerData* data_; +}; + +// NOLINTNEXTLINE - allow namespace overridden +} // namespace firebase + +#endif // FIREBASE_APP_SRC_INCLUDE_FIREBASE_UTIL_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/variant.h b/packages/firebase_core/firebase_core/firebase_core/firebase/variant.h new file mode 100644 index 000000000000..ef1d552dffa4 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/variant.h @@ -0,0 +1,1197 @@ +/* + * Copyright 2016 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIREBASE_APP_SRC_INCLUDE_FIREBASE_VARIANT_H_ +#define FIREBASE_APP_SRC_INCLUDE_FIREBASE_VARIANT_H_ + +#include + +#include +#include +#include +#include +#include + +#include "firebase/internal/common.h" + +/// @brief Namespace that encompasses all Firebase APIs. + +namespace firebase { +namespace internal { +class VariantInternal; +} +} // namespace firebase + +namespace firebase { + +// +// SWIG uses the Variant class as a readonly object, and so ignores most of the +// functions. In order to keep things clean, functions that should be exposed +// are explicitly listed in app.SWIG, and everything else is ignored. +// + +/// Variant data type used by Firebase libraries. +class Variant { + public: + /// Type of data that this variant object contains. + enum Type { + /// Null, or no data. + kTypeNull, + /// A 64-bit integer. + kTypeInt64, + /// A double-precision floating point number. + kTypeDouble, + /// A boolean value. + kTypeBool, + /// A statically-allocated string we point to. + kTypeStaticString, + /// A std::string. + kTypeMutableString, + /// A std::vector of Variant. + kTypeVector, + /// A std::map, mapping Variant to Variant. + kTypeMap, + /// An statically-allocated blob of data that we point to. Never constructed + /// by default. Use Variant::FromStaticBlob() to create a Variant of this + /// type. + kTypeStaticBlob, + /// A blob of data that the Variant holds. Never constructed by default. Use + /// Variant::FromMutableBlob() to create a Variant of this type, and copy + /// binary data from an existing source. + kTypeMutableBlob, + + // Note: If you add new types update enum InternalType; + }; + +// +// Because of the VariantVariantMap C# class, we need to hide the constructors +// explicitly, as the SWIG ignore does not seem to work with that macro. +// +#ifndef SWIG + /// @brief Construct a null Variant. + /// + /// The Variant constructed will be of type Null. + Variant() : type_(kInternalTypeNull), value_({}) {} + + /// @brief Construct a Variant with the given templated type. + /// + /// @param[in] value The value to construct the variant. + /// + /// Valid types for this constructor are `int`, `int64_t`, `float`, `double`, + /// `bool`, `const char*`, and `char*` (but see below for additional Variant + /// types). + /// + /// + /// Type `int` or `int64_t`: + /// * The Variant constructed will be of type Int64. + /// + /// Type `double` or `float`: + /// * The Variant constructed will be of type Double. + /// + /// Type `bool`: + /// * The Variant constructed will be of type Bool. + /// + /// Type `const char*`: + /// * The Variant constructed will be of type StaticString, and is_string() + /// will return true. **Note:** If you use this constructor, you must + /// ensure that the memory pointed to stays valid for the life of the + /// Variant, otherwise call mutable_string() or set_mutable_string(), + /// which will copy the string to an internal buffer. + /// + /// Type `char*`: + /// * The Variant constructed will be of type MutableString, and is_string() + /// will return true. + /// + /// Other types will result in compiler error unless using the following + /// constructor overloads: + /// * `std::string` + /// * `std::vector` + /// * `std::vector` where T is convertible to variant type + /// * `T*`, `size_t` where T is convertible to variant type + /// * `std::map` + /// * `std::map` where K and V is convertible to variant type + template + Variant(T value) // NOLINT + : type_(kInternalTypeNull) { + set_value_t(value); + } + + /// @brief Construct a Variant containing the given string value (makes a + /// copy). + /// + /// The Variant constructed will be of type MutableString, and is_string() + /// will return true. + /// + /// @param[in] value The string to use for the Variant. + Variant(const std::string& value) // NOLINT + : type_(kInternalTypeNull) { + set_mutable_string(value); + } + + /// @brief Construct a Variant containing the given std::vector of Variant. + /// + /// The Variant constructed will be of type Vector. + /// + /// @param[in] value The STL vector to copy into the Variant. + Variant(const std::vector& value) // NOLINT + : type_(kInternalTypeNull) { + set_vector(value); + } + + /// @brief Construct a Variant containing the given std::vector of something + /// that can be constructed into a Variant. + /// + /// The Variant constructed will be of type Vector. + /// + /// @param[in] value An STL vector containing elements that can be converted + /// to Variant (such as ints, strings, vectors). A Variant will be created for + /// each element, and copied into the Vector Variant constructed here. + template + Variant(const std::vector& value) // NOLINT + : type_(kInternalTypeNull) { + Clear(kTypeVector); + vector().reserve(value.size()); + for (size_t i = 0; i < value.size(); i++) { + vector().push_back(Variant(static_cast(value[i]))); + } + } + + /// @brief Construct a Variant from an array of supported types into a Vector. + /// + /// The Variant constructed will be of type Vector. + /// + /// @param[in] array_of_values A C array containing elements that can be + /// converted to Variant (such as ints, strings, vectors). A Variant will be + /// created for each element, and copied into the Vector Variant constructed + /// here. + /// @param[in] array_size Number of elements of the array. + template + Variant(const T array_of_values[], size_t array_size) + : type_(kInternalTypeNull) { + Clear(kTypeVector); + vector().reserve(array_size); + for (size_t i = 0; i < array_size; i++) { + vector()[i] = Variant(array_of_values[i]); + } + } + + /// @brief Construct a Variatn containing the given std::map of Variant to + /// Variant. + /// + /// The Variant constructed will be of type Map. + /// + /// @param[in] value The STL map to copy into the Variant. + Variant(const std::map& value) // NOLINT + : type_(kInternalTypeNull) { + set_map(value); + } + + /// @brief Construct a Variant containing the given std::map of something that + /// can be constructed into a Variant, to something that can be constructed + /// into a Variant. + /// + /// The Variant constructed will be of type Map. + /// + /// @param[in] value An STL map containing keys and values that can be + /// converted to Variant (such as ints, strings, vectors). A Variant will be + /// created for each key and for each value, and copied by pairs into the Map + /// Variant constructed here. + template + Variant(const std::map& value) // NOLINT + : type_(kInternalTypeNull) { + Clear(kTypeMap); + for (typename std::map::const_iterator i = value.begin(); + i != value.end(); ++i) { + map().insert(std::make_pair(Variant(i->first), Variant(i->second))); + } + } + + /// @brief Copy constructor. Performs a deep copy. + /// + /// @param[in] other Source Variant to copy from. + Variant(const Variant& other) : type_(kInternalTypeNull) { *this = other; } + + /// @brief Copy assignment operator. Performs a deep copy. + /// + /// @param[in] other Source Variant to copy from. + Variant& operator=(const Variant& other); + +#if defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) + + /// @brief Move constructor. Efficiently moves the more complex data types by + /// simply reassigning pointer ownership. + /// + /// @param[in] other Source Variant to move from. + Variant(Variant&& other) noexcept : type_(kInternalTypeNull) { + *this = std::move(other); + } + + /// @brief Move assignment operator. Efficiently moves the more complex data + /// types by simply reassigning pointer ownership. + /// + /// @param[in] other Source Variant to move from. + Variant& operator=(Variant&& other) noexcept; + +#endif // defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) +#endif // SWIG + + /// Destructor. Frees the memory that this Variant owns. + ~Variant() { Clear(); } + + /// @brief Equality operator. Both the type and the value must be equal + /// (except that static strings CAN be == to mutable strings). For container + /// types, element-by-element comparison is performed. For strings, string + /// comparison is performed. + /// + /// @param[in] other Variant to compare to. + /// + /// @return True if the Variants are of identical types and values, false + /// otherwise. + bool operator==(const Variant& other) const; + + /// @brief Inequality operator, only meant for internal use. + /// + /// Explanation: In order to use Variant as a key for std::map, we must + /// provide a comparison function. This comparison function is ONLY for + /// std::map to be able to use a Variant as a map key. + /// + /// We define v1 < v2 IFF: + /// * If different types, compare type as int: v1.type() < v2.type() + /// (note: this means that Variant(1) < Variant(0.0) - be careful!) + /// * If both are int64: v1.int64_value() < v2.int64_value(); + /// * If both are double: v1.double_value() < v2.double_value() + /// * If both are bool: v1.bool_value() < v2.bool_value(); + /// * If both are either static or mutable strings: strcmp(v1, v2) < 0 + /// * If both are vectors: + /// * If v1[0] < v2[0], that means v1 < v2 == true. Otherwise: + /// * If v1[0] > v2[0], that means v1 < v2 == false. Otherwise: + /// * Continue to the next element of both vectors and compare again. + /// * If you reach the end of one vector first, that vector is considered + /// to be lesser. + /// * If both are maps, iterate similar to vectors (since maps are ordered), + /// but for each element, first compare the key, then the value. + /// * If both are blobs, the smaller-sized blob is considered lesser. If both + /// blobs are the same size, use memcmp to compare the bytes. + /// + /// We have defined this operation such that if !(v1 < v2) && !(v2 < v1), it + /// must follow that v1 == v2. + /// + /// @param[in] other Variant to compare to. + /// + /// @return Results of the comparison, as described in this documentation. + /// + /// @note This will not give you the results you expect if you compare + /// Variants of different types! For example, Variant(0.0) < Variant(1). + bool operator<(const Variant& other) const; + + /// @brief Inequality operator: x != y is evaluated as !(x == y). + /// + /// @param[in] other Variant to compare to. + /// + /// @return Results of the comparison. + bool operator!=(const Variant& other) const { return !(*this == other); } + + /// @brief Inequality operator: x > y is evaluated as y < x + /// + /// @param[in] other Variant to compare to. + /// + /// @return Results of the comparison. + bool operator>(const Variant& other) const { return other < *this; } + + /// @brief Inequality operator: x >= y is evaluated as !(x < y) + /// + /// @param[in] other Variant to compare to. + /// + /// @return Results of the comparison. + bool operator>=(const Variant& other) const { return !(*this < other); } + + /// @brief Inequality operator: x <= y is evaluated as !(x > y) + /// + /// @param[in] other Variant to compare to. + /// + /// @return Results of the comparison. + bool operator<=(const Variant& other) const { return !(*this > other); } + + /// @brief Clear the given Variant data, optionally into a new type. Frees up + /// any memory that might have been allocated. After calling this, you can + /// access the Variant as the new type. + /// + /// @param[in] new_type Optional new type to clear the Variant to. You may + /// immediately begin using the Variant as that new type. + void Clear(Type new_type = kTypeNull); + + // Convenience functions (used similarly to constants). + + /// @brief Get a Variant of type Null. + /// + /// @return A Variant of type Null. + static Variant Null() { return Variant(); } + + /// @brief Get a Variant of integer value 0. + /// + /// @return A Variant of type Int64, with value 0. + static Variant Zero() { return Variant::FromInt64(0L); } + + /// @brief Get a Variant of integer value 1. + /// + /// @return A Variant of type Int64, with value 1. + static Variant One() { return Variant::FromInt64(1L); } + + /// @brief Get a Variant of double value 0.0. + /// + /// @return A Variant of type Double, with value 0.0. + static Variant ZeroPointZero() { return Variant::FromDouble(0.0); } + + /// @brief Get a Variant of double value 1.0. + /// + /// @return A Variant of type Double, with value 1.0. + static Variant OnePointZero() { return Variant::FromDouble(1.0); } + + /// @brief Get a Variant of bool value false. + /// + /// @return A Variant of type Bool, with value false. + static Variant False() { return Variant::FromBool(false); } + + /// @brief Get a Variant of bool value true. + /// + /// @return A Variant of type Bool, with value true. + static Variant True() { return Variant::FromBool(true); } + + /// @brief Get an empty string variant. + /// + /// @return A Variant of type StaticString, referring to an empty string. + static Variant EmptyString() { return Variant::FromStaticString(""); } + + /// @brief Get a Variant containing an empty mutable string. + /// + /// @return A Variant of type MutableString, containing an empty string. + static Variant EmptyMutableString() { + Variant v; + v.Clear(kTypeMutableString); + return v; + } + + /// @brief Get a Variant containing an empty vector. You can immediately call + /// vector() on it to work with the vector it contains. + /// + /// @return A Variant of type Vector, containing no elements. + static Variant EmptyVector() { + Variant v; + v.Clear(kTypeVector); + return v; + } + + /// @brief Get a Variant containing an empty map. You can immediately call + /// map() on + /// it to work with the map it contains. + /// + /// @return A Variant of type Map, containing no elements. + static Variant EmptyMap() { + Variant v; + v.Clear(kTypeMap); + return v; + } + + /// @brief Return a Variant containing an empty mutable blob of the requested + /// size, filled with 0-bytes. + /// + /// @param[in] size_bytes Size of the buffer you want, in bytes. + /// + /// @returns A Variant containing a mutable blob of the requested size, filled + /// with 0-bytes. + static Variant EmptyMutableBlob(size_t size_bytes) { + Variant v; + uint8_t* blank_data = new uint8_t[size_bytes]; + memset(blank_data, 0, size_bytes); + v.Clear(kTypeMutableBlob); + v.set_blob_pointer(blank_data, size_bytes); + return v; + } + + /// @brief Get the current type contained in this Variant. + /// + /// @return The Variant's type. + Type type() const { + // To avoid breaking user code, alias the small string type to mutable + // string. + if (type_ == kInternalTypeSmallString) { + return kTypeMutableString; + } + + return static_cast(type_); + } + + /// @brief Get whether this Variant is currently null. + /// + /// @return True if the Variant is Null, false otherwise. + bool is_null() const { return type() == kTypeNull; } + + /// @brief Get whether this Variant contains an integer. + /// + /// @return True if the Variant's type is Int64, false otherwise. + bool is_int64() const { return type() == kTypeInt64; } + + /// @brief Get whether this Variant contains a double. + /// + /// @return True if the Variant's type is Double, false otherwise. + bool is_double() const { return type() == kTypeDouble; } + + /// @brief Get whether this Variant contains a bool. + /// + /// @return True if the Variant's type is Bool, false otherwise. + bool is_bool() const { return type() == kTypeBool; } + + /// @brief Get whether this Variant contains a vector. + /// + /// @return True if the Variant's type is Vector, false otherwise. + bool is_vector() const { return type() == kTypeVector; } + + /// @brief Get whether this Variant contains a map. + /// + /// @return True if the Variant's type is Map, false otherwise. + bool is_map() const { return type() == kTypeMap; } + + /// @brief Get whether this Variant contains a static string. + /// + /// @return True if the Variant's type is StaticString, false otherwise. + bool is_static_string() const { return type() == kTypeStaticString; } + + /// @brief Get whether this Variant contains a mutable string. + /// + /// @return True if the Variant's type is MutableString, false otherwise. + bool is_mutable_string() const { return type() == kTypeMutableString; } + + /// @brief Get whether this Variant contains a string. + /// + /// @return True if the Variant's type is either StaticString or + /// MutableString or SmallString; false otherwise. + /// + /// @note No matter which type of string the Variant contains, you can read + /// its value via string_value(). + bool is_string() const { + return is_static_string() || is_mutable_string() || is_small_string(); + } + + /// @brief Get whether this Variant contains a static blob. + /// + /// @return True if the Variant's type is StaticBlob, false otherwise. + bool is_static_blob() const { return type() == kTypeStaticBlob; } + + /// @brief Get whether this Variant contains a mutable blob. + /// + /// @return True if the Variant's type is MutableBlob, false otherwise. + bool is_mutable_blob() const { return type() == kTypeMutableBlob; } + + /// @brief Get whether this Variant contains a blob. + /// + /// @return True if the Variant's type is either StaticBlob or + /// MutableBlob; false otherwise. + /// + /// @note No matter which type of blob the Variant contains, you can read + /// its data via blob_data() and get its size via blob_size(). + bool is_blob() const { return is_static_blob() || is_mutable_blob(); } + + /// @brief Get whether this Variant contains a numeric type, Int64 or Double. + /// + /// @return True if the Variant's type is either Int64 or Double; false + /// otherwise. + bool is_numeric() const { return is_int64() || is_double(); } + + /// @brief Get whether this Variant contains a fundamental type: Null, Int64, + /// Double, Bool, or one of the two String types. Essentially + /// !is_containerType(). + /// + /// @return True if the Variant's type is Int64, Double, Bool, or Null; false + /// otherwise. + bool is_fundamental_type() const { + return is_int64() || is_double() || is_string() || is_bool() || is_null(); + } + + /// @brief Get whether this Variant contains a container type: Vector or Map. + /// + /// @return True if the Variant's type is Vector or Map; false otherwise. + bool is_container_type() const { return is_vector() || is_map(); } + + /// @brief Get the current Variant converted into a string. Only valid for + /// fundamental types. + /// + /// Special cases: Booleans will be returned as "true" or "false". Null will + /// be returned as an empty string. The returned string may be either mutable + /// or static, depending on the source type. All other cases will return an + /// empty string. + /// + /// @return A Variant containing a String that represents the value of this + /// original Variant. + Variant AsString() const; + + /// @brief Get the current Variant converted into an integer. Only valid for + /// fundamental types. + /// + /// Special cases: If a String can be parsed as a number + /// via strtol(), it will be. If a Bool is true, this will return 1. All other + /// cases (including non-fundamental types) will return 0. + /// + /// @return A Variant containing an Int64 that represents the value of this + /// original Variant. + Variant AsInt64() const; + + /// @brief Get the current Variant converted into a floating-point + /// number. Only valid for fundamental types. + /// + /// Special cases: If a Bool is true, this will return 1. All other cases will + /// return 0. + /// + /// @return A Variant containing a Double that represents the value of this + /// original Variant. + Variant AsDouble() const; + + /// @brief Get the current Variant converted into a boolean. Null, 0, 0.0, + /// empty strings, empty vectors, empty maps, blobs of size 0, and "false" + /// (case-sensitive) are all considered false. All other values are true. + /// + /// @return A Variant of type Bool containing the original Variant interpreted + /// as a Bool. + Variant AsBool() const; + + /// @brief Mutable accessor for a Variant containing a string. + /// + /// If the Variant contains a static string, it will be converted into a + /// mutable string, which copies the const char*'s data into a std::string. + /// + /// @return Reference to the string contained in this Variant. + /// + /// @note If the Variant is not one of the two String types, this will assert. + std::string& mutable_string() { + if (type_ == kInternalTypeStaticString || + type_ == kInternalTypeSmallString) { + // Automatically promote a static or small string to a mutable string. + set_mutable_string(string_value(), false); + } + assert_is_type(kTypeMutableString); + return *value_.mutable_string_value; + } + + /// @brief Get the size of a blob. This method works with both static + /// and mutable blobs. + /// + /// @return Number of bytes of binary data contained in the blob. + size_t blob_size() const { + assert_is_blob(); + return value_.blob_value.size; + } + + /// @brief Get the pointer to the binary data contained in a blob. + /// This method works with both static and mutable blob. + /// + /// @return Pointer to the binary data. Use blob_size() to get the + /// number of bytes. + const uint8_t* blob_data() const { + assert_is_blob(); + return value_.blob_value.ptr; + } + + /// @brief Get a mutable pointer to the binary data contained in + /// a blob. + /// + /// If the Variant contains a static blob, it will be converted into a mutable + /// blob, which copies the binary data into the Variant's buffer. + /// + /// @returns Pointer to a mutable buffer of binary data. The size of the + /// buffer cannot be changed, but the contents are mutable. + uint8_t* mutable_blob_data() { + if (type_ == kInternalTypeStaticBlob) { + // Automatically promote a static blob to a mutable blob. + set_mutable_blob(blob_data(), blob_size()); + } + assert_is_type(kTypeMutableBlob); + return const_cast(value_.blob_value.ptr); + } + + /// @brief Const accessor for a Variant contianing mutable blob data. + /// + /// @note Unlike the non-const accessor, this accessor cannot "promote" a + /// static blob to mutable, and thus will assert if the Variant you pass in + /// is not of MutableBlob type. + /// + /// @returns Pointer to a mutable buffer of binary data. The size of the + /// buffer cannot be changed, but the contents are mutable. + uint8_t* mutable_blob_data() const { + assert_is_type(kTypeMutableBlob); + return const_cast(value_.blob_value.ptr); + } + + /// @brief Mutable accessor for a Variant containing a vector of Variant + /// data. + /// + /// @return Reference to the vector contained in this Variant. + /// + /// @note If the Variant is not of Vector type, this will assert. + std::vector& vector() { + assert_is_type(kTypeVector); + return *value_.vector_value; + } + /// @brief Mutable accessor for a Variant containing a map of Variant data. + /// + /// @return Reference to the map contained in this Variant. + /// + /// @note If the Variant is not of Map type, this will assert. + std::map& map() { + assert_is_type(kTypeMap); + return *value_.map_value; + } + + /// @brief Const accessor for a Variant containing an integer. + /// + /// @return The integer contained in this Variant. + /// + /// @note If the Variant is not of Int64 type, this will assert. + int64_t int64_value() const { + assert_is_type(kTypeInt64); + return value_.int64_value; + } + + /// @brief Const accessor for a Variant containing a double. + /// + /// @return The double contained in this Variant. + /// + /// @note If the Variant is not of Double type, this will assert. + double double_value() const { + assert_is_type(kTypeDouble); + return value_.double_value; + } + + /// @brief Const accessor for a Variant containing a bool. + /// + /// @return The bool contained in this Variant. + /// + /// @note If the Variant is not of Bool type, this will assert. + const bool& bool_value() const { + assert_is_type(kTypeBool); + return value_.bool_value; + } + + /// @brief Const accessor for a Variant containing a string. + /// + /// This can return both static and mutable strings. The pointer is only + /// guaranteed to persist if this Variant's type is StaticString. + /// + /// @return The string contained in this Variant. + /// + /// @note If the Variant is not of StaticString or MutableString type, this + /// will assert. + const char* string_value() const { + assert_is_string(); + if (type_ == kInternalTypeMutableString) + return value_.mutable_string_value->c_str(); + else if (type_ == kInternalTypeStaticString) + return value_.static_string_value; + else // if (type_ == kInternalTypeSmallString) + return value_.small_string; + } + + /// @brief Const accessor for a Variant containing a string. + /// + /// @note Unlike the non-const accessor, this accessor cannot "promote" a + /// static string to mutable, and thus returns a std::string copy instead of a + /// const reference to a std::string + /// + /// @return std::string with the string contents contained in this Variant. + std::string mutable_string() const { + assert_is_string(); + return string_value(); + } + + /// @brief Const accessor for a Variant containing a vector of Variant data. + /// + /// @return Reference to the vector contained in this Variant. + /// + /// @note If the Variant is not of Vector type, this will assert. + const std::vector& vector() const { + assert_is_type(kTypeVector); + return *value_.vector_value; + } + + /// @brief Const accessor for a Variant containing a map of strings to + /// Variant + /// data. + /// + /// @return Reference to the map contained in this Variant. + /// + /// @note If the Variant is not of Map type, this will assert. + const std::map& map() const { + assert_is_type(kTypeMap); + return *value_.map_value; + } + + /// @brief Sets the Variant value to null. + /// + /// The Variant's type will be Null. + void set_null() { Clear(kTypeNull); } + + /// @brief Sets the Variant to an 64-bit integer value. + /// + /// The Variant's type will be set to Int64. + /// + /// @param[in] value The 64-bit integer value for the Variant. + void set_int64_value(int64_t value) { + Clear(kTypeInt64); + value_.int64_value = value; + } + + /// @brief Sets the Variant to an double-precision floating point value. + /// + /// The Variant's type will be set to Double. + /// + /// @param[in] value The double-precision floating point value for the + /// Variant. + void set_double_value(double value) { + Clear(kTypeDouble); + value_.double_value = value; + } + + /// @brief Sets the Variant to the given boolean value. + /// + /// The Variant's type will be set to Bool. + /// + /// @param[in] value The boolean value for the Variant. + void set_bool_value(bool value) { + Clear(kTypeBool); + value_.bool_value = value; + } + + /// @brief Sets the Variant to point to a static string buffer. + /// + /// The Variant's type will be set to StaticString. + /// + /// @note If you use this method, you must ensure that the memory pointed to + /// stays valid for the life of the Variant, or otherwise call + /// mutable_string() or set_mutable_string(), which will copy the string to an + /// internal buffer. + /// + /// @param[in] value A pointer to the static null-terminated string for the + /// Variant. + void set_string_value(const char* value) { + Clear(kTypeStaticString); + value_.static_string_value = value; + } + + /// @brief Sets the Variant to a mutable string. + /// + /// The Variant's type will be set to MutableString. + /// + /// @param[in] value A pointer to a null-terminated string, which will be + /// copied into to the Variant. + void set_string_value(char* value) { + size_t len = strlen(value); + if (len < kMaxSmallStringSize) { + Clear(static_cast(kInternalTypeSmallString)); + strncpy(value_.small_string, value, len + 1); + } else { + set_mutable_string(std::string(value, len)); + } + } + + /// @brief Sets the Variant to a mutable string. + /// + /// The Variant's type will be set to MutableString. + /// + /// @param[in] value The string to use for the Variant. + void set_string_value(const std::string& value) { set_mutable_string(value); } + + /// @brief Sets the Variant to a copy of the given string. + /// + /// The Variant's type will be set to SmallString if the size of the string is + /// less than kMaxSmallStringSize (8 bytes on x86, 16 bytes on x64) or + /// otherwise set to MutableString. + /// + /// @param[in] value The string to use for the Variant. + /// @param[in] use_small_string Check to see if the input string should be + /// treated as a small string or left as a mutable string + void set_mutable_string(const std::string& value, + bool use_small_string = true) { + if (value.size() < kMaxSmallStringSize && use_small_string) { + Clear(static_cast(kInternalTypeSmallString)); + strncpy(value_.small_string, value.data(), value.size() + 1); + } else { + Clear(kTypeMutableString); + *value_.mutable_string_value = value; + } + } + + /// @brief Sets the Variant to a copy of the given binary data. + /// + /// The Variant's type will be set to MutableBlob. + /// + /// @param[in] src_data The data to use for the Variant. If you + /// pass in nullptr, no data will be copied, but a buffer of the + /// requested size will be allocated. + /// @param[in] size_bytes The size of the data, in bytes. + void set_mutable_blob(const void* src_data, size_t size_bytes) { + uint8_t* dest_data = new uint8_t[size_bytes]; // Will be deleted when + // `this` is deleted. + if (src_data != nullptr) { + memcpy(dest_data, src_data, size_bytes); + } + Clear(kTypeMutableBlob); + set_blob_pointer(dest_data, size_bytes); + } + + /// @brief Sets the Variant to point to static binary data. + /// + /// The Variant's type will be set to kTypeStaticBlob. + /// + /// @param[in] static_data Pointer to statically-allocated binary data. The + /// Variant will point to the data, not copy it. + /// @param[in] size_bytes Size of the data, in bytes. + /// + /// @note If you use this method, you must ensure that the memory pointer to + /// stays valid for the life of the Variant, or otherwise call + /// mutable_blob_data() or set_mutable_blob(), which will copy the data into + /// an internal buffer. + void set_static_blob(const void* static_data, size_t size_bytes) { + Clear(kTypeStaticBlob); + set_blob_pointer(static_data, size_bytes); + } + + /// @brief Sets the Variant to a copy of the given vector. + /// + /// The Variant's type will be set to Vector. + /// + /// @param[in] value The STL vector to copy into the Variant. + + void set_vector(const std::vector& value) { + Clear(kTypeVector); + *value_.vector_value = value; + } + + /// @brief Sets the Variant to a copy of the given map. + /// + /// The Variant's type will be set to Map. + /// + /// @param[in] value The STL map to copy into the Variant. + void set_map(const std::map& value) { + Clear(kTypeMap); + *value_.map_value = value; + } + + /// @brief Assigns an existing string which was allocated on the heap into the + /// Variant without performing a copy. This object will take over ownership of + /// the pointer, and will set the std::string* you pass in to NULL. + /// + /// The Variant's type will be set to MutableString. + /// + /// @param[in, out] str Pointer to a pointer to an STL string. The Variant + /// will take over ownership of the pointer to the string, and set the + /// pointer + /// you passed in to NULL. + void AssignMutableString(std::string** str) { + Clear(kTypeNull); + type_ = kInternalTypeMutableString; + value_.mutable_string_value = *str; + *str = NULL; // NOLINT + } + + /// @brief Assigns an existing vector which was allocated on the heap into the + /// Variant without performing a copy. This object will take over ownership of + /// the pointer, and will set the std::vector* you pass in to NULL. + /// + /// The Variant's type will be set to Vector. + /// + /// @param[in, out] vect Pointer to a pointer to an STL vector. The Variant + /// will take over ownership of the pointer to the vector, and set the + /// pointer + /// you passed in to NULL. + void AssignVector(std::vector** vect) { + Clear(kTypeNull); + type_ = kInternalTypeVector; + value_.vector_value = *vect; + *vect = NULL; // NOLINT + } + + /// @brief Assigns an existing map which was allocated on the heap into the + /// Variant without performing a copy. This object will take over ownership + /// of + /// the map, and will set the std::map** you pass in to NULL. + /// + /// The Variant's type will be set to Map. + /// + /// @param[in, out] map Pointer to a pointer to an STL map. The Variant will + /// take over ownership of the pointer to the map, and set the pointer you + /// passed in to NULL. + void AssignMap(std::map** map) { + Clear(kTypeNull); + type_ = kInternalTypeMap; + value_.map_value = *map; + *map = NULL; // NOLINT + } + + // Convenience methods for the times when constructors are too ambiguious. + + /// @brief Return a Variant from a 64-bit integer. + /// + /// @param[in] value 64-bit integer value to put into the Variant. + /// + /// @returns A Variant containing the 64-bit integer. + static Variant FromInt64(int64_t value) { return Variant(value); } + + /// @brief Return a Variant from a double-precision floating point number. + /// + /// @param[in] value Double-precision floating point value to put into the + /// Variant; + /// + /// @returns A Variant containing the double-precision floating point number. + static Variant FromDouble(double value) { return Variant(value); } + + /// @brief Return a Variant from a boolean. + /// + /// @param[in] value Boolean value to put into the Variant. + /// + /// @returns A Variant containing the Boolean. + static Variant FromBool(bool value) { return Variant(value); } + + /// @brief Return a Variant from a static string. + /// + /// @param[in] value Pointer to statically-allocated null-terminated string. + /// + /// @returns A Variant referring to the string pointer you passed in. + /// + /// @note If you use this function, you must ensure that the memory pointed + /// to stays valid for the life of the Variant, otherwise call + /// mutable_string() or set_mutable_string(), which will copy the string to an + /// internal buffer. + static Variant FromStaticString(const char* value) { return Variant(value); } + + /// @brief Return a Variant from a string. + /// + /// This method makes a copy of the string. + /// + /// @param[in] value String value to copy into the Variant. + /// + /// @returns A Variant containing a copy of the string. + static Variant FromMutableString(const std::string& value) { + return Variant(value); + } + + /// @brief Return a Variant that points to static binary data. + /// + /// @param[in] static_data Pointer to statically-allocated binary data. The + /// Variant will point to the data, not copy it. + /// @param[in] size_bytes Size of the data, in bytes. + /// + /// @returns A Variant pointing to the binary data. + /// + /// @note If you use this function, you must ensure that the memory pointed + /// to stays valid for the life of the Variant, otherwise call + /// mutable_blob() or set_mutable_blob(), which will copy the data to an + /// internal buffer. + static Variant FromStaticBlob(const void* static_data, size_t size_bytes) { + Variant v; + v.set_static_blob(static_data, size_bytes); + return v; + } + + /// @brief Return a Variant containing a copy of binary data. + /// + /// @param[in] src_data Pointer to binary data to be copied into the Variant. + /// @param[in] size_bytes Size of the data, in bytes. + /// + /// @returns A Variant containing a copy of the binary data. + static Variant FromMutableBlob(const void* src_data, size_t size_bytes) { + Variant v; + v.set_mutable_blob(src_data, size_bytes); + return v; + } + + /// @brief Return a Variant from a string, but make it mutable. + /// + /// Only copies the string once, unlike Variant(std::string(value)), which + /// copies the string twice. + /// + /// @param[in] value String value to copy into the Variant and make mutable. + /// + /// @returns A Variant containing a mutable copy of the string. + static Variant MutableStringFromStaticString(const char* value) { + std::string* str = new std::string(value); + Variant v; + v.AssignMutableString(&str); + return v; + } + + /// @brief Get the human-readable type name of a Variant type. + /// + /// @param[in] type Variant type to describe. + /// + /// @returns A string describing the type, suitable for error messages or + /// debugging. For example "Int64" or "MutableString". + static const char* TypeName(Type type); + + private: + // Internal Type of data that this variant object contains to avoid breaking + // API + enum InternalType { + /// Null, or no data. + kInternalTypeNull = kTypeNull, + /// A 64-bit integer. + kInternalTypeInt64 = kTypeInt64, + /// A double-precision floating point number. + kInternalTypeDouble = kTypeDouble, + /// A boolean value. + kInternalTypeBool = kTypeBool, + /// A statically-allocated string we point to. + kInternalTypeStaticString = kTypeStaticString, + /// A std::string. + kInternalTypeMutableString = kTypeMutableString, + /// A std::vector of Variant. + kInternalTypeVector = kTypeVector, + /// A std::map, mapping Variant to Variant. + kInternalTypeMap = kTypeMap, + /// An statically-allocated blob of data that we point to. Never constructed + /// by default. Use Variant::FromStaticBlob() to create a Variant of this + /// type. + kInternalTypeStaticBlob = kTypeStaticBlob, + /// A blob of data that the Variant holds. Never constructed by default. Use + /// Variant::FromMutableBlob() to create a Variant of this type, and copy + /// binary data from an existing source. + kInternalTypeMutableBlob = kTypeMutableBlob, + // A c string stored in the Variant internal data blob as opposed to be + // newed as a std::string. Max size is 16 bytes on x64 and 8 bytes on x86. + kInternalTypeSmallString = kTypeMutableBlob + 1, + // Not a valid type. Used to get the total number of Variant types. + kMaxTypeValue, + }; + + /// Human-readable type names, for error logging. + static const char* const kTypeNames[]; + + /// Assert that this Variant is of the given type, failing if it is not. + void assert_is_type(Type type) const; + + /// Assert that this Variant is NOT of the given type, failing if it is. + void assert_is_not_type(Type type) const; + + /// Assert that this Variant is a static string or mutable string, failing if + /// it is not. + void assert_is_string() const; + + /// Assert that this Variant is a static blob or mutable blob, failing if + /// it is not. + void assert_is_blob() const; + + /// Sets the blob's data pointer, for kTypeStaticBlob and kTypeMutableBlob. + /// Asserts if the Variant isn't a blob. Caller is responsible for managing + /// the pointer's memory and deleting any existing data at the location. + void set_blob_pointer(const void* blob_ptr, size_t size) { + assert_is_blob(); + value_.blob_value.ptr = static_cast(blob_ptr); + value_.blob_value.size = size; + } + + // If you hit a compiler error here it means you are trying to construct a + // variant with unsupported type. Ether cast to correct type or add support + // below. + template + void set_value_t(T value) = delete; + + // Get whether this Variant contains a small string. + bool is_small_string() const { return type_ == kInternalTypeSmallString; } + + // Current type contained in this Variant. + InternalType type_; + + // Older versions of visual studio cant have this inline in the union and do + // sizeof for small string + typedef struct { + const uint8_t* ptr; + size_t size; + } BlobValue; + + // Union of plain old data (scalars or pointers). + union Value { + int64_t int64_value; + double double_value; + bool bool_value; + const char* static_string_value; + std::string* mutable_string_value; + std::vector* vector_value; + std::map* map_value; + BlobValue blob_value; + char small_string[sizeof(BlobValue)]; + } value_; + + static constexpr size_t kMaxSmallStringSize = sizeof(Value::small_string); + + friend class firebase::internal::VariantInternal; +}; + +template <> +inline void Variant::set_value_t(int64_t value) { + set_int64_value(value); +} + +template <> +inline void Variant::set_value_t(int value) { + set_int64_value(static_cast(value)); +} + +template <> +inline void Variant::set_value_t(int16_t value) { + set_int64_value(static_cast(value)); +} + +template <> +inline void Variant::set_value_t(uint8_t value) { + set_int64_value(static_cast(value)); +} + +template <> +inline void Variant::set_value_t(int8_t value) { + set_int64_value(static_cast(value)); +} + +template <> +inline void Variant::set_value_t(char value) { + set_int64_value(static_cast(value)); +} + +template <> +inline void Variant::set_value_t(double value) { + set_double_value(value); +} + +template <> +inline void Variant::set_value_t(float value) { + set_double_value(static_cast(value)); +} + +template <> +inline void Variant::set_value_t(bool value) { + set_bool_value(value); +} + +template <> +inline void Variant::set_value_t(const char* value) { + set_string_value(value); +} + +template <> +inline void Variant::set_value_t(char* value) { + set_mutable_string(value); +} + +// NOLINTNEXTLINE - allow namespace overridden +} // namespace firebase + +#endif // FIREBASE_APP_SRC_INCLUDE_FIREBASE_VARIANT_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/version.h b/packages/firebase_core/firebase_core/firebase_core/firebase/version.h new file mode 100644 index 000000000000..79d77fc8af4a --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/firebase/version.h @@ -0,0 +1,68 @@ +// Copyright 2016 Google Inc. All Rights Reserved. + +#ifndef FIREBASE_APP_CLIENT_CPP_SRC_VERSION_H_ +#define FIREBASE_APP_CLIENT_CPP_SRC_VERSION_H_ + +/// @def FIREBASE_VERSION_MAJOR +/// @brief Major version number of the Firebase C++ SDK. +/// @see kFirebaseVersionString +#define FIREBASE_VERSION_MAJOR 10 +/// @def FIREBASE_VERSION_MINOR +/// @brief Minor version number of the Firebase C++ SDK. +/// @see kFirebaseVersionString +#define FIREBASE_VERSION_MINOR 5 +/// @def FIREBASE_VERSION_REVISION +/// @brief Revision number of the Firebase C++ SDK. +/// @see kFirebaseVersionString +#define FIREBASE_VERSION_REVISION 0 + +/// @cond FIREBASE_APP_INTERNAL +#define FIREBASE_STRING_EXPAND(X) #X +#define FIREBASE_STRING(X) FIREBASE_STRING_EXPAND(X) +/// @endcond + +// Version number. +// clang-format off +#define FIREBASE_VERSION_NUMBER_STRING \ + FIREBASE_STRING(FIREBASE_VERSION_MAJOR) "." \ + FIREBASE_STRING(FIREBASE_VERSION_MINOR) "." \ + FIREBASE_STRING(FIREBASE_VERSION_REVISION) +// clang-format on + +// Identifier for version string, e.g. kFirebaseVersionString. +#define FIREBASE_VERSION_IDENTIFIER(library) k##library##VersionString + +// Concatenated version string, e.g. "Firebase C++ x.y.z". +#define FIREBASE_VERSION_STRING(library) \ + #library " C++ " FIREBASE_VERSION_NUMBER_STRING + +#if !defined(DOXYGEN) +#if !defined(_WIN32) && !defined(__CYGWIN__) +#define DEFINE_FIREBASE_VERSION_STRING(library) \ + extern volatile __attribute__((weak)) \ + const char* FIREBASE_VERSION_IDENTIFIER(library); \ + volatile __attribute__((weak)) \ + const char* FIREBASE_VERSION_IDENTIFIER(library) = \ + FIREBASE_VERSION_STRING(library) +#else +#define DEFINE_FIREBASE_VERSION_STRING(library) \ + static const char* FIREBASE_VERSION_IDENTIFIER(library) = \ + FIREBASE_VERSION_STRING(library) +#endif // !defined(_WIN32) && !defined(__CYGWIN__) +#else // if defined(DOXYGEN) + +/// @brief Namespace that encompasses all Firebase APIs. +namespace firebase { + +/// @brief String which identifies the current version of the Firebase C++ +/// SDK. +/// +/// @see FIREBASE_VERSION_MAJOR +/// @see FIREBASE_VERSION_MINOR +/// @see FIREBASE_VERSION_REVISION +static const char* kFirebaseVersionString = FIREBASE_VERSION_STRING; + +} // namespace firebase +#endif // !defined(DOXYGEN) + +#endif // FIREBASE_APP_CLIENT_CPP_SRC_VERSION_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/generate_xml_from_google_services_json.py b/packages/firebase_core/firebase_core/firebase_core/generate_xml_from_google_services_json.py new file mode 100644 index 000000000000..8996cd8490f3 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/generate_xml_from_google_services_json.py @@ -0,0 +1,496 @@ +#!/usr/bin/python + +# Copyright 2016 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Stand-alone implementation of the Gradle Firebase plugin. + +Converts the services json file to xml: +https://googleplex-android.googlesource.com/platform/tools/base/+/studio-master-dev/build-system/google-services/src/main/groovy/com/google/gms/googleservices +""" + +__author__ = 'Wouter van Oortmerssen' + +import argparse +import ctypes +import json +import os +import platform +import sys +from xml.etree import ElementTree + +if platform.system().lower() == 'windows': + import ctypes.wintypes # pylint: disable=g-import-not-at-top + +# Map Python 2's unicode method to encode a string as bytes in python 3. +try: + unicode('') # See whether unicode class is available (Python < 3) +except NameError: + unicode = str # pylint: disable=redefined-builtin,invalid-name + +# Input filename if it isn't set. +DEFAULT_INPUT_FILENAME = 'app/google-services.json' +# Output filename if it isn't set. +DEFAULT_OUTPUT_FILENAME = 'res/values/googleservices.xml' +# Input filename for .plist files, if it isn't set. +DEFAULT_PLIST_INPUT_FILENAME = 'GoogleService-Info.plist' +# Output filename for .json files, if it isn't set. +DEFAULT_JSON_OUTPUT_FILENAME = 'google-services-desktop.json' + +OAUTH_CLIENT_TYPE_ANDROID_APP = 1 +OAUTH_CLIENT_TYPE_WEB = 3 + + +def read_xml_value(xml_node): + """Utility method for reading values from the plist XML. + + Args: + xml_node: An ElementTree node, that contains a value. + + Returns: + The value of the node, or None, if it could not be read. + """ + if xml_node.tag == 'string': + return xml_node.text + elif xml_node.tag == 'integer': + return int(xml_node.text) + elif xml_node.tag == 'real': + return float(xml_node.text) + elif xml_node.tag == 'false': + return 0 + elif xml_node.tag == 'true': + return 1 + else: + # other types of input are ignored. (data, dates, arrays, etc.) + return None + + +def construct_plist_dictionary(xml_root): + """Constructs a dictionary of values based on the contents of a plist file. + + Args: + xml_root: An ElementTree node, that represents the root of the xml file + that is to be parsed. (Which should be a dictionary containing + key-value pairs of the properties that need to be extracted.) + + Returns: + A dictionary, containing key-value pairs for all (supported) entries in the + node. + """ + xml_dict = xml_root.find('dict') + + if xml_dict is None: + return None + + plist_dict = {} + i = 0 + while i < len(xml_dict): + if xml_dict[i].tag == 'key': + key = xml_dict[i].text + i += 1 + if i < len(xml_dict): + value = read_xml_value(xml_dict[i]) + if value is not None: + plist_dict[key] = value + i += 1 + + return plist_dict + + +def update_dict_keys(key_map, input_dict): + """Creates a dict from input_dict with the same values but new keys. + + Two dictionaries are passed to this function: the key_map that represents a + mapping of source keys to destination keys, and the input_dict that is the + dictionary that is to be duplicated, replacing any key that matches a source + key with a destination key. Source keys that are not present in the + input_dict will not have their destination key represented in the result. + + In other words, if key_map is `{'old': 'new', 'foo': 'bar'}`, and input_dict + is `{'old': 10}`, the result will be `{'new': 10}`. + + Args: + key_map (dict): A dictionary of strings to strings that maps source keys to + destination keys. + input_dict (dict): The dictionary of string keys to any value type, which + is to be duplicated, replacing source keys with the corresponding + destination keys from key_map. + + Returns: + dict: A new dictionary with updated keys. + """ + return { + new_key: input_dict[old_key] + for (old_key, new_key) in key_map.items() + if old_key in input_dict + } + + +def construct_google_services_json(xml_dict): + """Constructs a google services json file from a dictionary. + + Args: + xml_dict: A dictionary of all the key/value pairs that are needed for the + output json file. + Returns: + A string representing the output json file. + """ + + try: + json_struct = { + 'project_info': + update_dict_keys( + { + 'GCM_SENDER_ID': 'project_number', + 'DATABASE_URL': 'firebase_url', + 'PROJECT_ID': 'project_id', + 'STORAGE_BUCKET': 'storage_bucket' + }, xml_dict), + 'client': [{ + 'client_info': { + 'mobilesdk_app_id': xml_dict['GOOGLE_APP_ID'], + 'android_client_info': { + 'package_name': xml_dict['BUNDLE_ID'] + } + }, + 'oauth_client': [{ + 'client_id': xml_dict['CLIENT_ID'], + }], + 'api_key': [{ + 'current_key': xml_dict['API_KEY'] + }], + 'services': { + 'analytics_service': { + 'status': xml_dict['IS_ANALYTICS_ENABLED'] + }, + 'appinvite_service': { + 'status': xml_dict['IS_APPINVITE_ENABLED'] + } + } + },], + 'configuration_version': + '1' + } + return json.dumps(json_struct, indent=2) + except KeyError as e: + sys.stderr.write('Could not find key in plist file: [%s]\n' % (e.args[0])) + return None + + +def convert_plist_to_json(plist_string, input_filename): + """Converts an input plist string into a .json file and saves it. + + Args: + plist_string: The contents of the loaded plist file. + + input_filename: The file name that the plist data was read from. + Returns: + the converted string, or None if there were errors. + """ + + try: + root = ElementTree.fromstring(plist_string) + except ElementTree.ParseError: + sys.stderr.write('Error parsing file %s.\n' + 'It does not appear to be valid XML.\n' % (input_filename)) + return None + + plist_dict = construct_plist_dictionary(root) + if plist_dict is None: + sys.stderr.write('In file %s, could not locate a top-level \'dict\' ' + 'element.\n' + 'File format should be plist XML, with a top-level ' + 'dictionary containing project settings as key-value ' + 'pairs.\n' % (input_filename)) + return None + + json_string = construct_google_services_json(plist_dict) + return json_string + + +def gen_string(parent, name, text): + """Generate one element and put into the list of keeps. + + Args: + parent: The object that will hold the string. + name: The name to store the string under. + text: The text of the string. + """ + if text: + prev = parent.get('tools:keep', '') + if prev: + prev += ',' + parent.set('tools:keep', prev + '@string/' + name) + child = ElementTree.SubElement(parent, 'string', { + 'name': name, + 'translatable': 'false' + }) + child.text = text + + +def indent(elem, level=0): + """Recurse through XML tree and add indentation. + + Args: + elem: The element to recurse over + level: The current indentation level. + """ + i = '\n' + level*' ' + if elem is not None: + if not elem.text or not elem.text.strip(): + elem.text = i + ' ' + if not elem.tail or not elem.tail.strip(): + elem.tail = i + for elem in elem: + indent(elem, level+1) + if not elem.tail or not elem.tail.strip(): + elem.tail = i + else: + if level and (not elem.tail or not elem.tail.strip()): + elem.tail = i + + +def argv_as_unicode_win32(): + """Returns unicode command line arguments on windows. + """ + + get_command_line_w = ctypes.cdll.kernel32.GetCommandLineW + get_command_line_w.restype = ctypes.wintypes.LPCWSTR + + # CommandLineToArgvW parses the Unicode command line + command_line_to_argv_w = ctypes.windll.shell32.CommandLineToArgvW + command_line_to_argv_w.argtypes = [ + ctypes.wintypes.LPCWSTR, + ctypes.POINTER(ctypes.c_int) + ] + command_line_to_argv_w.restype = ctypes.POINTER( + ctypes.wintypes.LPWSTR) + + argc = ctypes.c_int(0) + argv = command_line_to_argv_w(get_command_line_w(), argc) + + # Strip the python executable from the arguments if it exists + # (It would be listed as the first argument on the windows command line, but + # not in the arguments to the python script) + sys_argv_len = len(sys.argv) + return [unicode(argv[i]) for i in + range(argc.value - sys_argv_len, argc.value)] + + +def main(): + parser = argparse.ArgumentParser( + description=(( + 'Converts a Firebase %s into %s similar to the Gradle plugin, or ' + 'converts a Firebase %s into a %s suitible for use on desktop apps.' % + (DEFAULT_INPUT_FILENAME, DEFAULT_OUTPUT_FILENAME, + DEFAULT_PLIST_INPUT_FILENAME, DEFAULT_JSON_OUTPUT_FILENAME)))) + parser.add_argument('-i', help='Override input file name', + metavar='FILE', required=False) + parser.add_argument('-o', help='Override destination file name', + metavar='FILE', required=False) + parser.add_argument('-p', help=('Package ID to select within the set of ' + 'packages in the input file. If this is ' + 'not specified, the first package in the ' + 'input file is selected.')) + parser.add_argument('-l', help=('List all package IDs referenced by the ' + 'input file. If this is specified, ' + 'the output file is not created.'), + action='store_true', default=False, required=False) + parser.add_argument('-f', help=('Print project fields from the input file ' + 'in the form \'name=value\\n\' for each ' + 'field. If this is specified, the output ' + 'is not created.'), + action='store_true', default=False, required=False) + parser.add_argument( + '--plist', + help=( + 'Specifies a plist file to convert to a JSON configuration file. ' + 'If this is enabled, the script will expect a .plist file as input, ' + 'which it will convert into %s file. The output file is ' + '*not* suitable for use with Firebase on Android.' % + (DEFAULT_JSON_OUTPUT_FILENAME)), + action='store_true', + default=False, + required=False) + + # python 2 on Windows doesn't handle unicode arguments well, so we need to + # pre-process the command line arguments before trying to parse them. + if platform.system() == 'Windows': + sys.argv = argv_as_unicode_win32() + + args = parser.parse_args() + + if args.plist: + input_filename = DEFAULT_PLIST_INPUT_FILENAME + output_filename = DEFAULT_JSON_OUTPUT_FILENAME + else: + input_filename = DEFAULT_INPUT_FILENAME + output_filename = DEFAULT_OUTPUT_FILENAME + + if args.i: + # Encode the input string (type unicode) as a normal string (type str) + # using the 'utf-8' encoding so that it can be worked with the same as + # input names from other sources (like the defaults). + input_filename_raw = args.i.encode('utf-8') + # Decode the filename to a unicode string using the 'utf-8' encoding to + # properly handle filepaths with unicode characters in them. + input_filename = input_filename_raw.decode('utf-8') + + if args.o: + output_filename = args.o + + with open(input_filename, 'r') as ifile: + file_string = ifile.read() + + json_string = None + if args.plist: + json_string = convert_plist_to_json(file_string, input_filename) + if json_string is None: + return 1 + jsobj = json.loads(json_string) + else: + jsobj = json.loads(file_string) + + root = ElementTree.Element('resources') + root.set('xmlns:tools', 'http://schemas.android.com/tools') + + project_info = jsobj.get('project_info') + if project_info: + gen_string(root, 'firebase_database_url', project_info.get('firebase_url')) + gen_string(root, 'gcm_defaultSenderId', project_info.get('project_number')) + gen_string(root, 'google_storage_bucket', + project_info.get('storage_bucket')) + gen_string(root, 'project_id', project_info.get('project_id')) + + if args.f: + if not project_info: + sys.stderr.write('No project info found in %s.' % input_filename) + return 1 + for field, value in sorted(project_info.items()): + sys.stdout.write('%s=%s\n' % (field, value)) + return 0 + + packages = set() + client_list = jsobj.get('client') + if client_list: + # Search for the user specified package in the file. + selected_package_name = '' + selected_client = client_list[0] + find_package_name = args.p + for client in client_list: + package_name = client.get('client_info', {}).get( + 'android_client_info', {}).get('package_name', '') + if not package_name: + package_name = client.get('oauth_client', {}).get( + 'android_info', {}).get('package_name', '') + if package_name: + if not selected_package_name: + selected_package_name = package_name + selected_client = client + if package_name == find_package_name: + selected_package_name = package_name + selected_client = client + packages.add(package_name) + + if args.p and selected_package_name != find_package_name: + sys.stderr.write('No packages found in %s which match the package ' + 'name %s\n' + '\n' + 'Found the following:\n' + '%s\n' % (input_filename, find_package_name, + '\n'.join(packages))) + return 1 + + client_api_key = selected_client.get('api_key') + if client_api_key: + client_api_key0 = client_api_key[0] + gen_string(root, 'google_api_key', client_api_key0.get('current_key')) + gen_string(root, 'google_crash_reporting_api_key', + client_api_key0.get('current_key')) + + client_info = selected_client.get('client_info') + if client_info: + gen_string(root, 'google_app_id', client_info.get('mobilesdk_app_id')) + + # Only include the first matching OAuth client ID per type. + client_id_web_parsed = False + client_id_android_parsed = False + + oauth_client_list = selected_client.get('oauth_client') + if oauth_client_list: + for oauth_client in oauth_client_list: + client_type = oauth_client.get('client_type') + client_id = oauth_client.get('client_id') + if not (client_type and client_id): continue + if (client_type == OAUTH_CLIENT_TYPE_WEB and + not client_id_web_parsed): + gen_string(root, 'default_web_client_id', client_id) + client_id_web_parsed = True + if (client_type == OAUTH_CLIENT_TYPE_ANDROID_APP and + not client_id_android_parsed): + gen_string(root, 'default_android_client_id', client_id) + client_id_android_parsed = True + + services = selected_client.get('services') + if services: + ads_service = services.get('ads_service') + if ads_service: + gen_string(root, 'test_banner_ad_unit_id', + ads_service.get('test_banner_ad_unit_id')) + gen_string(root, 'test_interstitial_ad_unit_id', + ads_service.get('test_interstitial_ad_unit_id')) + analytics_service = services.get('analytics_service') + if analytics_service: + analytics_property = analytics_service.get('analytics_property') + if analytics_property: + gen_string(root, 'ga_trackingId', + analytics_property.get('tracking_id')) + # enable this once we have an example if this service being present + # in the json data: + maps_service_enabled = False + if maps_service_enabled: + maps_service = services.get('maps_service') + if maps_service: + maps_api_key = maps_service.get('api_key') + if maps_api_key: + for k in range(0, len(maps_api_key)): + # generates potentially multiple of these keys, which is + # the same behavior as the java plugin. + gen_string(root, 'google_maps_key', + maps_api_key[k].get('maps_api_key')) + + tree = ElementTree.ElementTree(root) + + indent(root) + + if args.l: + for package in sorted(packages): + if package: + sys.stdout.write(package + '\n') + else: + path = os.path.dirname(output_filename) + + if path and not os.path.exists(path): + os.makedirs(path) + + if not args.plist: + tree.write(output_filename, 'utf-8', True) + else: + with open(output_filename, 'w') as ofile: + ofile.write(json_string) + + return 0 + +if __name__ == '__main__': + sys.exit(main()) \ No newline at end of file diff --git a/packages/firebase_core/firebase_core/firebase_core/generated_bindings.dart b/packages/firebase_core/firebase_core/firebase_core/generated_bindings.dart new file mode 100644 index 000000000000..f58d1524bee8 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/generated_bindings.dart @@ -0,0 +1,26 @@ +// AUTO GENERATED FILE, DO NOT EDIT. +// +// Generated by `package:ffigen`. +import 'dart:ffi' as ffi; + +class NativeLibrary { + /// Holds the symbol lookup function. + final ffi.Pointer Function(String symbolName) + _lookup; + + /// The symbols are looked up in [dynamicLibrary]. + NativeLibrary(ffi.DynamicLibrary dynamicLibrary) + : _lookup = dynamicLibrary.lookup; + + /// The symbols are looked up with [lookup]. + NativeLibrary.fromLookup( + ffi.Pointer Function(String symbolName) + lookup) + : _lookup = lookup; + + late final ffi.Pointer _firebase = _lookup('firebase'); + + int get firebase => _firebase.value; + + set firebase(int value) => _firebase.value = value; +} diff --git a/packages/firebase_core/firebase_core/firebase_core/google-services-desktop.json b/packages/firebase_core/firebase_core/firebase_core/google-services-desktop.json new file mode 100644 index 000000000000..a3bf216f4de0 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/google-services-desktop.json @@ -0,0 +1,37 @@ +{ + "project_info": { + "project_number": "406099696497", + "firebase_url": "https://flutterfire-e2e-tests-default-rtdb.europe-west1.firebasedatabase.app", + "project_id": "flutterfire-e2e-tests", + "storage_bucket": "flutterfire-e2e-tests.appspot.com" + }, + "client": [ + { + "client_info": { + "mobilesdk_app_id": "1:406099696497:ios:58cbc26aca8e5cf83574d0", + "android_client_info": { + "package_name": "io.flutter.plugins.firebase.auth.example" + } + }, + "oauth_client": [ + { + "client_id": "406099696497-134k3722m01rtrsklhf3b7k8sqa5r7in.apps.googleusercontent.com" + } + ], + "api_key": [ + { + "current_key": "AIzaSyDooSUGSf63Ghq02_iIhtnmwMDs4HlWS6c" + } + ], + "services": { + "analytics_service": { + "status": 0 + }, + "appinvite_service": { + "status": 1 + } + } + } + ], + "configuration_version": "1" +} \ No newline at end of file diff --git a/packages/firebase_core/firebase_core/firebase_core/lib/firebase_core.dart b/packages/firebase_core/firebase_core/firebase_core/lib/firebase_core.dart new file mode 100644 index 000000000000..d1295e26ad15 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/lib/firebase_core.dart @@ -0,0 +1,8 @@ + +import 'firebase_core_platform_interface.dart'; + +class FirebaseCore { + Future getPlatformVersion() { + return FirebaseCorePlatform.instance.getPlatformVersion(); + } +} diff --git a/packages/firebase_core/firebase_core/firebase_core/lib/firebase_core_method_channel.dart b/packages/firebase_core/firebase_core/firebase_core/lib/firebase_core_method_channel.dart new file mode 100644 index 000000000000..5da300fa9013 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/lib/firebase_core_method_channel.dart @@ -0,0 +1,17 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter/services.dart'; + +import 'firebase_core_platform_interface.dart'; + +/// An implementation of [FirebaseCorePlatform] that uses method channels. +class MethodChannelFirebaseCore extends FirebaseCorePlatform { + /// The method channel used to interact with the native platform. + @visibleForTesting + final methodChannel = const MethodChannel('firebase_core'); + + @override + Future getPlatformVersion() async { + final version = await methodChannel.invokeMethod('getPlatformVersion'); + return version; + } +} diff --git a/packages/firebase_core/firebase_core/firebase_core/lib/firebase_core_platform_interface.dart b/packages/firebase_core/firebase_core/firebase_core/lib/firebase_core_platform_interface.dart new file mode 100644 index 000000000000..6f6e165b7957 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/lib/firebase_core_platform_interface.dart @@ -0,0 +1,29 @@ +import 'package:plugin_platform_interface/plugin_platform_interface.dart'; + +import 'firebase_core_method_channel.dart'; + +abstract class FirebaseCorePlatform extends PlatformInterface { + /// Constructs a FirebaseCorePlatform. + FirebaseCorePlatform() : super(token: _token); + + static final Object _token = Object(); + + static FirebaseCorePlatform _instance = MethodChannelFirebaseCore(); + + /// The default instance of [FirebaseCorePlatform] to use. + /// + /// Defaults to [MethodChannelFirebaseCore]. + static FirebaseCorePlatform get instance => _instance; + + /// Platform-specific implementations should set this with their own + /// platform-specific class that extends [FirebaseCorePlatform] when + /// they register themselves. + static set instance(FirebaseCorePlatform instance) { + PlatformInterface.verifyToken(instance, _token); + _instance = instance; + } + + Future getPlatformVersion() { + throw UnimplementedError('platformVersion() has not been implemented.'); + } +} diff --git a/packages/firebase_core/firebase_core/firebase_core/linux/CMakeLists.txt b/packages/firebase_core/firebase_core/firebase_core/linux/CMakeLists.txt new file mode 100644 index 000000000000..5cec31c86b71 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/linux/CMakeLists.txt @@ -0,0 +1,47 @@ +# The Flutter tooling requires that developers have CMake 3.10 or later +# installed. You should not increase this version, as doing so will cause +# the plugin to fail to compile for some customers of the plugin. +cmake_minimum_required(VERSION 3.10) + +# Project-level configuration. +set(PROJECT_NAME "firebase_core") +project(${PROJECT_NAME} LANGUAGES CXX) + +# This value is used when generating builds using this plugin, so it must +# not be changed. +set(PLUGIN_NAME "firebase_core_plugin") + +# Define the plugin library target. Its name must not be changed (see comment +# on PLUGIN_NAME above). +# +# Any new source files that you add to the plugin should be added here. +add_library(${PLUGIN_NAME} SHARED + "firebase_core_plugin.cc" +) + +# Apply a standard set of build settings that are configured in the +# application-level CMakeLists.txt. This can be removed for plugins that want +# full control over build settings. +apply_standard_settings(${PLUGIN_NAME}) + +# Symbols are hidden by default to reduce the chance of accidental conflicts +# between plugins. This should not be removed; any symbols that should be +# exported should be explicitly exported with the FLUTTER_PLUGIN_EXPORT macro. +set_target_properties(${PLUGIN_NAME} PROPERTIES + CXX_VISIBILITY_PRESET hidden) +target_compile_definitions(${PLUGIN_NAME} PRIVATE FLUTTER_PLUGIN_IMPL) + +# Source include directories and library dependencies. Add any plugin-specific +# dependencies here. +target_include_directories(${PLUGIN_NAME} INTERFACE + "${CMAKE_CURRENT_SOURCE_DIR}/include") +target_link_libraries(${PLUGIN_NAME} PRIVATE flutter) +target_link_libraries(${PLUGIN_NAME} PRIVATE PkgConfig::GTK) + +# List of absolute paths to libraries that should be bundled with the plugin. +# This list could contain prebuilt libraries, or libraries created by an +# external build triggered from this build file. +set(firebase_core_bundled_libraries + "" + PARENT_SCOPE +) diff --git a/packages/firebase_core/firebase_core/firebase_core/linux/firebase_core_plugin.cc b/packages/firebase_core/firebase_core/firebase_core/linux/firebase_core_plugin.cc new file mode 100644 index 000000000000..4fd897624ca4 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/linux/firebase_core_plugin.cc @@ -0,0 +1,70 @@ +#include "include/firebase_core/firebase_core_plugin.h" + +#include +#include +#include + +#include + +#define FIREBASE_CORE_PLUGIN(obj) \ + (G_TYPE_CHECK_INSTANCE_CAST((obj), firebase_core_plugin_get_type(), \ + FirebaseCorePlugin)) + +struct _FirebaseCorePlugin { + GObject parent_instance; +}; + +G_DEFINE_TYPE(FirebaseCorePlugin, firebase_core_plugin, g_object_get_type()) + +// Called when a method call is received from Flutter. +static void firebase_core_plugin_handle_method_call( + FirebaseCorePlugin* self, + FlMethodCall* method_call) { + g_autoptr(FlMethodResponse) response = nullptr; + + const gchar* method = fl_method_call_get_name(method_call); + + if (strcmp(method, "getPlatformVersion") == 0) { + struct utsname uname_data = {}; + uname(&uname_data); + g_autofree gchar *version = g_strdup_printf("Linux %s", uname_data.version); + g_autoptr(FlValue) result = fl_value_new_string(version); + response = FL_METHOD_RESPONSE(fl_method_success_response_new(result)); + } else { + response = FL_METHOD_RESPONSE(fl_method_not_implemented_response_new()); + } + + fl_method_call_respond(method_call, response, nullptr); +} + +static void firebase_core_plugin_dispose(GObject* object) { + G_OBJECT_CLASS(firebase_core_plugin_parent_class)->dispose(object); +} + +static void firebase_core_plugin_class_init(FirebaseCorePluginClass* klass) { + G_OBJECT_CLASS(klass)->dispose = firebase_core_plugin_dispose; +} + +static void firebase_core_plugin_init(FirebaseCorePlugin* self) {} + +static void method_call_cb(FlMethodChannel* channel, FlMethodCall* method_call, + gpointer user_data) { + FirebaseCorePlugin* plugin = FIREBASE_CORE_PLUGIN(user_data); + firebase_core_plugin_handle_method_call(plugin, method_call); +} + +void firebase_core_plugin_register_with_registrar(FlPluginRegistrar* registrar) { + FirebaseCorePlugin* plugin = FIREBASE_CORE_PLUGIN( + g_object_new(firebase_core_plugin_get_type(), nullptr)); + + g_autoptr(FlStandardMethodCodec) codec = fl_standard_method_codec_new(); + g_autoptr(FlMethodChannel) channel = + fl_method_channel_new(fl_plugin_registrar_get_messenger(registrar), + "firebase_core", + FL_METHOD_CODEC(codec)); + fl_method_channel_set_method_call_handler(channel, method_call_cb, + g_object_ref(plugin), + g_object_unref); + + g_object_unref(plugin); +} diff --git a/packages/firebase_core/firebase_core/firebase_core/linux/include/firebase_core/firebase_core_plugin.h b/packages/firebase_core/firebase_core/firebase_core/linux/include/firebase_core/firebase_core_plugin.h new file mode 100644 index 000000000000..3f15a61a3e72 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/linux/include/firebase_core/firebase_core_plugin.h @@ -0,0 +1,26 @@ +#ifndef FLUTTER_PLUGIN_FIREBASE_CORE_PLUGIN_H_ +#define FLUTTER_PLUGIN_FIREBASE_CORE_PLUGIN_H_ + +#include + +G_BEGIN_DECLS + +#ifdef FLUTTER_PLUGIN_IMPL +#define FLUTTER_PLUGIN_EXPORT __attribute__((visibility("default"))) +#else +#define FLUTTER_PLUGIN_EXPORT +#endif + +typedef struct _FirebaseCorePlugin FirebaseCorePlugin; +typedef struct { + GObjectClass parent_class; +} FirebaseCorePluginClass; + +FLUTTER_PLUGIN_EXPORT GType firebase_core_plugin_get_type(); + +FLUTTER_PLUGIN_EXPORT void firebase_core_plugin_register_with_registrar( + FlPluginRegistrar* registrar); + +G_END_DECLS + +#endif // FLUTTER_PLUGIN_FIREBASE_CORE_PLUGIN_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/pubspec.yaml b/packages/firebase_core/firebase_core/firebase_core/pubspec.yaml new file mode 100644 index 000000000000..ce38f84906e8 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/pubspec.yaml @@ -0,0 +1,34 @@ +name: firebase_core +description: A new Flutter plugin project. +version: 0.0.1 +homepage: + +environment: + sdk: '>=2.19.2 <3.0.0' + flutter: '>=2.5.0' + +dependencies: + ffi: ^2.0.1 + flutter: + sdk: flutter + plugin_platform_interface: ^2.0.2 + +dev_dependencies: + flutter_test: + sdk: flutter + flutter_lints: ^2.0.0 + ffigen: ^7.2.6 + +flutter: + plugin: + platforms: + linux: + pluginClass: FirebaseCorePlugin + +ffigen: + output: 'generated_bindings.dart' + headers: + entry-points: + - 'firebase/app.h' + include-directives: + - 'firebase/**.h' diff --git a/packages/firebase_core/firebase_core/firebase_core/test/firebase_core_method_channel_test.dart b/packages/firebase_core/firebase_core/firebase_core/test/firebase_core_method_channel_test.dart new file mode 100644 index 000000000000..70c7fc5e7362 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/test/firebase_core_method_channel_test.dart @@ -0,0 +1,24 @@ +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:firebase_core/firebase_core_method_channel.dart'; + +void main() { + MethodChannelFirebaseCore platform = MethodChannelFirebaseCore(); + const MethodChannel channel = MethodChannel('firebase_core'); + + TestWidgetsFlutterBinding.ensureInitialized(); + + setUp(() { + channel.setMockMethodCallHandler((MethodCall methodCall) async { + return '42'; + }); + }); + + tearDown(() { + channel.setMockMethodCallHandler(null); + }); + + test('getPlatformVersion', () async { + expect(await platform.getPlatformVersion(), '42'); + }); +} diff --git a/packages/firebase_core/firebase_core/firebase_core/test/firebase_core_test.dart b/packages/firebase_core/firebase_core/firebase_core/test/firebase_core_test.dart new file mode 100644 index 000000000000..bb8e54416b4e --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/test/firebase_core_test.dart @@ -0,0 +1,29 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:firebase_core/firebase_core.dart'; +import 'package:firebase_core/firebase_core_platform_interface.dart'; +import 'package:firebase_core/firebase_core_method_channel.dart'; +import 'package:plugin_platform_interface/plugin_platform_interface.dart'; + +class MockFirebaseCorePlatform + with MockPlatformInterfaceMixin + implements FirebaseCorePlatform { + + @override + Future getPlatformVersion() => Future.value('42'); +} + +void main() { + final FirebaseCorePlatform initialPlatform = FirebaseCorePlatform.instance; + + test('$MethodChannelFirebaseCore is the default instance', () { + expect(initialPlatform, isInstanceOf()); + }); + + test('getPlatformVersion', () async { + FirebaseCore firebaseCorePlugin = FirebaseCore(); + MockFirebaseCorePlatform fakePlatform = MockFirebaseCorePlatform(); + FirebaseCorePlatform.instance = fakePlatform; + + expect(await firebaseCorePlugin.getPlatformVersion(), '42'); + }); +} From f35108984515069ee055f8a6a69c464cd1eb8620 Mon Sep 17 00:00:00 2001 From: Guillaume Bernos Date: Mon, 6 Mar 2023 14:52:47 +0100 Subject: [PATCH 25/65] add windows --- .../firebase_core/firebase_core/.metadata | 12 +- .../firebase_core/example/windows/.gitignore | 17 ++ .../example/windows/CMakeLists.txt | 101 ++++++ .../example/windows/flutter/CMakeLists.txt | 104 +++++++ .../example/windows/runner/CMakeLists.txt | 40 +++ .../example/windows/runner/Runner.rc | 121 ++++++++ .../example/windows/runner/flutter_window.cpp | 66 ++++ .../example/windows/runner/flutter_window.h | 33 ++ .../example/windows/runner/main.cpp | 43 +++ .../example/windows/runner/resource.h | 16 + .../windows/runner/resources/app_icon.ico | Bin 0 -> 33772 bytes .../windows/runner/runner.exe.manifest | 20 ++ .../example/windows/runner/utils.cpp | 64 ++++ .../example/windows/runner/utils.h | 19 ++ .../example/windows/runner/win32_window.cpp | 288 ++++++++++++++++++ .../example/windows/runner/win32_window.h | 102 +++++++ .../firebase_core/firebase_core/pubspec.yaml | 2 + .../firebase_core/windows/.gitignore | 17 ++ .../firebase_core/windows/CMakeLists.txt | 53 ++++ .../windows/firebase_core_plugin.cpp | 59 ++++ .../windows/firebase_core_plugin.h | 32 ++ .../windows/firebase_core_plugin_c_api.cpp | 12 + .../firebase_core_plugin_c_api.h | 23 ++ 23 files changed, 1238 insertions(+), 6 deletions(-) create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/windows/.gitignore create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/windows/CMakeLists.txt create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/windows/flutter/CMakeLists.txt create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/windows/runner/CMakeLists.txt create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/windows/runner/Runner.rc create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/windows/runner/flutter_window.cpp create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/windows/runner/flutter_window.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/windows/runner/main.cpp create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/windows/runner/resource.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/windows/runner/resources/app_icon.ico create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/windows/runner/runner.exe.manifest create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/windows/runner/utils.cpp create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/windows/runner/utils.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/windows/runner/win32_window.cpp create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/windows/runner/win32_window.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/windows/.gitignore create mode 100644 packages/firebase_core/firebase_core/firebase_core/windows/CMakeLists.txt create mode 100644 packages/firebase_core/firebase_core/firebase_core/windows/firebase_core_plugin.cpp create mode 100644 packages/firebase_core/firebase_core/firebase_core/windows/firebase_core_plugin.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/windows/firebase_core_plugin_c_api.cpp create mode 100644 packages/firebase_core/firebase_core/firebase_core/windows/include/firebase_core/firebase_core_plugin_c_api.h diff --git a/packages/firebase_core/firebase_core/firebase_core/.metadata b/packages/firebase_core/firebase_core/firebase_core/.metadata index 74867a0b132b..97ef0fff36d0 100644 --- a/packages/firebase_core/firebase_core/firebase_core/.metadata +++ b/packages/firebase_core/firebase_core/firebase_core/.metadata @@ -4,7 +4,7 @@ # This file should be version controlled. version: - revision: 9944297138845a94256f1cf37beb88ff9a8e811a + revision: 12cb4eb7a009f52b347b62ade7cb4854b926af72 channel: stable project_type: plugin @@ -13,11 +13,11 @@ project_type: plugin migration: platforms: - platform: root - create_revision: 9944297138845a94256f1cf37beb88ff9a8e811a - base_revision: 9944297138845a94256f1cf37beb88ff9a8e811a - - platform: linux - create_revision: 9944297138845a94256f1cf37beb88ff9a8e811a - base_revision: 9944297138845a94256f1cf37beb88ff9a8e811a + create_revision: 12cb4eb7a009f52b347b62ade7cb4854b926af72 + base_revision: 12cb4eb7a009f52b347b62ade7cb4854b926af72 + - platform: windows + create_revision: 12cb4eb7a009f52b347b62ade7cb4854b926af72 + base_revision: 12cb4eb7a009f52b347b62ade7cb4854b926af72 # User provided section diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/.gitignore b/packages/firebase_core/firebase_core/firebase_core/example/windows/.gitignore new file mode 100644 index 000000000000..d492d0d98c8f --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/windows/.gitignore @@ -0,0 +1,17 @@ +flutter/ephemeral/ + +# Visual Studio user-specific files. +*.suo +*.user +*.userosscache +*.sln.docstates + +# Visual Studio build-related files. +x64/ +x86/ + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!*.[Cc]ache/ diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/CMakeLists.txt b/packages/firebase_core/firebase_core/firebase_core/example/windows/CMakeLists.txt new file mode 100644 index 000000000000..ddf92aa378e1 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/windows/CMakeLists.txt @@ -0,0 +1,101 @@ +# Project-level configuration. +cmake_minimum_required(VERSION 3.14) +project(firebase_core_example LANGUAGES CXX) + +# The name of the executable created for the application. Change this to change +# the on-disk name of your application. +set(BINARY_NAME "firebase_core_example") + +# Explicitly opt in to modern CMake behaviors to avoid warnings with recent +# versions of CMake. +cmake_policy(SET CMP0063 NEW) + +# Define build configuration option. +get_property(IS_MULTICONFIG GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG) +if(IS_MULTICONFIG) + set(CMAKE_CONFIGURATION_TYPES "Debug;Profile;Release" + CACHE STRING "" FORCE) +else() + if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) + set(CMAKE_BUILD_TYPE "Debug" CACHE + STRING "Flutter build mode" FORCE) + set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS + "Debug" "Profile" "Release") + endif() +endif() +# Define settings for the Profile build mode. +set(CMAKE_EXE_LINKER_FLAGS_PROFILE "${CMAKE_EXE_LINKER_FLAGS_RELEASE}") +set(CMAKE_SHARED_LINKER_FLAGS_PROFILE "${CMAKE_SHARED_LINKER_FLAGS_RELEASE}") +set(CMAKE_C_FLAGS_PROFILE "${CMAKE_C_FLAGS_RELEASE}") +set(CMAKE_CXX_FLAGS_PROFILE "${CMAKE_CXX_FLAGS_RELEASE}") + +# Use Unicode for all projects. +add_definitions(-DUNICODE -D_UNICODE) + +# Compilation settings that should be applied to most targets. +# +# Be cautious about adding new options here, as plugins use this function by +# default. In most cases, you should add new options to specific targets instead +# of modifying this function. +function(APPLY_STANDARD_SETTINGS TARGET) + target_compile_features(${TARGET} PUBLIC cxx_std_17) + target_compile_options(${TARGET} PRIVATE /W4 /WX /wd"4100") + target_compile_options(${TARGET} PRIVATE /EHsc) + target_compile_definitions(${TARGET} PRIVATE "_HAS_EXCEPTIONS=0") + target_compile_definitions(${TARGET} PRIVATE "$<$:_DEBUG>") +endfunction() + +# Flutter library and tool build rules. +set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") +add_subdirectory(${FLUTTER_MANAGED_DIR}) + +# Application build; see runner/CMakeLists.txt. +add_subdirectory("runner") + +# Generated plugin build rules, which manage building the plugins and adding +# them to the application. +include(flutter/generated_plugins.cmake) + + +# === Installation === +# Support files are copied into place next to the executable, so that it can +# run in place. This is done instead of making a separate bundle (as on Linux) +# so that building and running from within Visual Studio will work. +set(BUILD_BUNDLE_DIR "$") +# Make the "install" step default, as it's required to run. +set(CMAKE_VS_INCLUDE_INSTALL_TO_DEFAULT_BUILD 1) +if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) + set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) +endif() + +set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") +set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}") + +install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +if(PLUGIN_BUNDLED_LIBRARIES) + install(FILES "${PLUGIN_BUNDLED_LIBRARIES}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endif() + +# Fully re-copy the assets directory on each build to avoid having stale files +# from a previous install. +set(FLUTTER_ASSET_DIR_NAME "flutter_assets") +install(CODE " + file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") + " COMPONENT Runtime) +install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" + DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) + +# Install the AOT library on non-Debug builds only. +install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + CONFIGURATIONS Profile;Release + COMPONENT Runtime) diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/flutter/CMakeLists.txt b/packages/firebase_core/firebase_core/firebase_core/example/windows/flutter/CMakeLists.txt new file mode 100644 index 000000000000..930d2071a324 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/windows/flutter/CMakeLists.txt @@ -0,0 +1,104 @@ +# This file controls Flutter-level build steps. It should not be edited. +cmake_minimum_required(VERSION 3.14) + +set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") + +# Configuration provided via flutter tool. +include(${EPHEMERAL_DIR}/generated_config.cmake) + +# TODO: Move the rest of this into files in ephemeral. See +# https://github.com/flutter/flutter/issues/57146. +set(WRAPPER_ROOT "${EPHEMERAL_DIR}/cpp_client_wrapper") + +# === Flutter Library === +set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/flutter_windows.dll") + +# Published to parent scope for install step. +set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) +set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) +set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) +set(AOT_LIBRARY "${PROJECT_DIR}/build/windows/app.so" PARENT_SCOPE) + +list(APPEND FLUTTER_LIBRARY_HEADERS + "flutter_export.h" + "flutter_windows.h" + "flutter_messenger.h" + "flutter_plugin_registrar.h" + "flutter_texture_registrar.h" +) +list(TRANSFORM FLUTTER_LIBRARY_HEADERS PREPEND "${EPHEMERAL_DIR}/") +add_library(flutter INTERFACE) +target_include_directories(flutter INTERFACE + "${EPHEMERAL_DIR}" +) +target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}.lib") +add_dependencies(flutter flutter_assemble) + +# === Wrapper === +list(APPEND CPP_WRAPPER_SOURCES_CORE + "core_implementations.cc" + "standard_codec.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_CORE PREPEND "${WRAPPER_ROOT}/") +list(APPEND CPP_WRAPPER_SOURCES_PLUGIN + "plugin_registrar.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_PLUGIN PREPEND "${WRAPPER_ROOT}/") +list(APPEND CPP_WRAPPER_SOURCES_APP + "flutter_engine.cc" + "flutter_view_controller.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_APP PREPEND "${WRAPPER_ROOT}/") + +# Wrapper sources needed for a plugin. +add_library(flutter_wrapper_plugin STATIC + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_PLUGIN} +) +apply_standard_settings(flutter_wrapper_plugin) +set_target_properties(flutter_wrapper_plugin PROPERTIES + POSITION_INDEPENDENT_CODE ON) +set_target_properties(flutter_wrapper_plugin PROPERTIES + CXX_VISIBILITY_PRESET hidden) +target_link_libraries(flutter_wrapper_plugin PUBLIC flutter) +target_include_directories(flutter_wrapper_plugin PUBLIC + "${WRAPPER_ROOT}/include" +) +add_dependencies(flutter_wrapper_plugin flutter_assemble) + +# Wrapper sources needed for the runner. +add_library(flutter_wrapper_app STATIC + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_APP} +) +apply_standard_settings(flutter_wrapper_app) +target_link_libraries(flutter_wrapper_app PUBLIC flutter) +target_include_directories(flutter_wrapper_app PUBLIC + "${WRAPPER_ROOT}/include" +) +add_dependencies(flutter_wrapper_app flutter_assemble) + +# === Flutter tool backend === +# _phony_ is a non-existent file to force this command to run every time, +# since currently there's no way to get a full input/output list from the +# flutter tool. +set(PHONY_OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/_phony_") +set_source_files_properties("${PHONY_OUTPUT}" PROPERTIES SYMBOLIC TRUE) +add_custom_command( + OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} + ${CPP_WRAPPER_SOURCES_CORE} ${CPP_WRAPPER_SOURCES_PLUGIN} + ${CPP_WRAPPER_SOURCES_APP} + ${PHONY_OUTPUT} + COMMAND ${CMAKE_COMMAND} -E env + ${FLUTTER_TOOL_ENVIRONMENT} + "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.bat" + windows-x64 $ + VERBATIM +) +add_custom_target(flutter_assemble DEPENDS + "${FLUTTER_LIBRARY}" + ${FLUTTER_LIBRARY_HEADERS} + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_PLUGIN} + ${CPP_WRAPPER_SOURCES_APP} +) diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/CMakeLists.txt b/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/CMakeLists.txt new file mode 100644 index 000000000000..394917c053a0 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/CMakeLists.txt @@ -0,0 +1,40 @@ +cmake_minimum_required(VERSION 3.14) +project(runner LANGUAGES CXX) + +# Define the application target. To change its name, change BINARY_NAME in the +# top-level CMakeLists.txt, not the value here, or `flutter run` will no longer +# work. +# +# Any new source files that you add to the application should be added here. +add_executable(${BINARY_NAME} WIN32 + "flutter_window.cpp" + "main.cpp" + "utils.cpp" + "win32_window.cpp" + "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" + "Runner.rc" + "runner.exe.manifest" +) + +# Apply the standard set of build settings. This can be removed for applications +# that need different build settings. +apply_standard_settings(${BINARY_NAME}) + +# Add preprocessor definitions for the build version. +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION=\"${FLUTTER_VERSION}\"") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MAJOR=${FLUTTER_VERSION_MAJOR}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MINOR=${FLUTTER_VERSION_MINOR}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_PATCH=${FLUTTER_VERSION_PATCH}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_BUILD=${FLUTTER_VERSION_BUILD}") + +# Disable Windows macros that collide with C++ standard library functions. +target_compile_definitions(${BINARY_NAME} PRIVATE "NOMINMAX") + +# Add dependency libraries and include directories. Add any application-specific +# dependencies here. +target_link_libraries(${BINARY_NAME} PRIVATE flutter flutter_wrapper_app) +target_link_libraries(${BINARY_NAME} PRIVATE "dwmapi.lib") +target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") + +# Run the Flutter tool portions of the build. This must not be removed. +add_dependencies(${BINARY_NAME} flutter_assemble) diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/Runner.rc b/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/Runner.rc new file mode 100644 index 000000000000..c0d7fe21c712 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/Runner.rc @@ -0,0 +1,121 @@ +// Microsoft Visual C++ generated resource script. +// +#pragma code_page(65001) +#include "resource.h" + +#define APSTUDIO_READONLY_SYMBOLS +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 2 resource. +// +#include "winres.h" + +///////////////////////////////////////////////////////////////////////////// +#undef APSTUDIO_READONLY_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +// English (United States) resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) +LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US + +#ifdef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// TEXTINCLUDE +// + +1 TEXTINCLUDE +BEGIN + "resource.h\0" +END + +2 TEXTINCLUDE +BEGIN + "#include ""winres.h""\r\n" + "\0" +END + +3 TEXTINCLUDE +BEGIN + "\r\n" + "\0" +END + +#endif // APSTUDIO_INVOKED + + +///////////////////////////////////////////////////////////////////////////// +// +// Icon +// + +// Icon with lowest ID value placed first to ensure application icon +// remains consistent on all systems. +IDI_APP_ICON ICON "resources\\app_icon.ico" + + +///////////////////////////////////////////////////////////////////////////// +// +// Version +// + +#if defined(FLUTTER_VERSION_MAJOR) && defined(FLUTTER_VERSION_MINOR) && defined(FLUTTER_VERSION_PATCH) && defined(FLUTTER_VERSION_BUILD) +#define VERSION_AS_NUMBER FLUTTER_VERSION_MAJOR,FLUTTER_VERSION_MINOR,FLUTTER_VERSION_PATCH,FLUTTER_VERSION_BUILD +#else +#define VERSION_AS_NUMBER 1,0,0,0 +#endif + +#if defined(FLUTTER_VERSION) +#define VERSION_AS_STRING FLUTTER_VERSION +#else +#define VERSION_AS_STRING "1.0.0" +#endif + +VS_VERSION_INFO VERSIONINFO + FILEVERSION VERSION_AS_NUMBER + PRODUCTVERSION VERSION_AS_NUMBER + FILEFLAGSMASK VS_FFI_FILEFLAGSMASK +#ifdef _DEBUG + FILEFLAGS VS_FF_DEBUG +#else + FILEFLAGS 0x0L +#endif + FILEOS VOS__WINDOWS32 + FILETYPE VFT_APP + FILESUBTYPE 0x0L +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "040904e4" + BEGIN + VALUE "CompanyName", "com.example" "\0" + VALUE "FileDescription", "firebase_core_example" "\0" + VALUE "FileVersion", VERSION_AS_STRING "\0" + VALUE "InternalName", "firebase_core_example" "\0" + VALUE "LegalCopyright", "Copyright (C) 2023 com.example. All rights reserved." "\0" + VALUE "OriginalFilename", "firebase_core_example.exe" "\0" + VALUE "ProductName", "firebase_core_example" "\0" + VALUE "ProductVersion", VERSION_AS_STRING "\0" + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x409, 1252 + END +END + +#endif // English (United States) resources +///////////////////////////////////////////////////////////////////////////// + + + +#ifndef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 3 resource. +// + + +///////////////////////////////////////////////////////////////////////////// +#endif // not APSTUDIO_INVOKED diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/flutter_window.cpp b/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/flutter_window.cpp new file mode 100644 index 000000000000..b25e363efa42 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/flutter_window.cpp @@ -0,0 +1,66 @@ +#include "flutter_window.h" + +#include + +#include "flutter/generated_plugin_registrant.h" + +FlutterWindow::FlutterWindow(const flutter::DartProject& project) + : project_(project) {} + +FlutterWindow::~FlutterWindow() {} + +bool FlutterWindow::OnCreate() { + if (!Win32Window::OnCreate()) { + return false; + } + + RECT frame = GetClientArea(); + + // The size here must match the window dimensions to avoid unnecessary surface + // creation / destruction in the startup path. + flutter_controller_ = std::make_unique( + frame.right - frame.left, frame.bottom - frame.top, project_); + // Ensure that basic setup of the controller was successful. + if (!flutter_controller_->engine() || !flutter_controller_->view()) { + return false; + } + RegisterPlugins(flutter_controller_->engine()); + SetChildContent(flutter_controller_->view()->GetNativeWindow()); + + flutter_controller_->engine()->SetNextFrameCallback([&]() { + this->Show(); + }); + + return true; +} + +void FlutterWindow::OnDestroy() { + if (flutter_controller_) { + flutter_controller_ = nullptr; + } + + Win32Window::OnDestroy(); +} + +LRESULT +FlutterWindow::MessageHandler(HWND hwnd, UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + // Give Flutter, including plugins, an opportunity to handle window messages. + if (flutter_controller_) { + std::optional result = + flutter_controller_->HandleTopLevelWindowProc(hwnd, message, wparam, + lparam); + if (result) { + return *result; + } + } + + switch (message) { + case WM_FONTCHANGE: + flutter_controller_->engine()->ReloadSystemFonts(); + break; + } + + return Win32Window::MessageHandler(hwnd, message, wparam, lparam); +} diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/flutter_window.h b/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/flutter_window.h new file mode 100644 index 000000000000..6da0652f05f2 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/flutter_window.h @@ -0,0 +1,33 @@ +#ifndef RUNNER_FLUTTER_WINDOW_H_ +#define RUNNER_FLUTTER_WINDOW_H_ + +#include +#include + +#include + +#include "win32_window.h" + +// A window that does nothing but host a Flutter view. +class FlutterWindow : public Win32Window { + public: + // Creates a new FlutterWindow hosting a Flutter view running |project|. + explicit FlutterWindow(const flutter::DartProject& project); + virtual ~FlutterWindow(); + + protected: + // Win32Window: + bool OnCreate() override; + void OnDestroy() override; + LRESULT MessageHandler(HWND window, UINT const message, WPARAM const wparam, + LPARAM const lparam) noexcept override; + + private: + // The project to run. + flutter::DartProject project_; + + // The Flutter instance hosted by this window. + std::unique_ptr flutter_controller_; +}; + +#endif // RUNNER_FLUTTER_WINDOW_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/main.cpp b/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/main.cpp new file mode 100644 index 000000000000..2b640e48b2b0 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/main.cpp @@ -0,0 +1,43 @@ +#include +#include +#include + +#include "flutter_window.h" +#include "utils.h" + +int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev, + _In_ wchar_t *command_line, _In_ int show_command) { + // Attach to console when present (e.g., 'flutter run') or create a + // new console when running with a debugger. + if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent()) { + CreateAndAttachConsole(); + } + + // Initialize COM, so that it is available for use in the library and/or + // plugins. + ::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED); + + flutter::DartProject project(L"data"); + + std::vector command_line_arguments = + GetCommandLineArguments(); + + project.set_dart_entrypoint_arguments(std::move(command_line_arguments)); + + FlutterWindow window(project); + Win32Window::Point origin(10, 10); + Win32Window::Size size(1280, 720); + if (!window.Create(L"firebase_core_example", origin, size)) { + return EXIT_FAILURE; + } + window.SetQuitOnClose(true); + + ::MSG msg; + while (::GetMessage(&msg, nullptr, 0, 0)) { + ::TranslateMessage(&msg); + ::DispatchMessage(&msg); + } + + ::CoUninitialize(); + return EXIT_SUCCESS; +} diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/resource.h b/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/resource.h new file mode 100644 index 000000000000..66a65d1e4a79 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/resource.h @@ -0,0 +1,16 @@ +//{{NO_DEPENDENCIES}} +// Microsoft Visual C++ generated include file. +// Used by Runner.rc +// +#define IDI_APP_ICON 101 + +// Next default values for new objects +// +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_NEXT_RESOURCE_VALUE 102 +#define _APS_NEXT_COMMAND_VALUE 40001 +#define _APS_NEXT_CONTROL_VALUE 1001 +#define _APS_NEXT_SYMED_VALUE 101 +#endif +#endif diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/resources/app_icon.ico b/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/resources/app_icon.ico new file mode 100644 index 0000000000000000000000000000000000000000..c04e20caf6370ebb9253ad831cc31de4a9c965f6 GIT binary patch literal 33772 zcmeHQc|26z|35SKE&G-*mXah&B~fFkXr)DEO&hIfqby^T&>|8^_Ub8Vp#`BLl3lbZ zvPO!8k!2X>cg~Elr=IVxo~J*a`+9wR=A83c-k-DFd(XM&UI1VKCqM@V;DDtJ09WB} zRaHKiW(GT00brH|0EeTeKVbpbGZg?nK6-j827q-+NFM34gXjqWxJ*a#{b_apGN<-L_m3#8Z26atkEn& ze87Bvv^6vVmM+p+cQ~{u%=NJF>#(d;8{7Q{^rWKWNtf14H}>#&y7$lqmY6xmZryI& z($uy?c5-+cPnt2%)R&(KIWEXww>Cnz{OUpT>W$CbO$h1= z#4BPMkFG1Y)x}Ui+WXr?Z!w!t_hjRq8qTaWpu}FH{MsHlU{>;08goVLm{V<&`itk~ zE_Ys=D(hjiy+5=?=$HGii=Y5)jMe9|wWoD_K07(}edAxh`~LBorOJ!Cf@f{_gNCC| z%{*04ViE!#>@hc1t5bb+NO>ncf@@Dv01K!NxH$3Eg1%)|wLyMDF8^d44lV!_Sr}iEWefOaL z8f?ud3Q%Sen39u|%00W<#!E=-RpGa+H8}{ulxVl4mwpjaU+%2pzmi{3HM)%8vb*~-M9rPUAfGCSos8GUXp02|o~0BTV2l#`>>aFV&_P$ejS;nGwSVP8 zMbOaG7<7eKD>c12VdGH;?2@q7535sa7MN*L@&!m?L`ASG%boY7(&L5imY#EQ$KrBB z4@_tfP5m50(T--qv1BJcD&aiH#b-QC>8#7Fx@3yXlonJI#aEIi=8&ChiVpc#N=5le zM*?rDIdcpawoc5kizv$GEjnveyrp3sY>+5_R5;>`>erS%JolimF=A^EIsAK zsPoVyyUHCgf0aYr&alx`<)eb6Be$m&`JYSuBu=p8j%QlNNp$-5C{b4#RubPb|CAIS zGE=9OFLP7?Hgc{?k45)84biT0k&-C6C%Q}aI~q<(7BL`C#<6HyxaR%!dFx7*o^laG z=!GBF^cwK$IA(sn9y6>60Rw{mYRYkp%$jH z*xQM~+bp)G$_RhtFPYx2HTsWk80+p(uqv9@I9)y{b$7NK53rYL$ezbmRjdXS?V}fj zWxX_feWoLFNm3MG7pMUuFPs$qrQWO9!l2B(SIuy2}S|lHNbHzoE+M2|Zxhjq9+Ws8c{*}x^VAib7SbxJ*Q3EnY5lgI9 z=U^f3IW6T=TWaVj+2N%K3<%Un;CF(wUp`TC&Y|ZjyFu6co^uqDDB#EP?DV5v_dw~E zIRK*BoY9y-G_ToU2V_XCX4nJ32~`czdjT!zwme zGgJ0nOk3U4@IE5JwtM}pwimLjk{ln^*4HMU%Fl4~n(cnsLB}Ja-jUM>xIB%aY;Nq8 z)Fp8dv1tkqKanv<68o@cN|%thj$+f;zGSO7H#b+eMAV8xH$hLggtt?O?;oYEgbq@= zV(u9bbd12^%;?nyk6&$GPI%|+<_mEpJGNfl*`!KV;VfmZWw{n{rnZ51?}FDh8we_L z8OI9nE31skDqJ5Oa_ybn7|5@ui>aC`s34p4ZEu6-s!%{uU45$Zd1=p$^^dZBh zu<*pDDPLW+c>iWO$&Z_*{VSQKg7=YEpS3PssPn1U!lSm6eZIho*{@&20e4Y_lRklKDTUCKI%o4Pc<|G^Xgu$J^Q|B87U;`c1zGwf^-zH*VQ^x+i^OUWE0yd z;{FJq)2w!%`x7yg@>uGFFf-XJl4H`YtUG%0slGKOlXV`q?RP>AEWg#x!b{0RicxGhS!3$p7 zij;{gm!_u@D4$Ox%>>bPtLJ> zwKtYz?T_DR1jN>DkkfGU^<#6sGz|~p*I{y`aZ>^Di#TC|Z!7j_O1=Wo8thuit?WxR zh9_S>kw^{V^|g}HRUF=dcq>?q(pHxw!8rx4dC6vbQVmIhmICF#zU!HkHpQ>9S%Uo( zMw{eC+`&pb=GZRou|3;Po1}m46H6NGd$t<2mQh}kaK-WFfmj_66_17BX0|j-E2fe3Jat}ijpc53 zJV$$;PC<5aW`{*^Z6e5##^`Ed#a0nwJDT#Qq~^e8^JTA=z^Kl>La|(UQ!bI@#ge{Dzz@61p-I)kc2?ZxFt^QQ}f%ldLjO*GPj(5)V9IyuUakJX=~GnTgZ4$5!3E=V#t`yOG4U z(gphZB6u2zsj=qNFLYShhg$}lNpO`P9xOSnO*$@@UdMYES*{jJVj|9z-}F^riksLK zbsU+4-{281P9e2UjY6tse^&a)WM1MFw;p#_dHhWI7p&U*9TR0zKdVuQed%6{otTsq z$f~S!;wg#Bd9kez=Br{m|66Wv z#g1xMup<0)H;c2ZO6su_ii&m8j&+jJz4iKnGZ&wxoQX|5a>v&_e#6WA!MB_4asTxLRGQCC5cI(em z%$ZfeqP>!*q5kU>a+BO&ln=4Jm>Ef(QE8o&RgLkk%2}4Tf}U%IFP&uS7}&|Q-)`5< z+e>;s#4cJ-z%&-^&!xsYx777Wt(wZY9(3(avmr|gRe4cD+a8&!LY`1^T?7x{E<=kdY9NYw>A;FtTvQ=Y&1M%lyZPl$ss1oY^Sl8we}n}Aob#6 zl4jERwnt9BlSoWb@3HxYgga(752Vu6Y)k4yk9u~Kw>cA5&LHcrvn1Y-HoIuFWg~}4 zEw4bR`mXZQIyOAzo)FYqg?$5W<;^+XX%Uz61{-L6@eP|lLH%|w?g=rFc;OvEW;^qh z&iYXGhVt(G-q<+_j}CTbPS_=K>RKN0&;dubh0NxJyDOHFF;<1k!{k#7b{|Qok9hac z;gHz}6>H6C6RnB`Tt#oaSrX0p-j-oRJ;_WvS-qS--P*8}V943RT6kou-G=A+7QPGQ z!ze^UGxtW3FC0$|(lY9^L!Lx^?Q8cny(rR`es5U;-xBhphF%_WNu|aO<+e9%6LuZq zt(0PoagJG<%hyuf;te}n+qIl_Ej;czWdc{LX^pS>77s9t*2b4s5dvP_!L^3cwlc)E!(!kGrg~FescVT zZCLeua3f4;d;Tk4iXzt}g}O@nlK3?_o91_~@UMIl?@77Qc$IAlLE95#Z=TES>2E%z zxUKpK{_HvGF;5%Q7n&vA?`{%8ohlYT_?(3A$cZSi)MvIJygXD}TS-3UwyUxGLGiJP znblO~G|*uA^|ac8E-w#}uBtg|s_~s&t>-g0X%zIZ@;o_wNMr_;{KDg^O=rg`fhDZu zFp(VKd1Edj%F zWHPl+)FGj%J1BO3bOHVfH^3d1F{)*PL&sRX`~(-Zy3&9UQX)Z;c51tvaI2E*E7!)q zcz|{vpK7bjxix(k&6=OEIBJC!9lTkUbgg?4-yE{9+pFS)$Ar@vrIf`D0Bnsed(Cf? zObt2CJ>BKOl>q8PyFO6w)+6Iz`LW%T5^R`U_NIW0r1dWv6OY=TVF?N=EfA(k(~7VBW(S;Tu5m4Lg8emDG-(mOSSs=M9Q&N8jc^Y4&9RqIsk(yO_P(mcCr}rCs%1MW1VBrn=0-oQN(Xj!k%iKV zb%ricBF3G4S1;+8lzg5PbZ|$Se$)I=PwiK=cDpHYdov2QO1_a-*dL4KUi|g&oh>(* zq$<`dQ^fat`+VW?m)?_KLn&mp^-@d=&7yGDt<=XwZZC=1scwxO2^RRI7n@g-1o8ps z)&+et_~)vr8aIF1VY1Qrq~Xe``KJrQSnAZ{CSq3yP;V*JC;mmCT6oRLSs7=GA?@6g zUooM}@tKtx(^|aKK8vbaHlUQqwE0}>j&~YlN3H#vKGm@u)xxS?n9XrOWUfCRa< z`20Fld2f&;gg7zpo{Adh+mqNntMc-D$N^yWZAZRI+u1T1zWHPxk{+?vcS1D>08>@6 zLhE@`gt1Y9mAK6Z4p|u(5I%EkfU7rKFSM=E4?VG9tI;a*@?6!ey{lzN5=Y-!$WFSe z&2dtO>^0@V4WRc#L&P%R(?@KfSblMS+N+?xUN$u3K4Ys%OmEh+tq}fnU}i>6YHM?< zlnL2gl~sF!j!Y4E;j3eIU-lfa`RsOL*Tt<%EFC0gPzoHfNWAfKFIKZN8}w~(Yi~=q z>=VNLO2|CjkxP}RkutxjV#4fWYR1KNrPYq5ha9Wl+u>ipsk*I(HS@iLnmGH9MFlTU zaFZ*KSR0px>o+pL7BbhB2EC1%PJ{67_ z#kY&#O4@P=OV#-79y_W>Gv2dxL*@G7%LksNSqgId9v;2xJ zrh8uR!F-eU$NMx@S*+sk=C~Dxr9Qn7TfWnTupuHKuQ$;gGiBcU>GF5sWx(~4IP3`f zWE;YFO*?jGwYh%C3X<>RKHC-DZ!*r;cIr}GLOno^3U4tFSSoJp%oHPiSa%nh=Zgn% z14+8v@ygy0>UgEN1bczD6wK45%M>psM)y^)IfG*>3ItX|TzV*0i%@>L(VN!zdKb8S?Qf7BhjNpziA zR}?={-eu>9JDcl*R=OP9B8N$IcCETXah9SUDhr{yrld{G;PnCWRsPD7!eOOFBTWUQ=LrA_~)mFf&!zJX!Oc-_=kT<}m|K52 z)M=G#;p;Rdb@~h5D{q^K;^fX-m5V}L%!wVC2iZ1uu401Ll}#rocTeK|7FAeBRhNdQ zCc2d^aQnQp=MpOmak60N$OgS}a;p(l9CL`o4r(e-nN}mQ?M&isv-P&d$!8|1D1I(3-z!wi zTgoo)*Mv`gC?~bm?S|@}I|m-E2yqPEvYybiD5azInexpK8?9q*$9Yy9-t%5jU8~ym zgZDx>!@ujQ=|HJnwp^wv-FdD{RtzO9SnyfB{mH_(c!jHL*$>0o-(h(eqe*ZwF6Lvu z{7rkk%PEqaA>o+f{H02tzZ@TWy&su?VNw43! z-X+rN`6llvpUms3ZiSt)JMeztB~>9{J8SPmYs&qohxdYFi!ra8KR$35Zp9oR)eFC4 zE;P31#3V)n`w$fZ|4X-|%MX`xZDM~gJyl2W;O$H25*=+1S#%|53>|LyH za@yh+;325%Gq3;J&a)?%7X%t@WXcWL*BaaR*7UEZad4I8iDt7^R_Fd`XeUo256;sAo2F!HcIQKk;h})QxEsPE5BcKc7WyerTchgKmrfRX z!x#H_%cL#B9TWAqkA4I$R^8{%do3Y*&(;WFmJ zU7Dih{t1<{($VtJRl9|&EB?|cJ)xse!;}>6mSO$o5XIx@V|AA8ZcoD88ZM?C*;{|f zZVmf94_l1OmaICt`2sTyG!$^UeTHx9YuUP!omj(r|7zpm5475|yXI=rR>>fteLI+| z)MoiGho0oEt=*J(;?VY0QzwCqw@cVm?d7Y!z0A@u#H?sCJ*ecvyhj& z-F77lO;SH^dmf?L>3i>?Z*U}Em4ZYV_CjgfvzYsRZ+1B!Uo6H6mbS<-FFL`ytqvb& zE7+)2ahv-~dz(Hs+f})z{*4|{)b=2!RZK;PWwOnO=hG7xG`JU5>bAvUbdYd_CjvtHBHgtGdlO+s^9ca^Bv3`t@VRX2_AD$Ckg36OcQRF zXD6QtGfHdw*hx~V(MV-;;ZZF#dJ-piEF+s27z4X1qi5$!o~xBnvf=uopcn7ftfsZc zy@(PuOk`4GL_n(H9(E2)VUjqRCk9kR?w)v@xO6Jm_Mx})&WGEl=GS0#)0FAq^J*o! zAClhvoTsNP*-b~rN{8Yym3g{01}Ep^^Omf=SKqvN?{Q*C4HNNAcrowIa^mf+3PRy! z*_G-|3i8a;+q;iP@~Of_$(vtFkB8yOyWt2*K)vAn9El>=D;A$CEx6b*XF@4y_6M+2 zpeW`RHoI_p(B{%(&jTHI->hmNmZjHUj<@;7w0mx3&koy!2$@cfX{sN19Y}euYJFn& z1?)+?HCkD0MRI$~uB2UWri})0bru_B;klFdwsLc!ne4YUE;t41JqfG# zZJq6%vbsdx!wYeE<~?>o4V`A3?lN%MnKQ`z=uUivQN^vzJ|C;sdQ37Qn?;lpzg})y z)_2~rUdH}zNwX;Tp0tJ78+&I=IwOQ-fl30R79O8@?Ub8IIA(6I`yHn%lARVL`%b8+ z4$8D-|MZZWxc_)vu6@VZN!HsI$*2NOV&uMxBNzIbRgy%ob_ zhwEH{J9r$!dEix9XM7n&c{S(h>nGm?el;gaX0@|QnzFD@bne`el^CO$yXC?BDJ|Qg z+y$GRoR`?ST1z^e*>;!IS@5Ovb7*RlN>BV_UC!7E_F;N#ky%1J{+iixp(dUJj93aK zzHNN>R-oN7>kykHClPnoPTIj7zc6KM(Pnlb(|s??)SMb)4!sMHU^-ntJwY5Big7xv zb1Ew`Xj;|D2kzGja*C$eS44(d&RMU~c_Y14V9_TLTz0J#uHlsx`S6{nhsA0dWZ#cG zJ?`fO50E>*X4TQLv#nl%3GOk*UkAgt=IY+u0LNXqeln3Z zv$~&Li`ZJOKkFuS)dJRA>)b_Da%Q~axwA_8zNK{BH{#}#m}zGcuckz}riDE-z_Ms> zR8-EqAMcfyGJCtvTpaUVQtajhUS%c@Yj}&6Zz;-M7MZzqv3kA7{SuW$oW#=0az2wQ zg-WG@Vb4|D`pl~Il54N7Hmsauc_ne-a!o5#j3WaBBh@Wuefb!QJIOn5;d)%A#s+5% zuD$H=VNux9bE-}1&bcYGZ+>1Fo;3Z@e&zX^n!?JK*adSbONm$XW9z;Q^L>9U!}Toj2WdafJ%oL#h|yWWwyAGxzfrAWdDTtaKl zK4`5tDpPg5>z$MNv=X0LZ0d6l%D{(D8oT@+w0?ce$DZ6pv>{1&Ok67Ix1 zH}3=IEhPJEhItCC8E=`T`N5(k?G=B4+xzZ?<4!~ ze~z6Wk9!CHTI(0rLJ4{JU?E-puc;xusR?>G?;4vt;q~iI9=kDL=z0Rr%O$vU`30X$ zDZRFyZ`(omOy@u|i6h;wtJlP;+}$|Ak|k2dea7n?U1*$T!sXqqOjq^NxLPMmk~&qI zYg0W?yK8T(6+Ea+$YyspKK?kP$+B`~t3^Pib_`!6xCs32!i@pqXfFV6PmBIR<-QW= zN8L{pt0Vap0x`Gzn#E@zh@H)0FfVfA_Iu4fjYZ+umO1LXIbVc$pY+E234u)ttcrl$ z>s92z4vT%n6cMb>=XT6;l0+9e(|CZG)$@C7t7Z7Ez@a)h)!hyuV&B5K%%)P5?Lk|C zZZSVzdXp{@OXSP0hoU-gF8s8Um(#xzjP2Vem zec#-^JqTa&Y#QJ>-FBxd7tf`XB6e^JPUgagB8iBSEps;92KG`!#mvVcPQ5yNC-GEG zTiHEDYfH+0O15}r^+ z#jxj=@x8iNHWALe!P3R67TwmhItn**0JwnzSV2O&KE8KcT+0hWH^OPD1pwiuyx=b@ zNf5Jh0{9X)8;~Es)$t@%(3!OnbY+`@?i{mGX7Yy}8T_*0a6g;kaFPq;*=px5EhO{Cp%1kI<0?*|h8v!6WnO3cCJRF2-CRrU3JiLJnj@6;L)!0kWYAc_}F{2P))3HmCrz zQ&N&gE70;`!6*eJ4^1IR{f6j4(-l&X!tjHxkbHA^Zhrnhr9g{exN|xrS`5Pq=#Xf& zG%P=#ra-TyVFfgW%cZo5OSIwFL9WtXAlFOa+ubmI5t*3=g#Y zF%;70p5;{ZeFL}&}yOY1N1*Q;*<(kTB!7vM$QokF)yr2FlIU@$Ph58$Bz z0J?xQG=MlS4L6jA22eS42g|9*9pX@$#*sUeM(z+t?hr@r5J&D1rx}2pW&m*_`VDCW zUYY@v-;bAO0HqoAgbbiGGC<=ryf96}3pouhy3XJrX+!!u*O_>Si38V{uJmQ&USptX zKp#l(?>%^7;2%h(q@YWS#9;a!JhKlkR#Vd)ERILlgu!Hr@jA@V;sk4BJ-H#p*4EqC zDGjC*tl=@3Oi6)Bn^QwFpul18fpkbpg0+peH$xyPBqb%`$OUhPKyWb32o7clB*9Z< zN=i~NLjavrLtwgJ01bufP+>p-jR2I95|TpmKpQL2!oV>g(4RvS2pK4*ou%m(h6r3A zX#s&`9LU1ZG&;{CkOK!4fLDTnBys`M!vuz>Q&9OZ0hGQl!~!jSDg|~s*w52opC{sB ze|Cf2luD(*G13LcOAGA!s2FjSK8&IE5#W%J25w!vM0^VyQM!t)inj&RTiJ!wXzFgz z3^IqzB7I0L$llljsGq})thBy9UOyjtFO_*hYM_sgcMk>44jeH0V1FDyELc{S1F-;A zS;T^k^~4biG&V*Irq}O;e}j$$+E_#G?HKIn05iP3j|87TkGK~SqG!-KBg5+mN(aLm z8ybhIM`%C19UX$H$KY6JgXbY$0AT%rEpHC;u`rQ$Y=rxUdsc5*Kvc8jaYaO$^)cI6){P6K0r)I6DY4Wr4&B zLQUBraey#0HV|&c4v7PVo3n$zHj99(TZO^3?Ly%C4nYvJTL9eLBLHsM3WKKD>5!B` zQ=BsR3aR6PD(Fa>327E2HAu5TM~Wusc!)>~(gM)+3~m;92Jd;FnSib=M5d6;;5{%R zb4V7DEJ0V!CP-F*oU?gkc>ksUtAYP&V4ND5J>J2^jt*vcFflQWCrB&fLdT%O59PVJ zhid#toR=FNgD!q3&r8#wEBr`!wzvQu5zX?Q>nlSJ4i@WC*CN*-xU66F^V5crWevQ9gsq$I@z1o(a=k7LL~ z7m_~`o;_Ozha1$8Q}{WBehvAlO4EL60y5}8GDrZ< zXh&F}71JbW2A~8KfEWj&UWV#4+Z4p`b{uAj4&WC zha`}X@3~+Iz^WRlOHU&KngK>#j}+_o@LdBC1H-`gT+krWX3-;!)6?{FBp~%20a}FL zFP9%Emqcwa#(`=G>BBZ0qZDQhmZKJg_g8<=bBFKWr!dyg(YkpE+|R*SGpDVU!+VlU zFC54^DLv}`qa%49T>nNiA9Q7Ips#!Xx90tCU2gvK`(F+GPcL=J^>No{)~we#o@&mUb6c$ zCc*<|NJBk-#+{j9xkQ&ujB zI~`#kN~7W!f*-}wkG~Ld!JqZ@tK}eeSnsS5J1fMFXm|`LJx&}5`@dK3W^7#Wnm+_P zBZkp&j1fa2Y=eIjJ0}gh85jt43kaIXXv?xmo@eHrka!Z|vQv12HN#+!I5E z`(fbuW>gFiJL|uXJ!vKt#z3e3HlVdboH7;e#i3(2<)Fg-I@BR!qY#eof3MFZ&*Y@l zI|KJf&ge@p2Dq09Vu$$Qxb7!}{m-iRk@!)%KL)txi3;~Z4Pb}u@GsW;ELiWeG9V51 znX#}B&4Y2E7-H=OpNE@q{%hFLxwIpBF2t{vPREa8_{linXT;#1vMRWjOzLOP$-hf( z>=?$0;~~PnkqY;~K{EM6Vo-T(0K{A0}VUGmu*hR z{tw3hvBN%N3G3Yw`X5Te+F{J`(3w1s3-+1EbnFQKcrgrX1Jqvs@ADGe%M0s$EbK$$ zK)=y=upBc6SjGYAACCcI=Y*6Fi8_jgwZlLxD26fnQfJmb8^gHRN5(TemhX@0e=vr> zg`W}6U>x6VhoA3DqsGGD9uL1DhB3!OXO=k}59TqD@(0Nb{)Ut_luTioK_>7wjc!5C zIr@w}b`Fez3)0wQfKl&bae7;PcTA7%?f2xucM0G)wt_KO!Ewx>F~;=BI0j=Fb4>pp zv}0R^xM4eti~+^+gE$6b81p(kwzuDti(-K9bc|?+pJEl@H+jSYuxZQV8rl8 zjp@M{#%qItIUFN~KcO9Hed*`$5A-2~pAo~K&<-Q+`9`$CK>rzqAI4w~$F%vs9s{~x zg4BP%Gy*@m?;D6=SRX?888Q6peF@_4Z->8wAH~Cn!R$|Hhq2cIzFYqT_+cDourHbY z0qroxJnrZ4Gh+Ay+F`_c%+KRT>y3qw{)89?=hJ@=KO=@ep)aBJ$c!JHfBMJpsP*3G za7|)VJJ8B;4?n{~ldJF7%jmb`-ftIvNd~ekoufG(`K(3=LNc;HBY& z(lp#q8XAD#cIf}k49zX_i`*fO+#!zKA&%T3j@%)R+#yag067CU%yUEe47>wzGU8^` z1EXFT^@I!{J!F8!X?S6ph8J=gUi5tl93*W>7}_uR<2N2~e}FaG?}KPyugQ=-OGEZs z!GBoyYY+H*ANn4?Z)X4l+7H%`17i5~zRlRIX?t)6_eu=g2Q`3WBhxSUeea+M-S?RL zX9oBGKn%a!H+*hx4d2(I!gsi+@SQK%<{X22M~2tMulJoa)0*+z9=-YO+;DFEm5eE1U9b^B(Z}2^9!Qk`!A$wUE z7$Ar5?NRg2&G!AZqnmE64eh^Anss3i!{}%6@Et+4rr!=}!SBF8eZ2*J3ujCWbl;3; z48H~goPSv(8X61fKKdpP!Z7$88NL^Z?j`!^*I?-P4X^pMxyWz~@$(UeAcTSDd(`vO z{~rc;9|GfMJcApU3k}22a!&)k4{CU!e_ny^Y3cO;tOvOMKEyWz!vG(Kp*;hB?d|R3`2X~=5a6#^o5@qn?J-bI8Ppip{-yG z!k|VcGsq!jF~}7DMr49Wap-s&>o=U^T0!Lcy}!(bhtYsPQy z4|EJe{12QL#=c(suQ89Mhw9<`bui%nx7Nep`C&*M3~vMEACmcRYYRGtANq$F%zh&V zc)cEVeHz*Z1N)L7k-(k3np#{GcDh2Q@ya0YHl*n7fl*ZPAsbU-a94MYYtA#&!c`xGIaV;yzsmrjfieTEtqB_WgZp2*NplHx=$O{M~2#i_vJ{ps-NgK zQsxKK_CBM2PP_je+Xft`(vYfXXgIUr{=PA=7a8`2EHk)Ym2QKIforz# tySWtj{oF3N9@_;i*Fv5S)9x^z=nlWP>jpp-9)52ZmLVA=i*%6g{{fxOO~wEK literal 0 HcmV?d00001 diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/runner.exe.manifest b/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/runner.exe.manifest new file mode 100644 index 000000000000..a42ea7687cb6 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/runner.exe.manifest @@ -0,0 +1,20 @@ + + + + + PerMonitorV2 + + + + + + + + + + + + + + + diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/utils.cpp b/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/utils.cpp new file mode 100644 index 000000000000..f5bf9fa0f536 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/utils.cpp @@ -0,0 +1,64 @@ +#include "utils.h" + +#include +#include +#include +#include + +#include + +void CreateAndAttachConsole() { + if (::AllocConsole()) { + FILE *unused; + if (freopen_s(&unused, "CONOUT$", "w", stdout)) { + _dup2(_fileno(stdout), 1); + } + if (freopen_s(&unused, "CONOUT$", "w", stderr)) { + _dup2(_fileno(stdout), 2); + } + std::ios::sync_with_stdio(); + FlutterDesktopResyncOutputStreams(); + } +} + +std::vector GetCommandLineArguments() { + // Convert the UTF-16 command line arguments to UTF-8 for the Engine to use. + int argc; + wchar_t** argv = ::CommandLineToArgvW(::GetCommandLineW(), &argc); + if (argv == nullptr) { + return std::vector(); + } + + std::vector command_line_arguments; + + // Skip the first argument as it's the binary name. + for (int i = 1; i < argc; i++) { + command_line_arguments.push_back(Utf8FromUtf16(argv[i])); + } + + ::LocalFree(argv); + + return command_line_arguments; +} + +std::string Utf8FromUtf16(const wchar_t* utf16_string) { + if (utf16_string == nullptr) { + return std::string(); + } + int target_length = ::WideCharToMultiByte( + CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, + -1, nullptr, 0, nullptr, nullptr); + std::string utf8_string; + if (target_length == 0 || target_length > utf8_string.max_size()) { + return utf8_string; + } + utf8_string.resize(target_length); + int converted_length = ::WideCharToMultiByte( + CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, + -1, utf8_string.data(), + target_length, nullptr, nullptr); + if (converted_length == 0) { + return std::string(); + } + return utf8_string; +} diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/utils.h b/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/utils.h new file mode 100644 index 000000000000..3879d5475579 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/utils.h @@ -0,0 +1,19 @@ +#ifndef RUNNER_UTILS_H_ +#define RUNNER_UTILS_H_ + +#include +#include + +// Creates a console for the process, and redirects stdout and stderr to +// it for both the runner and the Flutter library. +void CreateAndAttachConsole(); + +// Takes a null-terminated wchar_t* encoded in UTF-16 and returns a std::string +// encoded in UTF-8. Returns an empty std::string on failure. +std::string Utf8FromUtf16(const wchar_t* utf16_string); + +// Gets the command line arguments passed in as a std::vector, +// encoded in UTF-8. Returns an empty std::vector on failure. +std::vector GetCommandLineArguments(); + +#endif // RUNNER_UTILS_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/win32_window.cpp b/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/win32_window.cpp new file mode 100644 index 000000000000..041a38554745 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/win32_window.cpp @@ -0,0 +1,288 @@ +#include "win32_window.h" + +#include +#include + +#include "resource.h" + +namespace { + +/// Window attribute that enables dark mode window decorations. +/// +/// Redefined in case the developer's machine has a Windows SDK older than +/// version 10.0.22000.0. +/// See: https://docs.microsoft.com/windows/win32/api/dwmapi/ne-dwmapi-dwmwindowattribute +#ifndef DWMWA_USE_IMMERSIVE_DARK_MODE +#define DWMWA_USE_IMMERSIVE_DARK_MODE 20 +#endif + +constexpr const wchar_t kWindowClassName[] = L"FLUTTER_RUNNER_WIN32_WINDOW"; + +/// Registry key for app theme preference. +/// +/// A value of 0 indicates apps should use dark mode. A non-zero or missing +/// value indicates apps should use light mode. +constexpr const wchar_t kGetPreferredBrightnessRegKey[] = + L"Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize"; +constexpr const wchar_t kGetPreferredBrightnessRegValue[] = L"AppsUseLightTheme"; + +// The number of Win32Window objects that currently exist. +static int g_active_window_count = 0; + +using EnableNonClientDpiScaling = BOOL __stdcall(HWND hwnd); + +// Scale helper to convert logical scaler values to physical using passed in +// scale factor +int Scale(int source, double scale_factor) { + return static_cast(source * scale_factor); +} + +// Dynamically loads the |EnableNonClientDpiScaling| from the User32 module. +// This API is only needed for PerMonitor V1 awareness mode. +void EnableFullDpiSupportIfAvailable(HWND hwnd) { + HMODULE user32_module = LoadLibraryA("User32.dll"); + if (!user32_module) { + return; + } + auto enable_non_client_dpi_scaling = + reinterpret_cast( + GetProcAddress(user32_module, "EnableNonClientDpiScaling")); + if (enable_non_client_dpi_scaling != nullptr) { + enable_non_client_dpi_scaling(hwnd); + } + FreeLibrary(user32_module); +} + +} // namespace + +// Manages the Win32Window's window class registration. +class WindowClassRegistrar { + public: + ~WindowClassRegistrar() = default; + + // Returns the singleton registar instance. + static WindowClassRegistrar* GetInstance() { + if (!instance_) { + instance_ = new WindowClassRegistrar(); + } + return instance_; + } + + // Returns the name of the window class, registering the class if it hasn't + // previously been registered. + const wchar_t* GetWindowClass(); + + // Unregisters the window class. Should only be called if there are no + // instances of the window. + void UnregisterWindowClass(); + + private: + WindowClassRegistrar() = default; + + static WindowClassRegistrar* instance_; + + bool class_registered_ = false; +}; + +WindowClassRegistrar* WindowClassRegistrar::instance_ = nullptr; + +const wchar_t* WindowClassRegistrar::GetWindowClass() { + if (!class_registered_) { + WNDCLASS window_class{}; + window_class.hCursor = LoadCursor(nullptr, IDC_ARROW); + window_class.lpszClassName = kWindowClassName; + window_class.style = CS_HREDRAW | CS_VREDRAW; + window_class.cbClsExtra = 0; + window_class.cbWndExtra = 0; + window_class.hInstance = GetModuleHandle(nullptr); + window_class.hIcon = + LoadIcon(window_class.hInstance, MAKEINTRESOURCE(IDI_APP_ICON)); + window_class.hbrBackground = 0; + window_class.lpszMenuName = nullptr; + window_class.lpfnWndProc = Win32Window::WndProc; + RegisterClass(&window_class); + class_registered_ = true; + } + return kWindowClassName; +} + +void WindowClassRegistrar::UnregisterWindowClass() { + UnregisterClass(kWindowClassName, nullptr); + class_registered_ = false; +} + +Win32Window::Win32Window() { + ++g_active_window_count; +} + +Win32Window::~Win32Window() { + --g_active_window_count; + Destroy(); +} + +bool Win32Window::Create(const std::wstring& title, + const Point& origin, + const Size& size) { + Destroy(); + + const wchar_t* window_class = + WindowClassRegistrar::GetInstance()->GetWindowClass(); + + const POINT target_point = {static_cast(origin.x), + static_cast(origin.y)}; + HMONITOR monitor = MonitorFromPoint(target_point, MONITOR_DEFAULTTONEAREST); + UINT dpi = FlutterDesktopGetDpiForMonitor(monitor); + double scale_factor = dpi / 96.0; + + HWND window = CreateWindow( + window_class, title.c_str(), WS_OVERLAPPEDWINDOW, + Scale(origin.x, scale_factor), Scale(origin.y, scale_factor), + Scale(size.width, scale_factor), Scale(size.height, scale_factor), + nullptr, nullptr, GetModuleHandle(nullptr), this); + + if (!window) { + return false; + } + + UpdateTheme(window); + + return OnCreate(); +} + +bool Win32Window::Show() { + return ShowWindow(window_handle_, SW_SHOWNORMAL); +} + +// static +LRESULT CALLBACK Win32Window::WndProc(HWND const window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + if (message == WM_NCCREATE) { + auto window_struct = reinterpret_cast(lparam); + SetWindowLongPtr(window, GWLP_USERDATA, + reinterpret_cast(window_struct->lpCreateParams)); + + auto that = static_cast(window_struct->lpCreateParams); + EnableFullDpiSupportIfAvailable(window); + that->window_handle_ = window; + } else if (Win32Window* that = GetThisFromHandle(window)) { + return that->MessageHandler(window, message, wparam, lparam); + } + + return DefWindowProc(window, message, wparam, lparam); +} + +LRESULT +Win32Window::MessageHandler(HWND hwnd, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + switch (message) { + case WM_DESTROY: + window_handle_ = nullptr; + Destroy(); + if (quit_on_close_) { + PostQuitMessage(0); + } + return 0; + + case WM_DPICHANGED: { + auto newRectSize = reinterpret_cast(lparam); + LONG newWidth = newRectSize->right - newRectSize->left; + LONG newHeight = newRectSize->bottom - newRectSize->top; + + SetWindowPos(hwnd, nullptr, newRectSize->left, newRectSize->top, newWidth, + newHeight, SWP_NOZORDER | SWP_NOACTIVATE); + + return 0; + } + case WM_SIZE: { + RECT rect = GetClientArea(); + if (child_content_ != nullptr) { + // Size and position the child window. + MoveWindow(child_content_, rect.left, rect.top, rect.right - rect.left, + rect.bottom - rect.top, TRUE); + } + return 0; + } + + case WM_ACTIVATE: + if (child_content_ != nullptr) { + SetFocus(child_content_); + } + return 0; + + case WM_DWMCOLORIZATIONCOLORCHANGED: + UpdateTheme(hwnd); + return 0; + } + + return DefWindowProc(window_handle_, message, wparam, lparam); +} + +void Win32Window::Destroy() { + OnDestroy(); + + if (window_handle_) { + DestroyWindow(window_handle_); + window_handle_ = nullptr; + } + if (g_active_window_count == 0) { + WindowClassRegistrar::GetInstance()->UnregisterWindowClass(); + } +} + +Win32Window* Win32Window::GetThisFromHandle(HWND const window) noexcept { + return reinterpret_cast( + GetWindowLongPtr(window, GWLP_USERDATA)); +} + +void Win32Window::SetChildContent(HWND content) { + child_content_ = content; + SetParent(content, window_handle_); + RECT frame = GetClientArea(); + + MoveWindow(content, frame.left, frame.top, frame.right - frame.left, + frame.bottom - frame.top, true); + + SetFocus(child_content_); +} + +RECT Win32Window::GetClientArea() { + RECT frame; + GetClientRect(window_handle_, &frame); + return frame; +} + +HWND Win32Window::GetHandle() { + return window_handle_; +} + +void Win32Window::SetQuitOnClose(bool quit_on_close) { + quit_on_close_ = quit_on_close; +} + +bool Win32Window::OnCreate() { + // No-op; provided for subclasses. + return true; +} + +void Win32Window::OnDestroy() { + // No-op; provided for subclasses. +} + +void Win32Window::UpdateTheme(HWND const window) { + DWORD light_mode; + DWORD light_mode_size = sizeof(light_mode); + LSTATUS result = RegGetValue(HKEY_CURRENT_USER, kGetPreferredBrightnessRegKey, + kGetPreferredBrightnessRegValue, + RRF_RT_REG_DWORD, nullptr, &light_mode, + &light_mode_size); + + if (result == ERROR_SUCCESS) { + BOOL enable_dark_mode = light_mode == 0; + DwmSetWindowAttribute(window, DWMWA_USE_IMMERSIVE_DARK_MODE, + &enable_dark_mode, sizeof(enable_dark_mode)); + } +} diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/win32_window.h b/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/win32_window.h new file mode 100644 index 000000000000..c86632d8a6b9 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/win32_window.h @@ -0,0 +1,102 @@ +#ifndef RUNNER_WIN32_WINDOW_H_ +#define RUNNER_WIN32_WINDOW_H_ + +#include + +#include +#include +#include + +// A class abstraction for a high DPI-aware Win32 Window. Intended to be +// inherited from by classes that wish to specialize with custom +// rendering and input handling +class Win32Window { + public: + struct Point { + unsigned int x; + unsigned int y; + Point(unsigned int x, unsigned int y) : x(x), y(y) {} + }; + + struct Size { + unsigned int width; + unsigned int height; + Size(unsigned int width, unsigned int height) + : width(width), height(height) {} + }; + + Win32Window(); + virtual ~Win32Window(); + + // Creates a win32 window with |title| that is positioned and sized using + // |origin| and |size|. New windows are created on the default monitor. Window + // sizes are specified to the OS in physical pixels, hence to ensure a + // consistent size this function will scale the inputted width and height as + // as appropriate for the default monitor. The window is invisible until + // |Show| is called. Returns true if the window was created successfully. + bool Create(const std::wstring& title, const Point& origin, const Size& size); + + // Show the current window. Returns true if the window was successfully shown. + bool Show(); + + // Release OS resources associated with window. + void Destroy(); + + // Inserts |content| into the window tree. + void SetChildContent(HWND content); + + // Returns the backing Window handle to enable clients to set icon and other + // window properties. Returns nullptr if the window has been destroyed. + HWND GetHandle(); + + // If true, closing this window will quit the application. + void SetQuitOnClose(bool quit_on_close); + + // Return a RECT representing the bounds of the current client area. + RECT GetClientArea(); + + protected: + // Processes and route salient window messages for mouse handling, + // size change and DPI. Delegates handling of these to member overloads that + // inheriting classes can handle. + virtual LRESULT MessageHandler(HWND window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept; + + // Called when CreateAndShow is called, allowing subclass window-related + // setup. Subclasses should return false if setup fails. + virtual bool OnCreate(); + + // Called when Destroy is called. + virtual void OnDestroy(); + + private: + friend class WindowClassRegistrar; + + // OS callback called by message pump. Handles the WM_NCCREATE message which + // is passed when the non-client area is being created and enables automatic + // non-client DPI scaling so that the non-client area automatically + // responsponds to changes in DPI. All other messages are handled by + // MessageHandler. + static LRESULT CALLBACK WndProc(HWND const window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept; + + // Retrieves a class instance pointer for |window| + static Win32Window* GetThisFromHandle(HWND const window) noexcept; + + // Update the window frame's theme to match the system theme. + static void UpdateTheme(HWND const window); + + bool quit_on_close_ = false; + + // window handle for top level window. + HWND window_handle_ = nullptr; + + // window handle for hosted content. + HWND child_content_ = nullptr; +}; + +#endif // RUNNER_WIN32_WINDOW_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/pubspec.yaml b/packages/firebase_core/firebase_core/firebase_core/pubspec.yaml index ce38f84906e8..c942173c517b 100644 --- a/packages/firebase_core/firebase_core/firebase_core/pubspec.yaml +++ b/packages/firebase_core/firebase_core/firebase_core/pubspec.yaml @@ -24,6 +24,8 @@ flutter: platforms: linux: pluginClass: FirebaseCorePlugin + windows: + pluginClass: FirebaseCorePluginCApi ffigen: output: 'generated_bindings.dart' diff --git a/packages/firebase_core/firebase_core/firebase_core/windows/.gitignore b/packages/firebase_core/firebase_core/firebase_core/windows/.gitignore new file mode 100644 index 000000000000..b3eb2be169a5 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/windows/.gitignore @@ -0,0 +1,17 @@ +flutter/ + +# Visual Studio user-specific files. +*.suo +*.user +*.userosscache +*.sln.docstates + +# Visual Studio build-related files. +x64/ +x86/ + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!*.[Cc]ache/ diff --git a/packages/firebase_core/firebase_core/firebase_core/windows/CMakeLists.txt b/packages/firebase_core/firebase_core/firebase_core/windows/CMakeLists.txt new file mode 100644 index 000000000000..2f368229d6e9 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/windows/CMakeLists.txt @@ -0,0 +1,53 @@ +# The Flutter tooling requires that developers have a version of Visual Studio +# installed that includes CMake 3.14 or later. You should not increase this +# version, as doing so will cause the plugin to fail to compile for some +# customers of the plugin. +cmake_minimum_required(VERSION 3.14) + +# Project-level configuration. +set(PROJECT_NAME "firebase_core") +project(${PROJECT_NAME} LANGUAGES CXX) + +# This value is used when generating builds using this plugin, so it must +# not be changed +set(PLUGIN_NAME "firebase_core_plugin") + +# Any new source files that you add to the plugin should be added here. +list(APPEND PLUGIN_SOURCES + "firebase_core_plugin.cpp" + "firebase_core_plugin.h" +) + +# Define the plugin library target. Its name must not be changed (see comment +# on PLUGIN_NAME above). +add_library(${PLUGIN_NAME} SHARED + "include/firebase_core/firebase_core_plugin_c_api.h" + "firebase_core_plugin_c_api.cpp" + ${PLUGIN_SOURCES} +) + +# Apply a standard set of build settings that are configured in the +# application-level CMakeLists.txt. This can be removed for plugins that want +# full control over build settings. +apply_standard_settings(${PLUGIN_NAME}) + +# Symbols are hidden by default to reduce the chance of accidental conflicts +# between plugins. This should not be removed; any symbols that should be +# exported should be explicitly exported with the FLUTTER_PLUGIN_EXPORT macro. +set_target_properties(${PLUGIN_NAME} PROPERTIES + CXX_VISIBILITY_PRESET hidden) +target_compile_definitions(${PLUGIN_NAME} PRIVATE FLUTTER_PLUGIN_IMPL) + +# Source include directories and library dependencies. Add any plugin-specific +# dependencies here. +target_include_directories(${PLUGIN_NAME} INTERFACE + "${CMAKE_CURRENT_SOURCE_DIR}/include") +target_link_libraries(${PLUGIN_NAME} PRIVATE flutter flutter_wrapper_plugin) + +# List of absolute paths to libraries that should be bundled with the plugin. +# This list could contain prebuilt libraries, or libraries created by an +# external build triggered from this build file. +set(firebase_core_bundled_libraries + "" + PARENT_SCOPE +) diff --git a/packages/firebase_core/firebase_core/firebase_core/windows/firebase_core_plugin.cpp b/packages/firebase_core/firebase_core/firebase_core/windows/firebase_core_plugin.cpp new file mode 100644 index 000000000000..e92cfe868845 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/windows/firebase_core_plugin.cpp @@ -0,0 +1,59 @@ +#include "firebase_core_plugin.h" + +// This must be included before many other Windows headers. +#include + +// For getPlatformVersion; remove unless needed for your plugin implementation. +#include + +#include +#include +#include + +#include +#include + +namespace firebase_core { + +// static +void FirebaseCorePlugin::RegisterWithRegistrar( + flutter::PluginRegistrarWindows *registrar) { + auto channel = + std::make_unique>( + registrar->messenger(), "firebase_core", + &flutter::StandardMethodCodec::GetInstance()); + + auto plugin = std::make_unique(); + + channel->SetMethodCallHandler( + [plugin_pointer = plugin.get()](const auto &call, auto result) { + plugin_pointer->HandleMethodCall(call, std::move(result)); + }); + + registrar->AddPlugin(std::move(plugin)); +} + +FirebaseCorePlugin::FirebaseCorePlugin() {} + +FirebaseCorePlugin::~FirebaseCorePlugin() {} + +void FirebaseCorePlugin::HandleMethodCall( + const flutter::MethodCall &method_call, + std::unique_ptr> result) { + if (method_call.method_name().compare("getPlatformVersion") == 0) { + std::ostringstream version_stream; + version_stream << "Windows "; + if (IsWindows10OrGreater()) { + version_stream << "10+"; + } else if (IsWindows8OrGreater()) { + version_stream << "8"; + } else if (IsWindows7OrGreater()) { + version_stream << "7"; + } + result->Success(flutter::EncodableValue(version_stream.str())); + } else { + result->NotImplemented(); + } +} + +} // namespace firebase_core diff --git a/packages/firebase_core/firebase_core/firebase_core/windows/firebase_core_plugin.h b/packages/firebase_core/firebase_core/firebase_core/windows/firebase_core_plugin.h new file mode 100644 index 000000000000..fe99490af2c2 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/windows/firebase_core_plugin.h @@ -0,0 +1,32 @@ +#ifndef FLUTTER_PLUGIN_FIREBASE_CORE_PLUGIN_H_ +#define FLUTTER_PLUGIN_FIREBASE_CORE_PLUGIN_H_ + +#include +#include + +#include + +namespace firebase_core { + +class FirebaseCorePlugin : public flutter::Plugin { + public: + static void RegisterWithRegistrar(flutter::PluginRegistrarWindows *registrar); + + FirebaseCorePlugin(); + + virtual ~FirebaseCorePlugin(); + + // Disallow copy and assign. + FirebaseCorePlugin(const FirebaseCorePlugin&) = delete; + FirebaseCorePlugin& operator=(const FirebaseCorePlugin&) = delete; + + private: + // Called when a method is called on this plugin's channel from Dart. + void HandleMethodCall( + const flutter::MethodCall &method_call, + std::unique_ptr> result); +}; + +} // namespace firebase_core + +#endif // FLUTTER_PLUGIN_FIREBASE_CORE_PLUGIN_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/windows/firebase_core_plugin_c_api.cpp b/packages/firebase_core/firebase_core/firebase_core/windows/firebase_core_plugin_c_api.cpp new file mode 100644 index 000000000000..f0ca223fcf26 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/windows/firebase_core_plugin_c_api.cpp @@ -0,0 +1,12 @@ +#include "include/firebase_core/firebase_core_plugin_c_api.h" + +#include + +#include "firebase_core_plugin.h" + +void FirebaseCorePluginCApiRegisterWithRegistrar( + FlutterDesktopPluginRegistrarRef registrar) { + firebase_core::FirebaseCorePlugin::RegisterWithRegistrar( + flutter::PluginRegistrarManager::GetInstance() + ->GetRegistrar(registrar)); +} diff --git a/packages/firebase_core/firebase_core/firebase_core/windows/include/firebase_core/firebase_core_plugin_c_api.h b/packages/firebase_core/firebase_core/firebase_core/windows/include/firebase_core/firebase_core_plugin_c_api.h new file mode 100644 index 000000000000..4ef141db19bd --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/windows/include/firebase_core/firebase_core_plugin_c_api.h @@ -0,0 +1,23 @@ +#ifndef FLUTTER_PLUGIN_FIREBASE_CORE_PLUGIN_C_API_H_ +#define FLUTTER_PLUGIN_FIREBASE_CORE_PLUGIN_C_API_H_ + +#include + +#ifdef FLUTTER_PLUGIN_IMPL +#define FLUTTER_PLUGIN_EXPORT __declspec(dllexport) +#else +#define FLUTTER_PLUGIN_EXPORT __declspec(dllimport) +#endif + +#if defined(__cplusplus) +extern "C" { +#endif + +FLUTTER_PLUGIN_EXPORT void FirebaseCorePluginCApiRegisterWithRegistrar( + FlutterDesktopPluginRegistrarRef registrar); + +#if defined(__cplusplus) +} // extern "C" +#endif + +#endif // FLUTTER_PLUGIN_FIREBASE_CORE_PLUGIN_C_API_H_ From b2316358a30f618ad022c5f6bb8c59c19a1c49b3 Mon Sep 17 00:00:00 2001 From: Guillaume Bernos Date: Mon, 6 Mar 2023 15:24:46 +0100 Subject: [PATCH 26/65] add windows --- .../flutter/generated_plugin_registrant.cc | 14 +++++++++++ .../flutter/generated_plugin_registrant.h | 15 ++++++++++++ .../windows/flutter/generated_plugins.cmake | 24 +++++++++++++++++++ .../firebase_core/windows/CMakeLists.txt | 12 ++++++++++ 4 files changed, 65 insertions(+) create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/windows/flutter/generated_plugin_registrant.cc create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/windows/flutter/generated_plugin_registrant.h create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/windows/flutter/generated_plugins.cmake diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/flutter/generated_plugin_registrant.cc b/packages/firebase_core/firebase_core/firebase_core/example/windows/flutter/generated_plugin_registrant.cc new file mode 100644 index 000000000000..1a82e7d01dce --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/windows/flutter/generated_plugin_registrant.cc @@ -0,0 +1,14 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#include "generated_plugin_registrant.h" + +#include + +void RegisterPlugins(flutter::PluginRegistry* registry) { + FirebaseCorePluginCApiRegisterWithRegistrar( + registry->GetRegistrarForPlugin("FirebaseCorePluginCApi")); +} diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/flutter/generated_plugin_registrant.h b/packages/firebase_core/firebase_core/firebase_core/example/windows/flutter/generated_plugin_registrant.h new file mode 100644 index 000000000000..dc139d85a931 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/windows/flutter/generated_plugin_registrant.h @@ -0,0 +1,15 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#ifndef GENERATED_PLUGIN_REGISTRANT_ +#define GENERATED_PLUGIN_REGISTRANT_ + +#include + +// Registers Flutter plugins. +void RegisterPlugins(flutter::PluginRegistry* registry); + +#endif // GENERATED_PLUGIN_REGISTRANT_ diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/flutter/generated_plugins.cmake b/packages/firebase_core/firebase_core/firebase_core/example/windows/flutter/generated_plugins.cmake new file mode 100644 index 000000000000..fa8a39bab15e --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/windows/flutter/generated_plugins.cmake @@ -0,0 +1,24 @@ +# +# Generated file, do not edit. +# + +list(APPEND FLUTTER_PLUGIN_LIST + firebase_core +) + +list(APPEND FLUTTER_FFI_PLUGIN_LIST +) + +set(PLUGIN_BUNDLED_LIBRARIES) + +foreach(plugin ${FLUTTER_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/windows plugins/${plugin}) + target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) + list(APPEND PLUGIN_BUNDLED_LIBRARIES $) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) +endforeach(plugin) + +foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/windows plugins/${ffi_plugin}) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries}) +endforeach(ffi_plugin) diff --git a/packages/firebase_core/firebase_core/firebase_core/windows/CMakeLists.txt b/packages/firebase_core/firebase_core/firebase_core/windows/CMakeLists.txt index 2f368229d6e9..c6ef1ebf3727 100644 --- a/packages/firebase_core/firebase_core/firebase_core/windows/CMakeLists.txt +++ b/packages/firebase_core/firebase_core/firebase_core/windows/CMakeLists.txt @@ -26,6 +26,18 @@ add_library(${PLUGIN_NAME} SHARED ${PLUGIN_SOURCES} ) +# Add Firebase libraries to the target using the function from the SDK. +add_subdirectory(${FIREBASE_CPP_SDK_DIR} bin/ EXCLUDE_FROM_ALL) + +# The Firebase C++ library `firebase_app` is required, +# and it must always be listed last. + +# Add the Firebase SDKs for the products you want to use in your app +# For example, to use Firebase Authentication and Firebase Realtime Database +set(firebase_libs firebase_auth firebase_app) +target_link_libraries(${target_name} "${firebase_libs}") + + # Apply a standard set of build settings that are configured in the # application-level CMakeLists.txt. This can be removed for plugins that want # full control over build settings. From 5ba84f8044f1070a7abbd29498b5e253fb0fbed6 Mon Sep 17 00:00:00 2001 From: Guillaume Bernos Date: Mon, 6 Mar 2023 16:15:41 +0100 Subject: [PATCH 27/65] add windows --- .../firebase_core/windows/CMakeLists.txt | 18 +++++++----------- 1 file changed, 7 insertions(+), 11 deletions(-) diff --git a/packages/firebase_core/firebase_core/firebase_core/windows/CMakeLists.txt b/packages/firebase_core/firebase_core/firebase_core/windows/CMakeLists.txt index c6ef1ebf3727..bd3c3fdc2bdb 100644 --- a/packages/firebase_core/firebase_core/firebase_core/windows/CMakeLists.txt +++ b/packages/firebase_core/firebase_core/firebase_core/windows/CMakeLists.txt @@ -26,17 +26,6 @@ add_library(${PLUGIN_NAME} SHARED ${PLUGIN_SOURCES} ) -# Add Firebase libraries to the target using the function from the SDK. -add_subdirectory(${FIREBASE_CPP_SDK_DIR} bin/ EXCLUDE_FROM_ALL) - -# The Firebase C++ library `firebase_app` is required, -# and it must always be listed last. - -# Add the Firebase SDKs for the products you want to use in your app -# For example, to use Firebase Authentication and Firebase Realtime Database -set(firebase_libs firebase_auth firebase_app) -target_link_libraries(${target_name} "${firebase_libs}") - # Apply a standard set of build settings that are configured in the # application-level CMakeLists.txt. This can be removed for plugins that want @@ -52,6 +41,13 @@ target_compile_definitions(${PLUGIN_NAME} PRIVATE FLUTTER_PLUGIN_IMPL) # Source include directories and library dependencies. Add any plugin-specific # dependencies here. + +add_subdirectory(${FIREBASE_CPP_SDK_DIR} bin/ EXCLUDE_FROM_ALL) +target_include_directories(${PLUGIN_NAME} INTERFACE + "${FIREBASE_CPP_SDK_DIR}/include") +set(firebase_libs firebase_auth firebase_database firebase_app) +target_link_libraries(${PLUGIN_NAME} PRIVATE "${firebase_libs}") + target_include_directories(${PLUGIN_NAME} INTERFACE "${CMAKE_CURRENT_SOURCE_DIR}/include") target_link_libraries(${PLUGIN_NAME} PRIVATE flutter flutter_wrapper_plugin) From 226d0dbd0cca027890754da8326071e9ffbd5cca Mon Sep 17 00:00:00 2001 From: Guillaume Bernos Date: Mon, 6 Mar 2023 17:09:15 +0100 Subject: [PATCH 28/65] add windows --- .../example/bin/CMakeFiles/generate.stamp | 1 + .../bin/CMakeFiles/generate.stamp.depend | 5 + .../firebase_core/example/bin/INSTALL.vcxproj | 165 ++++++++++++++++++ .../example/bin/INSTALL.vcxproj.filters | 13 ++ .../example/bin/cmake_install.cmake | 34 ++++ .../runner/google-services-desktop.json | 37 ++++ .../firebase_core/windows/CMakeLists.txt | 4 +- .../windows/firebase_core_plugin.cpp | 4 + 8 files changed, 261 insertions(+), 2 deletions(-) create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/bin/CMakeFiles/generate.stamp create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/bin/CMakeFiles/generate.stamp.depend create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/bin/INSTALL.vcxproj create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/bin/INSTALL.vcxproj.filters create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/bin/cmake_install.cmake create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/windows/runner/google-services-desktop.json diff --git a/packages/firebase_core/firebase_core/firebase_core/example/bin/CMakeFiles/generate.stamp b/packages/firebase_core/firebase_core/firebase_core/example/bin/CMakeFiles/generate.stamp new file mode 100644 index 000000000000..9b5f49fa9f14 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/bin/CMakeFiles/generate.stamp @@ -0,0 +1 @@ +# CMake generation timestamp file for this directory. diff --git a/packages/firebase_core/firebase_core/firebase_core/example/bin/CMakeFiles/generate.stamp.depend b/packages/firebase_core/firebase_core/firebase_core/example/bin/CMakeFiles/generate.stamp.depend new file mode 100644 index 000000000000..5b8da13f857a --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/bin/CMakeFiles/generate.stamp.depend @@ -0,0 +1,5 @@ +# CMake generation dependency list for this directory. +C:/Program Files/Microsoft Visual Studio/2022/Community/Common7/IDE/CommonExtensions/Microsoft/CMake/CMake/share/cmake-3.25/Modules/FindPackageHandleStandardArgs.cmake +C:/Program Files/Microsoft Visual Studio/2022/Community/Common7/IDE/CommonExtensions/Microsoft/CMake/CMake/share/cmake-3.25/Modules/FindPackageMessage.cmake +C:/Program Files/Microsoft Visual Studio/2022/Community/Common7/IDE/CommonExtensions/Microsoft/CMake/CMake/share/cmake-3.25/Modules/FindPkgConfig.cmake +C:/Users/guill/Downloads/firebase_cpp_sdk_10.5.0/firebase_cpp_sdk/CMakeLists.txt diff --git a/packages/firebase_core/firebase_core/firebase_core/example/bin/INSTALL.vcxproj b/packages/firebase_core/firebase_core/firebase_core/example/bin/INSTALL.vcxproj new file mode 100644 index 000000000000..05091bebad78 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/bin/INSTALL.vcxproj @@ -0,0 +1,165 @@ + + + + x64 + + + + Debug + x64 + + + Profile + x64 + + + Release + x64 + + + + {B2284ACE-B264-3C77-ADAD-5516EBC85159} + Win32Proj + 10.0.22000.0 + x64 + INSTALL + NoUpgrade + + + + Utility + MultiByte + v143 + + + Utility + MultiByte + v143 + + + Utility + MultiByte + v143 + + + + + + + + + + <_ProjectFileVersion>10.0.20506.1 + $(Platform)\$(Configuration)\$(ProjectName)\ + $(Platform)\$(Configuration)\$(ProjectName)\ + $(Platform)\$(Configuration)\$(ProjectName)\ + + + + Always + + setlocal +"C:\Program Files\Microsoft Visual Studio\2022\Community\Common7\IDE\CommonExtensions\Microsoft\CMake\CMake\bin\cmake.exe" -DBUILD_TYPE=$(Configuration) -P cmake_install.cmake +if %errorlevel% neq 0 goto :cmEnd +:cmEnd +endlocal & call :cmErrorLevel %errorlevel% & goto :cmDone +:cmErrorLevel +exit /b %1 +:cmDone +if %errorlevel% neq 0 goto :VCEnd + + + + + Always + + setlocal +"C:\Program Files\Microsoft Visual Studio\2022\Community\Common7\IDE\CommonExtensions\Microsoft\CMake\CMake\bin\cmake.exe" -DBUILD_TYPE=$(Configuration) -P cmake_install.cmake +if %errorlevel% neq 0 goto :cmEnd +:cmEnd +endlocal & call :cmErrorLevel %errorlevel% & goto :cmDone +:cmErrorLevel +exit /b %1 +:cmDone +if %errorlevel% neq 0 goto :VCEnd + + + + + Always + + setlocal +"C:\Program Files\Microsoft Visual Studio\2022\Community\Common7\IDE\CommonExtensions\Microsoft\CMake\CMake\bin\cmake.exe" -DBUILD_TYPE=$(Configuration) -P cmake_install.cmake +if %errorlevel% neq 0 goto :cmEnd +:cmEnd +endlocal & call :cmErrorLevel %errorlevel% & goto :cmDone +:cmErrorLevel +exit /b %1 +:cmDone +if %errorlevel% neq 0 goto :VCEnd + + + + + + setlocal +cd . +if %errorlevel% neq 0 goto :cmEnd +:cmEnd +endlocal & call :cmErrorLevel %errorlevel% & goto :cmDone +:cmErrorLevel +exit /b %1 +:cmDone +if %errorlevel% neq 0 goto :VCEnd + %(AdditionalInputs) + C:\Users\guill\Developer\flutterfire\packages\firebase_core\firebase_core\firebase_core\example\bin\CMakeFiles\INSTALL_force + false + false + + setlocal +cd . +if %errorlevel% neq 0 goto :cmEnd +:cmEnd +endlocal & call :cmErrorLevel %errorlevel% & goto :cmDone +:cmErrorLevel +exit /b %1 +:cmDone +if %errorlevel% neq 0 goto :VCEnd + %(AdditionalInputs) + C:\Users\guill\Developer\flutterfire\packages\firebase_core\firebase_core\firebase_core\example\bin\CMakeFiles\INSTALL_force + false + false + + setlocal +cd . +if %errorlevel% neq 0 goto :cmEnd +:cmEnd +endlocal & call :cmErrorLevel %errorlevel% & goto :cmDone +:cmErrorLevel +exit /b %1 +:cmDone +if %errorlevel% neq 0 goto :VCEnd + %(AdditionalInputs) + C:\Users\guill\Developer\flutterfire\packages\firebase_core\firebase_core\firebase_core\example\bin\CMakeFiles\INSTALL_force + false + false + + + + + {DC08768F-F57C-313C-94F0-E16194F54223} + ZERO_CHECK + false + Never + + + {DF648812-5598-379C-A5B5-8A3EAC6BC5B0} + ALL_BUILD + false + Never + + + + + + \ No newline at end of file diff --git a/packages/firebase_core/firebase_core/firebase_core/example/bin/INSTALL.vcxproj.filters b/packages/firebase_core/firebase_core/firebase_core/example/bin/INSTALL.vcxproj.filters new file mode 100644 index 000000000000..69fed1abf535 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/bin/INSTALL.vcxproj.filters @@ -0,0 +1,13 @@ + + + + + CMake Rules + + + + + {EAE753BC-CF7B-3081-8331-9EFFB2F8D8A5} + + + diff --git a/packages/firebase_core/firebase_core/firebase_core/example/bin/cmake_install.cmake b/packages/firebase_core/firebase_core/firebase_core/example/bin/cmake_install.cmake new file mode 100644 index 000000000000..8cf9b6c06b96 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/bin/cmake_install.cmake @@ -0,0 +1,34 @@ +# Install script for directory: C:/Users/guill/Downloads/firebase_cpp_sdk_10.5.0/firebase_cpp_sdk + +# Set the install prefix +if(NOT DEFINED CMAKE_INSTALL_PREFIX) + set(CMAKE_INSTALL_PREFIX "$") +endif() +string(REGEX REPLACE "/$" "" CMAKE_INSTALL_PREFIX "${CMAKE_INSTALL_PREFIX}") + +# Set the install configuration name. +if(NOT DEFINED CMAKE_INSTALL_CONFIG_NAME) + if(BUILD_TYPE) + string(REGEX REPLACE "^[^A-Za-z0-9_]+" "" + CMAKE_INSTALL_CONFIG_NAME "${BUILD_TYPE}") + else() + set(CMAKE_INSTALL_CONFIG_NAME "Release") + endif() + message(STATUS "Install configuration: \"${CMAKE_INSTALL_CONFIG_NAME}\"") +endif() + +# Set the component getting installed. +if(NOT CMAKE_INSTALL_COMPONENT) + if(COMPONENT) + message(STATUS "Install component: \"${COMPONENT}\"") + set(CMAKE_INSTALL_COMPONENT "${COMPONENT}") + else() + set(CMAKE_INSTALL_COMPONENT) + endif() +endif() + +# Is this installation the result of a crosscompile? +if(NOT DEFINED CMAKE_CROSSCOMPILING) + set(CMAKE_CROSSCOMPILING "FALSE") +endif() + diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/google-services-desktop.json b/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/google-services-desktop.json new file mode 100644 index 000000000000..a3bf216f4de0 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/google-services-desktop.json @@ -0,0 +1,37 @@ +{ + "project_info": { + "project_number": "406099696497", + "firebase_url": "https://flutterfire-e2e-tests-default-rtdb.europe-west1.firebasedatabase.app", + "project_id": "flutterfire-e2e-tests", + "storage_bucket": "flutterfire-e2e-tests.appspot.com" + }, + "client": [ + { + "client_info": { + "mobilesdk_app_id": "1:406099696497:ios:58cbc26aca8e5cf83574d0", + "android_client_info": { + "package_name": "io.flutter.plugins.firebase.auth.example" + } + }, + "oauth_client": [ + { + "client_id": "406099696497-134k3722m01rtrsklhf3b7k8sqa5r7in.apps.googleusercontent.com" + } + ], + "api_key": [ + { + "current_key": "AIzaSyDooSUGSf63Ghq02_iIhtnmwMDs4HlWS6c" + } + ], + "services": { + "analytics_service": { + "status": 0 + }, + "appinvite_service": { + "status": 1 + } + } + } + ], + "configuration_version": "1" +} \ No newline at end of file diff --git a/packages/firebase_core/firebase_core/firebase_core/windows/CMakeLists.txt b/packages/firebase_core/firebase_core/firebase_core/windows/CMakeLists.txt index bd3c3fdc2bdb..e75e1384506a 100644 --- a/packages/firebase_core/firebase_core/firebase_core/windows/CMakeLists.txt +++ b/packages/firebase_core/firebase_core/firebase_core/windows/CMakeLists.txt @@ -41,8 +41,8 @@ target_compile_definitions(${PLUGIN_NAME} PRIVATE FLUTTER_PLUGIN_IMPL) # Source include directories and library dependencies. Add any plugin-specific # dependencies here. - -add_subdirectory(${FIREBASE_CPP_SDK_DIR} bin/ EXCLUDE_FROM_ALL) +set(MSVC_RUNTIME_MODE MD) +add_subdirectory(C:/Users/guill/Downloads/firebase_cpp_sdk_10.5.0/firebase_cpp_sdk C:/Users/guill/Developer/flutterfire/packages/firebase_core/firebase_core/firebase_core/example/bin/ EXCLUDE_FROM_ALL) target_include_directories(${PLUGIN_NAME} INTERFACE "${FIREBASE_CPP_SDK_DIR}/include") set(firebase_libs firebase_auth firebase_database firebase_app) diff --git a/packages/firebase_core/firebase_core/firebase_core/windows/firebase_core_plugin.cpp b/packages/firebase_core/firebase_core/firebase_core/windows/firebase_core_plugin.cpp index e92cfe868845..7dd2b9945a72 100644 --- a/packages/firebase_core/firebase_core/firebase_core/windows/firebase_core_plugin.cpp +++ b/packages/firebase_core/firebase_core/firebase_core/windows/firebase_core_plugin.cpp @@ -2,6 +2,7 @@ // This must be included before many other Windows headers. #include +#include "firebase/app.h" // For getPlatformVersion; remove unless needed for your plugin implementation. #include @@ -12,6 +13,7 @@ #include #include +using ::firebase::App; namespace firebase_core { @@ -41,6 +43,8 @@ void FirebaseCorePlugin::HandleMethodCall( const flutter::MethodCall &method_call, std::unique_ptr> result) { if (method_call.method_name().compare("getPlatformVersion") == 0) { + App* app = App::Create(); + std::cout << static_cast(reinterpret_cast(app)); std::ostringstream version_stream; version_stream << "Windows "; if (IsWindows10OrGreater()) { From b6cb3874337bca83563d208c1b15d67917cc2bd7 Mon Sep 17 00:00:00 2001 From: Guillaume Bernos Date: Mon, 6 Mar 2023 17:19:28 +0100 Subject: [PATCH 29/65] right position for google service file --- .../example/google-services-desktop.json | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 packages/firebase_core/firebase_core/firebase_core/example/google-services-desktop.json diff --git a/packages/firebase_core/firebase_core/firebase_core/example/google-services-desktop.json b/packages/firebase_core/firebase_core/firebase_core/example/google-services-desktop.json new file mode 100644 index 000000000000..a3bf216f4de0 --- /dev/null +++ b/packages/firebase_core/firebase_core/firebase_core/example/google-services-desktop.json @@ -0,0 +1,37 @@ +{ + "project_info": { + "project_number": "406099696497", + "firebase_url": "https://flutterfire-e2e-tests-default-rtdb.europe-west1.firebasedatabase.app", + "project_id": "flutterfire-e2e-tests", + "storage_bucket": "flutterfire-e2e-tests.appspot.com" + }, + "client": [ + { + "client_info": { + "mobilesdk_app_id": "1:406099696497:ios:58cbc26aca8e5cf83574d0", + "android_client_info": { + "package_name": "io.flutter.plugins.firebase.auth.example" + } + }, + "oauth_client": [ + { + "client_id": "406099696497-134k3722m01rtrsklhf3b7k8sqa5r7in.apps.googleusercontent.com" + } + ], + "api_key": [ + { + "current_key": "AIzaSyDooSUGSf63Ghq02_iIhtnmwMDs4HlWS6c" + } + ], + "services": { + "analytics_service": { + "status": 0 + }, + "appinvite_service": { + "status": 1 + } + } + } + ], + "configuration_version": "1" +} \ No newline at end of file From bd34981d761502ee9569920c52d1080c81d0d7e6 Mon Sep 17 00:00:00 2001 From: Guillaume Bernos Date: Mon, 6 Mar 2023 17:21:03 +0100 Subject: [PATCH 30/65] add windows --- .../firebase_core/firebase_core/windows/CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/firebase_core/firebase_core/firebase_core/windows/CMakeLists.txt b/packages/firebase_core/firebase_core/firebase_core/windows/CMakeLists.txt index e75e1384506a..35c68f4a1910 100644 --- a/packages/firebase_core/firebase_core/firebase_core/windows/CMakeLists.txt +++ b/packages/firebase_core/firebase_core/firebase_core/windows/CMakeLists.txt @@ -42,7 +42,7 @@ target_compile_definitions(${PLUGIN_NAME} PRIVATE FLUTTER_PLUGIN_IMPL) # Source include directories and library dependencies. Add any plugin-specific # dependencies here. set(MSVC_RUNTIME_MODE MD) -add_subdirectory(C:/Users/guill/Downloads/firebase_cpp_sdk_10.5.0/firebase_cpp_sdk C:/Users/guill/Developer/flutterfire/packages/firebase_core/firebase_core/firebase_core/example/bin/ EXCLUDE_FROM_ALL) +add_subdirectory(${FIREBASE_CPP_SDK_DIR} bin/ EXCLUDE_FROM_ALL) target_include_directories(${PLUGIN_NAME} INTERFACE "${FIREBASE_CPP_SDK_DIR}/include") set(firebase_libs firebase_auth firebase_database firebase_app) From cb2fc58a6e4317f223e0ba97930f45879ff5c14a Mon Sep 17 00:00:00 2001 From: Guillaume Bernos Date: Mon, 6 Mar 2023 14:52:47 +0100 Subject: [PATCH 31/65] add windows --- .../firebase_core/firebase_core/windows/CMakeLists.txt | 1 - .../firebase_core/windows/firebase_core_plugin.cpp | 7 ++----- 2 files changed, 2 insertions(+), 6 deletions(-) diff --git a/packages/firebase_core/firebase_core/firebase_core/windows/CMakeLists.txt b/packages/firebase_core/firebase_core/firebase_core/windows/CMakeLists.txt index 35c68f4a1910..c26d21bc2f0f 100644 --- a/packages/firebase_core/firebase_core/firebase_core/windows/CMakeLists.txt +++ b/packages/firebase_core/firebase_core/firebase_core/windows/CMakeLists.txt @@ -26,7 +26,6 @@ add_library(${PLUGIN_NAME} SHARED ${PLUGIN_SOURCES} ) - # Apply a standard set of build settings that are configured in the # application-level CMakeLists.txt. This can be removed for plugins that want # full control over build settings. diff --git a/packages/firebase_core/firebase_core/firebase_core/windows/firebase_core_plugin.cpp b/packages/firebase_core/firebase_core/firebase_core/windows/firebase_core_plugin.cpp index 7dd2b9945a72..457e78e218b8 100644 --- a/packages/firebase_core/firebase_core/firebase_core/windows/firebase_core_plugin.cpp +++ b/packages/firebase_core/firebase_core/firebase_core/windows/firebase_core_plugin.cpp @@ -2,11 +2,11 @@ // This must be included before many other Windows headers. #include + #include "firebase/app.h" // For getPlatformVersion; remove unless needed for your plugin implementation. #include - #include #include #include @@ -43,14 +43,11 @@ void FirebaseCorePlugin::HandleMethodCall( const flutter::MethodCall &method_call, std::unique_ptr> result) { if (method_call.method_name().compare("getPlatformVersion") == 0) { - App* app = App::Create(); + App *app = App::Create(); std::cout << static_cast(reinterpret_cast(app)); std::ostringstream version_stream; - version_stream << "Windows "; if (IsWindows10OrGreater()) { version_stream << "10+"; - } else if (IsWindows8OrGreater()) { - version_stream << "8"; } else if (IsWindows7OrGreater()) { version_stream << "7"; } From 25d474e90a7feb39e06ca1cb71a85ebc3ee23822 Mon Sep 17 00:00:00 2001 From: Guillaume Bernos Date: Mon, 6 Mar 2023 15:24:46 +0100 Subject: [PATCH 32/65] add windows --- .../firebase_core/windows/CMakeLists.txt | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/packages/firebase_core/firebase_core/firebase_core/windows/CMakeLists.txt b/packages/firebase_core/firebase_core/firebase_core/windows/CMakeLists.txt index c26d21bc2f0f..6966f1504099 100644 --- a/packages/firebase_core/firebase_core/firebase_core/windows/CMakeLists.txt +++ b/packages/firebase_core/firebase_core/firebase_core/windows/CMakeLists.txt @@ -26,6 +26,18 @@ add_library(${PLUGIN_NAME} SHARED ${PLUGIN_SOURCES} ) +# Add Firebase libraries to the target using the function from the SDK. +add_subdirectory(${FIREBASE_CPP_SDK_DIR} bin/ EXCLUDE_FROM_ALL) + +# The Firebase C++ library `firebase_app` is required, +# and it must always be listed last. + +# Add the Firebase SDKs for the products you want to use in your app +# For example, to use Firebase Authentication and Firebase Realtime Database +set(firebase_libs firebase_auth firebase_app) +target_link_libraries(${target_name} "${firebase_libs}") + + # Apply a standard set of build settings that are configured in the # application-level CMakeLists.txt. This can be removed for plugins that want # full control over build settings. From 37e9e6ad9f7da890bf67fc2647154feeb53e372e Mon Sep 17 00:00:00 2001 From: Guillaume Bernos Date: Mon, 6 Mar 2023 16:15:41 +0100 Subject: [PATCH 33/65] add windows --- .../firebase_core/windows/CMakeLists.txt | 11 ----------- 1 file changed, 11 deletions(-) diff --git a/packages/firebase_core/firebase_core/firebase_core/windows/CMakeLists.txt b/packages/firebase_core/firebase_core/firebase_core/windows/CMakeLists.txt index 6966f1504099..35c68f4a1910 100644 --- a/packages/firebase_core/firebase_core/firebase_core/windows/CMakeLists.txt +++ b/packages/firebase_core/firebase_core/firebase_core/windows/CMakeLists.txt @@ -26,17 +26,6 @@ add_library(${PLUGIN_NAME} SHARED ${PLUGIN_SOURCES} ) -# Add Firebase libraries to the target using the function from the SDK. -add_subdirectory(${FIREBASE_CPP_SDK_DIR} bin/ EXCLUDE_FROM_ALL) - -# The Firebase C++ library `firebase_app` is required, -# and it must always be listed last. - -# Add the Firebase SDKs for the products you want to use in your app -# For example, to use Firebase Authentication and Firebase Realtime Database -set(firebase_libs firebase_auth firebase_app) -target_link_libraries(${target_name} "${firebase_libs}") - # Apply a standard set of build settings that are configured in the # application-level CMakeLists.txt. This can be removed for plugins that want From 3e9ed9535835463ee0334bd5e295c4cfbeceff4d Mon Sep 17 00:00:00 2001 From: Guillaume Bernos Date: Tue, 14 Mar 2023 11:04:55 +0100 Subject: [PATCH 34/65] feat(core, windows): add windows support to firebase_core --- .../example/google-services-desktop.json | 0 .../firebase_core/firebase_core/.gitignore | 30 - .../firebase_core/firebase_core/.metadata | 30 - .../firebase_core/.vscode/settings.json | 3 - .../firebase_core/firebase_core/CHANGELOG.md | 3 - .../firebase_core/GoogleService-Info.plist | 38 - .../firebase_core/firebase_core/LICENSE | 1 - .../firebase_core/firebase_core/README.md | 15 - .../firebase_core/analysis_options.yaml | 4 - .../firebase_core/example/.gitignore | 44 - .../firebase_core/example/README.md | 16 - .../example/analysis_options.yaml | 29 - .../example/bin/CMakeFiles/generate.stamp | 1 - .../bin/CMakeFiles/generate.stamp.depend | 5 - .../firebase_core/example/bin/INSTALL.vcxproj | 165 --- .../example/bin/INSTALL.vcxproj.filters | 13 - .../example/bin/cmake_install.cmake | 34 - .../firebase_core/example/lib/main.dart | 63 - .../firebase_core/example/linux/.gitignore | 1 - .../example/linux/CMakeLists.txt | 150 --- .../example/linux/flutter/CMakeLists.txt | 88 -- .../flutter/generated_plugin_registrant.cc | 15 - .../flutter/generated_plugin_registrant.h | 15 - .../linux/flutter/generated_plugins.cmake | 24 - .../firebase_core/example/linux/main.cc | 6 - .../example/linux/my_application.cc | 104 -- .../example/linux/my_application.h | 18 - .../firebase_core/example/pubspec.yaml | 83 -- .../example/test/widget_test.dart | 27 - .../firebase_core/example/windows/.gitignore | 17 - .../example/windows/CMakeLists.txt | 101 -- .../example/windows/flutter/CMakeLists.txt | 104 -- .../flutter/generated_plugin_registrant.cc | 14 - .../flutter/generated_plugin_registrant.h | 15 - .../windows/flutter/generated_plugins.cmake | 24 - .../example/windows/runner/CMakeLists.txt | 40 - .../example/windows/runner/Runner.rc | 121 -- .../example/windows/runner/flutter_window.cpp | 66 - .../example/windows/runner/flutter_window.h | 33 - .../runner/google-services-desktop.json | 37 - .../example/windows/runner/main.cpp | 43 - .../example/windows/runner/resource.h | 16 - .../windows/runner/resources/app_icon.ico | Bin 33772 -> 0 bytes .../windows/runner/runner.exe.manifest | 20 - .../example/windows/runner/utils.cpp | 64 - .../example/windows/runner/utils.h | 19 - .../example/windows/runner/win32_window.cpp | 288 ---- .../example/windows/runner/win32_window.h | 102 -- .../firebase_core/firebase/admob.h | 215 --- .../firebase/admob/banner_view.h | 427 ------ .../firebase/admob/interstitial_ad.h | 259 ---- .../firebase/admob/native_express_ad_view.h | 446 ------ .../firebase/admob/rewarded_video.h | 407 ------ .../firebase_core/firebase/admob/types.h | 244 ---- .../firebase_core/firebase/analytics.h | 569 -------- .../firebase/analytics/event_names.h | 472 ------- .../firebase/analytics/parameter_names.h | 755 ----------- .../firebase/analytics/user_property_names.h | 50 - .../firebase_core/firebase/app.h | 787 ----------- .../firebase_core/firebase/auth.h | 939 ------------- .../firebase_core/firebase/auth/credential.h | 633 --------- .../firebase_core/firebase/auth/types.h | 473 ------- .../firebase_core/firebase/auth/user.h | 501 ------- .../firebase_core/firebase/database.h | 199 --- .../firebase_core/firebase/database/common.h | 83 -- .../firebase/database/data_snapshot.h | 205 --- .../firebase/database/database_reference.h | 477 ------- .../firebase/database/disconnection.h | 156 --- .../firebase/database/listener.h | 112 -- .../firebase/database/mutable_data.h | 165 --- .../firebase_core/firebase/database/query.h | 358 ----- .../firebase/database/transaction.h | 102 -- .../firebase_core/firebase/dynamic_links.h | 117 -- .../firebase/dynamic_links/components.h | 336 ----- .../firebase_core/firebase/firestore.h | 458 ------- .../firebase/firestore/collection_reference.h | 183 --- .../firebase/firestore/document_change.h | 203 --- .../firebase/firestore/document_reference.h | 351 ----- .../firebase/firestore/document_snapshot.h | 297 ---- .../firebase/firestore/field_path.h | 205 --- .../firebase/firestore/field_value.h | 436 ------ .../firebase/firestore/firestore_errors.h | 116 -- .../firebase/firestore/firestore_version.h | 29 - .../firebase/firestore/geo_point.h | 120 -- .../firestore/listener_registration.h | 130 -- .../firestore/load_bundle_task_progress.h | 101 -- .../firebase/firestore/map_field_value.h | 37 - .../firebase/firestore/metadata_changes.h | 41 - .../firebase_core/firebase/firestore/query.h | 683 ---------- .../firebase/firestore/query_snapshot.h | 194 --- .../firebase/firestore/set_options.h | 161 --- .../firebase/firestore/settings.h | 247 ---- .../firebase/firestore/snapshot_metadata.h | 159 --- .../firebase_core/firebase/firestore/source.h | 59 - .../firebase/firestore/timestamp.h | 252 ---- .../firebase/firestore/transaction.h | 143 -- .../firebase/firestore/transaction_options.h | 137 -- .../firebase/firestore/write_batch.h | 188 --- .../firebase_core/firebase/functions.h | 115 -- .../firebase/functions/callable_reference.h | 124 -- .../firebase/functions/callable_result.h | 96 -- .../firebase_core/firebase/functions/common.h | 202 --- .../firebase_core/firebase/future.h | 533 -------- .../firebase_core/firebase/gma.h | 207 --- .../firebase_core/firebase/gma/ad_view.h | 267 ---- .../firebase/gma/interstitial_ad.h | 128 -- .../firebase_core/firebase/gma/rewarded_ad.h | 152 --- .../firebase_core/firebase/gma/types.h | 939 ------------- .../firebase_core/firebase/installations.h | 123 -- .../firebase_core/firebase/internal/common.h | 128 -- .../firebase/internal/future_impl.h | 359 ----- .../firebase_core/firebase/internal/mutex.h | 100 -- .../firebase/internal/platform.h | 110 -- .../firebase/internal/type_traits.h | 134 -- .../firebase_core/firebase/log.h | 54 - .../firebase_core/firebase/messaging.h | 728 ---------- .../firebase_core/firebase/remote_config.h | 526 -------- .../firebase_core/firebase/storage.h | 161 --- .../firebase_core/firebase/storage/common.h | 62 - .../firebase/storage/controller.h | 146 -- .../firebase_core/firebase/storage/listener.h | 74 - .../firebase_core/firebase/storage/metadata.h | 276 ---- .../firebase/storage/storage_reference.h | 361 ----- .../firebase_core/firebase/util.h | 101 -- .../firebase_core/firebase/variant.h | 1197 ----------------- .../firebase_core/firebase/version.h | 68 - .../generate_xml_from_google_services_json.py | 496 ------- .../firebase_core/generated_bindings.dart | 26 - .../google-services-desktop.json | 37 - .../firebase_core/lib/firebase_core.dart | 8 - .../lib/firebase_core_method_channel.dart | 17 - .../lib/firebase_core_platform_interface.dart | 29 - .../firebase_core/linux/CMakeLists.txt | 47 - .../linux/firebase_core_plugin.cc | 70 - .../firebase_core/firebase_core_plugin.h | 26 - .../firebase_core/firebase_core/pubspec.yaml | 36 - .../firebase_core_method_channel_test.dart | 24 - .../test/firebase_core_test.dart | 29 - .../firebase_core/firebase_core/pubspec.yaml | 3 + .../{firebase_core => }/windows/.gitignore | 0 .../windows/CMakeLists.txt | 0 .../windows/firebase_core_plugin.cpp | 0 .../windows/firebase_core_plugin.h | 0 .../windows/firebase_core_plugin_c_api.cpp | 0 .../firebase_core_plugin_c_api.h | 0 145 files changed, 3 insertions(+), 24882 deletions(-) rename packages/firebase_core/firebase_core/{firebase_core => }/example/google-services-desktop.json (100%) delete mode 100644 packages/firebase_core/firebase_core/firebase_core/.gitignore delete mode 100644 packages/firebase_core/firebase_core/firebase_core/.metadata delete mode 100644 packages/firebase_core/firebase_core/firebase_core/.vscode/settings.json delete mode 100644 packages/firebase_core/firebase_core/firebase_core/CHANGELOG.md delete mode 100644 packages/firebase_core/firebase_core/firebase_core/GoogleService-Info.plist delete mode 100644 packages/firebase_core/firebase_core/firebase_core/LICENSE delete mode 100644 packages/firebase_core/firebase_core/firebase_core/README.md delete mode 100644 packages/firebase_core/firebase_core/firebase_core/analysis_options.yaml delete mode 100644 packages/firebase_core/firebase_core/firebase_core/example/.gitignore delete mode 100644 packages/firebase_core/firebase_core/firebase_core/example/README.md delete mode 100644 packages/firebase_core/firebase_core/firebase_core/example/analysis_options.yaml delete mode 100644 packages/firebase_core/firebase_core/firebase_core/example/bin/CMakeFiles/generate.stamp delete mode 100644 packages/firebase_core/firebase_core/firebase_core/example/bin/CMakeFiles/generate.stamp.depend delete mode 100644 packages/firebase_core/firebase_core/firebase_core/example/bin/INSTALL.vcxproj delete mode 100644 packages/firebase_core/firebase_core/firebase_core/example/bin/INSTALL.vcxproj.filters delete mode 100644 packages/firebase_core/firebase_core/firebase_core/example/bin/cmake_install.cmake delete mode 100644 packages/firebase_core/firebase_core/firebase_core/example/lib/main.dart delete mode 100644 packages/firebase_core/firebase_core/firebase_core/example/linux/.gitignore delete mode 100644 packages/firebase_core/firebase_core/firebase_core/example/linux/CMakeLists.txt delete mode 100644 packages/firebase_core/firebase_core/firebase_core/example/linux/flutter/CMakeLists.txt delete mode 100644 packages/firebase_core/firebase_core/firebase_core/example/linux/flutter/generated_plugin_registrant.cc delete mode 100644 packages/firebase_core/firebase_core/firebase_core/example/linux/flutter/generated_plugin_registrant.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/example/linux/flutter/generated_plugins.cmake delete mode 100644 packages/firebase_core/firebase_core/firebase_core/example/linux/main.cc delete mode 100644 packages/firebase_core/firebase_core/firebase_core/example/linux/my_application.cc delete mode 100644 packages/firebase_core/firebase_core/firebase_core/example/linux/my_application.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/example/pubspec.yaml delete mode 100644 packages/firebase_core/firebase_core/firebase_core/example/test/widget_test.dart delete mode 100644 packages/firebase_core/firebase_core/firebase_core/example/windows/.gitignore delete mode 100644 packages/firebase_core/firebase_core/firebase_core/example/windows/CMakeLists.txt delete mode 100644 packages/firebase_core/firebase_core/firebase_core/example/windows/flutter/CMakeLists.txt delete mode 100644 packages/firebase_core/firebase_core/firebase_core/example/windows/flutter/generated_plugin_registrant.cc delete mode 100644 packages/firebase_core/firebase_core/firebase_core/example/windows/flutter/generated_plugin_registrant.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/example/windows/flutter/generated_plugins.cmake delete mode 100644 packages/firebase_core/firebase_core/firebase_core/example/windows/runner/CMakeLists.txt delete mode 100644 packages/firebase_core/firebase_core/firebase_core/example/windows/runner/Runner.rc delete mode 100644 packages/firebase_core/firebase_core/firebase_core/example/windows/runner/flutter_window.cpp delete mode 100644 packages/firebase_core/firebase_core/firebase_core/example/windows/runner/flutter_window.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/example/windows/runner/google-services-desktop.json delete mode 100644 packages/firebase_core/firebase_core/firebase_core/example/windows/runner/main.cpp delete mode 100644 packages/firebase_core/firebase_core/firebase_core/example/windows/runner/resource.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/example/windows/runner/resources/app_icon.ico delete mode 100644 packages/firebase_core/firebase_core/firebase_core/example/windows/runner/runner.exe.manifest delete mode 100644 packages/firebase_core/firebase_core/firebase_core/example/windows/runner/utils.cpp delete mode 100644 packages/firebase_core/firebase_core/firebase_core/example/windows/runner/utils.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/example/windows/runner/win32_window.cpp delete mode 100644 packages/firebase_core/firebase_core/firebase_core/example/windows/runner/win32_window.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/admob.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/admob/banner_view.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/admob/interstitial_ad.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/admob/native_express_ad_view.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/admob/rewarded_video.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/admob/types.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/analytics.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/analytics/event_names.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/analytics/parameter_names.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/analytics/user_property_names.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/app.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/auth.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/auth/credential.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/auth/types.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/auth/user.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/database.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/database/common.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/database/data_snapshot.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/database/database_reference.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/database/disconnection.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/database/listener.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/database/mutable_data.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/database/query.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/database/transaction.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/dynamic_links.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/dynamic_links/components.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/collection_reference.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/document_change.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/document_reference.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/document_snapshot.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/field_path.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/field_value.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/firestore_errors.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/firestore_version.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/geo_point.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/listener_registration.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/load_bundle_task_progress.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/map_field_value.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/metadata_changes.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/query.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/query_snapshot.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/set_options.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/settings.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/snapshot_metadata.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/source.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/timestamp.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/transaction.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/transaction_options.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/firestore/write_batch.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/functions.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/functions/callable_reference.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/functions/callable_result.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/functions/common.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/future.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/gma.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/gma/ad_view.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/gma/interstitial_ad.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/gma/rewarded_ad.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/gma/types.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/installations.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/internal/common.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/internal/future_impl.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/internal/mutex.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/internal/platform.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/internal/type_traits.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/log.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/messaging.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/remote_config.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/storage.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/storage/common.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/storage/controller.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/storage/listener.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/storage/metadata.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/storage/storage_reference.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/util.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/variant.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/firebase/version.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/generate_xml_from_google_services_json.py delete mode 100644 packages/firebase_core/firebase_core/firebase_core/generated_bindings.dart delete mode 100644 packages/firebase_core/firebase_core/firebase_core/google-services-desktop.json delete mode 100644 packages/firebase_core/firebase_core/firebase_core/lib/firebase_core.dart delete mode 100644 packages/firebase_core/firebase_core/firebase_core/lib/firebase_core_method_channel.dart delete mode 100644 packages/firebase_core/firebase_core/firebase_core/lib/firebase_core_platform_interface.dart delete mode 100644 packages/firebase_core/firebase_core/firebase_core/linux/CMakeLists.txt delete mode 100644 packages/firebase_core/firebase_core/firebase_core/linux/firebase_core_plugin.cc delete mode 100644 packages/firebase_core/firebase_core/firebase_core/linux/include/firebase_core/firebase_core_plugin.h delete mode 100644 packages/firebase_core/firebase_core/firebase_core/pubspec.yaml delete mode 100644 packages/firebase_core/firebase_core/firebase_core/test/firebase_core_method_channel_test.dart delete mode 100644 packages/firebase_core/firebase_core/firebase_core/test/firebase_core_test.dart rename packages/firebase_core/firebase_core/{firebase_core => }/windows/.gitignore (100%) rename packages/firebase_core/firebase_core/{firebase_core => }/windows/CMakeLists.txt (100%) rename packages/firebase_core/firebase_core/{firebase_core => }/windows/firebase_core_plugin.cpp (100%) rename packages/firebase_core/firebase_core/{firebase_core => }/windows/firebase_core_plugin.h (100%) rename packages/firebase_core/firebase_core/{firebase_core => }/windows/firebase_core_plugin_c_api.cpp (100%) rename packages/firebase_core/firebase_core/{firebase_core => }/windows/include/firebase_core/firebase_core_plugin_c_api.h (100%) diff --git a/packages/firebase_core/firebase_core/firebase_core/example/google-services-desktop.json b/packages/firebase_core/firebase_core/example/google-services-desktop.json similarity index 100% rename from packages/firebase_core/firebase_core/firebase_core/example/google-services-desktop.json rename to packages/firebase_core/firebase_core/example/google-services-desktop.json diff --git a/packages/firebase_core/firebase_core/firebase_core/.gitignore b/packages/firebase_core/firebase_core/firebase_core/.gitignore deleted file mode 100644 index 96486fd93024..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/.gitignore +++ /dev/null @@ -1,30 +0,0 @@ -# Miscellaneous -*.class -*.log -*.pyc -*.swp -.DS_Store -.atom/ -.buildlog/ -.history -.svn/ -migrate_working_dir/ - -# IntelliJ related -*.iml -*.ipr -*.iws -.idea/ - -# The .vscode folder contains launch configuration and tasks you configure in -# VS Code which you may wish to be included in version control, so this line -# is commented out by default. -#.vscode/ - -# Flutter/Dart/Pub related -# Libraries should not include pubspec.lock, per https://dart.dev/guides/libraries/private-files#pubspeclock. -/pubspec.lock -**/doc/api/ -.dart_tool/ -.packages -build/ diff --git a/packages/firebase_core/firebase_core/firebase_core/.metadata b/packages/firebase_core/firebase_core/firebase_core/.metadata deleted file mode 100644 index 97ef0fff36d0..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/.metadata +++ /dev/null @@ -1,30 +0,0 @@ -# This file tracks properties of this Flutter project. -# Used by Flutter tool to assess capabilities and perform upgrades etc. -# -# This file should be version controlled. - -version: - revision: 12cb4eb7a009f52b347b62ade7cb4854b926af72 - channel: stable - -project_type: plugin - -# Tracks metadata for the flutter migrate command -migration: - platforms: - - platform: root - create_revision: 12cb4eb7a009f52b347b62ade7cb4854b926af72 - base_revision: 12cb4eb7a009f52b347b62ade7cb4854b926af72 - - platform: windows - create_revision: 12cb4eb7a009f52b347b62ade7cb4854b926af72 - base_revision: 12cb4eb7a009f52b347b62ade7cb4854b926af72 - - # User provided section - - # List of Local paths (relative to this file) that should be - # ignored by the migrate tool. - # - # Files that are not part of the templates will be ignored by default. - unmanaged_files: - - 'lib/main.dart' - - 'ios/Runner.xcodeproj/project.pbxproj' diff --git a/packages/firebase_core/firebase_core/firebase_core/.vscode/settings.json b/packages/firebase_core/firebase_core/firebase_core/.vscode/settings.json deleted file mode 100644 index deec1e1d3994..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/.vscode/settings.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "cmake.sourceDirectory": "${workspaceFolder}/linux" -} diff --git a/packages/firebase_core/firebase_core/firebase_core/CHANGELOG.md b/packages/firebase_core/firebase_core/firebase_core/CHANGELOG.md deleted file mode 100644 index 41cc7d8192ec..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/CHANGELOG.md +++ /dev/null @@ -1,3 +0,0 @@ -## 0.0.1 - -* TODO: Describe initial release. diff --git a/packages/firebase_core/firebase_core/firebase_core/GoogleService-Info.plist b/packages/firebase_core/firebase_core/firebase_core/GoogleService-Info.plist deleted file mode 100644 index f325ead98dbc..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/GoogleService-Info.plist +++ /dev/null @@ -1,38 +0,0 @@ - - - - - CLIENT_ID - 406099696497-134k3722m01rtrsklhf3b7k8sqa5r7in.apps.googleusercontent.com - REVERSED_CLIENT_ID - com.googleusercontent.apps.406099696497-134k3722m01rtrsklhf3b7k8sqa5r7in - ANDROID_CLIENT_ID - 406099696497-17qn06u8a0dc717u8ul7s49ampk13lul.apps.googleusercontent.com - API_KEY - AIzaSyDooSUGSf63Ghq02_iIhtnmwMDs4HlWS6c - GCM_SENDER_ID - 406099696497 - PLIST_VERSION - 1 - BUNDLE_ID - io.flutter.plugins.firebase.auth.example - PROJECT_ID - flutterfire-e2e-tests - STORAGE_BUCKET - flutterfire-e2e-tests.appspot.com - IS_ADS_ENABLED - - IS_ANALYTICS_ENABLED - - IS_APPINVITE_ENABLED - - IS_GCM_ENABLED - - IS_SIGNIN_ENABLED - - GOOGLE_APP_ID - 1:406099696497:ios:58cbc26aca8e5cf83574d0 - DATABASE_URL - https://flutterfire-e2e-tests-default-rtdb.europe-west1.firebasedatabase.app - - \ No newline at end of file diff --git a/packages/firebase_core/firebase_core/firebase_core/LICENSE b/packages/firebase_core/firebase_core/firebase_core/LICENSE deleted file mode 100644 index ba75c69f7f21..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/LICENSE +++ /dev/null @@ -1 +0,0 @@ -TODO: Add your license here. diff --git a/packages/firebase_core/firebase_core/firebase_core/README.md b/packages/firebase_core/firebase_core/firebase_core/README.md deleted file mode 100644 index b373aba55a5f..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/README.md +++ /dev/null @@ -1,15 +0,0 @@ -# firebase_core - -A new Flutter plugin project. - -## Getting Started - -This project is a starting point for a Flutter -[plug-in package](https://flutter.dev/developing-packages/), -a specialized package that includes platform-specific implementation code for -Android and/or iOS. - -For help getting started with Flutter development, view the -[online documentation](https://flutter.dev/docs), which offers tutorials, -samples, guidance on mobile development, and a full API reference. - diff --git a/packages/firebase_core/firebase_core/firebase_core/analysis_options.yaml b/packages/firebase_core/firebase_core/firebase_core/analysis_options.yaml deleted file mode 100644 index a5744c1cfbe7..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/analysis_options.yaml +++ /dev/null @@ -1,4 +0,0 @@ -include: package:flutter_lints/flutter.yaml - -# Additional information about this file can be found at -# https://dart.dev/guides/language/analysis-options diff --git a/packages/firebase_core/firebase_core/firebase_core/example/.gitignore b/packages/firebase_core/firebase_core/firebase_core/example/.gitignore deleted file mode 100644 index 24476c5d1eb5..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/example/.gitignore +++ /dev/null @@ -1,44 +0,0 @@ -# Miscellaneous -*.class -*.log -*.pyc -*.swp -.DS_Store -.atom/ -.buildlog/ -.history -.svn/ -migrate_working_dir/ - -# IntelliJ related -*.iml -*.ipr -*.iws -.idea/ - -# The .vscode folder contains launch configuration and tasks you configure in -# VS Code which you may wish to be included in version control, so this line -# is commented out by default. -#.vscode/ - -# Flutter/Dart/Pub related -**/doc/api/ -**/ios/Flutter/.last_build_id -.dart_tool/ -.flutter-plugins -.flutter-plugins-dependencies -.packages -.pub-cache/ -.pub/ -/build/ - -# Symbolication related -app.*.symbols - -# Obfuscation related -app.*.map.json - -# Android Studio will place build artifacts here -/android/app/debug -/android/app/profile -/android/app/release diff --git a/packages/firebase_core/firebase_core/firebase_core/example/README.md b/packages/firebase_core/firebase_core/firebase_core/example/README.md deleted file mode 100644 index d1f452146bce..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/example/README.md +++ /dev/null @@ -1,16 +0,0 @@ -# firebase_core_example - -Demonstrates how to use the firebase_core plugin. - -## Getting Started - -This project is a starting point for a Flutter application. - -A few resources to get you started if this is your first Flutter project: - -- [Lab: Write your first Flutter app](https://docs.flutter.dev/get-started/codelab) -- [Cookbook: Useful Flutter samples](https://docs.flutter.dev/cookbook) - -For help getting started with Flutter development, view the -[online documentation](https://docs.flutter.dev/), which offers tutorials, -samples, guidance on mobile development, and a full API reference. diff --git a/packages/firebase_core/firebase_core/firebase_core/example/analysis_options.yaml b/packages/firebase_core/firebase_core/firebase_core/example/analysis_options.yaml deleted file mode 100644 index 61b6c4de17c9..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/example/analysis_options.yaml +++ /dev/null @@ -1,29 +0,0 @@ -# This file configures the analyzer, which statically analyzes Dart code to -# check for errors, warnings, and lints. -# -# The issues identified by the analyzer are surfaced in the UI of Dart-enabled -# IDEs (https://dart.dev/tools#ides-and-editors). The analyzer can also be -# invoked from the command line by running `flutter analyze`. - -# The following line activates a set of recommended lints for Flutter apps, -# packages, and plugins designed to encourage good coding practices. -include: package:flutter_lints/flutter.yaml - -linter: - # The lint rules applied to this project can be customized in the - # section below to disable rules from the `package:flutter_lints/flutter.yaml` - # included above or to enable additional rules. A list of all available lints - # and their documentation is published at - # https://dart-lang.github.io/linter/lints/index.html. - # - # Instead of disabling a lint rule for the entire project in the - # section below, it can also be suppressed for a single line of code - # or a specific dart file by using the `// ignore: name_of_lint` and - # `// ignore_for_file: name_of_lint` syntax on the line or in the file - # producing the lint. - rules: - # avoid_print: false # Uncomment to disable the `avoid_print` rule - # prefer_single_quotes: true # Uncomment to enable the `prefer_single_quotes` rule - -# Additional information about this file can be found at -# https://dart.dev/guides/language/analysis-options diff --git a/packages/firebase_core/firebase_core/firebase_core/example/bin/CMakeFiles/generate.stamp b/packages/firebase_core/firebase_core/firebase_core/example/bin/CMakeFiles/generate.stamp deleted file mode 100644 index 9b5f49fa9f14..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/example/bin/CMakeFiles/generate.stamp +++ /dev/null @@ -1 +0,0 @@ -# CMake generation timestamp file for this directory. diff --git a/packages/firebase_core/firebase_core/firebase_core/example/bin/CMakeFiles/generate.stamp.depend b/packages/firebase_core/firebase_core/firebase_core/example/bin/CMakeFiles/generate.stamp.depend deleted file mode 100644 index 5b8da13f857a..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/example/bin/CMakeFiles/generate.stamp.depend +++ /dev/null @@ -1,5 +0,0 @@ -# CMake generation dependency list for this directory. -C:/Program Files/Microsoft Visual Studio/2022/Community/Common7/IDE/CommonExtensions/Microsoft/CMake/CMake/share/cmake-3.25/Modules/FindPackageHandleStandardArgs.cmake -C:/Program Files/Microsoft Visual Studio/2022/Community/Common7/IDE/CommonExtensions/Microsoft/CMake/CMake/share/cmake-3.25/Modules/FindPackageMessage.cmake -C:/Program Files/Microsoft Visual Studio/2022/Community/Common7/IDE/CommonExtensions/Microsoft/CMake/CMake/share/cmake-3.25/Modules/FindPkgConfig.cmake -C:/Users/guill/Downloads/firebase_cpp_sdk_10.5.0/firebase_cpp_sdk/CMakeLists.txt diff --git a/packages/firebase_core/firebase_core/firebase_core/example/bin/INSTALL.vcxproj b/packages/firebase_core/firebase_core/firebase_core/example/bin/INSTALL.vcxproj deleted file mode 100644 index 05091bebad78..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/example/bin/INSTALL.vcxproj +++ /dev/null @@ -1,165 +0,0 @@ - - - - x64 - - - - Debug - x64 - - - Profile - x64 - - - Release - x64 - - - - {B2284ACE-B264-3C77-ADAD-5516EBC85159} - Win32Proj - 10.0.22000.0 - x64 - INSTALL - NoUpgrade - - - - Utility - MultiByte - v143 - - - Utility - MultiByte - v143 - - - Utility - MultiByte - v143 - - - - - - - - - - <_ProjectFileVersion>10.0.20506.1 - $(Platform)\$(Configuration)\$(ProjectName)\ - $(Platform)\$(Configuration)\$(ProjectName)\ - $(Platform)\$(Configuration)\$(ProjectName)\ - - - - Always - - setlocal -"C:\Program Files\Microsoft Visual Studio\2022\Community\Common7\IDE\CommonExtensions\Microsoft\CMake\CMake\bin\cmake.exe" -DBUILD_TYPE=$(Configuration) -P cmake_install.cmake -if %errorlevel% neq 0 goto :cmEnd -:cmEnd -endlocal & call :cmErrorLevel %errorlevel% & goto :cmDone -:cmErrorLevel -exit /b %1 -:cmDone -if %errorlevel% neq 0 goto :VCEnd - - - - - Always - - setlocal -"C:\Program Files\Microsoft Visual Studio\2022\Community\Common7\IDE\CommonExtensions\Microsoft\CMake\CMake\bin\cmake.exe" -DBUILD_TYPE=$(Configuration) -P cmake_install.cmake -if %errorlevel% neq 0 goto :cmEnd -:cmEnd -endlocal & call :cmErrorLevel %errorlevel% & goto :cmDone -:cmErrorLevel -exit /b %1 -:cmDone -if %errorlevel% neq 0 goto :VCEnd - - - - - Always - - setlocal -"C:\Program Files\Microsoft Visual Studio\2022\Community\Common7\IDE\CommonExtensions\Microsoft\CMake\CMake\bin\cmake.exe" -DBUILD_TYPE=$(Configuration) -P cmake_install.cmake -if %errorlevel% neq 0 goto :cmEnd -:cmEnd -endlocal & call :cmErrorLevel %errorlevel% & goto :cmDone -:cmErrorLevel -exit /b %1 -:cmDone -if %errorlevel% neq 0 goto :VCEnd - - - - - - setlocal -cd . -if %errorlevel% neq 0 goto :cmEnd -:cmEnd -endlocal & call :cmErrorLevel %errorlevel% & goto :cmDone -:cmErrorLevel -exit /b %1 -:cmDone -if %errorlevel% neq 0 goto :VCEnd - %(AdditionalInputs) - C:\Users\guill\Developer\flutterfire\packages\firebase_core\firebase_core\firebase_core\example\bin\CMakeFiles\INSTALL_force - false - false - - setlocal -cd . -if %errorlevel% neq 0 goto :cmEnd -:cmEnd -endlocal & call :cmErrorLevel %errorlevel% & goto :cmDone -:cmErrorLevel -exit /b %1 -:cmDone -if %errorlevel% neq 0 goto :VCEnd - %(AdditionalInputs) - C:\Users\guill\Developer\flutterfire\packages\firebase_core\firebase_core\firebase_core\example\bin\CMakeFiles\INSTALL_force - false - false - - setlocal -cd . -if %errorlevel% neq 0 goto :cmEnd -:cmEnd -endlocal & call :cmErrorLevel %errorlevel% & goto :cmDone -:cmErrorLevel -exit /b %1 -:cmDone -if %errorlevel% neq 0 goto :VCEnd - %(AdditionalInputs) - C:\Users\guill\Developer\flutterfire\packages\firebase_core\firebase_core\firebase_core\example\bin\CMakeFiles\INSTALL_force - false - false - - - - - {DC08768F-F57C-313C-94F0-E16194F54223} - ZERO_CHECK - false - Never - - - {DF648812-5598-379C-A5B5-8A3EAC6BC5B0} - ALL_BUILD - false - Never - - - - - - \ No newline at end of file diff --git a/packages/firebase_core/firebase_core/firebase_core/example/bin/INSTALL.vcxproj.filters b/packages/firebase_core/firebase_core/firebase_core/example/bin/INSTALL.vcxproj.filters deleted file mode 100644 index 69fed1abf535..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/example/bin/INSTALL.vcxproj.filters +++ /dev/null @@ -1,13 +0,0 @@ - - - - - CMake Rules - - - - - {EAE753BC-CF7B-3081-8331-9EFFB2F8D8A5} - - - diff --git a/packages/firebase_core/firebase_core/firebase_core/example/bin/cmake_install.cmake b/packages/firebase_core/firebase_core/firebase_core/example/bin/cmake_install.cmake deleted file mode 100644 index 8cf9b6c06b96..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/example/bin/cmake_install.cmake +++ /dev/null @@ -1,34 +0,0 @@ -# Install script for directory: C:/Users/guill/Downloads/firebase_cpp_sdk_10.5.0/firebase_cpp_sdk - -# Set the install prefix -if(NOT DEFINED CMAKE_INSTALL_PREFIX) - set(CMAKE_INSTALL_PREFIX "$") -endif() -string(REGEX REPLACE "/$" "" CMAKE_INSTALL_PREFIX "${CMAKE_INSTALL_PREFIX}") - -# Set the install configuration name. -if(NOT DEFINED CMAKE_INSTALL_CONFIG_NAME) - if(BUILD_TYPE) - string(REGEX REPLACE "^[^A-Za-z0-9_]+" "" - CMAKE_INSTALL_CONFIG_NAME "${BUILD_TYPE}") - else() - set(CMAKE_INSTALL_CONFIG_NAME "Release") - endif() - message(STATUS "Install configuration: \"${CMAKE_INSTALL_CONFIG_NAME}\"") -endif() - -# Set the component getting installed. -if(NOT CMAKE_INSTALL_COMPONENT) - if(COMPONENT) - message(STATUS "Install component: \"${COMPONENT}\"") - set(CMAKE_INSTALL_COMPONENT "${COMPONENT}") - else() - set(CMAKE_INSTALL_COMPONENT) - endif() -endif() - -# Is this installation the result of a crosscompile? -if(NOT DEFINED CMAKE_CROSSCOMPILING) - set(CMAKE_CROSSCOMPILING "FALSE") -endif() - diff --git a/packages/firebase_core/firebase_core/firebase_core/example/lib/main.dart b/packages/firebase_core/firebase_core/firebase_core/example/lib/main.dart deleted file mode 100644 index 4e2b473ad9e0..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/example/lib/main.dart +++ /dev/null @@ -1,63 +0,0 @@ -import 'package:flutter/material.dart'; -import 'dart:async'; - -import 'package:flutter/services.dart'; -import 'package:firebase_core/firebase_core.dart'; - -void main() { - runApp(const MyApp()); -} - -class MyApp extends StatefulWidget { - const MyApp({super.key}); - - @override - State createState() => _MyAppState(); -} - -class _MyAppState extends State { - String _platformVersion = 'Unknown'; - final _firebaseCorePlugin = FirebaseCore(); - - @override - void initState() { - super.initState(); - initPlatformState(); - } - - // Platform messages are asynchronous, so we initialize in an async method. - Future initPlatformState() async { - String platformVersion; - // Platform messages may fail, so we use a try/catch PlatformException. - // We also handle the message potentially returning null. - try { - platformVersion = - await _firebaseCorePlugin.getPlatformVersion() ?? 'Unknown platform version'; - } on PlatformException { - platformVersion = 'Failed to get platform version.'; - } - - // If the widget was removed from the tree while the asynchronous platform - // message was in flight, we want to discard the reply rather than calling - // setState to update our non-existent appearance. - if (!mounted) return; - - setState(() { - _platformVersion = platformVersion; - }); - } - - @override - Widget build(BuildContext context) { - return MaterialApp( - home: Scaffold( - appBar: AppBar( - title: const Text('Plugin example app'), - ), - body: Center( - child: Text('Running on: $_platformVersion\n'), - ), - ), - ); - } -} diff --git a/packages/firebase_core/firebase_core/firebase_core/example/linux/.gitignore b/packages/firebase_core/firebase_core/firebase_core/example/linux/.gitignore deleted file mode 100644 index d3896c98444f..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/example/linux/.gitignore +++ /dev/null @@ -1 +0,0 @@ -flutter/ephemeral diff --git a/packages/firebase_core/firebase_core/firebase_core/example/linux/CMakeLists.txt b/packages/firebase_core/firebase_core/firebase_core/example/linux/CMakeLists.txt deleted file mode 100644 index 9ae42276201e..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/example/linux/CMakeLists.txt +++ /dev/null @@ -1,150 +0,0 @@ -# Project-level configuration. -cmake_minimum_required(VERSION 3.10) -project(runner LANGUAGES CXX) - -# The name of the executable created for the application. Change this to change -# the on-disk name of your application. -set(BINARY_NAME "firebase_core_example") -# The unique GTK application identifier for this application. See: -# https://wiki.gnome.org/HowDoI/ChooseApplicationID -set(APPLICATION_ID "com.example.firebase_core") - -# Explicitly opt in to modern CMake behaviors to avoid warnings with recent -# versions of CMake. -cmake_policy(SET CMP0063 NEW) - -# Load bundled libraries from the lib/ directory relative to the binary. -set(CMAKE_INSTALL_RPATH "$ORIGIN/lib") - -# Root filesystem for cross-building. -if(FLUTTER_TARGET_PLATFORM_SYSROOT) - set(CMAKE_SYSROOT ${FLUTTER_TARGET_PLATFORM_SYSROOT}) - set(CMAKE_FIND_ROOT_PATH ${CMAKE_SYSROOT}) - set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) - set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY) - set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) - set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) -endif() - -# Define build configuration options. -if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) - set(CMAKE_BUILD_TYPE "Debug" CACHE - STRING "Flutter build mode" FORCE) - set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS - "Debug" "Profile" "Release") -endif() - -# Compilation settings that should be applied to most targets. -# -# Be cautious about adding new options here, as plugins use this function by -# default. In most cases, you should add new options to specific targets instead -# of modifying this function. -function(APPLY_STANDARD_SETTINGS TARGET) - target_compile_features(${TARGET} PUBLIC cxx_std_14) - target_compile_options(${TARGET} PRIVATE -Wall -Werror) - target_compile_options(${TARGET} PRIVATE "$<$>:-O3>") - target_compile_definitions(${TARGET} PRIVATE "$<$>:NDEBUG>") -endfunction() - -# Flutter library and tool build rules. -set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") -add_subdirectory(${FLUTTER_MANAGED_DIR}) - -# Add Firebase libraries to the target using the function from the SDK. -add_subdirectory(${FIREBASE_CPP_SDK_DIR} bin/ EXCLUDE_FROM_ALL) - -# The Firebase C++ library `firebase_app` is required, -# and it must always be listed last. - -# Add the Firebase SDKs for the products you want to use in your app -# For example, to use Firebase Authentication and Firebase Realtime Database -set(firebase_libs firebase_auth firebase_database firebase_app) -target_link_libraries(${target_name} "${firebase_libs}") - - -# System-level dependencies. -find_package(PkgConfig REQUIRED) -pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) - -add_definitions(-DAPPLICATION_ID="${APPLICATION_ID}") - -# Define the application target. To change its name, change BINARY_NAME above, -# not the value here, or `flutter run` will no longer work. -# -# Any new source files that you add to the application should be added here. -add_executable(${BINARY_NAME} - "main.cc" - "my_application.cc" - "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" -) - -# Apply the standard set of build settings. This can be removed for applications -# that need different build settings. -apply_standard_settings(${BINARY_NAME}) - -# Add dependency libraries. Add any application-specific dependencies here. -target_link_libraries(${BINARY_NAME} PRIVATE flutter) -target_link_libraries(${BINARY_NAME} PRIVATE PkgConfig::GTK) - -# Run the Flutter tool portions of the build. This must not be removed. -add_dependencies(${BINARY_NAME} flutter_assemble) - -# Only the install-generated bundle's copy of the executable will launch -# correctly, since the resources must in the right relative locations. To avoid -# people trying to run the unbundled copy, put it in a subdirectory instead of -# the default top-level location. -set_target_properties(${BINARY_NAME} - PROPERTIES - RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/intermediates_do_not_run" -) - -# Generated plugin build rules, which manage building the plugins and adding -# them to the application. -include(flutter/generated_plugins.cmake) - - -# === Installation === -# By default, "installing" just makes a relocatable bundle in the build -# directory. -set(BUILD_BUNDLE_DIR "${PROJECT_BINARY_DIR}/bundle") -if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) - set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) -endif() - -# Start with a clean build bundle directory every time. -install(CODE " - file(REMOVE_RECURSE \"${BUILD_BUNDLE_DIR}/\") - " COMPONENT Runtime) - -set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") -set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}/lib") - -install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" - COMPONENT Runtime) - -install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" - COMPONENT Runtime) - -install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" - COMPONENT Runtime) - -foreach(bundled_library ${PLUGIN_BUNDLED_LIBRARIES}) - install(FILES "${bundled_library}" - DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" - COMPONENT Runtime) -endforeach(bundled_library) - -# Fully re-copy the assets directory on each build to avoid having stale files -# from a previous install. -set(FLUTTER_ASSET_DIR_NAME "flutter_assets") -install(CODE " - file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") - " COMPONENT Runtime) -install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" - DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) - -# Install the AOT library on non-Debug builds only. -if(NOT CMAKE_BUILD_TYPE MATCHES "Debug") - install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" - COMPONENT Runtime) -endif() diff --git a/packages/firebase_core/firebase_core/firebase_core/example/linux/flutter/CMakeLists.txt b/packages/firebase_core/firebase_core/firebase_core/example/linux/flutter/CMakeLists.txt deleted file mode 100644 index d5bd01648a96..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/example/linux/flutter/CMakeLists.txt +++ /dev/null @@ -1,88 +0,0 @@ -# This file controls Flutter-level build steps. It should not be edited. -cmake_minimum_required(VERSION 3.10) - -set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") - -# Configuration provided via flutter tool. -include(${EPHEMERAL_DIR}/generated_config.cmake) - -# TODO: Move the rest of this into files in ephemeral. See -# https://github.com/flutter/flutter/issues/57146. - -# Serves the same purpose as list(TRANSFORM ... PREPEND ...), -# which isn't available in 3.10. -function(list_prepend LIST_NAME PREFIX) - set(NEW_LIST "") - foreach(element ${${LIST_NAME}}) - list(APPEND NEW_LIST "${PREFIX}${element}") - endforeach(element) - set(${LIST_NAME} "${NEW_LIST}" PARENT_SCOPE) -endfunction() - -# === Flutter Library === -# System-level dependencies. -find_package(PkgConfig REQUIRED) -pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) -pkg_check_modules(GLIB REQUIRED IMPORTED_TARGET glib-2.0) -pkg_check_modules(GIO REQUIRED IMPORTED_TARGET gio-2.0) - -set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/libflutter_linux_gtk.so") - -# Published to parent scope for install step. -set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) -set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) -set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) -set(AOT_LIBRARY "${PROJECT_DIR}/build/lib/libapp.so" PARENT_SCOPE) - -list(APPEND FLUTTER_LIBRARY_HEADERS - "fl_basic_message_channel.h" - "fl_binary_codec.h" - "fl_binary_messenger.h" - "fl_dart_project.h" - "fl_engine.h" - "fl_json_message_codec.h" - "fl_json_method_codec.h" - "fl_message_codec.h" - "fl_method_call.h" - "fl_method_channel.h" - "fl_method_codec.h" - "fl_method_response.h" - "fl_plugin_registrar.h" - "fl_plugin_registry.h" - "fl_standard_message_codec.h" - "fl_standard_method_codec.h" - "fl_string_codec.h" - "fl_value.h" - "fl_view.h" - "flutter_linux.h" -) -list_prepend(FLUTTER_LIBRARY_HEADERS "${EPHEMERAL_DIR}/flutter_linux/") -add_library(flutter INTERFACE) -target_include_directories(flutter INTERFACE - "${EPHEMERAL_DIR}" -) -target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}") -target_link_libraries(flutter INTERFACE - PkgConfig::GTK - PkgConfig::GLIB - PkgConfig::GIO -) -add_dependencies(flutter flutter_assemble) - -# === Flutter tool backend === -# _phony_ is a non-existent file to force this command to run every time, -# since currently there's no way to get a full input/output list from the -# flutter tool. -add_custom_command( - OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} - ${CMAKE_CURRENT_BINARY_DIR}/_phony_ - COMMAND ${CMAKE_COMMAND} -E env - ${FLUTTER_TOOL_ENVIRONMENT} - "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.sh" - ${FLUTTER_TARGET_PLATFORM} ${CMAKE_BUILD_TYPE} - VERBATIM -) -add_custom_target(flutter_assemble DEPENDS - "${FLUTTER_LIBRARY}" - ${FLUTTER_LIBRARY_HEADERS} -) diff --git a/packages/firebase_core/firebase_core/firebase_core/example/linux/flutter/generated_plugin_registrant.cc b/packages/firebase_core/firebase_core/firebase_core/example/linux/flutter/generated_plugin_registrant.cc deleted file mode 100644 index 15034725064f..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/example/linux/flutter/generated_plugin_registrant.cc +++ /dev/null @@ -1,15 +0,0 @@ -// -// Generated file. Do not edit. -// - -// clang-format off - -#include "generated_plugin_registrant.h" - -#include - -void fl_register_plugins(FlPluginRegistry* registry) { - g_autoptr(FlPluginRegistrar) firebase_core_registrar = - fl_plugin_registry_get_registrar_for_plugin(registry, "FirebaseCorePlugin"); - firebase_core_plugin_register_with_registrar(firebase_core_registrar); -} diff --git a/packages/firebase_core/firebase_core/firebase_core/example/linux/flutter/generated_plugin_registrant.h b/packages/firebase_core/firebase_core/firebase_core/example/linux/flutter/generated_plugin_registrant.h deleted file mode 100644 index e0f0a47bc08f..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/example/linux/flutter/generated_plugin_registrant.h +++ /dev/null @@ -1,15 +0,0 @@ -// -// Generated file. Do not edit. -// - -// clang-format off - -#ifndef GENERATED_PLUGIN_REGISTRANT_ -#define GENERATED_PLUGIN_REGISTRANT_ - -#include - -// Registers Flutter plugins. -void fl_register_plugins(FlPluginRegistry* registry); - -#endif // GENERATED_PLUGIN_REGISTRANT_ diff --git a/packages/firebase_core/firebase_core/firebase_core/example/linux/flutter/generated_plugins.cmake b/packages/firebase_core/firebase_core/firebase_core/example/linux/flutter/generated_plugins.cmake deleted file mode 100644 index 1d55b5b0bf79..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/example/linux/flutter/generated_plugins.cmake +++ /dev/null @@ -1,24 +0,0 @@ -# -# Generated file, do not edit. -# - -list(APPEND FLUTTER_PLUGIN_LIST - firebase_core -) - -list(APPEND FLUTTER_FFI_PLUGIN_LIST -) - -set(PLUGIN_BUNDLED_LIBRARIES) - -foreach(plugin ${FLUTTER_PLUGIN_LIST}) - add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/linux plugins/${plugin}) - target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) - list(APPEND PLUGIN_BUNDLED_LIBRARIES $) - list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) -endforeach(plugin) - -foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST}) - add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/linux plugins/${ffi_plugin}) - list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries}) -endforeach(ffi_plugin) diff --git a/packages/firebase_core/firebase_core/firebase_core/example/linux/main.cc b/packages/firebase_core/firebase_core/firebase_core/example/linux/main.cc deleted file mode 100644 index e7c5c5437037..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/example/linux/main.cc +++ /dev/null @@ -1,6 +0,0 @@ -#include "my_application.h" - -int main(int argc, char** argv) { - g_autoptr(MyApplication) app = my_application_new(); - return g_application_run(G_APPLICATION(app), argc, argv); -} diff --git a/packages/firebase_core/firebase_core/firebase_core/example/linux/my_application.cc b/packages/firebase_core/firebase_core/firebase_core/example/linux/my_application.cc deleted file mode 100644 index b699538ff8ee..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/example/linux/my_application.cc +++ /dev/null @@ -1,104 +0,0 @@ -#include "my_application.h" - -#include -#ifdef GDK_WINDOWING_X11 -#include -#endif - -#include "flutter/generated_plugin_registrant.h" - -struct _MyApplication { - GtkApplication parent_instance; - char** dart_entrypoint_arguments; -}; - -G_DEFINE_TYPE(MyApplication, my_application, GTK_TYPE_APPLICATION) - -// Implements GApplication::activate. -static void my_application_activate(GApplication* application) { - MyApplication* self = MY_APPLICATION(application); - GtkWindow* window = - GTK_WINDOW(gtk_application_window_new(GTK_APPLICATION(application))); - - // Use a header bar when running in GNOME as this is the common style used - // by applications and is the setup most users will be using (e.g. Ubuntu - // desktop). - // If running on X and not using GNOME then just use a traditional title bar - // in case the window manager does more exotic layout, e.g. tiling. - // If running on Wayland assume the header bar will work (may need changing - // if future cases occur). - gboolean use_header_bar = TRUE; -#ifdef GDK_WINDOWING_X11 - GdkScreen* screen = gtk_window_get_screen(window); - if (GDK_IS_X11_SCREEN(screen)) { - const gchar* wm_name = gdk_x11_screen_get_window_manager_name(screen); - if (g_strcmp0(wm_name, "GNOME Shell") != 0) { - use_header_bar = FALSE; - } - } -#endif - if (use_header_bar) { - GtkHeaderBar* header_bar = GTK_HEADER_BAR(gtk_header_bar_new()); - gtk_widget_show(GTK_WIDGET(header_bar)); - gtk_header_bar_set_title(header_bar, "firebase_core_example"); - gtk_header_bar_set_show_close_button(header_bar, TRUE); - gtk_window_set_titlebar(window, GTK_WIDGET(header_bar)); - } else { - gtk_window_set_title(window, "firebase_core_example"); - } - - gtk_window_set_default_size(window, 1280, 720); - gtk_widget_show(GTK_WIDGET(window)); - - g_autoptr(FlDartProject) project = fl_dart_project_new(); - fl_dart_project_set_dart_entrypoint_arguments(project, self->dart_entrypoint_arguments); - - FlView* view = fl_view_new(project); - gtk_widget_show(GTK_WIDGET(view)); - gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(view)); - - fl_register_plugins(FL_PLUGIN_REGISTRY(view)); - - gtk_widget_grab_focus(GTK_WIDGET(view)); -} - -// Implements GApplication::local_command_line. -static gboolean my_application_local_command_line(GApplication* application, gchar*** arguments, int* exit_status) { - MyApplication* self = MY_APPLICATION(application); - // Strip out the first argument as it is the binary name. - self->dart_entrypoint_arguments = g_strdupv(*arguments + 1); - - g_autoptr(GError) error = nullptr; - if (!g_application_register(application, nullptr, &error)) { - g_warning("Failed to register: %s", error->message); - *exit_status = 1; - return TRUE; - } - - g_application_activate(application); - *exit_status = 0; - - return TRUE; -} - -// Implements GObject::dispose. -static void my_application_dispose(GObject* object) { - MyApplication* self = MY_APPLICATION(object); - g_clear_pointer(&self->dart_entrypoint_arguments, g_strfreev); - G_OBJECT_CLASS(my_application_parent_class)->dispose(object); -} - -static void my_application_class_init(MyApplicationClass* klass) { - G_APPLICATION_CLASS(klass)->activate = my_application_activate; - G_APPLICATION_CLASS(klass)->local_command_line = my_application_local_command_line; - G_OBJECT_CLASS(klass)->dispose = my_application_dispose; -} - -static void my_application_init(MyApplication* self) {} - -MyApplication* my_application_new() { - return MY_APPLICATION(g_object_new(my_application_get_type(), - "application-id", APPLICATION_ID, - "flags", G_APPLICATION_NON_UNIQUE, - nullptr)); -} diff --git a/packages/firebase_core/firebase_core/firebase_core/example/linux/my_application.h b/packages/firebase_core/firebase_core/firebase_core/example/linux/my_application.h deleted file mode 100644 index 72271d5e4170..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/example/linux/my_application.h +++ /dev/null @@ -1,18 +0,0 @@ -#ifndef FLUTTER_MY_APPLICATION_H_ -#define FLUTTER_MY_APPLICATION_H_ - -#include - -G_DECLARE_FINAL_TYPE(MyApplication, my_application, MY, APPLICATION, - GtkApplication) - -/** - * my_application_new: - * - * Creates a new Flutter-based application. - * - * Returns: a new #MyApplication. - */ -MyApplication* my_application_new(); - -#endif // FLUTTER_MY_APPLICATION_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/example/pubspec.yaml b/packages/firebase_core/firebase_core/firebase_core/example/pubspec.yaml deleted file mode 100644 index dd3d2b2c7b7e..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/example/pubspec.yaml +++ /dev/null @@ -1,83 +0,0 @@ -name: firebase_core_example -description: Demonstrates how to use the firebase_core plugin. -# The following line prevents the package from being accidentally published to -# pub.dev using `flutter pub publish`. This is preferred for private packages. -publish_to: 'none' # Remove this line if you wish to publish to pub.dev - -environment: - sdk: '>=2.19.2 <3.0.0' - -# Dependencies specify other packages that your package needs in order to work. -# To automatically upgrade your package dependencies to the latest versions -# consider running `flutter pub upgrade --major-versions`. Alternatively, -# dependencies can be manually updated by changing the version numbers below to -# the latest version available on pub.dev. To see which dependencies have newer -# versions available, run `flutter pub outdated`. -dependencies: - flutter: - sdk: flutter - - firebase_core: - # When depending on this package from a real application you should use: - # firebase_core: ^x.y.z - # See https://dart.dev/tools/pub/dependencies#version-constraints - # The example app is bundled with the plugin so we use a path dependency on - # the parent directory to use the current plugin's version. - path: ../ - - # The following adds the Cupertino Icons font to your application. - # Use with the CupertinoIcons class for iOS style icons. - cupertino_icons: ^1.0.2 - -dev_dependencies: - flutter_test: - sdk: flutter - - # The "flutter_lints" package below contains a set of recommended lints to - # encourage good coding practices. The lint set provided by the package is - # activated in the `analysis_options.yaml` file located at the root of your - # package. See that file for information about deactivating specific lint - # rules and activating additional ones. - flutter_lints: ^2.0.0 - -# For information on the generic Dart part of this file, see the -# following page: https://dart.dev/tools/pub/pubspec - -# The following section is specific to Flutter packages. -flutter: - - # The following line ensures that the Material Icons font is - # included with your application, so that you can use the icons in - # the material Icons class. - uses-material-design: true - - # To add assets to your application, add an assets section, like this: - # assets: - # - images/a_dot_burr.jpeg - # - images/a_dot_ham.jpeg - - # An image asset can refer to one or more resolution-specific "variants", see - # https://flutter.dev/assets-and-images/#resolution-aware - - # For details regarding adding assets from package dependencies, see - # https://flutter.dev/assets-and-images/#from-packages - - # To add custom fonts to your application, add a fonts section here, - # in this "flutter" section. Each entry in this list should have a - # "family" key with the font family name, and a "fonts" key with a - # list giving the asset and other descriptors for the font. For - # example: - # fonts: - # - family: Schyler - # fonts: - # - asset: fonts/Schyler-Regular.ttf - # - asset: fonts/Schyler-Italic.ttf - # style: italic - # - family: Trajan Pro - # fonts: - # - asset: fonts/TrajanPro.ttf - # - asset: fonts/TrajanPro_Bold.ttf - # weight: 700 - # - # For details regarding fonts from package dependencies, - # see https://flutter.dev/custom-fonts/#from-packages diff --git a/packages/firebase_core/firebase_core/firebase_core/example/test/widget_test.dart b/packages/firebase_core/firebase_core/firebase_core/example/test/widget_test.dart deleted file mode 100644 index d343f68407e8..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/example/test/widget_test.dart +++ /dev/null @@ -1,27 +0,0 @@ -// This is a basic Flutter widget test. -// -// To perform an interaction with a widget in your test, use the WidgetTester -// utility in the flutter_test package. For example, you can send tap and scroll -// gestures. You can also use WidgetTester to find child widgets in the widget -// tree, read text, and verify that the values of widget properties are correct. - -import 'package:flutter/material.dart'; -import 'package:flutter_test/flutter_test.dart'; - -import 'package:firebase_core_example/main.dart'; - -void main() { - testWidgets('Verify Platform version', (WidgetTester tester) async { - // Build our app and trigger a frame. - await tester.pumpWidget(const MyApp()); - - // Verify that platform version is retrieved. - expect( - find.byWidgetPredicate( - (Widget widget) => widget is Text && - widget.data!.startsWith('Running on:'), - ), - findsOneWidget, - ); - }); -} diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/.gitignore b/packages/firebase_core/firebase_core/firebase_core/example/windows/.gitignore deleted file mode 100644 index d492d0d98c8f..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/example/windows/.gitignore +++ /dev/null @@ -1,17 +0,0 @@ -flutter/ephemeral/ - -# Visual Studio user-specific files. -*.suo -*.user -*.userosscache -*.sln.docstates - -# Visual Studio build-related files. -x64/ -x86/ - -# Visual Studio cache files -# files ending in .cache can be ignored -*.[Cc]ache -# but keep track of directories ending in .cache -!*.[Cc]ache/ diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/CMakeLists.txt b/packages/firebase_core/firebase_core/firebase_core/example/windows/CMakeLists.txt deleted file mode 100644 index ddf92aa378e1..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/example/windows/CMakeLists.txt +++ /dev/null @@ -1,101 +0,0 @@ -# Project-level configuration. -cmake_minimum_required(VERSION 3.14) -project(firebase_core_example LANGUAGES CXX) - -# The name of the executable created for the application. Change this to change -# the on-disk name of your application. -set(BINARY_NAME "firebase_core_example") - -# Explicitly opt in to modern CMake behaviors to avoid warnings with recent -# versions of CMake. -cmake_policy(SET CMP0063 NEW) - -# Define build configuration option. -get_property(IS_MULTICONFIG GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG) -if(IS_MULTICONFIG) - set(CMAKE_CONFIGURATION_TYPES "Debug;Profile;Release" - CACHE STRING "" FORCE) -else() - if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) - set(CMAKE_BUILD_TYPE "Debug" CACHE - STRING "Flutter build mode" FORCE) - set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS - "Debug" "Profile" "Release") - endif() -endif() -# Define settings for the Profile build mode. -set(CMAKE_EXE_LINKER_FLAGS_PROFILE "${CMAKE_EXE_LINKER_FLAGS_RELEASE}") -set(CMAKE_SHARED_LINKER_FLAGS_PROFILE "${CMAKE_SHARED_LINKER_FLAGS_RELEASE}") -set(CMAKE_C_FLAGS_PROFILE "${CMAKE_C_FLAGS_RELEASE}") -set(CMAKE_CXX_FLAGS_PROFILE "${CMAKE_CXX_FLAGS_RELEASE}") - -# Use Unicode for all projects. -add_definitions(-DUNICODE -D_UNICODE) - -# Compilation settings that should be applied to most targets. -# -# Be cautious about adding new options here, as plugins use this function by -# default. In most cases, you should add new options to specific targets instead -# of modifying this function. -function(APPLY_STANDARD_SETTINGS TARGET) - target_compile_features(${TARGET} PUBLIC cxx_std_17) - target_compile_options(${TARGET} PRIVATE /W4 /WX /wd"4100") - target_compile_options(${TARGET} PRIVATE /EHsc) - target_compile_definitions(${TARGET} PRIVATE "_HAS_EXCEPTIONS=0") - target_compile_definitions(${TARGET} PRIVATE "$<$:_DEBUG>") -endfunction() - -# Flutter library and tool build rules. -set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") -add_subdirectory(${FLUTTER_MANAGED_DIR}) - -# Application build; see runner/CMakeLists.txt. -add_subdirectory("runner") - -# Generated plugin build rules, which manage building the plugins and adding -# them to the application. -include(flutter/generated_plugins.cmake) - - -# === Installation === -# Support files are copied into place next to the executable, so that it can -# run in place. This is done instead of making a separate bundle (as on Linux) -# so that building and running from within Visual Studio will work. -set(BUILD_BUNDLE_DIR "$") -# Make the "install" step default, as it's required to run. -set(CMAKE_VS_INCLUDE_INSTALL_TO_DEFAULT_BUILD 1) -if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) - set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) -endif() - -set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") -set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}") - -install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" - COMPONENT Runtime) - -install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" - COMPONENT Runtime) - -install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" - COMPONENT Runtime) - -if(PLUGIN_BUNDLED_LIBRARIES) - install(FILES "${PLUGIN_BUNDLED_LIBRARIES}" - DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" - COMPONENT Runtime) -endif() - -# Fully re-copy the assets directory on each build to avoid having stale files -# from a previous install. -set(FLUTTER_ASSET_DIR_NAME "flutter_assets") -install(CODE " - file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") - " COMPONENT Runtime) -install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" - DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) - -# Install the AOT library on non-Debug builds only. -install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" - CONFIGURATIONS Profile;Release - COMPONENT Runtime) diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/flutter/CMakeLists.txt b/packages/firebase_core/firebase_core/firebase_core/example/windows/flutter/CMakeLists.txt deleted file mode 100644 index 930d2071a324..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/example/windows/flutter/CMakeLists.txt +++ /dev/null @@ -1,104 +0,0 @@ -# This file controls Flutter-level build steps. It should not be edited. -cmake_minimum_required(VERSION 3.14) - -set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") - -# Configuration provided via flutter tool. -include(${EPHEMERAL_DIR}/generated_config.cmake) - -# TODO: Move the rest of this into files in ephemeral. See -# https://github.com/flutter/flutter/issues/57146. -set(WRAPPER_ROOT "${EPHEMERAL_DIR}/cpp_client_wrapper") - -# === Flutter Library === -set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/flutter_windows.dll") - -# Published to parent scope for install step. -set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) -set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) -set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) -set(AOT_LIBRARY "${PROJECT_DIR}/build/windows/app.so" PARENT_SCOPE) - -list(APPEND FLUTTER_LIBRARY_HEADERS - "flutter_export.h" - "flutter_windows.h" - "flutter_messenger.h" - "flutter_plugin_registrar.h" - "flutter_texture_registrar.h" -) -list(TRANSFORM FLUTTER_LIBRARY_HEADERS PREPEND "${EPHEMERAL_DIR}/") -add_library(flutter INTERFACE) -target_include_directories(flutter INTERFACE - "${EPHEMERAL_DIR}" -) -target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}.lib") -add_dependencies(flutter flutter_assemble) - -# === Wrapper === -list(APPEND CPP_WRAPPER_SOURCES_CORE - "core_implementations.cc" - "standard_codec.cc" -) -list(TRANSFORM CPP_WRAPPER_SOURCES_CORE PREPEND "${WRAPPER_ROOT}/") -list(APPEND CPP_WRAPPER_SOURCES_PLUGIN - "plugin_registrar.cc" -) -list(TRANSFORM CPP_WRAPPER_SOURCES_PLUGIN PREPEND "${WRAPPER_ROOT}/") -list(APPEND CPP_WRAPPER_SOURCES_APP - "flutter_engine.cc" - "flutter_view_controller.cc" -) -list(TRANSFORM CPP_WRAPPER_SOURCES_APP PREPEND "${WRAPPER_ROOT}/") - -# Wrapper sources needed for a plugin. -add_library(flutter_wrapper_plugin STATIC - ${CPP_WRAPPER_SOURCES_CORE} - ${CPP_WRAPPER_SOURCES_PLUGIN} -) -apply_standard_settings(flutter_wrapper_plugin) -set_target_properties(flutter_wrapper_plugin PROPERTIES - POSITION_INDEPENDENT_CODE ON) -set_target_properties(flutter_wrapper_plugin PROPERTIES - CXX_VISIBILITY_PRESET hidden) -target_link_libraries(flutter_wrapper_plugin PUBLIC flutter) -target_include_directories(flutter_wrapper_plugin PUBLIC - "${WRAPPER_ROOT}/include" -) -add_dependencies(flutter_wrapper_plugin flutter_assemble) - -# Wrapper sources needed for the runner. -add_library(flutter_wrapper_app STATIC - ${CPP_WRAPPER_SOURCES_CORE} - ${CPP_WRAPPER_SOURCES_APP} -) -apply_standard_settings(flutter_wrapper_app) -target_link_libraries(flutter_wrapper_app PUBLIC flutter) -target_include_directories(flutter_wrapper_app PUBLIC - "${WRAPPER_ROOT}/include" -) -add_dependencies(flutter_wrapper_app flutter_assemble) - -# === Flutter tool backend === -# _phony_ is a non-existent file to force this command to run every time, -# since currently there's no way to get a full input/output list from the -# flutter tool. -set(PHONY_OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/_phony_") -set_source_files_properties("${PHONY_OUTPUT}" PROPERTIES SYMBOLIC TRUE) -add_custom_command( - OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} - ${CPP_WRAPPER_SOURCES_CORE} ${CPP_WRAPPER_SOURCES_PLUGIN} - ${CPP_WRAPPER_SOURCES_APP} - ${PHONY_OUTPUT} - COMMAND ${CMAKE_COMMAND} -E env - ${FLUTTER_TOOL_ENVIRONMENT} - "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.bat" - windows-x64 $ - VERBATIM -) -add_custom_target(flutter_assemble DEPENDS - "${FLUTTER_LIBRARY}" - ${FLUTTER_LIBRARY_HEADERS} - ${CPP_WRAPPER_SOURCES_CORE} - ${CPP_WRAPPER_SOURCES_PLUGIN} - ${CPP_WRAPPER_SOURCES_APP} -) diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/flutter/generated_plugin_registrant.cc b/packages/firebase_core/firebase_core/firebase_core/example/windows/flutter/generated_plugin_registrant.cc deleted file mode 100644 index 1a82e7d01dce..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/example/windows/flutter/generated_plugin_registrant.cc +++ /dev/null @@ -1,14 +0,0 @@ -// -// Generated file. Do not edit. -// - -// clang-format off - -#include "generated_plugin_registrant.h" - -#include - -void RegisterPlugins(flutter::PluginRegistry* registry) { - FirebaseCorePluginCApiRegisterWithRegistrar( - registry->GetRegistrarForPlugin("FirebaseCorePluginCApi")); -} diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/flutter/generated_plugin_registrant.h b/packages/firebase_core/firebase_core/firebase_core/example/windows/flutter/generated_plugin_registrant.h deleted file mode 100644 index dc139d85a931..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/example/windows/flutter/generated_plugin_registrant.h +++ /dev/null @@ -1,15 +0,0 @@ -// -// Generated file. Do not edit. -// - -// clang-format off - -#ifndef GENERATED_PLUGIN_REGISTRANT_ -#define GENERATED_PLUGIN_REGISTRANT_ - -#include - -// Registers Flutter plugins. -void RegisterPlugins(flutter::PluginRegistry* registry); - -#endif // GENERATED_PLUGIN_REGISTRANT_ diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/flutter/generated_plugins.cmake b/packages/firebase_core/firebase_core/firebase_core/example/windows/flutter/generated_plugins.cmake deleted file mode 100644 index fa8a39bab15e..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/example/windows/flutter/generated_plugins.cmake +++ /dev/null @@ -1,24 +0,0 @@ -# -# Generated file, do not edit. -# - -list(APPEND FLUTTER_PLUGIN_LIST - firebase_core -) - -list(APPEND FLUTTER_FFI_PLUGIN_LIST -) - -set(PLUGIN_BUNDLED_LIBRARIES) - -foreach(plugin ${FLUTTER_PLUGIN_LIST}) - add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/windows plugins/${plugin}) - target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) - list(APPEND PLUGIN_BUNDLED_LIBRARIES $) - list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) -endforeach(plugin) - -foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST}) - add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/windows plugins/${ffi_plugin}) - list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries}) -endforeach(ffi_plugin) diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/CMakeLists.txt b/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/CMakeLists.txt deleted file mode 100644 index 394917c053a0..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/CMakeLists.txt +++ /dev/null @@ -1,40 +0,0 @@ -cmake_minimum_required(VERSION 3.14) -project(runner LANGUAGES CXX) - -# Define the application target. To change its name, change BINARY_NAME in the -# top-level CMakeLists.txt, not the value here, or `flutter run` will no longer -# work. -# -# Any new source files that you add to the application should be added here. -add_executable(${BINARY_NAME} WIN32 - "flutter_window.cpp" - "main.cpp" - "utils.cpp" - "win32_window.cpp" - "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" - "Runner.rc" - "runner.exe.manifest" -) - -# Apply the standard set of build settings. This can be removed for applications -# that need different build settings. -apply_standard_settings(${BINARY_NAME}) - -# Add preprocessor definitions for the build version. -target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION=\"${FLUTTER_VERSION}\"") -target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MAJOR=${FLUTTER_VERSION_MAJOR}") -target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MINOR=${FLUTTER_VERSION_MINOR}") -target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_PATCH=${FLUTTER_VERSION_PATCH}") -target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_BUILD=${FLUTTER_VERSION_BUILD}") - -# Disable Windows macros that collide with C++ standard library functions. -target_compile_definitions(${BINARY_NAME} PRIVATE "NOMINMAX") - -# Add dependency libraries and include directories. Add any application-specific -# dependencies here. -target_link_libraries(${BINARY_NAME} PRIVATE flutter flutter_wrapper_app) -target_link_libraries(${BINARY_NAME} PRIVATE "dwmapi.lib") -target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") - -# Run the Flutter tool portions of the build. This must not be removed. -add_dependencies(${BINARY_NAME} flutter_assemble) diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/Runner.rc b/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/Runner.rc deleted file mode 100644 index c0d7fe21c712..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/Runner.rc +++ /dev/null @@ -1,121 +0,0 @@ -// Microsoft Visual C++ generated resource script. -// -#pragma code_page(65001) -#include "resource.h" - -#define APSTUDIO_READONLY_SYMBOLS -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 2 resource. -// -#include "winres.h" - -///////////////////////////////////////////////////////////////////////////// -#undef APSTUDIO_READONLY_SYMBOLS - -///////////////////////////////////////////////////////////////////////////// -// English (United States) resources - -#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) -LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US - -#ifdef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// TEXTINCLUDE -// - -1 TEXTINCLUDE -BEGIN - "resource.h\0" -END - -2 TEXTINCLUDE -BEGIN - "#include ""winres.h""\r\n" - "\0" -END - -3 TEXTINCLUDE -BEGIN - "\r\n" - "\0" -END - -#endif // APSTUDIO_INVOKED - - -///////////////////////////////////////////////////////////////////////////// -// -// Icon -// - -// Icon with lowest ID value placed first to ensure application icon -// remains consistent on all systems. -IDI_APP_ICON ICON "resources\\app_icon.ico" - - -///////////////////////////////////////////////////////////////////////////// -// -// Version -// - -#if defined(FLUTTER_VERSION_MAJOR) && defined(FLUTTER_VERSION_MINOR) && defined(FLUTTER_VERSION_PATCH) && defined(FLUTTER_VERSION_BUILD) -#define VERSION_AS_NUMBER FLUTTER_VERSION_MAJOR,FLUTTER_VERSION_MINOR,FLUTTER_VERSION_PATCH,FLUTTER_VERSION_BUILD -#else -#define VERSION_AS_NUMBER 1,0,0,0 -#endif - -#if defined(FLUTTER_VERSION) -#define VERSION_AS_STRING FLUTTER_VERSION -#else -#define VERSION_AS_STRING "1.0.0" -#endif - -VS_VERSION_INFO VERSIONINFO - FILEVERSION VERSION_AS_NUMBER - PRODUCTVERSION VERSION_AS_NUMBER - FILEFLAGSMASK VS_FFI_FILEFLAGSMASK -#ifdef _DEBUG - FILEFLAGS VS_FF_DEBUG -#else - FILEFLAGS 0x0L -#endif - FILEOS VOS__WINDOWS32 - FILETYPE VFT_APP - FILESUBTYPE 0x0L -BEGIN - BLOCK "StringFileInfo" - BEGIN - BLOCK "040904e4" - BEGIN - VALUE "CompanyName", "com.example" "\0" - VALUE "FileDescription", "firebase_core_example" "\0" - VALUE "FileVersion", VERSION_AS_STRING "\0" - VALUE "InternalName", "firebase_core_example" "\0" - VALUE "LegalCopyright", "Copyright (C) 2023 com.example. All rights reserved." "\0" - VALUE "OriginalFilename", "firebase_core_example.exe" "\0" - VALUE "ProductName", "firebase_core_example" "\0" - VALUE "ProductVersion", VERSION_AS_STRING "\0" - END - END - BLOCK "VarFileInfo" - BEGIN - VALUE "Translation", 0x409, 1252 - END -END - -#endif // English (United States) resources -///////////////////////////////////////////////////////////////////////////// - - - -#ifndef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 3 resource. -// - - -///////////////////////////////////////////////////////////////////////////// -#endif // not APSTUDIO_INVOKED diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/flutter_window.cpp b/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/flutter_window.cpp deleted file mode 100644 index b25e363efa42..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/flutter_window.cpp +++ /dev/null @@ -1,66 +0,0 @@ -#include "flutter_window.h" - -#include - -#include "flutter/generated_plugin_registrant.h" - -FlutterWindow::FlutterWindow(const flutter::DartProject& project) - : project_(project) {} - -FlutterWindow::~FlutterWindow() {} - -bool FlutterWindow::OnCreate() { - if (!Win32Window::OnCreate()) { - return false; - } - - RECT frame = GetClientArea(); - - // The size here must match the window dimensions to avoid unnecessary surface - // creation / destruction in the startup path. - flutter_controller_ = std::make_unique( - frame.right - frame.left, frame.bottom - frame.top, project_); - // Ensure that basic setup of the controller was successful. - if (!flutter_controller_->engine() || !flutter_controller_->view()) { - return false; - } - RegisterPlugins(flutter_controller_->engine()); - SetChildContent(flutter_controller_->view()->GetNativeWindow()); - - flutter_controller_->engine()->SetNextFrameCallback([&]() { - this->Show(); - }); - - return true; -} - -void FlutterWindow::OnDestroy() { - if (flutter_controller_) { - flutter_controller_ = nullptr; - } - - Win32Window::OnDestroy(); -} - -LRESULT -FlutterWindow::MessageHandler(HWND hwnd, UINT const message, - WPARAM const wparam, - LPARAM const lparam) noexcept { - // Give Flutter, including plugins, an opportunity to handle window messages. - if (flutter_controller_) { - std::optional result = - flutter_controller_->HandleTopLevelWindowProc(hwnd, message, wparam, - lparam); - if (result) { - return *result; - } - } - - switch (message) { - case WM_FONTCHANGE: - flutter_controller_->engine()->ReloadSystemFonts(); - break; - } - - return Win32Window::MessageHandler(hwnd, message, wparam, lparam); -} diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/flutter_window.h b/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/flutter_window.h deleted file mode 100644 index 6da0652f05f2..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/flutter_window.h +++ /dev/null @@ -1,33 +0,0 @@ -#ifndef RUNNER_FLUTTER_WINDOW_H_ -#define RUNNER_FLUTTER_WINDOW_H_ - -#include -#include - -#include - -#include "win32_window.h" - -// A window that does nothing but host a Flutter view. -class FlutterWindow : public Win32Window { - public: - // Creates a new FlutterWindow hosting a Flutter view running |project|. - explicit FlutterWindow(const flutter::DartProject& project); - virtual ~FlutterWindow(); - - protected: - // Win32Window: - bool OnCreate() override; - void OnDestroy() override; - LRESULT MessageHandler(HWND window, UINT const message, WPARAM const wparam, - LPARAM const lparam) noexcept override; - - private: - // The project to run. - flutter::DartProject project_; - - // The Flutter instance hosted by this window. - std::unique_ptr flutter_controller_; -}; - -#endif // RUNNER_FLUTTER_WINDOW_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/google-services-desktop.json b/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/google-services-desktop.json deleted file mode 100644 index a3bf216f4de0..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/google-services-desktop.json +++ /dev/null @@ -1,37 +0,0 @@ -{ - "project_info": { - "project_number": "406099696497", - "firebase_url": "https://flutterfire-e2e-tests-default-rtdb.europe-west1.firebasedatabase.app", - "project_id": "flutterfire-e2e-tests", - "storage_bucket": "flutterfire-e2e-tests.appspot.com" - }, - "client": [ - { - "client_info": { - "mobilesdk_app_id": "1:406099696497:ios:58cbc26aca8e5cf83574d0", - "android_client_info": { - "package_name": "io.flutter.plugins.firebase.auth.example" - } - }, - "oauth_client": [ - { - "client_id": "406099696497-134k3722m01rtrsklhf3b7k8sqa5r7in.apps.googleusercontent.com" - } - ], - "api_key": [ - { - "current_key": "AIzaSyDooSUGSf63Ghq02_iIhtnmwMDs4HlWS6c" - } - ], - "services": { - "analytics_service": { - "status": 0 - }, - "appinvite_service": { - "status": 1 - } - } - } - ], - "configuration_version": "1" -} \ No newline at end of file diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/main.cpp b/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/main.cpp deleted file mode 100644 index 2b640e48b2b0..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/main.cpp +++ /dev/null @@ -1,43 +0,0 @@ -#include -#include -#include - -#include "flutter_window.h" -#include "utils.h" - -int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev, - _In_ wchar_t *command_line, _In_ int show_command) { - // Attach to console when present (e.g., 'flutter run') or create a - // new console when running with a debugger. - if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent()) { - CreateAndAttachConsole(); - } - - // Initialize COM, so that it is available for use in the library and/or - // plugins. - ::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED); - - flutter::DartProject project(L"data"); - - std::vector command_line_arguments = - GetCommandLineArguments(); - - project.set_dart_entrypoint_arguments(std::move(command_line_arguments)); - - FlutterWindow window(project); - Win32Window::Point origin(10, 10); - Win32Window::Size size(1280, 720); - if (!window.Create(L"firebase_core_example", origin, size)) { - return EXIT_FAILURE; - } - window.SetQuitOnClose(true); - - ::MSG msg; - while (::GetMessage(&msg, nullptr, 0, 0)) { - ::TranslateMessage(&msg); - ::DispatchMessage(&msg); - } - - ::CoUninitialize(); - return EXIT_SUCCESS; -} diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/resource.h b/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/resource.h deleted file mode 100644 index 66a65d1e4a79..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/resource.h +++ /dev/null @@ -1,16 +0,0 @@ -//{{NO_DEPENDENCIES}} -// Microsoft Visual C++ generated include file. -// Used by Runner.rc -// -#define IDI_APP_ICON 101 - -// Next default values for new objects -// -#ifdef APSTUDIO_INVOKED -#ifndef APSTUDIO_READONLY_SYMBOLS -#define _APS_NEXT_RESOURCE_VALUE 102 -#define _APS_NEXT_COMMAND_VALUE 40001 -#define _APS_NEXT_CONTROL_VALUE 1001 -#define _APS_NEXT_SYMED_VALUE 101 -#endif -#endif diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/resources/app_icon.ico b/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/resources/app_icon.ico deleted file mode 100644 index c04e20caf6370ebb9253ad831cc31de4a9c965f6..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 33772 zcmeHQc|26z|35SKE&G-*mXah&B~fFkXr)DEO&hIfqby^T&>|8^_Ub8Vp#`BLl3lbZ zvPO!8k!2X>cg~Elr=IVxo~J*a`+9wR=A83c-k-DFd(XM&UI1VKCqM@V;DDtJ09WB} zRaHKiW(GT00brH|0EeTeKVbpbGZg?nK6-j827q-+NFM34gXjqWxJ*a#{b_apGN<-L_m3#8Z26atkEn& ze87Bvv^6vVmM+p+cQ~{u%=NJF>#(d;8{7Q{^rWKWNtf14H}>#&y7$lqmY6xmZryI& z($uy?c5-+cPnt2%)R&(KIWEXww>Cnz{OUpT>W$CbO$h1= z#4BPMkFG1Y)x}Ui+WXr?Z!w!t_hjRq8qTaWpu}FH{MsHlU{>;08goVLm{V<&`itk~ zE_Ys=D(hjiy+5=?=$HGii=Y5)jMe9|wWoD_K07(}edAxh`~LBorOJ!Cf@f{_gNCC| z%{*04ViE!#>@hc1t5bb+NO>ncf@@Dv01K!NxH$3Eg1%)|wLyMDF8^d44lV!_Sr}iEWefOaL z8f?ud3Q%Sen39u|%00W<#!E=-RpGa+H8}{ulxVl4mwpjaU+%2pzmi{3HM)%8vb*~-M9rPUAfGCSos8GUXp02|o~0BTV2l#`>>aFV&_P$ejS;nGwSVP8 zMbOaG7<7eKD>c12VdGH;?2@q7535sa7MN*L@&!m?L`ASG%boY7(&L5imY#EQ$KrBB z4@_tfP5m50(T--qv1BJcD&aiH#b-QC>8#7Fx@3yXlonJI#aEIi=8&ChiVpc#N=5le zM*?rDIdcpawoc5kizv$GEjnveyrp3sY>+5_R5;>`>erS%JolimF=A^EIsAK zsPoVyyUHCgf0aYr&alx`<)eb6Be$m&`JYSuBu=p8j%QlNNp$-5C{b4#RubPb|CAIS zGE=9OFLP7?Hgc{?k45)84biT0k&-C6C%Q}aI~q<(7BL`C#<6HyxaR%!dFx7*o^laG z=!GBF^cwK$IA(sn9y6>60Rw{mYRYkp%$jH z*xQM~+bp)G$_RhtFPYx2HTsWk80+p(uqv9@I9)y{b$7NK53rYL$ezbmRjdXS?V}fj zWxX_feWoLFNm3MG7pMUuFPs$qrQWO9!l2B(SIuy2}S|lHNbHzoE+M2|Zxhjq9+Ws8c{*}x^VAib7SbxJ*Q3EnY5lgI9 z=U^f3IW6T=TWaVj+2N%K3<%Un;CF(wUp`TC&Y|ZjyFu6co^uqDDB#EP?DV5v_dw~E zIRK*BoY9y-G_ToU2V_XCX4nJ32~`czdjT!zwme zGgJ0nOk3U4@IE5JwtM}pwimLjk{ln^*4HMU%Fl4~n(cnsLB}Ja-jUM>xIB%aY;Nq8 z)Fp8dv1tkqKanv<68o@cN|%thj$+f;zGSO7H#b+eMAV8xH$hLggtt?O?;oYEgbq@= zV(u9bbd12^%;?nyk6&$GPI%|+<_mEpJGNfl*`!KV;VfmZWw{n{rnZ51?}FDh8we_L z8OI9nE31skDqJ5Oa_ybn7|5@ui>aC`s34p4ZEu6-s!%{uU45$Zd1=p$^^dZBh zu<*pDDPLW+c>iWO$&Z_*{VSQKg7=YEpS3PssPn1U!lSm6eZIho*{@&20e4Y_lRklKDTUCKI%o4Pc<|G^Xgu$J^Q|B87U;`c1zGwf^-zH*VQ^x+i^OUWE0yd z;{FJq)2w!%`x7yg@>uGFFf-XJl4H`YtUG%0slGKOlXV`q?RP>AEWg#x!b{0RicxGhS!3$p7 zij;{gm!_u@D4$Ox%>>bPtLJ> zwKtYz?T_DR1jN>DkkfGU^<#6sGz|~p*I{y`aZ>^Di#TC|Z!7j_O1=Wo8thuit?WxR zh9_S>kw^{V^|g}HRUF=dcq>?q(pHxw!8rx4dC6vbQVmIhmICF#zU!HkHpQ>9S%Uo( zMw{eC+`&pb=GZRou|3;Po1}m46H6NGd$t<2mQh}kaK-WFfmj_66_17BX0|j-E2fe3Jat}ijpc53 zJV$$;PC<5aW`{*^Z6e5##^`Ed#a0nwJDT#Qq~^e8^JTA=z^Kl>La|(UQ!bI@#ge{Dzz@61p-I)kc2?ZxFt^QQ}f%ldLjO*GPj(5)V9IyuUakJX=~GnTgZ4$5!3E=V#t`yOG4U z(gphZB6u2zsj=qNFLYShhg$}lNpO`P9xOSnO*$@@UdMYES*{jJVj|9z-}F^riksLK zbsU+4-{281P9e2UjY6tse^&a)WM1MFw;p#_dHhWI7p&U*9TR0zKdVuQed%6{otTsq z$f~S!;wg#Bd9kez=Br{m|66Wv z#g1xMup<0)H;c2ZO6su_ii&m8j&+jJz4iKnGZ&wxoQX|5a>v&_e#6WA!MB_4asTxLRGQCC5cI(em z%$ZfeqP>!*q5kU>a+BO&ln=4Jm>Ef(QE8o&RgLkk%2}4Tf}U%IFP&uS7}&|Q-)`5< z+e>;s#4cJ-z%&-^&!xsYx777Wt(wZY9(3(avmr|gRe4cD+a8&!LY`1^T?7x{E<=kdY9NYw>A;FtTvQ=Y&1M%lyZPl$ss1oY^Sl8we}n}Aob#6 zl4jERwnt9BlSoWb@3HxYgga(752Vu6Y)k4yk9u~Kw>cA5&LHcrvn1Y-HoIuFWg~}4 zEw4bR`mXZQIyOAzo)FYqg?$5W<;^+XX%Uz61{-L6@eP|lLH%|w?g=rFc;OvEW;^qh z&iYXGhVt(G-q<+_j}CTbPS_=K>RKN0&;dubh0NxJyDOHFF;<1k!{k#7b{|Qok9hac z;gHz}6>H6C6RnB`Tt#oaSrX0p-j-oRJ;_WvS-qS--P*8}V943RT6kou-G=A+7QPGQ z!ze^UGxtW3FC0$|(lY9^L!Lx^?Q8cny(rR`es5U;-xBhphF%_WNu|aO<+e9%6LuZq zt(0PoagJG<%hyuf;te}n+qIl_Ej;czWdc{LX^pS>77s9t*2b4s5dvP_!L^3cwlc)E!(!kGrg~FescVT zZCLeua3f4;d;Tk4iXzt}g}O@nlK3?_o91_~@UMIl?@77Qc$IAlLE95#Z=TES>2E%z zxUKpK{_HvGF;5%Q7n&vA?`{%8ohlYT_?(3A$cZSi)MvIJygXD}TS-3UwyUxGLGiJP znblO~G|*uA^|ac8E-w#}uBtg|s_~s&t>-g0X%zIZ@;o_wNMr_;{KDg^O=rg`fhDZu zFp(VKd1Edj%F zWHPl+)FGj%J1BO3bOHVfH^3d1F{)*PL&sRX`~(-Zy3&9UQX)Z;c51tvaI2E*E7!)q zcz|{vpK7bjxix(k&6=OEIBJC!9lTkUbgg?4-yE{9+pFS)$Ar@vrIf`D0Bnsed(Cf? zObt2CJ>BKOl>q8PyFO6w)+6Iz`LW%T5^R`U_NIW0r1dWv6OY=TVF?N=EfA(k(~7VBW(S;Tu5m4Lg8emDG-(mOSSs=M9Q&N8jc^Y4&9RqIsk(yO_P(mcCr}rCs%1MW1VBrn=0-oQN(Xj!k%iKV zb%ricBF3G4S1;+8lzg5PbZ|$Se$)I=PwiK=cDpHYdov2QO1_a-*dL4KUi|g&oh>(* zq$<`dQ^fat`+VW?m)?_KLn&mp^-@d=&7yGDt<=XwZZC=1scwxO2^RRI7n@g-1o8ps z)&+et_~)vr8aIF1VY1Qrq~Xe``KJrQSnAZ{CSq3yP;V*JC;mmCT6oRLSs7=GA?@6g zUooM}@tKtx(^|aKK8vbaHlUQqwE0}>j&~YlN3H#vKGm@u)xxS?n9XrOWUfCRa< z`20Fld2f&;gg7zpo{Adh+mqNntMc-D$N^yWZAZRI+u1T1zWHPxk{+?vcS1D>08>@6 zLhE@`gt1Y9mAK6Z4p|u(5I%EkfU7rKFSM=E4?VG9tI;a*@?6!ey{lzN5=Y-!$WFSe z&2dtO>^0@V4WRc#L&P%R(?@KfSblMS+N+?xUN$u3K4Ys%OmEh+tq}fnU}i>6YHM?< zlnL2gl~sF!j!Y4E;j3eIU-lfa`RsOL*Tt<%EFC0gPzoHfNWAfKFIKZN8}w~(Yi~=q z>=VNLO2|CjkxP}RkutxjV#4fWYR1KNrPYq5ha9Wl+u>ipsk*I(HS@iLnmGH9MFlTU zaFZ*KSR0px>o+pL7BbhB2EC1%PJ{67_ z#kY&#O4@P=OV#-79y_W>Gv2dxL*@G7%LksNSqgId9v;2xJ zrh8uR!F-eU$NMx@S*+sk=C~Dxr9Qn7TfWnTupuHKuQ$;gGiBcU>GF5sWx(~4IP3`f zWE;YFO*?jGwYh%C3X<>RKHC-DZ!*r;cIr}GLOno^3U4tFSSoJp%oHPiSa%nh=Zgn% z14+8v@ygy0>UgEN1bczD6wK45%M>psM)y^)IfG*>3ItX|TzV*0i%@>L(VN!zdKb8S?Qf7BhjNpziA zR}?={-eu>9JDcl*R=OP9B8N$IcCETXah9SUDhr{yrld{G;PnCWRsPD7!eOOFBTWUQ=LrA_~)mFf&!zJX!Oc-_=kT<}m|K52 z)M=G#;p;Rdb@~h5D{q^K;^fX-m5V}L%!wVC2iZ1uu401Ll}#rocTeK|7FAeBRhNdQ zCc2d^aQnQp=MpOmak60N$OgS}a;p(l9CL`o4r(e-nN}mQ?M&isv-P&d$!8|1D1I(3-z!wi zTgoo)*Mv`gC?~bm?S|@}I|m-E2yqPEvYybiD5azInexpK8?9q*$9Yy9-t%5jU8~ym zgZDx>!@ujQ=|HJnwp^wv-FdD{RtzO9SnyfB{mH_(c!jHL*$>0o-(h(eqe*ZwF6Lvu z{7rkk%PEqaA>o+f{H02tzZ@TWy&su?VNw43! z-X+rN`6llvpUms3ZiSt)JMeztB~>9{J8SPmYs&qohxdYFi!ra8KR$35Zp9oR)eFC4 zE;P31#3V)n`w$fZ|4X-|%MX`xZDM~gJyl2W;O$H25*=+1S#%|53>|LyH za@yh+;325%Gq3;J&a)?%7X%t@WXcWL*BaaR*7UEZad4I8iDt7^R_Fd`XeUo256;sAo2F!HcIQKk;h})QxEsPE5BcKc7WyerTchgKmrfRX z!x#H_%cL#B9TWAqkA4I$R^8{%do3Y*&(;WFmJ zU7Dih{t1<{($VtJRl9|&EB?|cJ)xse!;}>6mSO$o5XIx@V|AA8ZcoD88ZM?C*;{|f zZVmf94_l1OmaICt`2sTyG!$^UeTHx9YuUP!omj(r|7zpm5475|yXI=rR>>fteLI+| z)MoiGho0oEt=*J(;?VY0QzwCqw@cVm?d7Y!z0A@u#H?sCJ*ecvyhj& z-F77lO;SH^dmf?L>3i>?Z*U}Em4ZYV_CjgfvzYsRZ+1B!Uo6H6mbS<-FFL`ytqvb& zE7+)2ahv-~dz(Hs+f})z{*4|{)b=2!RZK;PWwOnO=hG7xG`JU5>bAvUbdYd_CjvtHBHgtGdlO+s^9ca^Bv3`t@VRX2_AD$Ckg36OcQRF zXD6QtGfHdw*hx~V(MV-;;ZZF#dJ-piEF+s27z4X1qi5$!o~xBnvf=uopcn7ftfsZc zy@(PuOk`4GL_n(H9(E2)VUjqRCk9kR?w)v@xO6Jm_Mx})&WGEl=GS0#)0FAq^J*o! zAClhvoTsNP*-b~rN{8Yym3g{01}Ep^^Omf=SKqvN?{Q*C4HNNAcrowIa^mf+3PRy! z*_G-|3i8a;+q;iP@~Of_$(vtFkB8yOyWt2*K)vAn9El>=D;A$CEx6b*XF@4y_6M+2 zpeW`RHoI_p(B{%(&jTHI->hmNmZjHUj<@;7w0mx3&koy!2$@cfX{sN19Y}euYJFn& z1?)+?HCkD0MRI$~uB2UWri})0bru_B;klFdwsLc!ne4YUE;t41JqfG# zZJq6%vbsdx!wYeE<~?>o4V`A3?lN%MnKQ`z=uUivQN^vzJ|C;sdQ37Qn?;lpzg})y z)_2~rUdH}zNwX;Tp0tJ78+&I=IwOQ-fl30R79O8@?Ub8IIA(6I`yHn%lARVL`%b8+ z4$8D-|MZZWxc_)vu6@VZN!HsI$*2NOV&uMxBNzIbRgy%ob_ zhwEH{J9r$!dEix9XM7n&c{S(h>nGm?el;gaX0@|QnzFD@bne`el^CO$yXC?BDJ|Qg z+y$GRoR`?ST1z^e*>;!IS@5Ovb7*RlN>BV_UC!7E_F;N#ky%1J{+iixp(dUJj93aK zzHNN>R-oN7>kykHClPnoPTIj7zc6KM(Pnlb(|s??)SMb)4!sMHU^-ntJwY5Big7xv zb1Ew`Xj;|D2kzGja*C$eS44(d&RMU~c_Y14V9_TLTz0J#uHlsx`S6{nhsA0dWZ#cG zJ?`fO50E>*X4TQLv#nl%3GOk*UkAgt=IY+u0LNXqeln3Z zv$~&Li`ZJOKkFuS)dJRA>)b_Da%Q~axwA_8zNK{BH{#}#m}zGcuckz}riDE-z_Ms> zR8-EqAMcfyGJCtvTpaUVQtajhUS%c@Yj}&6Zz;-M7MZzqv3kA7{SuW$oW#=0az2wQ zg-WG@Vb4|D`pl~Il54N7Hmsauc_ne-a!o5#j3WaBBh@Wuefb!QJIOn5;d)%A#s+5% zuD$H=VNux9bE-}1&bcYGZ+>1Fo;3Z@e&zX^n!?JK*adSbONm$XW9z;Q^L>9U!}Toj2WdafJ%oL#h|yWWwyAGxzfrAWdDTtaKl zK4`5tDpPg5>z$MNv=X0LZ0d6l%D{(D8oT@+w0?ce$DZ6pv>{1&Ok67Ix1 zH}3=IEhPJEhItCC8E=`T`N5(k?G=B4+xzZ?<4!~ ze~z6Wk9!CHTI(0rLJ4{JU?E-puc;xusR?>G?;4vt;q~iI9=kDL=z0Rr%O$vU`30X$ zDZRFyZ`(omOy@u|i6h;wtJlP;+}$|Ak|k2dea7n?U1*$T!sXqqOjq^NxLPMmk~&qI zYg0W?yK8T(6+Ea+$YyspKK?kP$+B`~t3^Pib_`!6xCs32!i@pqXfFV6PmBIR<-QW= zN8L{pt0Vap0x`Gzn#E@zh@H)0FfVfA_Iu4fjYZ+umO1LXIbVc$pY+E234u)ttcrl$ z>s92z4vT%n6cMb>=XT6;l0+9e(|CZG)$@C7t7Z7Ez@a)h)!hyuV&B5K%%)P5?Lk|C zZZSVzdXp{@OXSP0hoU-gF8s8Um(#xzjP2Vem zec#-^JqTa&Y#QJ>-FBxd7tf`XB6e^JPUgagB8iBSEps;92KG`!#mvVcPQ5yNC-GEG zTiHEDYfH+0O15}r^+ z#jxj=@x8iNHWALe!P3R67TwmhItn**0JwnzSV2O&KE8KcT+0hWH^OPD1pwiuyx=b@ zNf5Jh0{9X)8;~Es)$t@%(3!OnbY+`@?i{mGX7Yy}8T_*0a6g;kaFPq;*=px5EhO{Cp%1kI<0?*|h8v!6WnO3cCJRF2-CRrU3JiLJnj@6;L)!0kWYAc_}F{2P))3HmCrz zQ&N&gE70;`!6*eJ4^1IR{f6j4(-l&X!tjHxkbHA^Zhrnhr9g{exN|xrS`5Pq=#Xf& zG%P=#ra-TyVFfgW%cZo5OSIwFL9WtXAlFOa+ubmI5t*3=g#Y zF%;70p5;{ZeFL}&}yOY1N1*Q;*<(kTB!7vM$QokF)yr2FlIU@$Ph58$Bz z0J?xQG=MlS4L6jA22eS42g|9*9pX@$#*sUeM(z+t?hr@r5J&D1rx}2pW&m*_`VDCW zUYY@v-;bAO0HqoAgbbiGGC<=ryf96}3pouhy3XJrX+!!u*O_>Si38V{uJmQ&USptX zKp#l(?>%^7;2%h(q@YWS#9;a!JhKlkR#Vd)ERILlgu!Hr@jA@V;sk4BJ-H#p*4EqC zDGjC*tl=@3Oi6)Bn^QwFpul18fpkbpg0+peH$xyPBqb%`$OUhPKyWb32o7clB*9Z< zN=i~NLjavrLtwgJ01bufP+>p-jR2I95|TpmKpQL2!oV>g(4RvS2pK4*ou%m(h6r3A zX#s&`9LU1ZG&;{CkOK!4fLDTnBys`M!vuz>Q&9OZ0hGQl!~!jSDg|~s*w52opC{sB ze|Cf2luD(*G13LcOAGA!s2FjSK8&IE5#W%J25w!vM0^VyQM!t)inj&RTiJ!wXzFgz z3^IqzB7I0L$llljsGq})thBy9UOyjtFO_*hYM_sgcMk>44jeH0V1FDyELc{S1F-;A zS;T^k^~4biG&V*Irq}O;e}j$$+E_#G?HKIn05iP3j|87TkGK~SqG!-KBg5+mN(aLm z8ybhIM`%C19UX$H$KY6JgXbY$0AT%rEpHC;u`rQ$Y=rxUdsc5*Kvc8jaYaO$^)cI6){P6K0r)I6DY4Wr4&B zLQUBraey#0HV|&c4v7PVo3n$zHj99(TZO^3?Ly%C4nYvJTL9eLBLHsM3WKKD>5!B` zQ=BsR3aR6PD(Fa>327E2HAu5TM~Wusc!)>~(gM)+3~m;92Jd;FnSib=M5d6;;5{%R zb4V7DEJ0V!CP-F*oU?gkc>ksUtAYP&V4ND5J>J2^jt*vcFflQWCrB&fLdT%O59PVJ zhid#toR=FNgD!q3&r8#wEBr`!wzvQu5zX?Q>nlSJ4i@WC*CN*-xU66F^V5crWevQ9gsq$I@z1o(a=k7LL~ z7m_~`o;_Ozha1$8Q}{WBehvAlO4EL60y5}8GDrZ< zXh&F}71JbW2A~8KfEWj&UWV#4+Z4p`b{uAj4&WC zha`}X@3~+Iz^WRlOHU&KngK>#j}+_o@LdBC1H-`gT+krWX3-;!)6?{FBp~%20a}FL zFP9%Emqcwa#(`=G>BBZ0qZDQhmZKJg_g8<=bBFKWr!dyg(YkpE+|R*SGpDVU!+VlU zFC54^DLv}`qa%49T>nNiA9Q7Ips#!Xx90tCU2gvK`(F+GPcL=J^>No{)~we#o@&mUb6c$ zCc*<|NJBk-#+{j9xkQ&ujB zI~`#kN~7W!f*-}wkG~Ld!JqZ@tK}eeSnsS5J1fMFXm|`LJx&}5`@dK3W^7#Wnm+_P zBZkp&j1fa2Y=eIjJ0}gh85jt43kaIXXv?xmo@eHrka!Z|vQv12HN#+!I5E z`(fbuW>gFiJL|uXJ!vKt#z3e3HlVdboH7;e#i3(2<)Fg-I@BR!qY#eof3MFZ&*Y@l zI|KJf&ge@p2Dq09Vu$$Qxb7!}{m-iRk@!)%KL)txi3;~Z4Pb}u@GsW;ELiWeG9V51 znX#}B&4Y2E7-H=OpNE@q{%hFLxwIpBF2t{vPREa8_{linXT;#1vMRWjOzLOP$-hf( z>=?$0;~~PnkqY;~K{EM6Vo-T(0K{A0}VUGmu*hR z{tw3hvBN%N3G3Yw`X5Te+F{J`(3w1s3-+1EbnFQKcrgrX1Jqvs@ADGe%M0s$EbK$$ zK)=y=upBc6SjGYAACCcI=Y*6Fi8_jgwZlLxD26fnQfJmb8^gHRN5(TemhX@0e=vr> zg`W}6U>x6VhoA3DqsGGD9uL1DhB3!OXO=k}59TqD@(0Nb{)Ut_luTioK_>7wjc!5C zIr@w}b`Fez3)0wQfKl&bae7;PcTA7%?f2xucM0G)wt_KO!Ewx>F~;=BI0j=Fb4>pp zv}0R^xM4eti~+^+gE$6b81p(kwzuDti(-K9bc|?+pJEl@H+jSYuxZQV8rl8 zjp@M{#%qItIUFN~KcO9Hed*`$5A-2~pAo~K&<-Q+`9`$CK>rzqAI4w~$F%vs9s{~x zg4BP%Gy*@m?;D6=SRX?888Q6peF@_4Z->8wAH~Cn!R$|Hhq2cIzFYqT_+cDourHbY z0qroxJnrZ4Gh+Ay+F`_c%+KRT>y3qw{)89?=hJ@=KO=@ep)aBJ$c!JHfBMJpsP*3G za7|)VJJ8B;4?n{~ldJF7%jmb`-ftIvNd~ekoufG(`K(3=LNc;HBY& z(lp#q8XAD#cIf}k49zX_i`*fO+#!zKA&%T3j@%)R+#yag067CU%yUEe47>wzGU8^` z1EXFT^@I!{J!F8!X?S6ph8J=gUi5tl93*W>7}_uR<2N2~e}FaG?}KPyugQ=-OGEZs z!GBoyYY+H*ANn4?Z)X4l+7H%`17i5~zRlRIX?t)6_eu=g2Q`3WBhxSUeea+M-S?RL zX9oBGKn%a!H+*hx4d2(I!gsi+@SQK%<{X22M~2tMulJoa)0*+z9=-YO+;DFEm5eE1U9b^B(Z}2^9!Qk`!A$wUE z7$Ar5?NRg2&G!AZqnmE64eh^Anss3i!{}%6@Et+4rr!=}!SBF8eZ2*J3ujCWbl;3; z48H~goPSv(8X61fKKdpP!Z7$88NL^Z?j`!^*I?-P4X^pMxyWz~@$(UeAcTSDd(`vO z{~rc;9|GfMJcApU3k}22a!&)k4{CU!e_ny^Y3cO;tOvOMKEyWz!vG(Kp*;hB?d|R3`2X~=5a6#^o5@qn?J-bI8Ppip{-yG z!k|VcGsq!jF~}7DMr49Wap-s&>o=U^T0!Lcy}!(bhtYsPQy z4|EJe{12QL#=c(suQ89Mhw9<`bui%nx7Nep`C&*M3~vMEACmcRYYRGtANq$F%zh&V zc)cEVeHz*Z1N)L7k-(k3np#{GcDh2Q@ya0YHl*n7fl*ZPAsbU-a94MYYtA#&!c`xGIaV;yzsmrjfieTEtqB_WgZp2*NplHx=$O{M~2#i_vJ{ps-NgK zQsxKK_CBM2PP_je+Xft`(vYfXXgIUr{=PA=7a8`2EHk)Ym2QKIforz# tySWtj{oF3N9@_;i*Fv5S)9x^z=nlWP>jpp-9)52ZmLVA=i*%6g{{fxOO~wEK diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/runner.exe.manifest b/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/runner.exe.manifest deleted file mode 100644 index a42ea7687cb6..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/runner.exe.manifest +++ /dev/null @@ -1,20 +0,0 @@ - - - - - PerMonitorV2 - - - - - - - - - - - - - - - diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/utils.cpp b/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/utils.cpp deleted file mode 100644 index f5bf9fa0f536..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/utils.cpp +++ /dev/null @@ -1,64 +0,0 @@ -#include "utils.h" - -#include -#include -#include -#include - -#include - -void CreateAndAttachConsole() { - if (::AllocConsole()) { - FILE *unused; - if (freopen_s(&unused, "CONOUT$", "w", stdout)) { - _dup2(_fileno(stdout), 1); - } - if (freopen_s(&unused, "CONOUT$", "w", stderr)) { - _dup2(_fileno(stdout), 2); - } - std::ios::sync_with_stdio(); - FlutterDesktopResyncOutputStreams(); - } -} - -std::vector GetCommandLineArguments() { - // Convert the UTF-16 command line arguments to UTF-8 for the Engine to use. - int argc; - wchar_t** argv = ::CommandLineToArgvW(::GetCommandLineW(), &argc); - if (argv == nullptr) { - return std::vector(); - } - - std::vector command_line_arguments; - - // Skip the first argument as it's the binary name. - for (int i = 1; i < argc; i++) { - command_line_arguments.push_back(Utf8FromUtf16(argv[i])); - } - - ::LocalFree(argv); - - return command_line_arguments; -} - -std::string Utf8FromUtf16(const wchar_t* utf16_string) { - if (utf16_string == nullptr) { - return std::string(); - } - int target_length = ::WideCharToMultiByte( - CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, - -1, nullptr, 0, nullptr, nullptr); - std::string utf8_string; - if (target_length == 0 || target_length > utf8_string.max_size()) { - return utf8_string; - } - utf8_string.resize(target_length); - int converted_length = ::WideCharToMultiByte( - CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, - -1, utf8_string.data(), - target_length, nullptr, nullptr); - if (converted_length == 0) { - return std::string(); - } - return utf8_string; -} diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/utils.h b/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/utils.h deleted file mode 100644 index 3879d5475579..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/utils.h +++ /dev/null @@ -1,19 +0,0 @@ -#ifndef RUNNER_UTILS_H_ -#define RUNNER_UTILS_H_ - -#include -#include - -// Creates a console for the process, and redirects stdout and stderr to -// it for both the runner and the Flutter library. -void CreateAndAttachConsole(); - -// Takes a null-terminated wchar_t* encoded in UTF-16 and returns a std::string -// encoded in UTF-8. Returns an empty std::string on failure. -std::string Utf8FromUtf16(const wchar_t* utf16_string); - -// Gets the command line arguments passed in as a std::vector, -// encoded in UTF-8. Returns an empty std::vector on failure. -std::vector GetCommandLineArguments(); - -#endif // RUNNER_UTILS_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/win32_window.cpp b/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/win32_window.cpp deleted file mode 100644 index 041a38554745..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/win32_window.cpp +++ /dev/null @@ -1,288 +0,0 @@ -#include "win32_window.h" - -#include -#include - -#include "resource.h" - -namespace { - -/// Window attribute that enables dark mode window decorations. -/// -/// Redefined in case the developer's machine has a Windows SDK older than -/// version 10.0.22000.0. -/// See: https://docs.microsoft.com/windows/win32/api/dwmapi/ne-dwmapi-dwmwindowattribute -#ifndef DWMWA_USE_IMMERSIVE_DARK_MODE -#define DWMWA_USE_IMMERSIVE_DARK_MODE 20 -#endif - -constexpr const wchar_t kWindowClassName[] = L"FLUTTER_RUNNER_WIN32_WINDOW"; - -/// Registry key for app theme preference. -/// -/// A value of 0 indicates apps should use dark mode. A non-zero or missing -/// value indicates apps should use light mode. -constexpr const wchar_t kGetPreferredBrightnessRegKey[] = - L"Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize"; -constexpr const wchar_t kGetPreferredBrightnessRegValue[] = L"AppsUseLightTheme"; - -// The number of Win32Window objects that currently exist. -static int g_active_window_count = 0; - -using EnableNonClientDpiScaling = BOOL __stdcall(HWND hwnd); - -// Scale helper to convert logical scaler values to physical using passed in -// scale factor -int Scale(int source, double scale_factor) { - return static_cast(source * scale_factor); -} - -// Dynamically loads the |EnableNonClientDpiScaling| from the User32 module. -// This API is only needed for PerMonitor V1 awareness mode. -void EnableFullDpiSupportIfAvailable(HWND hwnd) { - HMODULE user32_module = LoadLibraryA("User32.dll"); - if (!user32_module) { - return; - } - auto enable_non_client_dpi_scaling = - reinterpret_cast( - GetProcAddress(user32_module, "EnableNonClientDpiScaling")); - if (enable_non_client_dpi_scaling != nullptr) { - enable_non_client_dpi_scaling(hwnd); - } - FreeLibrary(user32_module); -} - -} // namespace - -// Manages the Win32Window's window class registration. -class WindowClassRegistrar { - public: - ~WindowClassRegistrar() = default; - - // Returns the singleton registar instance. - static WindowClassRegistrar* GetInstance() { - if (!instance_) { - instance_ = new WindowClassRegistrar(); - } - return instance_; - } - - // Returns the name of the window class, registering the class if it hasn't - // previously been registered. - const wchar_t* GetWindowClass(); - - // Unregisters the window class. Should only be called if there are no - // instances of the window. - void UnregisterWindowClass(); - - private: - WindowClassRegistrar() = default; - - static WindowClassRegistrar* instance_; - - bool class_registered_ = false; -}; - -WindowClassRegistrar* WindowClassRegistrar::instance_ = nullptr; - -const wchar_t* WindowClassRegistrar::GetWindowClass() { - if (!class_registered_) { - WNDCLASS window_class{}; - window_class.hCursor = LoadCursor(nullptr, IDC_ARROW); - window_class.lpszClassName = kWindowClassName; - window_class.style = CS_HREDRAW | CS_VREDRAW; - window_class.cbClsExtra = 0; - window_class.cbWndExtra = 0; - window_class.hInstance = GetModuleHandle(nullptr); - window_class.hIcon = - LoadIcon(window_class.hInstance, MAKEINTRESOURCE(IDI_APP_ICON)); - window_class.hbrBackground = 0; - window_class.lpszMenuName = nullptr; - window_class.lpfnWndProc = Win32Window::WndProc; - RegisterClass(&window_class); - class_registered_ = true; - } - return kWindowClassName; -} - -void WindowClassRegistrar::UnregisterWindowClass() { - UnregisterClass(kWindowClassName, nullptr); - class_registered_ = false; -} - -Win32Window::Win32Window() { - ++g_active_window_count; -} - -Win32Window::~Win32Window() { - --g_active_window_count; - Destroy(); -} - -bool Win32Window::Create(const std::wstring& title, - const Point& origin, - const Size& size) { - Destroy(); - - const wchar_t* window_class = - WindowClassRegistrar::GetInstance()->GetWindowClass(); - - const POINT target_point = {static_cast(origin.x), - static_cast(origin.y)}; - HMONITOR monitor = MonitorFromPoint(target_point, MONITOR_DEFAULTTONEAREST); - UINT dpi = FlutterDesktopGetDpiForMonitor(monitor); - double scale_factor = dpi / 96.0; - - HWND window = CreateWindow( - window_class, title.c_str(), WS_OVERLAPPEDWINDOW, - Scale(origin.x, scale_factor), Scale(origin.y, scale_factor), - Scale(size.width, scale_factor), Scale(size.height, scale_factor), - nullptr, nullptr, GetModuleHandle(nullptr), this); - - if (!window) { - return false; - } - - UpdateTheme(window); - - return OnCreate(); -} - -bool Win32Window::Show() { - return ShowWindow(window_handle_, SW_SHOWNORMAL); -} - -// static -LRESULT CALLBACK Win32Window::WndProc(HWND const window, - UINT const message, - WPARAM const wparam, - LPARAM const lparam) noexcept { - if (message == WM_NCCREATE) { - auto window_struct = reinterpret_cast(lparam); - SetWindowLongPtr(window, GWLP_USERDATA, - reinterpret_cast(window_struct->lpCreateParams)); - - auto that = static_cast(window_struct->lpCreateParams); - EnableFullDpiSupportIfAvailable(window); - that->window_handle_ = window; - } else if (Win32Window* that = GetThisFromHandle(window)) { - return that->MessageHandler(window, message, wparam, lparam); - } - - return DefWindowProc(window, message, wparam, lparam); -} - -LRESULT -Win32Window::MessageHandler(HWND hwnd, - UINT const message, - WPARAM const wparam, - LPARAM const lparam) noexcept { - switch (message) { - case WM_DESTROY: - window_handle_ = nullptr; - Destroy(); - if (quit_on_close_) { - PostQuitMessage(0); - } - return 0; - - case WM_DPICHANGED: { - auto newRectSize = reinterpret_cast(lparam); - LONG newWidth = newRectSize->right - newRectSize->left; - LONG newHeight = newRectSize->bottom - newRectSize->top; - - SetWindowPos(hwnd, nullptr, newRectSize->left, newRectSize->top, newWidth, - newHeight, SWP_NOZORDER | SWP_NOACTIVATE); - - return 0; - } - case WM_SIZE: { - RECT rect = GetClientArea(); - if (child_content_ != nullptr) { - // Size and position the child window. - MoveWindow(child_content_, rect.left, rect.top, rect.right - rect.left, - rect.bottom - rect.top, TRUE); - } - return 0; - } - - case WM_ACTIVATE: - if (child_content_ != nullptr) { - SetFocus(child_content_); - } - return 0; - - case WM_DWMCOLORIZATIONCOLORCHANGED: - UpdateTheme(hwnd); - return 0; - } - - return DefWindowProc(window_handle_, message, wparam, lparam); -} - -void Win32Window::Destroy() { - OnDestroy(); - - if (window_handle_) { - DestroyWindow(window_handle_); - window_handle_ = nullptr; - } - if (g_active_window_count == 0) { - WindowClassRegistrar::GetInstance()->UnregisterWindowClass(); - } -} - -Win32Window* Win32Window::GetThisFromHandle(HWND const window) noexcept { - return reinterpret_cast( - GetWindowLongPtr(window, GWLP_USERDATA)); -} - -void Win32Window::SetChildContent(HWND content) { - child_content_ = content; - SetParent(content, window_handle_); - RECT frame = GetClientArea(); - - MoveWindow(content, frame.left, frame.top, frame.right - frame.left, - frame.bottom - frame.top, true); - - SetFocus(child_content_); -} - -RECT Win32Window::GetClientArea() { - RECT frame; - GetClientRect(window_handle_, &frame); - return frame; -} - -HWND Win32Window::GetHandle() { - return window_handle_; -} - -void Win32Window::SetQuitOnClose(bool quit_on_close) { - quit_on_close_ = quit_on_close; -} - -bool Win32Window::OnCreate() { - // No-op; provided for subclasses. - return true; -} - -void Win32Window::OnDestroy() { - // No-op; provided for subclasses. -} - -void Win32Window::UpdateTheme(HWND const window) { - DWORD light_mode; - DWORD light_mode_size = sizeof(light_mode); - LSTATUS result = RegGetValue(HKEY_CURRENT_USER, kGetPreferredBrightnessRegKey, - kGetPreferredBrightnessRegValue, - RRF_RT_REG_DWORD, nullptr, &light_mode, - &light_mode_size); - - if (result == ERROR_SUCCESS) { - BOOL enable_dark_mode = light_mode == 0; - DwmSetWindowAttribute(window, DWMWA_USE_IMMERSIVE_DARK_MODE, - &enable_dark_mode, sizeof(enable_dark_mode)); - } -} diff --git a/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/win32_window.h b/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/win32_window.h deleted file mode 100644 index c86632d8a6b9..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/example/windows/runner/win32_window.h +++ /dev/null @@ -1,102 +0,0 @@ -#ifndef RUNNER_WIN32_WINDOW_H_ -#define RUNNER_WIN32_WINDOW_H_ - -#include - -#include -#include -#include - -// A class abstraction for a high DPI-aware Win32 Window. Intended to be -// inherited from by classes that wish to specialize with custom -// rendering and input handling -class Win32Window { - public: - struct Point { - unsigned int x; - unsigned int y; - Point(unsigned int x, unsigned int y) : x(x), y(y) {} - }; - - struct Size { - unsigned int width; - unsigned int height; - Size(unsigned int width, unsigned int height) - : width(width), height(height) {} - }; - - Win32Window(); - virtual ~Win32Window(); - - // Creates a win32 window with |title| that is positioned and sized using - // |origin| and |size|. New windows are created on the default monitor. Window - // sizes are specified to the OS in physical pixels, hence to ensure a - // consistent size this function will scale the inputted width and height as - // as appropriate for the default monitor. The window is invisible until - // |Show| is called. Returns true if the window was created successfully. - bool Create(const std::wstring& title, const Point& origin, const Size& size); - - // Show the current window. Returns true if the window was successfully shown. - bool Show(); - - // Release OS resources associated with window. - void Destroy(); - - // Inserts |content| into the window tree. - void SetChildContent(HWND content); - - // Returns the backing Window handle to enable clients to set icon and other - // window properties. Returns nullptr if the window has been destroyed. - HWND GetHandle(); - - // If true, closing this window will quit the application. - void SetQuitOnClose(bool quit_on_close); - - // Return a RECT representing the bounds of the current client area. - RECT GetClientArea(); - - protected: - // Processes and route salient window messages for mouse handling, - // size change and DPI. Delegates handling of these to member overloads that - // inheriting classes can handle. - virtual LRESULT MessageHandler(HWND window, - UINT const message, - WPARAM const wparam, - LPARAM const lparam) noexcept; - - // Called when CreateAndShow is called, allowing subclass window-related - // setup. Subclasses should return false if setup fails. - virtual bool OnCreate(); - - // Called when Destroy is called. - virtual void OnDestroy(); - - private: - friend class WindowClassRegistrar; - - // OS callback called by message pump. Handles the WM_NCCREATE message which - // is passed when the non-client area is being created and enables automatic - // non-client DPI scaling so that the non-client area automatically - // responsponds to changes in DPI. All other messages are handled by - // MessageHandler. - static LRESULT CALLBACK WndProc(HWND const window, - UINT const message, - WPARAM const wparam, - LPARAM const lparam) noexcept; - - // Retrieves a class instance pointer for |window| - static Win32Window* GetThisFromHandle(HWND const window) noexcept; - - // Update the window frame's theme to match the system theme. - static void UpdateTheme(HWND const window); - - bool quit_on_close_ = false; - - // window handle for top level window. - HWND window_handle_ = nullptr; - - // window handle for hosted content. - HWND child_content_ = nullptr; -}; - -#endif // RUNNER_WIN32_WINDOW_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/admob.h b/packages/firebase_core/firebase_core/firebase_core/firebase/admob.h deleted file mode 100644 index 957c86b7e168..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/admob.h +++ /dev/null @@ -1,215 +0,0 @@ -/* - * Copyright 2016 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_H_ -#define FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_H_ - -#include "firebase/internal/platform.h" - -#if FIREBASE_PLATFORM_ANDROID -#include -#endif // FIREBASE_PLATFORM_ANDROID - -#include "firebase/admob/banner_view.h" -#include "firebase/admob/interstitial_ad.h" -#include "firebase/admob/rewarded_video.h" -#include "firebase/admob/types.h" -#include "firebase/app.h" -#include "firebase/internal/common.h" - -#if !defined(DOXYGEN) && !defined(SWIG) -FIREBASE_APP_REGISTER_CALLBACKS_REFERENCE(admob) -#endif // !defined(DOXYGEN) && !defined(SWIG) - -namespace firebase { - -/// @deprecated The functionality in the firebase::admob namespace -/// has been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the new -/// SDK in our migration guide. -/// -/// @brief API for AdMob with Firebase. -/// -/// The AdMob API allows you to load and display mobile ads using the Google -/// Mobile Ads SDK. Each ad format has its own header file. -namespace admob { - -/// @deprecated -/// @brief Initializes AdMob via Firebase. -/// -/// The functionality in the firebase::admob namespace has -/// been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the -/// new SDK in our migration -/// guide. -/// -/// @param app The Firebase app for which to initialize mobile ads. -/// -/// @return kInitResultSuccess if initialization succeeded, or -/// kInitResultFailedMissingDependency on Android if Google Play services is not -/// available on the current device and the Google Mobile Ads SDK requires -/// Google Play services (for example, when using 'play-services-ads-lite'). -FIREBASE_DEPRECATED InitResult Initialize(const ::firebase::App& app); - -/// @deprecated -/// @brief Initializes AdMob via Firebase with the publisher's AdMob app ID. -/// -/// The functionality in the firebase::admob namespace has -/// been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the -/// new SDK in our migration -/// guide. -/// -/// Initializing the Google Mobile Ads SDK with the AdMob app ID at app launch -/// allows the SDK to fetch app-level settings and perform configuration tasks -/// as early as possible. This can help reduce latency for the initial ad -/// request. AdMob app IDs are unique identifiers given to mobile apps when -/// they're registered in the AdMob console. To find your app ID in the AdMob -/// console, click the App management (https://apps.admob.com/#account/appmgmt:) -/// option under the settings dropdown (located in the upper right-hand corner). -/// App IDs have the form ca-app-pub-XXXXXXXXXXXXXXXX~NNNNNNNNNN. -/// -/// @param[in] app The Firebase app for which to initialize mobile ads. -/// @param[in] admob_app_id The publisher's AdMob app ID. -/// -/// @return kInitResultSuccess if initialization succeeded, or -/// kInitResultFailedMissingDependency on Android if Google Play services is not -/// available on the current device and the Google Mobile Ads SDK requires -/// Google Play services (for example, when using 'play-services-ads-lite'). -FIREBASE_DEPRECATED InitResult Initialize(const ::firebase::App& app, - const char* admob_app_id); - -#if FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) -/// @deprecated -/// @brief Initializes AdMob without Firebase for Android. -/// -/// The functionality in the firebase::admob namespace has -/// been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the -/// new SDK in our migration -/// guide. -/// -/// The arguments to @ref Initialize are platform-specific so the caller must do -/// something like this: -/// @code -/// #if defined(__ANDROID__) -/// firebase::admob::Initialize(jni_env, activity); -/// #else -/// firebase::admob::Initialize(); -/// #endif -/// @endcode -/// -/// @param[in] jni_env JNIEnv pointer. -/// @param[in] activity Activity used to start the application. -/// -/// @return kInitResultSuccess if initialization succeeded, or -/// kInitResultFailedMissingDependency on Android if Google Play services is not -/// available on the current device and the AdMob SDK requires -/// Google Play services (for example when using 'play-services-ads-lite'). -FIREBASE_DEPRECATED InitResult Initialize(JNIEnv* jni_env, jobject activity); - -/// @deprecated -/// @brief Initializes AdMob via Firebase with the publisher's AdMob app ID. -/// -/// The functionality in the firebase::admob namespace has -/// been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the -/// new SDK in our migration -/// guide. -/// -/// Initializing the Google Mobile Ads SDK with the AdMob app ID at app launch -/// allows the SDK to fetch app-level settings and perform configuration tasks -/// as early as possible. This can help reduce latency for the initial ad -/// request. AdMob app IDs are unique identifiers given to mobile apps when -/// they're registered in the AdMob console. To find your app ID in the AdMob -/// console, click the App management (https://apps.admob.com/#account/appmgmt:) -/// option under the settings dropdown (located in the upper right-hand corner). -/// App IDs have the form ca-app-pub-XXXXXXXXXXXXXXXX~NNNNNNNNNN. -/// -/// The arguments to @ref Initialize are platform-specific so the caller must do -/// something like this: -/// @code -/// #if defined(__ANDROID__) -/// firebase::admob::Initialize(jni_env, activity, admob_app_id); -/// #else -/// firebase::admob::Initialize(admob_app_id); -/// #endif -/// @endcode -/// -/// @param[in] jni_env JNIEnv pointer. -/// @param[in] activity Activity used to start the application. -/// @param[in] admob_app_id The publisher's AdMob app ID. -/// -/// @return kInitResultSuccess if initialization succeeded, or -/// kInitResultFailedMissingDependency on Android if Google Play services is not -/// available on the current device and the AdMob SDK requires -/// Google Play services (for example when using 'play-services-ads-lite'). -FIREBASE_DEPRECATED InitResult Initialize(JNIEnv* jni_env, jobject activity, - const char* admob_app_id); -#endif // defined(__ANDROID__) || defined(DOXYGEN) -#if !FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) -/// @deprecated -/// @brief Initializes AdMob without Firebase for iOS. -/// -/// The functionality in the firebase::admob namespace has -/// been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the -/// new SDK in our migration -/// guide. -FIREBASE_DEPRECATED InitResult Initialize(); - -/// @deprecated -/// @brief Initializes AdMob with the publisher's AdMob app ID and without -/// Firebase for iOS. -/// -/// The functionality in the firebase::admob namespace has -/// been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the -/// new SDK in our migration -/// guide. -/// -/// Initializing the Google Mobile Ads SDK with the AdMob app ID at app launch -/// allows the SDK to fetch app-level settings and perform configuration tasks -/// as early as possible. This can help reduce latency for the initial ad -/// request. AdMob app IDs are unique identifiers given to mobile apps when -/// they're registered in the AdMob console. To find your app ID in the AdMob -/// console, click the App management (https://apps.admob.com/#account/appmgmt:) -/// option under the settings dropdown (located in the upper right-hand corner). -/// App IDs have the form ca-app-pub-XXXXXXXXXXXXXXXX~NNNNNNNNNN. -/// -/// @param[in] admob_app_id The publisher's AdMob app ID. -/// -/// @return kInitResultSuccess if initialization succeeded -FIREBASE_DEPRECATED InitResult Initialize(const char* admob_app_id); -#endif // !defined(__ANDROID__) || defined(DOXYGEN) - -/// @deprecated -/// @brief Terminate AdMob. -/// -/// The functionality in the firebase::admob namespace has -/// been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the -/// new SDK in our migration -/// guide. -/// -/// Frees resources associated with AdMob that were allocated during -/// @ref firebase::admob::Initialize(). -FIREBASE_DEPRECATED void Terminate(); - -} // namespace admob -} // namespace firebase - -#endif // FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/admob/banner_view.h b/packages/firebase_core/firebase_core/firebase_core/firebase/admob/banner_view.h deleted file mode 100644 index 2d691f2d3a77..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/admob/banner_view.h +++ /dev/null @@ -1,427 +0,0 @@ -/* - * Copyright 2016 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_BANNER_VIEW_H_ -#define FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_BANNER_VIEW_H_ - -#include "firebase/admob/types.h" -#include "firebase/future.h" -#include "firebase/internal/common.h" - -namespace firebase { -namespace admob { - -namespace internal { -// Forward declaration for platform-specific data, implemented in each library. -class BannerViewInternal; -} // namespace internal - -/// @deprecated The functionality in the firebase::admob namespace -/// has been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the new -/// SDK in our migration guide. -/// -/// @brief Loads and displays AdMob banner ads. -/// -/// Each BannerView object corresponds to a single AdMob banner placement. There -/// are methods to load an ad, move it, show it and hide it, and retrieve the -/// bounds of the ad onscreen. -/// -/// BannerView objects maintain a presentation state that indicates whether -/// or not they're currently onscreen, as well as a set of bounds (stored in a -/// @ref BoundingBox struct), but otherwise provide information about -/// their current state through Futures. Methods like @ref Initialize, -/// @ref LoadAd, and @ref Hide each have a corresponding @ref Future from which -/// the result of the last call can be determined. The two variants of -/// @ref MoveTo share a single result @ref Future, since they're essentially the -/// same action. -/// -/// In addition, applications can create their own subclasses of -/// @ref BannerView::Listener, pass an instance to the @ref SetListener method, -/// and receive callbacks whenever the presentation state or bounding box of the -/// ad changes. -/// -/// For example, you could initialize, load, and show a banner view while -/// checking the result of the previous action at each step as follows: -/// -/// @code -/// namespace admob = ::firebase::admob; -/// admob::BannerView* banner_view = new admob::BannerView(); -/// banner_view->Initialize(ad_parent, "YOUR_AD_UNIT_ID", desired_ad_size) -/// @endcode -/// -/// Then, later: -/// -/// @code -/// if (banner_view->InitializeLastResult().status() == -/// ::firebase::kFutureStatusComplete && -/// banner_view->InitializeLastResult().error() == -/// firebase::admob::kAdMobErrorNone) { -/// banner_view->LoadAd(your_ad_request); -/// } -/// @endcode -/// -class BannerView { - public: -#ifdef INTERNAL_EXPERIMENTAL -// LINT.IfChange -#endif // INTERNAL_EXPERIMENTAL - /// @deprecated - /// @brief The presentation state of a @ref BannerView. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - enum PresentationState { - /// BannerView is currently hidden. - kPresentationStateHidden = 0, - /// BannerView is visible, but does not contain an ad. - kPresentationStateVisibleWithoutAd, - /// BannerView is visible and contains an ad. - kPresentationStateVisibleWithAd, - /// BannerView is visible and has opened a partial overlay on the screen. - kPresentationStateOpenedPartialOverlay, - /// BannerView is completely covering the screen or has caused focus to - /// leave the application (for example, when opening an external browser - /// during a clickthrough). - kPresentationStateCoveringUI, - }; -#ifdef INTERNAL_EXPERIMENTAL -// LINT.ThenChange(//depot_firebase_cpp/admob/client/cpp/src_java/com/google/firebase/admob/internal/cpp/ConstantsHelper.java) -#endif // INTERNAL_EXPERIMENTAL - -#ifdef INTERNAL_EXPERIMENTAL -// LINT.IfChange -#endif // INTERNAL_EXPERIMENTAL - /// @deprecated - /// @brief The possible screen positions for a @ref BannerView. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - enum Position { - /// Top of the screen, horizontally centered. - kPositionTop = 0, - /// Bottom of the screen, horizontally centered. - kPositionBottom, - /// Top-left corner of the screen. - kPositionTopLeft, - /// Top-right corner of the screen. - kPositionTopRight, - /// Bottom-left corner of the screen. - kPositionBottomLeft, - /// Bottom-right corner of the screen. - kPositionBottomRight, - }; -#ifdef INTERNAL_EXPERIMENTAL -// LINT.ThenChange(//depot_firebase_cpp/admob/client/cpp/src_java/com/google/firebase/admob/internal/cpp/ConstantsHelper.java) -#endif // INTERNAL_EXPERIMENTAL - - /// @deprecated - /// @brief A listener class that developers can extend and pass to a @ref - /// BannerView object's @ref SetListener method to be notified of changes to - /// the presentation state and bounding box. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - class Listener { - public: - /// @deprecated - /// @brief This method is called when the @ref BannerView object's - /// presentation state changes. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - /// @param[in] banner_view The banner view whose presentation state changed. - /// @param[in] state The new presentation state. - virtual void OnPresentationStateChanged(BannerView* banner_view, - PresentationState state) = 0; - /// @deprecated - /// @brief This method is called when the @ref BannerView object's bounding - /// box changes. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - /// @param[in] banner_view The banner view whose bounding box changed. - /// @param[in] box The new bounding box. - virtual void OnBoundingBoxChanged(BannerView* banner_view, - BoundingBox box) = 0; - virtual ~Listener(); - }; - - /// @deprecated - /// @brief Creates an uninitialized @ref BannerView object. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - /// - /// @ref Initialize must be called before the object is used. - FIREBASE_DEPRECATED BannerView(); - - ~BannerView(); - - /// @deprecated - /// @brief Initializes the @ref BannerView object. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - /// @param[in] parent The platform-specific UI element that will host the ad. - /// @param[in] ad_unit_id The ad unit ID to use when requesting ads. - /// @param[in] size The desired ad size for the banner. - FIREBASE_DEPRECATED Future Initialize(AdParent parent, - const char* ad_unit_id, - AdSize size); - - /// @deprecated - /// @brief Returns a @ref Future that has the status of the last call to - /// @ref Initialize. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - FIREBASE_DEPRECATED Future InitializeLastResult() const; - - /// @deprecated - /// @brief Begins an asynchronous request for an ad. If successful, the ad - /// will automatically be displayed in the BannerView. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - /// @param[in] request An AdRequest struct with information about the request - /// to be made (such as targeting info). - FIREBASE_DEPRECATED Future LoadAd(const AdRequest& request); - - /// @deprecated - /// @brief Returns a @ref Future containing the status of the last call to - /// @ref LoadAd. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - FIREBASE_DEPRECATED Future LoadAdLastResult() const; - - /// @deprecated - /// @brief Hides the BannerView. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - FIREBASE_DEPRECATED Future Hide(); - - /// @deprecated - /// @brief Returns a @ref Future containing the status of the last call to - /// @ref Hide. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - FIREBASE_DEPRECATED Future HideLastResult() const; - - /// @deprecated - /// @brief Shows the @ref BannerView. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - FIREBASE_DEPRECATED Future Show(); - - /// @deprecated - /// @brief Returns a @ref Future containing the status of the last call to - /// @ref Show. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - FIREBASE_DEPRECATED Future ShowLastResult() const; - - /// @deprecated - /// @brief Pauses the @ref BannerView. Should be called whenever the C++ - /// engine pauses or the application loses focus. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - FIREBASE_DEPRECATED Future Pause(); - - /// @deprecated - /// @brief Returns a @ref Future containing the status of the last call to - /// @ref Pause. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - FIREBASE_DEPRECATED Future PauseLastResult() const; - - /// @deprecated - /// @brief Resumes the @ref BannerView after pausing. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - FIREBASE_DEPRECATED Future Resume(); - - /// @deprecated - /// @brief Returns a @ref Future containing the status of the last call to - /// @ref Resume. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - FIREBASE_DEPRECATED Future ResumeLastResult() const; - - /// @deprecated - /// @brief Cleans up and deallocates any resources used by the @ref - /// BannerView. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - FIREBASE_DEPRECATED Future Destroy(); - - /// @deprecated - /// @brief Returns a @ref Future containing the status of the last call to - /// @ref Destroy. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - FIREBASE_DEPRECATED Future DestroyLastResult() const; - - /// @deprecated - /// @brief Moves the @ref BannerView so that its top-left corner is located at - /// (x, y). Coordinates are in pixels from the top-left corner of the screen. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - /// @param[in] x The desired horizontal coordinate. - /// @param[in] y The desired vertical coordinate. - FIREBASE_DEPRECATED Future MoveTo(int x, int y); - - /// @deprecated - /// @brief Moves the @ref BannerView so that it's located at the given - /// pre-defined position. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - /// @param[in] position The pre-defined position to which to move the - /// @ref BannerView. - FIREBASE_DEPRECATED Future MoveTo(Position position); - - /// @deprecated - /// @brief Returns a @ref Future containing the status of the last call to - /// either version of @ref MoveTo. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - FIREBASE_DEPRECATED Future MoveToLastResult() const; - - /// @deprecated - /// @brief Returns the current presentation state of the @ref BannerView. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - /// @return The current presentation state. - FIREBASE_DEPRECATED PresentationState presentation_state() const; - - /// @deprecated - /// @brief Retrieves the @ref BannerView's current onscreen size and location. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - FIREBASE_DEPRECATED BoundingBox bounding_box() const; - - /// @deprecated - /// @brief Sets the @ref Listener for this object. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - /// @param[in] listener A valid BannerView::Listener to receive callbacks. - FIREBASE_DEPRECATED void SetListener(Listener* listener); - - private: - // An internal, platform-specific implementation object that this class uses - // to interact with the Google Mobile Ads SDKs for iOS and Android. - internal::BannerViewInternal* internal_; -}; - -} // namespace admob -} // namespace firebase - -#endif // FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_BANNER_VIEW_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/admob/interstitial_ad.h b/packages/firebase_core/firebase_core/firebase_core/firebase/admob/interstitial_ad.h deleted file mode 100644 index b201ab7c3487..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/admob/interstitial_ad.h +++ /dev/null @@ -1,259 +0,0 @@ -/* - * Copyright 2016 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_INTERSTITIAL_AD_H_ -#define FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_INTERSTITIAL_AD_H_ - -#include "firebase/admob/types.h" -#include "firebase/future.h" -#include "firebase/internal/common.h" - -namespace firebase { -namespace admob { - -namespace internal { -// Forward declaration for platform-specific data, implemented in each library. -class InterstitialAdInternal; -} // namespace internal - -/// @deprecated The functionality in the firebase::admob namespace -/// has been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the new -/// SDK in our migration guide. -/// -/// @brief Loads and displays AdMob interstitial ads. -/// -/// @ref InterstitialAd is a single-use object that can load and show a -/// single AdMob interstitial ad. -/// -/// InterstitialAd objects maintain a presentation state that indicates whether -/// or not they're currently onscreen, but otherwise provide information about -/// their current state through Futures. @ref Initialize, @ref LoadAd, and -/// @ref Show each have a corresponding @ref Future from which you can determine -/// result of the previous call. -/// -/// In addition, applications can create their own subclasses of -/// @ref InterstitialAd::Listener, pass an instance to the @ref SetListener -/// method, and receive callbacks whenever the presentation state changes. -/// -/// Here's how one might initialize, load, and show an interstitial ad while -/// checking against the result of the previous action at each step: -/// -/// @code -/// namespace admob = ::firebase::admob; -/// admob::InterstitialAd* interstitial = new admob::InterstitialAd(); -/// interstitial->Initialize(ad_parent, "YOUR_AD_UNIT_ID") -/// @endcode -/// -/// Then, later: -/// -/// @code -/// if (interstitial->InitializeLastResult().status() == -/// ::firebase::kFutureStatusComplete && -/// interstitial->InitializeLastResult().error() == -/// firebase::admob::kAdMobErrorNone) { -/// interstitial->LoadAd(my_ad_request); -/// } -/// @endcode -/// -/// And after that: -/// -/// @code -/// if (interstitial->LoadAdLastResult().status() == -/// ::firebase::kFutureStatusComplete && -/// interstitial->LoadAdLastResult().error() == -/// firebase::admob::kAdMobErrorNone)) { -/// interstitial->Show(); -/// } -/// @endcode -/// -class InterstitialAd { - public: -#ifdef INTERNAL_EXPERIMENTAL -// LINT.IfChange -#endif // INTERNAL_EXPERIMENTAL - /// @deprecated - /// @brief The presentation states of an @ref InterstitialAd. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - enum PresentationState { - /// InterstitialAd is not currently being shown. - kPresentationStateHidden = 0, - /// InterstitialAd is being shown or has caused focus to leave the - /// application (for example, when opening an external browser during a - /// clickthrough). - kPresentationStateCoveringUI, - }; -#ifdef INTERNAL_EXPERIMENTAL -// LINT.ThenChange(//depot_firebase_cpp/admob/client/cpp/src_java/com/google/firebase/admob/internal/cpp/InterstitialAdHelper.java) -#endif // INTERNAL_EXPERIMENTAL - - /// @deprecated - /// @brief A listener class that developers can extend and pass to an - /// @ref InterstitialAd object's @ref SetListener method to be notified of - /// presentation state changes. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - /// @param[in] interstitial_ad The interstitial ad whose presentation state - /// changed. - /// @param[in] state The new presentation state. - virtual void OnPresentationStateChanged(InterstitialAd* interstitial_ad, - PresentationState state) = 0; - virtual ~Listener(); - }; - - /// @deprecated - /// @brief Creates an uninitialized @ref InterstitialAd object. - /// @ref Initialize must be called before the object is used. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - FIREBASE_DEPRECATED InterstitialAd(); - - ~InterstitialAd(); - - /// @deprecated - /// @brief Initialize the @ref InterstitialAd object. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - /// @param[in] parent The platform-specific UI element that will host the ad. - /// @param[in] ad_unit_id The ad unit ID to use in loading the ad. - FIREBASE_DEPRECATED Future Initialize(AdParent parent, - const char* ad_unit_id); - - /// @deprecated - /// @brief Returns a @ref Future containing the status of the last call to - /// @ref Initialize. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - FIREBASE_DEPRECATED Future InitializeLastResult() const; - - /// @deprecated - /// @brief Begins an asynchronous request for an ad. - /// - /// The @ref InterstitialAd::presentation_state method can be used to track - /// the progress of the request. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - /// @param[in] request An AdRequest struct with information about the request - /// to be made (such as targeting info). - FIREBASE_DEPRECATED Future LoadAd(const AdRequest& request); - - /// @deprecated - /// @brief Returns a @ref Future containing the status of the last call to - /// @ref LoadAd. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - FIREBASE_DEPRECATED Future LoadAdLastResult() const; - - /// @deprecated - /// @brief Shows the @ref InterstitialAd. This should not be called unless an - /// ad has already been loaded. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - FIREBASE_DEPRECATED Future Show(); - - /// @deprecated - /// @brief Returns a @ref Future containing the status of the last call to - /// @ref Show. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - FIREBASE_DEPRECATED Future ShowLastResult() const; - - /// @deprecated - /// @brief Returns the current presentation state of the @ref InterstitialAd. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - /// @return The current presentation state. - FIREBASE_DEPRECATED PresentationState presentation_state() const; - - /// @deprecated - /// @brief Sets the @ref Listener for this @ref InterstitialAd. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - /// @param[in] listener A valid InterstititalAd::Listener to receive - /// callbacks. - FIREBASE_DEPRECATED void SetListener(Listener* listener); - - private: - // An internal, platform-specific implementation object that this class uses - // to interact with the Google Mobile Ads SDKs for iOS and Android. - internal::InterstitialAdInternal* internal_; -}; - -} // namespace admob -} // namespace firebase - -#endif // FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_INTERSTITIAL_AD_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/admob/native_express_ad_view.h b/packages/firebase_core/firebase_core/firebase_core/firebase/admob/native_express_ad_view.h deleted file mode 100644 index 7e571967825e..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/admob/native_express_ad_view.h +++ /dev/null @@ -1,446 +0,0 @@ -/* - * Copyright 2016 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_NATIVE_EXPRESS_AD_VIEW_H_ -#define FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_NATIVE_EXPRESS_AD_VIEW_H_ - -#include "firebase/admob/types.h" -#include "firebase/future.h" -#include "firebase/internal/common.h" - -namespace firebase { -namespace admob { - -namespace internal { -// Forward declaration for platform-specific data, implemented in each library. -class NativeExpressAdViewInternal; -} // namespace internal - -/// @deprecated The functionality in the firebase::admob namespace -/// has been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the new -/// SDK in our migration guide. -/// Native Express Ads has been discontinued, and are no longer served. -/// -/// @brief Loads and displays ads from AdMob Native Ads Express. -/// -/// Each NativeExpressAdView object corresponds to a single AdMob Native Express -/// ad placement. There are methods to load an ad, move it, show it and hide it, -/// and retrieve the bounds of the ad onscreen. -/// -/// NativeExpressAdView objects maintain a presentation state that indicates -/// whether or not they're currently onscreen, as well as a set of bounds -/// (stored in a @ref BoundingBox struct), but otherwise provide information -/// about their current state through Futures. Methods like @ref Initialize, -/// @ref LoadAd, and @ref Hide each have a corresponding @ref Future from which -/// the result of the last call can be determined. The two variants of -/// @ref MoveTo share a single result @ref Future, since they're essentially the -/// same action. -/// -/// In addition, applications can create their own subclasses of -/// @ref NativeExpressAdView::Listener, pass an instance to the @ref SetListener -/// method, and receive callbacks whenever the presentation state or bounding -/// box of the ad changes. -/// -/// For example, you could initialize, load, and show a native express ad view -/// while checking the result of the previous action at each step as follows: -/// -/// @code -/// namespace admob = ::firebase::admob; -/// admob::NativeExpressAdView* ad_view = new admob::NativeExpressAdView(); -/// ad_view->Initialize(ad_parent, "YOUR_AD_UNIT_ID", desired_ad_size) -/// @endcode -/// -/// Then, later: -/// -/// @code -/// if (ad_view->InitializeLastResult().Status() == -/// ::firebase::kFutureStatusComplete && -/// ad_view->InitializeLastResult().Error() == -/// firebase::admob::kAdMobErrorNone) { -/// ad_view->LoadAd(your_ad_request); -/// } -/// @endcode -class NativeExpressAdView { - public: -#ifdef INTERNAL_EXPERIMENTAL -// LINT.IfChange -#endif // INTERNAL_EXPERIMENTAL - /// @deprecated - /// @brief The presentation state of a @ref NativeExpressAdView. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - enum PresentationState { - /// NativeExpressAdView is currently hidden. - kPresentationStateHidden = 0, - /// NativeExpressAdView is visible, but does not contain an ad. - kPresentationStateVisibleWithoutAd, - /// NativeExpressAdView is visible and contains an ad. - kPresentationStateVisibleWithAd, - /// NativeExpressAdView is visible and has opened a partial overlay on the - /// screen. - kPresentationStateOpenedPartialOverlay, - /// NativeExpressAdView is completely covering the screen or has caused - /// focus to leave the application (for example, when opening an external - /// browser during a clickthrough). - kPresentationStateCoveringUI, - }; -#ifdef INTERNAL_EXPERIMENTAL -// LINT.ThenChange(//depot_firebase_cpp/admob/client/cpp/src_java/com/google/firebase/admob/internal/cpp/ConstantsHelper.java) -#endif // INTERNAL_EXPERIMENTAL - -#ifdef INTERNAL_EXPERIMENTAL -// LINT.IfChange -#endif // INTERNAL_EXPERIMENTAL - /// @deprecated - /// @brief The possible screen positions for a @ref NativeExpressAdView. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - enum Position { - /// Top of the screen, horizontally centered. - kPositionTop = 0, - /// Bottom of the screen, horizontally centered. - kPositionBottom, - /// Top-left corner of the screen. - kPositionTopLeft, - /// Top-right corner of the screen. - kPositionTopRight, - /// Bottom-left corner of the screen. - kPositionBottomLeft, - /// Bottom-right corner of the screen. - kPositionBottomRight, - }; -#ifdef INTERNAL_EXPERIMENTAL -// LINT.ThenChange(//depot_firebase_cpp/admob/client/cpp/src_java/com/google/firebase/admob/internal/cpp/ConstantsHelper.java) -#endif // INTERNAL_EXPERIMENTAL - - /// @deprecated - /// @brief A listener class that developers can extend and pass to a - /// @ref NativeExpressAdView object's @ref SetListener method to be notified - /// of changes to the presentation state and bounding box. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - class Listener { - public: - /// @deprecated - /// @brief This method is called when the @ref NativeExpressAdView object's - /// presentation state changes. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - /// @param[in] ad_view The native express ad view whose presentation state - /// changed. - /// @param[in] state The new presentation state. - FIREBASE_DEPRECATED virtual void OnPresentationStateChanged( - NativeExpressAdView* ad_view, PresentationState state) = 0; - - /// @deprecated - /// @brief This method is called when the @ref NativeExpressAdView object's - /// bounding box changes. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - /// - /// @ref Initialize must be called before the object is used. - FIREBASE_DEPRECATED NativeExpressAdView(); - - ~NativeExpressAdView(); - - /// @deprecated - /// @brief Initializes the @ref NativeExpressAdView object. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - /// @param[in] parent The platform-specific UI element that will host the ad. - /// @param[in] ad_unit_id The ad unit ID to use when requesting ads. - /// @param[in] size The desired ad size for the native express ad. - FIREBASE_DEPRECATED Future Initialize(AdParent parent, - const char* ad_unit_id, - AdSize size); - - /// @deprecated - /// @brief Returns a @ref Future that has the status of the last call to - /// @ref Initialize. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - FIREBASE_DEPRECATED Future InitializeLastResult() const; - - /// @deprecated - /// @brief Begins an asynchronous request for an ad. If successful, the ad - /// will automatically be displayed in the NativeExpressAdView. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - /// @param[in] request An AdRequest struct with information about the request - /// to be made (such as targeting info). - FIREBASE_DEPRECATED Future LoadAd(const AdRequest& request); - - /// @deprecated - /// @brief Returns a @ref Future containing the status of the last call to - /// @ref LoadAd. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - FIREBASE_DEPRECATED Future LoadAdLastResult() const; - - /// @deprecated - /// @brief Hides the NativeExpressAdView. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - FIREBASE_DEPRECATED Future Hide(); - - /// @deprecated - /// @brief Returns a @ref Future containing the status of the last call to - /// @ref Hide. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - FIREBASE_DEPRECATED Future HideLastResult() const; - - /// @deprecated - /// @brief Shows the @ref NativeExpressAdView. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - FIREBASE_DEPRECATED Future Show(); - - /// @deprecated - /// @brief Returns a @ref Future containing the status of the last call to - /// @ref Show. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - FIREBASE_DEPRECATED Future ShowLastResult() const; - - /// @deprecated - /// @brief Pauses the @ref NativeExpressAdView. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - /// - /// Should be called whenever the C++ engine pauses or the application loses - /// focus. - FIREBASE_DEPRECATED Future Pause(); - - /// @deprecated - /// @brief Returns a @ref Future containing the status of the last call to - /// @ref Pause. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - FIREBASE_DEPRECATED Future PauseLastResult() const; - - /// @deprecated - /// @brief Resumes the @ref NativeExpressAdView after pausing. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - FIREBASE_DEPRECATED Future Resume(); - - /// @deprecated - /// @brief Returns a @ref Future containing the status of the last call to - /// @ref Resume. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - FIREBASE_DEPRECATED Future ResumeLastResult() const; - - /// @deprecated - /// @brief Cleans up and deallocates any resources used by the - /// @ref NativeExpressAdView. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - FIREBASE_DEPRECATED Future Destroy(); - - /// @deprecated - /// @brief Returns a @ref Future containing the status of the last call to - /// @ref Destroy. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - FIREBASE_DEPRECATED Future DestroyLastResult() const; - - /// @deprecated - /// @brief Moves the @ref NativeExpressAdView so that its top-left corner is - /// located at (x, y). Coordinates are in pixels from the top-left corner of - /// the screen. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - /// - /// When built for Android, the library will not display an ad on top of or - /// beneath an Activity's status bar. If a call to MoveTo would result in an - /// overlap, the @ref NativeExpressAdView is placed just below the status bar, - /// so no overlap occurs. - /// @param[in] x The desired horizontal coordinate. - /// @param[in] y The desired vertical coordinate. - FIREBASE_DEPRECATED Future MoveTo(int x, int y); - - /// @deprecated - /// @brief Moves the @ref NativeExpressAdView so that it's located at the - /// given pre-defined position. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - /// @param[in] position The pre-defined position to which to move the - /// @ref NativeExpressAdView. - FIREBASE_DEPRECATED Future MoveTo(Position position); - - /// @deprecated - /// @brief Returns a @ref Future containing the status of the last call to - /// either version of @ref MoveTo. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - FIREBASE_DEPRECATED Future MoveToLastResult() const; - - /// @deprecated - /// @brief Returns the current presentation state of the - /// @ref NativeExpressAdView. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - /// @return The current presentation state. - FIREBASE_DEPRECATED PresentationState GetPresentationState() const; - - /// @deprecated - /// @brief Retrieves the @ref NativeExpressAdView's current onscreen size and - /// location. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - /// @return The current size and location. Values are in pixels, and location - /// coordinates originate from the top-left corner of the screen. - FIREBASE_DEPRECATED BoundingBox GetBoundingBox() const; - - /// @deprecated - /// @brief Sets the @ref Listener for this object. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - /// @param[in] listener A valid NativeExpressAdView::Listener to receive - /// callbacks. - FIREBASE_DEPRECATED void SetListener(Listener* listener); - - private: - // An internal, platform-specific implementation object that this class uses - // to interact with the Google Mobile Ads SDKs for iOS and Android. - internal::NativeExpressAdViewInternal* internal_; -}; - -} // namespace admob -} // namespace firebase - -#endif // FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_NATIVE_EXPRESS_AD_VIEW_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/admob/rewarded_video.h b/packages/firebase_core/firebase_core/firebase_core/firebase/admob/rewarded_video.h deleted file mode 100644 index 32bea80b5550..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/admob/rewarded_video.h +++ /dev/null @@ -1,407 +0,0 @@ -/* - * Copyright 2016 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_REWARDED_VIDEO_H_ -#define FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_REWARDED_VIDEO_H_ - -#include -#include - -#include "firebase/admob/types.h" -#include "firebase/future.h" - -namespace firebase { - -// Forward declaration of Firebase's internal Mutex. -class Mutex; - -namespace admob { - -/// @deprecated The functionality in the firebase::admob namespace -/// has been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the new -/// SDK in our migration guide. -/// -/// @brief Loads and displays rewarded video ads via AdMob mediation. -/// -/// The rewarded_video namespace contains methods to load and display rewarded -/// video ads via the Google Mobile Ads SDK. The underlying SDK objects for -/// rewarded video on Android and iOS are singletons, so there are no objects -/// to represent individual ads here. Instead, methods in the rewarded_video -/// namespace are invoked to initialize, load, and show. -/// -/// The basic steps for loading and displaying an ad are: -/// -/// 1. Call @ref Initialize to init the library and mediation adapters. -/// 2. Call @ref LoadAd to load an ad (some SDKs may have cached an ad at init -/// time). -/// 3. Call @ref Show to show the ad to the user. -/// 4. Repeat steps 2 and 3 as desired. -/// 5. Call @ref Destroy when your app is completely finished showing rewarded -/// video ads. -/// -/// Note that Initialize must be the very first thing called, and @ref Destroy -/// must be the very last. -/// -/// The library maintains a presentation state that indicates whether or not an -/// ad is currently onscreen, but otherwise provides information about its -/// current state through Futures. @ref Initialize, @ref LoadAd, and so on each -/// have a corresponding @ref Future from which apps can determine the result of -/// the previous call. -/// -/// In addition, applications can create their own subclasses of @ref Listener, -/// pass an instance to the @ref SetListener method, and receive callbacks -/// whenever the presentation state changes or an ad has been viewed in full and -/// the user is due a reward. -/// -/// Here's how one might initialize, load, and show a rewarded video ad while -/// checking against the result of the previous action at each step: -/// -/// @code -/// firebase::admob::rewarded_video::Initialize(); -/// @endcode -/// -/// Then, later: -/// -/// @code -/// if (firebase::admob::rewarded_video::InitializeLastResult().status() == -/// firebase::kFutureStatusComplete && -/// firebase::admob::rewarded_video::InitializeLastResult().error() == -/// firebase::admob::kAdMobErrorNone) { -/// firebase::admob::rewarded_video::LoadAd(my_ad_unit_str, my_ad_request); -/// } -/// @endcode -/// -/// And after that: -/// -/// @code -/// if (firebase::admob::rewarded_video::LoadAdLastResult().status() == -/// firebase::kFutureStatusComplete && -/// firebase::admob::rewarded_video::LoadAdLastResult().error() == -/// firebase::admob::kAdMobErrorNone) { -/// firebase::admob::rewarded_video::Show(my_ad_parent); -/// } -/// @endcode -namespace rewarded_video { -#ifdef INTERNAL_EXPERIMENTAL -// LINT.IfChange -#endif // INTERNAL_EXPERIMENTAL -/// @deprecated -/// @brief The possible presentation states for rewarded video. -/// -/// The functionality in the firebase::admob namespace has -/// been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the -/// new SDK in our migration -/// guide. -enum PresentationState { - /// No ad is currently being shown. - kPresentationStateHidden = 0, - /// A rewarded video ad is completely covering the screen or has caused - /// focus to leave the application (for example, when opening an external - /// browser during a clickthrough), but the video associated with the ad has - /// yet to begin playing. - kPresentationStateCoveringUI, - /// All of the above conditions are true *except* that the video associated - /// with the ad began playing at some point in the past. - kPresentationStateVideoHasStarted, - /// The rewarded video has played and completed. - kPresentationStateVideoHasCompleted, -}; -#ifdef INTERNAL_EXPERIMENTAL -// LINT.ThenChange(//depot_firebase_cpp/admob/client/cpp/src_java/com/google/firebase/admob/internal/cpp/RewardedVideoHelper.java) -#endif // INTERNAL_EXPERIMENTAL - -/// @deprecated -/// @brief A reward to be given to the user in exchange for watching a rewarded -/// video ad. -/// -/// The functionality in the firebase::admob namespace has -/// been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the -/// new SDK in our migration -/// guide. -struct RewardItem { - /// The reward amount. - float amount; - /// A string description of the type of reward (such as "coins" or "points"). - std::string reward_type; -}; - -/// @deprecated -/// @brief A listener class that developers can extend and pass to @ref -/// SetListener to be notified of rewards and changes to the presentation state. -/// -/// The functionality in the firebase::admob namespace has -/// been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the -/// new SDK in our migration -/// guide. -class Listener { - public: - /// @deprecated - /// @brief Invoked when the user should be given a reward for watching an ad. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - /// @param[in] reward The user's reward. - FIREBASE_DEPRECATED virtual void OnRewarded(RewardItem reward) = 0; - - /// @deprecated - /// @brief Invoked when the presentation state of the ad changes. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - /// @param[in] state The new presentation state. - FIREBASE_DEPRECATED virtual void OnPresentationStateChanged( - PresentationState state) = 0; - - virtual ~Listener(); -}; - -/// @deprecated -/// @brief A polling-based listener that developers can instantiate and pass to -/// @ref SetListener in order to queue rewards for later retrieval. -/// -/// The functionality in the firebase::admob namespace has -/// been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the -/// new SDK in our migration -/// guide. -/// -/// The @ref PollReward method should be used to retrieve awards granted by the -/// Mobile Ads SDK and queued by this class. -/// @ref rewarded_video::presentation_state can be used to poll the current -/// presentation state, so no additional method has been added for it. -class PollableRewardListener : public Listener { - public: - /// @deprecated - /// @brief Default constructor. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - FIREBASE_DEPRECATED PollableRewardListener(); - ~PollableRewardListener(); - - /// @deprecated - /// @brief Invoked when the user should be given a reward for watching an ad. - /// - /// Deprecated. The functionality in the firebase::admob - /// namespace has been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the new - /// SDK in our migration - /// guide. - FIREBASE_DEPRECATED void OnRewarded(RewardItem reward); - - /// @deprecated - /// @brief nvoked when the presentation state of the ad changes. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - FIREBASE_DEPRECATED void OnPresentationStateChanged(PresentationState state); - - /// @deprecated - /// @brief Pop the oldest queued reward, and copy its data into the provided - /// RewardItem. - /// - /// The functionality in the firebase::admob namespace has - /// been replaced by the Google Mobile Ads SDK in the - /// firebase::gma namespace. Learn how to transition to the - /// new SDK in our migration - /// guide. - /// - /// If no reward is available, the struct is unchanged. - /// @param reward Pointer to a struct that reward data can be copied into. - /// @returns true if a reward was popped and data was copied, false otherwise. - FIREBASE_DEPRECATED bool PollReward(RewardItem* reward); - - private: - Mutex* mutex_; - - // Rewards granted by the Mobile Ads SDK. - std::queue rewards_; -}; - -/// @deprecated -/// @brief Initializes rewarded video. This must be the first method invoked in -/// this namespace. -/// -/// The functionality in the firebase::admob namespace has -/// been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the -/// new SDK in our migration -/// guide. -FIREBASE_DEPRECATED Future Initialize(); - -/// @deprecated -/// @brief Returns a @ref Future that has the status of the last call to -/// @ref Initialize. -/// -/// The functionality in the firebase::admob namespace has -/// been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the -/// new SDK in our migration -/// guide. -FIREBASE_DEPRECATED Future InitializeLastResult(); - -/// @deprecated -/// @brief Begins an asynchronous request for an ad. -/// -/// The functionality in the firebase::admob namespace has -/// been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the -/// new SDK in our migration -/// guide. -/// @param[in] ad_unit_id The ad unit ID to use in the request. -/// @param[in] request An AdRequest struct with information about the request -/// to be made (such as targeting info). -FIREBASE_DEPRECATED Future LoadAd(const char* ad_unit_id, - const AdRequest& request); - -/// @deprecated -/// @brief Returns a @ref Future containing the status of the last call to -/// @ref LoadAd. -/// -/// The functionality in the firebase::admob namespace has -/// been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the -/// new SDK in our migration -/// guide. -FIREBASE_DEPRECATED Future LoadAdLastResult(); - -/// @deprecated -/// @brief Shows an ad, assuming one has loaded. -/// -/// The functionality in the firebase::admob namespace has -/// been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the -/// new SDK in our migration -/// guide. -/// -/// @ref LoadAd must be called before this method. -/// @param[in] parent An @ref AdParent that is a reference to an iOS -/// UIView or an Android Activity. -FIREBASE_DEPRECATED Future Show(AdParent parent); - -/// @deprecated -/// @brief Returns a @ref Future containing the status of the last call to -/// @ref Show. -/// -/// Deprecated. The functionality in the firebase::admob -/// namespace has been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the new -/// SDK in our migration -/// guide. -FIREBASE_DEPRECATED Future ShowLastResult(); - -/// @deprecated -/// @brief Pauses any background processing associated with rewarded video. -/// -/// The functionality in the firebase::admob namespace has -/// been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the -/// new SDK in our migration -/// guide. -/// -/// Should be called whenever the C++ engine pauses or the application loses -/// focus. -FIREBASE_DEPRECATED Future Pause(); - -/// @deprecated -/// @brief Returns a @ref Future containing the status of the last call to -/// @ref Pause. -/// -/// The functionality in the firebase::admob namespace has -/// been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the -/// new SDK in our migration -/// guide. -FIREBASE_DEPRECATED Future PauseLastResult(); - -/// @deprecated -/// @brief Resumes the rewarded video system after pausing. -/// -/// The functionality in the firebase::admob namespace has -/// been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the -/// new SDK in our migration -/// guide. -FIREBASE_DEPRECATED Future Resume(); - -/// @deprecated -/// @brief Returns a @ref Future containing the status of the last call to -/// @ref Resume. -/// -/// The functionality in the firebase::admob namespace has -/// been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the -/// new SDK in our migration -/// guide. -FIREBASE_DEPRECATED Future ResumeLastResult(); - -/// @deprecated -/// @brief Cleans up and deallocates any resources used by rewarded video. -/// -/// The functionality in the firebase::admob namespace has -/// been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the -/// new SDK in our migration -/// guide. -/// -/// No other methods in rewarded_video should be called once this method has -/// been invoked. The system is closed for business at that point. -FIREBASE_DEPRECATED void Destroy(); - -/// @deprecated -/// @brief Returns the current presentation state, indicating if an ad is -/// visible or if a video has started playing. -/// -/// The functionality in the firebase::admob namespace has -/// been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the -/// new SDK in our migration -/// guide. -/// @return The current presentation state. -FIREBASE_DEPRECATED PresentationState presentation_state(); - -/// @deprecated -/// @brief Sets the @ref Listener that should receive callbacks. -/// -/// The functionality in the firebase::admob namespace has -/// been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the -/// new SDK in our migration -/// guide. -/// @param[in] listener A valid Listener. -FIREBASE_DEPRECATED void SetListener(Listener* listener); - -} // namespace rewarded_video -} // namespace admob -} // namespace firebase - -#endif // FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_REWARDED_VIDEO_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/admob/types.h b/packages/firebase_core/firebase_core/firebase_core/firebase/admob/types.h deleted file mode 100644 index 21a8379f2d96..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/admob/types.h +++ /dev/null @@ -1,244 +0,0 @@ -/* - * Copyright 2016 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_TYPES_H_ -#define FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_TYPES_H_ - -#include "firebase/internal/platform.h" - -#if FIREBASE_PLATFORM_ANDROID -#include -#elif FIREBASE_PLATFORM_IOS || FIREBASE_PLATFORM_TVOS -extern "C" { -#include -} // extern "C" -#endif // FIREBASE_PLATFORM_ANDROID, FIREBASE_PLATFORM_IOS, - // FIREBASE_PLATFORM_TVOS - -namespace firebase { -namespace admob { - -/// @deprecated The functionality in the firebase::admob namespace -/// has been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the new -/// SDK in our migration guide. -/// -/// @brief This is a platform specific datatype that is required to create an -/// AdMob ad. -/// -/// The following defines the datatype on each platform: -///

    -///
  • Android: A `jobject` which references an Android Activity.
  • -///
  • iOS: An `id` which references an iOS UIView.
  • -///
-/// -#if FIREBASE_PLATFORM_ANDROID -/// An Android Activity from Java. -typedef jobject AdParent; -#elif FIREBASE_PLATFORM_IOS || FIREBASE_PLATFORM_TVOS -/// A pointer to an iOS UIView. -typedef id AdParent; -#else -/// A void pointer for stub classes. -typedef void *AdParent; -#endif // FIREBASE_PLATFORM_ANDROID, FIREBASE_PLATFORM_IOS, - // FIREBASE_PLATFORM_TVOS - -#ifdef INTERNAL_EXPERIMENTAL -// LINT.IfChange -#endif // INTERNAL_EXPERIMENTAL -/// @deprecated -/// @brief Error codes returned by Future::error(). -/// -/// The functionality in the firebase::admob namespace has -/// been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the -/// new SDK in our migration -/// guide. -enum AdMobError { - /// Call completed successfully. - kAdMobErrorNone, - /// The ad has not been fully initialized. - kAdMobErrorUninitialized, - /// The ad is already initialized (repeat call). - kAdMobErrorAlreadyInitialized, - /// A call has failed because an ad is currently loading. - kAdMobErrorLoadInProgress, - /// A call to load an ad has failed due to an internal SDK error. - kAdMobErrorInternalError, - /// A call to load an ad has failed due to an invalid request. - kAdMobErrorInvalidRequest, - /// A call to load an ad has failed due to a network error. - kAdMobErrorNetworkError, - /// A call to load an ad has failed because no ad was available to serve. - kAdMobErrorNoFill, - /// An attempt has been made to show an ad on an Android Activity that has - /// no window token (such as one that's not done initializing). - kAdMobErrorNoWindowToken, - /// Fallback error for any unidentified cases. - kAdMobErrorUnknown, -}; -#ifdef INTERNAL_EXPERIMENTAL -// LINT.ThenChange(//depot_firebase_cpp/admob/client/cpp/src_java/com/google/firebase/admob/internal/cpp/ConstantsHelper.java) -#endif // INTERNAL_EXPERIMENTAL - -/// @deprecated -/// @brief Types of ad sizes. -/// -/// The functionality in the firebase::admob namespace has -/// been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the -/// new SDK in our migration -/// guide. -enum AdSizeType { kAdSizeStandard = 0 }; - -/// @deprecated -/// @brief An ad size value to be used in requesting ads. -/// -/// The functionality in the firebase::admob namespace has -/// been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the -/// new SDK in our migration -/// guide. -struct AdSize { - /// The type of ad size. - AdSizeType ad_size_type; - /// Height of the ad (in points or dp). - int height; - /// Width of the ad (in points or dp). - int width; -}; - -/// @deprecated -/// @brief Gender information used as part of the -/// @ref firebase::admob::AdRequest struct. -/// -/// The functionality in the firebase::admob namespace has -/// been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the -/// new SDK in our migration -/// guide. -enum Gender { - /// The gender of the current user is unknown or unspecified by the - /// publisher. - kGenderUnknown = 0, - /// The current user is known to be male. - kGenderMale, - /// The current user is known to be female. - kGenderFemale -}; - -/// @deprecated -/// @brief Indicates whether an ad request is considered tagged for -/// child-directed treatment. -/// -/// The functionality in the firebase::admob namespace has -/// been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the -/// new SDK in our migration -/// guide. -enum ChildDirectedTreatmentState { - /// The child-directed status for the request is not indicated. - kChildDirectedTreatmentStateUnknown = 0, - /// The request is tagged for child-directed treatment. - kChildDirectedTreatmentStateTagged, - /// The request is not tagged for child-directed treatment. - kChildDirectedTreatmentStateNotTagged -}; - -/// @deprecated -/// @brief Generic Key-Value container used for the "extras" values in an -/// @ref firebase::admob::AdRequest. -/// -/// The functionality in the firebase::admob namespace has -/// been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the -/// new SDK in our migration -/// guide. -struct KeyValuePair { - /// The name for an "extra." - const char *key; - /// The value for an "extra." - const char *value; -}; - -/// @deprecated -/// @brief The information needed to request an ad. -/// -/// The functionality in the firebase::admob namespace has -/// been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the -/// new SDK in our migration -/// guide. -struct AdRequest { - /// An array of test device IDs specifying devices that test ads will be - /// returned for. - const char **test_device_ids; - /// The number of entries in the array referenced by test_device_ids. - unsigned int test_device_id_count; - /// An array of keywords or phrases describing the current user activity, such - /// as "Sports Scores" or "Football." - const char **keywords; - /// The number of entries in the array referenced by keywords. - unsigned int keyword_count; - /// A @ref KeyValuePair specifying additional parameters accepted by an ad - /// network. - const KeyValuePair *extras; - /// The number of entries in the array referenced by extras. - unsigned int extras_count; - /// The day the user was born. Specify the user's birthday to increase ad - /// relevancy. - int birthday_day; - /// The month the user was born. Specify the user's birthday to increase ad - /// relevancy. - int birthday_month; - /// The year the user was born. Specify the user's birthday to increase ad - /// relevancy. - int birthday_year; - /// The user's @ref Gender. Specify the user's gender to increase ad - /// relevancy. - Gender gender; - /// Specifies whether the request should be considered as child-directed for - /// purposes of the Children’s Online Privacy Protection Act (COPPA). - ChildDirectedTreatmentState tagged_for_child_directed_treatment; -}; - -/// @deprecated -/// @brief The screen location and dimensions of an ad view once it has been -/// initialized. -/// -/// The functionality in the firebase::admob namespace has -/// been replaced by the Google Mobile Ads SDK in the -/// firebase::gma namespace. Learn how to transition to the -/// new SDK in our migration -/// guide. -struct BoundingBox { - /// Default constructor which initializes all member variables to 0. - BoundingBox() : height(0), width(0), x(0), y(0) {} - /// Height of the ad in pixels. - int height; - /// Width of the ad in pixels. - int width; - /// Horizontal position of the ad in pixels from the left. - int x; - /// Vertical position of the ad in pixels from the top. - int y; -}; - -} // namespace admob -} // namespace firebase - -#endif // FIREBASE_ADMOB_SRC_INCLUDE_FIREBASE_ADMOB_TYPES_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/analytics.h b/packages/firebase_core/firebase_core/firebase_core/firebase/analytics.h deleted file mode 100644 index 973890b20fce..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/analytics.h +++ /dev/null @@ -1,569 +0,0 @@ -/* - * Copyright 2016 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_ANALYTICS_SRC_INCLUDE_FIREBASE_ANALYTICS_H_ -#define FIREBASE_ANALYTICS_SRC_INCLUDE_FIREBASE_ANALYTICS_H_ - -#include -#include -#include -#include - -#include "firebase/app.h" -#include "firebase/future.h" -#include "firebase/internal/common.h" -#include "firebase/variant.h" - -#if !defined(DOXYGEN) && !defined(SWIG) -FIREBASE_APP_REGISTER_CALLBACKS_REFERENCE(analytics) -#endif // !defined(DOXYGEN) && !defined(SWIG) - -/// @brief Namespace that encompasses all Firebase APIs. -namespace firebase { - -/// @brief Firebase Analytics API. -/// -/// See the developer guides for general -/// information on using Firebase Analytics in your apps. -namespace analytics { - -/// @brief Event parameter. -/// -/// Parameters supply information that contextualize events (see @ref LogEvent). -/// You can associate up to 25 unique Parameters with each event type (name). -/// -/// -/// @if swig_examples -/// Common event types are provided as static properties of the -/// FirebaseAnalytics class (e.g FirebaseAnalytics.EventPostScore) where -/// parameters of these events are also provided in this FirebaseAnalytics -/// class (e.g FirebaseAnalytics.ParameterScore). -/// -/// You are not limited to the set of event types and parameter names -/// suggested in FirebaseAnalytics class properties. Additional Parameters can -/// be supplied for suggested event types or custom Parameters for custom event -/// types. -/// @endif -/// -/// @if cpp_examples -/// Common event types (names) are suggested in @ref event_names -/// (%event_names.h) with parameters of common event types defined in -/// @ref parameter_names (%parameter_names.h). -/// -/// You are not limited to the set of event types and parameter names suggested -/// in @ref event_names (%event_names.h) and %parameter_names.h respectively. -/// Additional Parameters can be supplied for suggested event types or custom -/// Parameters for custom event types. -/// @endif -/// -/// Parameter names must be a combination of letters and digits -/// (matching the regular expression [a-zA-Z0-9]) between 1 and 40 characters -/// long starting with a letter [a-zA-Z] character. The "firebase_", -/// "google_" and "ga_" prefixes are reserved and should not be used. -/// -/// Parameter string values can be up to 100 characters long. -/// -/// -/// @if swig_examples -/// An array of Parameter class instances can be passed to LogEvent in order -/// to associate parameters's of an event with values where each value can be -/// a double, 64-bit integer or string. -/// @endif -/// -/// @if cpp_examples -/// An array of this structure is passed to LogEvent in order to associate -/// parameter's of an event (Parameter::name) with values (Parameter::value) -/// where each value can be a double, 64-bit integer or string. -/// @endif -/// -/// For example, a game may log an achievement event along with the -/// character the player is using and the level they're currently on: -/// -/// -/// @if swig_examples -/// @code{.cs} -/// using Firebase.Analytics; -/// -/// int currentLevel = GetCurrentLevel(); -/// Parameter[] AchievementParameters = { -/// new Parameter(FirebaseAnalytics.ParameterAchievementID, -/// "ultimate_wizard"), -/// new Parameter(FirebaseAnalytics.ParameterCharacter, "mysterion"), -/// new Parameter(FirebaseAnalytics.ParameterLevel, currentLevel), -/// }; -/// FirebaseAnalytics.LogEvent(FirebaseAnalytics.EventLevelUp, -/// AchievementParameters); -/// @endcode -/// @endif -/// -/// @if cpp_examples -/// @code{.cpp} -/// using namespace firebase::analytics; -/// int64_t current_level = GetCurrentLevel(); -/// const Parameter achievement_parameters[] = { -/// Parameter(kParameterAchievementID, "ultimate_wizard"), -/// Parameter(kParameterCharacter, "mysterion"), -/// Parameter(kParameterLevel, current_level), -/// }; -/// LogEvent(kEventUnlockAchievement, achievement_parameters, -/// sizeof(achievement_parameters) / -/// sizeof(achievement_parameters[0])); -/// @endcode -/// @endif -/// -struct Parameter { -#ifndef SWIG - /// Construct an empty parameter. - /// - /// This is provided to allow initialization after construction. - Parameter() : name(nullptr) {} -#endif // !SWIG - -// -// We don't want to pull in Variant in the C# interface. -// -#ifndef SWIG - /// Construct a parameter. - /// - /// @param parameter_name Name of the parameter (see Parameter::name). - /// @param parameter_value Value for the parameter. Variants can - /// hold numbers and strings. - Parameter(const char* parameter_name, Variant parameter_value) - : name(parameter_name) { - value = parameter_value; - } -#endif // !SWIG - - /// Construct a 64-bit integer parameter. - /// - /// @param parameter_name Name of the parameter. - /// @if cpp_examples - /// (see Parameter::name). - /// @endif - /// - /// @if swig_examples - /// Parameter names must be a combination of letters and digits - /// (matching the regular expression [a-zA-Z0-9]) between 1 and 40 characters - /// long starting with a letter [a-zA-Z] character. - /// @endif - /// - /// @param parameter_value Integer value for the parameter. - Parameter(const char* parameter_name, int parameter_value) - : name(parameter_name) { - value = parameter_value; - } - - /// Construct a 64-bit integer parameter. - /// - /// @param parameter_name Name of the parameter. - /// @if cpp_examples - /// (see Parameter::name). - /// @endif - /// - /// @if swig_examples - /// Parameter names must be a combination of letters and digits - /// (matching the regular expression [a-zA-Z0-9]) between 1 and 40 characters - /// long starting with a letter [a-zA-Z] character. - /// @endif - /// - /// @param parameter_value Integer value for the parameter. - Parameter(const char* parameter_name, int64_t parameter_value) - : name(parameter_name) { - value = parameter_value; - } - - /// Construct a floating point parameter. - /// - /// @param parameter_name Name of the parameter. - /// @if cpp_examples - /// (see Parameter::name). - /// @endif - /// - /// @if swig_examples - /// Parameter names must be a combination of letters and digits - /// (matching the regular expression [a-zA-Z0-9]) between 1 and 40 characters - /// long starting with a letter [a-zA-Z] character. - /// @endif - /// - /// @param parameter_value Floating point value for the parameter. - Parameter(const char* parameter_name, double parameter_value) - : name(parameter_name) { - value = parameter_value; - } - - /// Construct a string parameter. - /// - /// @param parameter_name Name of the parameter. - /// @if cpp_examples - /// (see Parameter::name). - /// @endif - /// - /// @if swig_examples - /// Parameter names must be a combination of letters and digits - /// (matching the regular expression [a-zA-Z0-9]) between 1 and 40 characters - /// long starting with a letter [a-zA-Z] character. - /// @endif - /// - /// @param parameter_value String value for the parameter, can be up to 100 - /// characters long. - Parameter(const char* parameter_name, const char* parameter_value) - : name(parameter_name) { - value = parameter_value; - } - -#ifndef SWIG - // - // Skipping implementation values because the C# API members are - // immutable, and there's no other need to read these values in - // C#. The class just needs to be passed to the C++ layers. - // This also avoids having to solve the nested union, which is - // unsupported in swig. - // - - /// @brief Name of the parameter. - /// - /// Parameter names must be a combination of letters and digits - /// (matching the regular expression [a-zA-Z0-9]) between 1 and 40 characters - /// long starting with a letter [a-zA-Z] character. The "firebase_", - /// "google_" and "ga_" prefixes are reserved and should not be used. - const char* name; - /// @brief Value of the parameter. - /// - /// See firebase::Variant for usage information. - /// @note String values can be up to 100 characters long. - Variant value; -#endif // SWIG -}; - -/// @brief Initialize the Analytics API. -/// -/// This must be called prior to calling any other methods in the -/// firebase::analytics namespace. -/// -/// @param[in] app Default @ref firebase::App instance. -/// -/// @see firebase::App::GetInstance(). -void Initialize(const App& app); - -/// @brief Terminate the Analytics API. -/// -/// Cleans up resources associated with the API. -void Terminate(); - -/// @brief Sets whether analytics collection is enabled for this app on this -/// device. -/// -/// This setting is persisted across app sessions. By default it is enabled. -/// -/// @param[in] enabled true to enable analytics collection, false to disable. -void SetAnalyticsCollectionEnabled(bool enabled); - -/// @brief The type of consent to set. -/// -/// Supported consent types are kConsentTypeAdStorage and -/// kConsentTypeAnalyticsStorage. Omitting a type retains its previous status. -enum ConsentType { kConsentTypeAdStorage = 0, kConsentTypeAnalyticsStorage }; - -/// @brief The status value of the consent type. -/// -/// Supported statuses are kConsentStatusGranted and kConsentStatusDenied. -enum ConsentStatus { kConsentStatusGranted = 0, kConsentStatusDenied }; - -/// @brief Sets the applicable end user consent state (e.g., for device -/// identifiers) for this app on this device. -/// -/// Use the consent map to specify individual consent type values. Settings are -/// persisted across app sessions. By default consent types are set to -/// "granted". -void SetConsent(const std::map& consent_settings); - -/// @brief Log an event with one string parameter. -/// -/// @param[in] name Name of the event to log. Should contain 1 to 40 -/// alphanumeric characters or underscores. The name must start with an -/// alphabetic character. Some event names are reserved. -/// -/// @if swig_examples -/// See the FirebaseAnalytics.Event properties for the list of reserved event -/// names. -/// @endif -/// -/// @if cpp_examples -/// See @ref event_names (%event_names.h) for the list of reserved event names. -/// @endif -/// The "firebase_" prefix is reserved and should not be used. Note that event -/// names are case-sensitive and that logging two events whose names differ -/// only in case will result in two distinct events. -/// @param[in] parameter_name Name of the parameter to log. -/// For more information, see @ref Parameter. -/// @param[in] parameter_value Value of the parameter to log. -/// -/// -/// @if swig_examples -/// @see LogEvent(string, Parameter[]) -/// @endif -/// -/// @if cpp_examples -/// @see LogEvent(const char*, const Parameter*, size_t) -/// @endif -void LogEvent(const char* name, const char* parameter_name, - const char* parameter_value); - -/// @brief Log an event with one float parameter. -/// -/// @param[in] name Name of the event to log. Should contain 1 to 40 -/// alphanumeric characters or underscores. The name must start with an -/// alphabetic character. Some event names are reserved. -/// -/// @if swig_examples -/// See the FirebaseAnalytics.Event properties for the list of reserved event -/// names. -/// @endif -/// -/// @if cpp_examples -/// See @ref event_names (%event_names.h) for the list of reserved event names. -/// @endif -/// The "firebase_" prefix is reserved and should not be used. Note that event -/// names are case-sensitive and that logging two events whose names differ -/// only in case will result in two distinct events. -/// @param[in] parameter_name Name of the parameter to log. -/// For more information, see @ref Parameter. -/// @param[in] parameter_value Value of the parameter to log. -/// -/// -/// @if swig_examples -/// @see LogEvent(string, Parameter[]) -/// @endif -/// -/// @if cpp_examples -/// @see LogEvent(const char*, const Parameter*, size_t) -/// @endif -void LogEvent(const char* name, const char* parameter_name, - const double parameter_value); - -/// @brief Log an event with one 64-bit integer parameter. -/// -/// @param[in] name Name of the event to log. Should contain 1 to 40 -/// alphanumeric characters or underscores. The name must start with an -/// alphabetic character. Some event names are reserved. -/// -/// @if swig_examples -/// See the FirebaseAnalytics.Event properties for the list of reserved event -/// names. -/// @endif -/// -/// @if cpp_examples -/// See @ref event_names (%event_names.h) for the list of reserved event names. -/// @endif -/// The "firebase_" prefix is reserved and should not be used. Note that event -/// names are case-sensitive and that logging two events whose names differ -/// only in case will result in two distinct events. -/// @param[in] parameter_name Name of the parameter to log. -/// For more information, see @ref Parameter. -/// @param[in] parameter_value Value of the parameter to log. -/// -/// -/// @if swig_examples -/// @see LogEvent(string, Parameter[]) -/// @endif -/// -/// @if cpp_examples -/// @see LogEvent(const char*, const Parameter*, size_t) -/// @endif -void LogEvent(const char* name, const char* parameter_name, - const int64_t parameter_value); - -/// @brief Log an event with one integer parameter -/// (stored as a 64-bit integer). -/// -/// @param[in] name Name of the event to log. Should contain 1 to 40 -/// alphanumeric characters or underscores. The name must start with an -/// alphabetic character. Some event names are reserved. -/// -/// @if swig_examples -/// See the FirebaseAnalytics.Event properties for the list of reserved event -/// names. -/// @endif -/// -/// @if cpp_examples -/// See @ref event_names (%event_names.h) for the list of reserved event names. -/// @endif -/// The "firebase_" prefix is reserved and should not be used. Note that event -/// names are case-sensitive and that logging two events whose names differ -/// only in case will result in two distinct events. -/// @param[in] parameter_name Name of the parameter to log. -/// For more information, see @ref Parameter. -/// @param[in] parameter_value Value of the parameter to log. -/// -/// -/// @if swig_examples -/// @see LogEvent(string, Parameter[]) -/// @endif -/// -/// @if cpp_examples -/// @see LogEvent(const char*, const Parameter*, size_t) -/// @endif -void LogEvent(const char* name, const char* parameter_name, - const int parameter_value); - -/// @brief Log an event with no parameters. -/// -/// @param[in] name Name of the event to log. Should contain 1 to 40 -/// alphanumeric characters or underscores. The name must start with an -/// alphabetic character. Some event names are reserved. -/// -/// @if swig_examples -/// See the FirebaseAnalytics.Event properties for the list of reserved event -/// names. -/// @endif -/// -/// @if cpp_examples -/// See @ref event_names (%event_names.h) for the list of reserved event names. -/// @endif -/// The "firebase_" prefix is reserved and should not be used. Note that event -/// names are case-sensitive and that logging two events whose names differ -/// only in case will result in two distinct events. -/// -/// -/// @if swig_examples -/// @see LogEvent(string, Parameter[]) -/// @endif -/// -/// @if cpp_examples -/// @see LogEvent(const char*, const Parameter*, size_t) -/// @endif -void LogEvent(const char* name); - -// clang-format off -#ifdef SWIG -// Modify the following overload with unsafe, so that we can do some pinning -// in the C# code. -%csmethodmodifiers LogEvent "public unsafe" -#endif // SWIG -// clang-format on - -/// @brief Log an event with associated parameters. -/// -/// An Event is an important occurrence in your app that you want to -/// measure. You can report up to 500 different types of events per app and -/// you can associate up to 25 unique parameters with each Event type. -/// -/// Some common events are documented in @ref event_names (%event_names.h), -/// but you may also choose to specify custom event types that are associated -/// with your specific app. -/// -/// @param[in] name Name of the event to log. Should contain 1 to 40 -/// alphanumeric characters or underscores. The name must start with an -/// alphabetic character. Some event names are reserved. See @ref event_names -/// (%event_names.h) for the list of reserved event names. The "firebase_" -/// prefix is reserved and should not be used. Note that event names are -/// case-sensitive and that logging two events whose names differ only in -/// case will result in two distinct events. -/// @param[in] parameters Array of Parameter structures. -/// @param[in] number_of_parameters Number of elements in the parameters -/// array. -void LogEvent(const char* name, const Parameter* parameters, - size_t number_of_parameters); - -/// Initiates on-device conversion measurement given a user email address on iOS -/// and tvOS (no-op on Android). On iOS and tvOS, this method requires the -/// dependency GoogleAppMeasurementOnDeviceConversion to be linked in, -/// otherwise the invocation results in a no-op. -/// @param[in] email_address User email address. Include a domain name for all -/// email addresses (e.g. gmail.com or hotmail.co.jp). -void InitiateOnDeviceConversionMeasurementWithEmailAddress( - const char* email_address); - -/// @brief Set a user property to the given value. -/// -/// Properties associated with a user allow a developer to segment users -/// into groups that are useful to their application. Up to 25 properties -/// can be associated with a user. -/// -/// Suggested property names are listed @ref user_property_names -/// (%user_property_names.h) but you're not limited to this set. For example, -/// the "gamertype" property could be used to store the type of player where -/// a range of values could be "casual", "mid_core", or "core". -/// -/// @param[in] name Name of the user property to set. This must be a -/// combination of letters and digits (matching the regular expression -/// [a-zA-Z0-9] between 1 and 40 characters long starting with a letter -/// [a-zA-Z] character. -/// @param[in] property Value to set the user property to. Set this -/// argument to NULL or nullptr to remove the user property. The value can be -/// between 1 to 100 characters long. -void SetUserProperty(const char* name, const char* property); - -/// @brief Sets the user ID property. -/// -/// This feature must be used in accordance with -/// Google's Privacy -/// Policy -/// -/// @param[in] user_id The user ID associated with the user of this app on this -/// device. The user ID must be non-empty and no more than 256 characters long. -/// Setting user_id to NULL or nullptr removes the user ID. -void SetUserId(const char* user_id); - -/// @brief Sets the duration of inactivity that terminates the current session. -/// -/// @note The default value is 1800000 (30 minutes). -/// -/// @param milliseconds The duration of inactivity that terminates the current -/// session. -void SetSessionTimeoutDuration(int64_t milliseconds); - -/// Clears all analytics data for this app from the device and resets the app -/// instance id. -void ResetAnalyticsData(); - -/// Get the instance ID from the analytics service. -/// -/// @note This is *not* the same ID as the ID returned by -/// @if cpp_examples -/// firebase::instance_id::InstanceId. -/// @else -/// Firebase.InstanceId.FirebaseInstanceId. -/// @endif -/// -/// @returns Object which can be used to retrieve the analytics instance ID. -Future GetAnalyticsInstanceId(); - -/// Get the result of the most recent GetAnalyticsInstanceId() call. -/// -/// @returns Object which can be used to retrieve the analytics instance ID. -Future GetAnalyticsInstanceIdLastResult(); - -/// Asynchronously retrieves the identifier of the current app -/// session. -/// -/// The session ID retrieval could fail due to Analytics collection -/// disabled, or if the app session was expired. -/// -/// @returns Object which can be used to retrieve the identifier of the current -/// app session. -Future GetSessionId(); - -/// Get the result of the most recent GetSessionId() call. -/// -/// @returns Object which can be used to retrieve the identifier of the current -/// app session. -Future GetSessionIdLastResult(); - -} // namespace analytics -} // namespace firebase - -#endif // FIREBASE_ANALYTICS_SRC_INCLUDE_FIREBASE_ANALYTICS_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/analytics/event_names.h b/packages/firebase_core/firebase_core/firebase_core/firebase/analytics/event_names.h deleted file mode 100644 index 4f1d4e5a0e2b..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/analytics/event_names.h +++ /dev/null @@ -1,472 +0,0 @@ -// Copyright 2023 Google Inc. All Rights Reserved. - -#ifndef FIREBASE_ANALYTICS_CLIENT_CPP_INCLUDE_FIREBASE_ANALYTICS_EVENT_NAMES_H_ -#define FIREBASE_ANALYTICS_CLIENT_CPP_INCLUDE_FIREBASE_ANALYTICS_EVENT_NAMES_H_ - -/// @brief Namespace that encompasses all Firebase APIs. -namespace firebase { -/// @brief Firebase Analytics API. -namespace analytics { - - - -/// @defgroup event_names Analytics Events -/// -/// Predefined event names. -/// -/// An Event is an important occurrence in your app that you want to -/// measure. You can report up to 500 different types of Events per app -/// and you can associate up to 25 unique parameters with each Event type. -/// Some common events are suggested below, but you may also choose to -/// specify custom Event types that are associated with your specific app. -/// Each event type is identified by a unique name. Event names can be up -/// to 40 characters long, may only contain alphanumeric characters and -/// underscores ("_"), and must start with an alphabetic character. The -/// "firebase_", "google_", and "ga_" prefixes are reserved and should not -/// be used. -/// @{ - - -/// Ad Impression event. This event signifies when a user sees an ad -/// impression. Note: If you supply the @c AnalyticsParameterValue -/// parameter, you must also supply the @c AnalyticsParameterCurrency -/// parameter so that revenue metrics can be computed accurately. Params: -/// -///
    -///
  • @c AnalyticsParameterAdPlatform (String) (optional)
  • -///
  • @c AnalyticsParameterAdFormat (String) (optional)
  • -///
  • @c AnalyticsParameterAdSource (String) (optional)
  • -///
  • @c AnalyticsParameterAdUnitName (String) (optional)
  • -///
  • @c AnalyticsParameterCurrency (String) (optional)
  • -///
  • @c AnalyticsParameterValue (Double) (optional)
  • -///
-static const char*const kEventAdImpression = - "ad_impression"; - -/// Add Payment Info event. This event signifies that a user has submitted -/// their payment information. Note: If you supply the @c -/// AnalyticsParameterValue parameter, you must also supply the @c -/// AnalyticsParameterCurrency parameter so that revenue metrics can be -/// computed accurately. Params: -/// -///
    -///
  • @c AnalyticsParameterCoupon (String) (optional)
  • -///
  • @c AnalyticsParameterCurrency (String) (optional)
  • -///
  • @c AnalyticsParameterItems ([[String: Any]]) (optional)
  • -///
  • @c AnalyticsParameterPaymentType (String) (optional)
  • -///
  • @c AnalyticsParameterValue (Double) (optional)
  • -///
-static const char*const kEventAddPaymentInfo = - "add_payment_info"; - -/// Add Shipping Info event. This event signifies that a user has -/// submitted their shipping information. Note: If you supply the @c -/// AnalyticsParameterValue parameter, you must also supply the @c -/// AnalyticsParameterCurrency parameter so that revenue metrics can be -/// computed accurately. Params: -/// -///
    -///
  • @c AnalyticsParameterCoupon (String) (optional)
  • -///
  • @c AnalyticsParameterCurrency (String) (optional)
  • -///
  • @c AnalyticsParameterItems ([[String: Any]]) (optional)
  • -///
  • @c AnalyticsParameterShippingTier (String) (optional)
  • -///
  • @c AnalyticsParameterValue (Double) (optional)
  • -///
-static const char*const kEventAddShippingInfo = - "add_shipping_info"; - -/// E-Commerce Add To Cart event. This event signifies that an item(s) was -/// added to a cart for purchase. Add this event to a funnel with @c -/// AnalyticsEventPurchase to gauge the effectiveness of your -/// checParameter(kout, If you supply the @c AnalyticsParameterValue -/// parameter), you must also supply the @c AnalyticsParameterCurrency -/// parameter so that revenue metrics can be computed accurately. Params: -/// -///
    -///
  • @c AnalyticsParameterCurrency (String) (optional)
  • -///
  • @c AnalyticsParameterItems ([[String: Any]]) (optional)
  • -///
  • @c AnalyticsParameterValue (Double) (optional)
  • -///
-static const char*const kEventAddToCart = "add_to_cart"; - -/// E-Commerce Add To Wishlist event. This event signifies that an item -/// was added to a wishlist. Use this event to identify popular gift -/// items. Note: If you supply the @c AnalyticsParameterValue parameter, -/// you must also supply the @c AnalyticsParameterCurrency parameter so -/// that revenue metrics can be computed accurately. Params: -/// -///
    -///
  • @c AnalyticsParameterCurrency (String) (optional)
  • -///
  • @c AnalyticsParameterItems ([[String: Any]]) (optional)
  • -///
  • @c AnalyticsParameterValue (Double) (optional)
  • -///
-static const char*const kEventAddToWishlist = - "add_to_wishlist"; - -/// App Open event. By logging this event when an App becomes active, -/// developers can understand how often users leave and return during the -/// course of a Session. Although Sessions are automatically reported, -/// this event can provide further clarification around the continuous -/// engagement of app-users. -static const char*const kEventAppOpen = "app_open"; - -/// E-Commerce Begin Checkout event. This event signifies that a user has -/// begun the process of checking out. Add this event to a funnel with -/// your @c AnalyticsEventPurchase event to gauge the effectiveness of -/// your checkout process. Note: If you supply the @c -/// AnalyticsParameterValue parameter, you must also supply the @c -/// AnalyticsParameterCurrency parameter so that revenue metrics can be -/// computed accurately. Params: -/// -///
    -///
  • @c AnalyticsParameterCoupon (String) (optional)
  • -///
  • @c AnalyticsParameterCurrency (String) (optional)
  • -///
  • @c AnalyticsParameterItems ([[String: Any]]) (optional)
  • -///
  • @c AnalyticsParameterValue (Double) (optional)
  • -///
-static const char*const kEventBeginCheckout = - "begin_checkout"; - -/// Campaign Detail event. Log this event to supply the referral details -/// of a re-engagement campaign. Note: you must supply at least one of the -/// required parameters AnalyticsParameterSource, AnalyticsParameterMedium -/// or AnalyticsParameterCampaign. Params: -/// -///
    -///
  • @c AnalyticsParameterSource (String)
  • -///
  • @c AnalyticsParameterMedium (String)
  • -///
  • @c AnalyticsParameterCampaign (String)
  • -///
  • @c AnalyticsParameterTerm (String) (optional)
  • -///
  • @c AnalyticsParameterContent (String) (optional)
  • -///
  • @c AnalyticsParameterAdNetworkClickID (String) (optional)
  • -///
  • @c AnalyticsParameterCP1 (String) (optional)
  • -///
  • @c AnalyticsParameterCampaignID (String) (optional)
  • -///
  • @c AnalyticsParameterCreativeFormat (String) (optional)
  • -///
  • @c AnalyticsParameterMarketingTactic (String) (optional)
  • -///
  • @c AnalyticsParameterSourcePlatform (String) (optional)
  • -///
-static const char*const kEventCampaignDetails = - "campaign_details"; - -/// Earn Virtual Currency event. This event tracks the awarding of virtual -/// currency in your app. Log this along with @c -/// AnalyticsEventSpendVirtualCurrency to better understand your virtual -/// economy. Params: -/// -///
    -///
  • @c AnalyticsParameterVirtualCurrencyName (String)
  • -///
  • @c AnalyticsParameterValue (Int or Double)
  • -///
-static const char*const kEventEarnVirtualCurrency - = "earn_virtual_currency"; - -/// Generate Lead event. Log this event when a lead has been generated in -/// the app to understand the efficacy of your install and re-engagement -/// campaigns. Note: If you supply the @c AnalyticsParameterValue -/// parameter, you must also supply the @c AnalyticsParameterCurrency -/// parameter so that revenue metrics can be computed accurately. Params: -/// -///
    -///
  • @c AnalyticsParameterCurrency (String) (optional)
  • -///
  • @c AnalyticsParameterValue (Double) (optional)
  • -///
-static const char*const kEventGenerateLead = - "generate_lead"; - -/// Join Group event. Log this event when a user joins a group such as a -/// guild, team or family. Use this event to analyze how popular certain -/// groups or social features are in your app. Params: -/// -///
    -///
  • @c AnalyticsParameterGroupID (String)
  • -///
-static const char*const kEventJoinGroup = "join_group"; - -/// Level End event. Log this event when the user finishes a level. -/// Params: -/// -///
    -///
  • @c AnalyticsParameterLevelName (String)
  • -///
  • @c AnalyticsParameterSuccess (String)
  • -///
-static const char*const kEventLevelEnd = "level_end"; - -/// Level Start event. Log this event when the user starts a new level. -/// Params: -/// -///
    -///
  • @c AnalyticsParameterLevelName (String)
  • -///
-static const char*const kEventLevelStart = "level_start"; - -/// Level Up event. This event signifies that a player has leveled up in -/// your gaming app. It can help you gauge the level distribution of your -/// userbase and help you identify certain levels that are difficult to -/// pass. Params: -/// -///
    -///
  • @c AnalyticsParameterLevel (Int)
  • -///
  • @c AnalyticsParameterCharacter (String) (optional)
  • -///
-static const char*const kEventLevelUp = "level_up"; - -/// Login event. Apps with a login feature can report this event to -/// signify that a user has logged in. -static const char*const kEventLogin = "login"; - -/// Post Score event. Log this event when the user posts a score in your -/// gaming app. This event can help you understand how users are actually -/// performing in your game and it can help you correlate high scores with -/// certain audiences or behaviors. Params: -/// -///
    -///
  • @c AnalyticsParameterScore (Int)
  • -///
  • @c AnalyticsParameterLevel (Int) (optional)
  • -///
  • @c AnalyticsParameterCharacter (String) (optional)
  • -///
-static const char*const kEventPostScore = "post_score"; - -/// E-Commerce Purchase event. This event signifies that an item(s) was -/// purchased by a user. Note: This is different from the in-app purchase -/// event, which is reported automatically for App Store-based apps. Note: -/// If you supply the @c AnalyticsParameterValue parameter, you must also -/// supply the @c AnalyticsParameterCurrency parameter so that revenue -/// metrics can be computed accurately. Params: -/// -///
    -///
  • @c AnalyticsParameterAffiliation (String) (optional)
  • -///
  • @c AnalyticsParameterCoupon (String) (optional)
  • -///
  • @c AnalyticsParameterCurrency (String) (optional)
  • -///
  • @c AnalyticsParameterEndDate (String) (optional)
  • -///
  • @c AnalyticsParameterItemID (String) (optional)
  • -///
  • @c AnalyticsParameterItems ([[String: Any]]) (optional)
  • -///
  • @c AnalyticsParameterShipping (Double) (optional)
  • -///
  • @c AnalyticsParameterStartDate (String) (optional)
  • -///
  • @c AnalyticsParameterTax (Double) (optional)
  • -///
  • @c AnalyticsParameterTransactionID (String) (optional)
  • -///
  • @c AnalyticsParameterValue (Double) (optional)
  • -///
-static const char*const kEventPurchase = "purchase"; - -/// E-Commerce Refund event. This event signifies that a refund was -/// issued. Note: If you supply the @c AnalyticsParameterValue parameter, -/// you must also supply the @c AnalyticsParameterCurrency parameter so -/// that revenue metrics can be computed accurately. Params: -/// -///
    -///
  • @c AnalyticsParameterAffiliation (String) (optional)
  • -///
  • @c AnalyticsParameterCoupon (String) (optional)
  • -///
  • @c AnalyticsParameterCurrency (String) (optional)
  • -///
  • @c AnalyticsParameterItems ([[String: Any]]) (optional)
  • -///
  • @c AnalyticsParameterShipping (Double) (optional)
  • -///
  • @c AnalyticsParameterTax (Double) (optional)
  • -///
  • @c AnalyticsParameterTransactionID (String) (optional)
  • -///
  • @c AnalyticsParameterValue (Double) (optional)
  • -///
-static const char*const kEventRefund = "refund"; - -/// E-Commerce Remove from Cart event. This event signifies that an -/// item(s) was removed from a cart. Note: If you supply the @c -/// AnalyticsParameterValue parameter, you must also supply the @c -/// AnalyticsParameterCurrency parameter so that revenue metrics can be -/// computed accurately. Params: -/// -///
    -///
  • @c AnalyticsParameterCurrency (String) (optional)
  • -///
  • @c AnalyticsParameterItems ([[String: Any]]) (optional)
  • -///
  • @c AnalyticsParameterValue (Double) (optional)
  • -///
-static const char*const kEventRemoveFromCart = - "remove_from_cart"; - -/// Screen View event. This event signifies a screen view. Use this when a -/// screen transition occurs. This event can be logged irrespective of -/// whether automatic screen tracking is enabled. Params: -/// -///
    -///
  • @c AnalyticsParameterScreenClass (String) (optional)
  • -///
  • @c AnalyticsParameterScreenName (String) (optional)
  • -///
-static const char*const kEventScreenView = "screen_view"; - -/// Search event. Apps that support search features can use this event to -/// contextualize search operations by supplying the appropriate, -/// corresponding parameters. This event can help you identify the most -/// popular content in your app. Params: -/// -///
    -///
  • @c AnalyticsParameterSearchTerm (String)
  • -///
  • @c AnalyticsParameterStartDate (String) (optional)
  • -///
  • @c AnalyticsParameterEndDate (String) (optional)
  • -///
  • @c AnalyticsParameterNumberOfNights (Int) (optional) for hotel bookings
  • -///
  • @c AnalyticsParameterNumberOfRooms (Int) (optional) for hotel bookings
  • -///
  • @c AnalyticsParameterNumberOfPassengers (Int) (optional) for travel bookings
  • -///
  • @c AnalyticsParameterOrigin (String) (optional)
  • -///
  • @c AnalyticsParameterDestination (String) (optional)
  • -///
  • @c AnalyticsParameterTravelClass (String) (optional) for travel bookings
  • -///
-static const char*const kEventSearch = "search"; - -/// Select Content event. This general purpose event signifies that a user -/// has selected some content of a certain type in an app. The content can -/// be any object in your app. This event can help you identify popular -/// content and categories of content in your app. Params: -/// -///
    -///
  • @c AnalyticsParameterContentType (String)
  • -///
  • @c AnalyticsParameterItemID (String)
  • -///
-static const char*const kEventSelectContent = - "select_content"; - -/// Select Item event. This event signifies that an item was selected by a -/// user from a list. Use the appropriate parameters to contextualize the -/// event. Use this event to discover the most popular items selected. -/// Params: -/// -///
    -///
  • @c AnalyticsParameterItems ([[String: Any]]) (optional)
  • -///
  • @c AnalyticsParameterItemListID (String) (optional)
  • -///
  • @c AnalyticsParameterItemListName (String) (optional)
  • -///
-static const char*const kEventSelectItem = "select_item"; - -/// Select promotion event. This event signifies that a user has selected -/// a promotion offer. Use the appropriate parameters to contextualize the -/// event, such as the item(s) for which the promotion applies. Params: -/// -///
    -///
  • @c AnalyticsParameterCreativeName (String) (optional)
  • -///
  • @c AnalyticsParameterCreativeSlot (String) (optional)
  • -///
  • @c AnalyticsParameterItems ([[String: Any]]) (optional)
  • -///
  • @c AnalyticsParameterLocationID (String) (optional)
  • -///
  • @c AnalyticsParameterPromotionID (String) (optional)
  • -///
  • @c AnalyticsParameterPromotionName (String) (optional)
  • -///
-static const char*const kEventSelectPromotion = - "select_promotion"; - -/// Share event. Apps with social features can log the Share event to -/// identify the most viral content. Params: -/// -///
    -///
  • @c AnalyticsParameterContentType (String)
  • -///
  • @c AnalyticsParameterItemID (String)
  • -///
-static const char*const kEventShare = "share"; - -/// Sign Up event. This event indicates that a user has signed up for an -/// account in your app. The parameter signifies the method by which the -/// user signed up. Use this event to understand the different behaviors -/// between logged in and logged out users. Params: -/// -///
    -///
  • @c AnalyticsParameterMethod (String)
  • -///
-static const char*const kEventSignUp = "sign_up"; - -/// Spend Virtual Currency event. This event tracks the sale of virtual -/// goods in your app and can help you identify which virtual goods are -/// the most popular objects of purchase. Params: -/// -///
    -///
  • @c AnalyticsParameterItemName (String)
  • -///
  • @c AnalyticsParameterVirtualCurrencyName (String)
  • -///
  • @c AnalyticsParameterValue (Int or Double)
  • -///
-static const char*const kEventSpendVirtualCurrency - = "spend_virtual_currency"; - -/// Tutorial Begin event. This event signifies the start of the -/// on-boarding process in your app. Use this in a funnel with @c -/// AnalyticsEventTutorialComplete to understand how many users complete -/// this process and move on to the full app experience. -static const char*const kEventTutorialBegin = - "tutorial_begin"; - -/// Tutorial End event. Use this event to signify the user's completion of -/// your app's on-boarding process. Add this to a funnel with @c -/// AnalyticsEventTutorialBegin to gauge the completion rate of your -/// on-boarding process. -static const char*const kEventTutorialComplete = - "tutorial_complete"; - -/// Unlock Achievement event. Log this event when the user has unlocked an -/// achievement in your game. Since achievements generally represent the -/// breadth of a gaming experience, this event can help you understand how -/// many users are experiencing all that your game has to offer. Params: -/// -///
    -///
  • @c AnalyticsParameterAchievementID (String)
  • -///
-static const char*const kEventUnlockAchievement = - "unlock_achievement"; - -/// E-commerce View Cart event. This event signifies that a user has -/// viewed their cart. Use this to analyze your purchase funnel. Note: If -/// you supply the @c AnalyticsParameterValue parameter, you must also -/// supply the @c AnalyticsParameterCurrency parameter so that revenue -/// metrics can be computed accurately. Params: -/// -///
    -///
  • @c AnalyticsParameterCurrency (String) (optional)
  • -///
  • @c AnalyticsParameterItems ([[String: Any]]) (optional)
  • -///
  • @c AnalyticsParameterValue (Double) (optional)
  • -///
-static const char*const kEventViewCart = "view_cart"; - -/// View Item event. This event signifies that a user has viewed an item. -/// Use the appropriate parameters to contextualize the event. Use this -/// event to discover the most popular items viewed in your app. Note: If -/// you supply the @c AnalyticsParameterValue parameter, you must also -/// supply the @c AnalyticsParameterCurrency parameter so that revenue -/// metrics can be computed accurately. Params: -/// -///
    -///
  • @c AnalyticsParameterCurrency (String) (optional)
  • -///
  • @c AnalyticsParameterItems ([[String: Any]]) (optional)
  • -///
  • @c AnalyticsParameterValue (Double) (optional)
  • -///
-static const char*const kEventViewItem = "view_item"; - -/// View Item List event. Log this event when a user sees a list of items -/// or offerings. Params: -/// -///
    -///
  • @c AnalyticsParameterItems ([[String: Any]]) (optional)
  • -///
  • @c AnalyticsParameterItemListID (String) (optional)
  • -///
  • @c AnalyticsParameterItemListName (String) (optional)
  • -///
-static const char*const kEventViewItemList = - "view_item_list"; - -/// View Promotion event. This event signifies that a promotion was shown -/// to a user. Add this event to a funnel with the @c -/// AnalyticsEventAddToCart and @c AnalyticsEventPurchase to gauge your -/// conversion process. Params: -/// -///
    -///
  • @c AnalyticsParameterCreativeName (String) (optional)
  • -///
  • @c AnalyticsParameterCreativeSlot (String) (optional)
  • -///
  • @c AnalyticsParameterItems ([[String: Any]]) (optional)
  • -///
  • @c AnalyticsParameterLocationID (String) (optional)
  • -///
  • @c AnalyticsParameterPromotionID (String) (optional)
  • -///
  • @c AnalyticsParameterPromotionName (String) (optional)
  • -///
-static const char*const kEventViewPromotion = - "view_promotion"; - -/// View Search Results event. Log this event when the user has been -/// presented with the results of a search. Params: -/// -///
    -///
  • @c AnalyticsParameterSearchTerm (String)
  • -///
-static const char*const kEventViewSearchResults = - "view_search_results"; -/// @} - -} // namespace analytics -} // namespace firebase - -#endif // FIREBASE_ANALYTICS_CLIENT_CPP_INCLUDE_FIREBASE_ANALYTICS_EVENT_NAMES_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/analytics/parameter_names.h b/packages/firebase_core/firebase_core/firebase_core/firebase/analytics/parameter_names.h deleted file mode 100644 index fcc43c22fbc8..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/analytics/parameter_names.h +++ /dev/null @@ -1,755 +0,0 @@ -// Copyright 2023 Google Inc. All Rights Reserved. - -#ifndef FIREBASE_ANALYTICS_CLIENT_CPP_INCLUDE_FIREBASE_ANALYTICS_PARAMETER_NAMES_H_ -#define FIREBASE_ANALYTICS_CLIENT_CPP_INCLUDE_FIREBASE_ANALYTICS_PARAMETER_NAMES_H_ - -/// @brief Namespace that encompasses all Firebase APIs. -namespace firebase { -/// @brief Firebase Analytics API. -namespace analytics { - - - -/// @defgroup parameter_names Analytics Parameters -/// -/// Predefined event parameter names. -/// -/// Params supply information that contextualize Events. You can associate -/// up to 25 unique Params with each Event type. Some Params are suggested -/// below for certain common Events, but you are not limited to these. You -/// may supply extra Params for suggested Events or custom Params for -/// Custom events. Param names can be up to 40 characters long, may only -/// contain alphanumeric characters and underscores ("_"), and must start -/// with an alphabetic character. Param values can be up to 100 characters -/// long. The "firebase_", "google_", and "ga_" prefixes are reserved and -/// should not be used. -/// @{ - - -/// Game achievement ID (String). -/// @code -/// let params = [ -/// AnalyticsParameterAchievementID : "10_matches_won", -/// // ... -/// ] -/// @endcode -static const char*const kParameterAchievementID = - "achievement_id"; - -/// The ad format (e.g. Banner, Interstitial, Rewarded, Native, Rewarded -/// Interstitial, Instream). (String). -/// @code -/// let params = [ -/// AnalyticsParameterAdFormat : "Banner", -/// // ... -/// ] -/// @endcode -static const char*const kParameterAdFormat = - "ad_format"; - -/// Ad Network Click ID (String). Used for network-specific click IDs -/// which vary in format. -/// @code -/// let params = [ -/// AnalyticsParameterAdNetworParameter(kClickID, "1234567"), -/// // ... -/// ] -/// @endcode -static const char*const kParameterAdNetworkClickID - = "aclid"; - -/// The ad platform (e.g. MoPub, IronSource) (String). -/// @code -/// let params = [ -/// AnalyticsParameterAdPlatform : "MoPub", -/// // ... -/// ] -/// @endcode -static const char*const kParameterAdPlatform = - "ad_platform"; - -/// The ad source (e.g. AdColony) (String). -/// @code -/// let params = [ -/// AnalyticsParameterAdSource : "AdColony", -/// // ... -/// ] -/// @endcode -static const char*const kParameterAdSource = - "ad_source"; - -/// The ad unit name (e.g. Banner_03) (String). -/// @code -/// let params = [ -/// AnalyticsParameterAdUnitName : "Banner_03", -/// // ... -/// ] -/// @endcode -static const char*const kParameterAdUnitName = - "ad_unit_name"; - -/// A product affiliation to designate a supplying company or brick and -/// mortar store location -/// (String). @code -/// let params = [ -/// AnalyticsParameterAffiliation : "Google Store", -/// // ... -/// ] -/// @endcode -static const char*const kParameterAffiliation = - "affiliation"; - -/// Campaign custom parameter (String). Used as a method of capturing -/// custom data in a campaign. Use varies by network. -/// @code -/// let params = [ -/// AnalyticsParameterCP1 : "custom_data", -/// // ... -/// ] -/// @endcode -static const char*const kParameterCP1 = "cp1"; - -/// The individual campaign name, slogan, promo code, etc. Some networks -/// have pre-defined macro to capture campaign information, otherwise can -/// be populated by developer. Highly Recommended (String). -/// @code -/// let params = [ -/// AnalyticsParameterCampaign : "winter_promotion", -/// // ... -/// ] -/// @endcode -static const char*const kParameterCampaign = - "campaign"; - -/// Campaign ID (String). Used for keyword analysis to identify a specific -/// product promotion or strategic campaign. This is a required key for -/// GA4 data import. -/// @code -/// let params = [ -/// AnalyticsParameterCampaignID : "7877652710", -/// // ... -/// ] -/// @endcode -static const char*const kParameterCampaignID = - "campaign_id"; - -/// Character used in game (String). -/// @code -/// let params = [ -/// AnalyticsParameterCharacter : "beat_boss", -/// // ... -/// ] -/// @endcode -static const char*const kParameterCharacter = - "character"; - -/// Campaign content (String). -static const char*const kParameterContent = "content"; - -/// Type of content selected (String). -/// @code -/// let params = [ -/// AnalyticsParameterContentType : "news article", -/// // ... -/// ] -/// @endcode -static const char*const kParameterContentType = - "content_type"; - -/// Coupon code used for a purchase (String). -/// @code -/// let params = [ -/// AnalyticsParameterCoupon : "SUMMER_FUN", -/// // ... -/// ] -/// @endcode -static const char*const kParameterCoupon = "coupon"; - -/// Creative Format (String). Used to identify the high-level -/// classification of the type of ad served by a specific campaign. -/// @code -/// let params = [ -/// AnalyticsParameterCreativeFormat : "display", -/// // ... -/// ] -/// @endcode -static const char*const kParameterCreativeFormat = - "creative_format"; - -/// The name of a creative used in a promotional spot (String). -/// @code -/// let params = [ -/// AnalyticsParameterCreativeName : "Summer Sale", -/// // ... -/// ] -/// @endcode -static const char*const kParameterCreativeName = - "creative_name"; - -/// The name of a creative slot (String). -/// @code -/// let params = [ -/// AnalyticsParameterCreativeSlot : "summer_banner2", -/// // ... -/// ] -/// @endcode -static const char*const kParameterCreativeSlot = - "creative_slot"; - -/// Currency of the purchase or items associated with the event, in -/// 3-letter -/// ISO_4217 format (String). -/// @code -/// let params = [ -/// AnalyticsParameterCurrency : "USD", -/// // ... -/// ] -/// @endcode -static const char*const kParameterCurrency = - "currency"; - -/// Flight or Travel destination (String). -/// @code -/// let params = [ -/// AnalyticsParameterDestination : "Mountain View, CA", -/// // ... -/// ] -/// @endcode -static const char*const kParameterDestination = - "destination"; - -/// Monetary value of discount associated with a purchase (Double). -/// @code -/// let params = [ -/// AnalyticsParameterDiscount : 2.0, -/// AnalyticsParameterCurrency : "USD", // e.g. $2.00 USD -/// // ... -/// ] -/// @endcode -static const char*const kParameterDiscount = - "discount"; - -/// The arrival date, check-out date or rental end date for the item. This -/// should be in YYYY-MM-DD format (String). -/// @code -/// let params = [ -/// AnalyticsParameterEndDate : "2015-09-14", -/// // ... -/// ] -/// @endcode -static const char*const kParameterEndDate = "end_date"; - -/// Indicates that the associated event should either extend the current -/// session or start a new session if no session was active when the event -/// was logged. Specify 1 to extend the current session or to start a new -/// session; any other value will not extend or start a session. -/// @code -/// let params = [ -/// AnalyticsParameterExtendSession : 1, -/// // ... -/// ] -/// @endcode -static const char*const kParameterExtendSession = - "extend_session"; - -/// Flight number for travel events (String). -/// @code -/// let params = [ -/// AnalyticsParameterFlightNumber : "ZZ800", -/// // ... -/// ] -/// @endcode -static const char*const kParameterFlightNumber = - "flight_number"; - -/// Group/clan/guild ID (String). -/// @code -/// let params = [ -/// AnalyticsParameterGroupID : "g1", -/// // ... -/// ] -/// @endcode -static const char*const kParameterGroupID = "group_id"; - -/// The index of the item in a list (Int). -/// @code -/// let params = [ -/// AnalyticsParameterIndex : 5, -/// // ... -/// ] -/// @endcode -static const char*const kParameterIndex = "index"; - -/// Item brand (String). -/// @code -/// let params = [ -/// AnalyticsParameterItemBrand : "Google", -/// // ... -/// ] -/// @endcode -static const char*const kParameterItemBrand = - "item_brand"; - -/// Item category (context-specific) (String). -/// @code -/// let params = [ -/// AnalyticsParameterItemCategory : "pants", -/// // ... -/// ] -/// @endcode -static const char*const kParameterItemCategory = - "item_category"; - -/// Item Category (context-specific) (String). -/// @code -/// let params = [ -/// AnalyticsParameterItemCategory2 : "pants", -/// // ... -/// ] -/// @endcode -static const char*const kParameterItemCategory2 = - "item_category2"; - -/// Item Category (context-specific) (String). -/// @code -/// let params = [ -/// AnalyticsParameterItemCategory3 : "pants", -/// // ... -/// ] -/// @endcode -static const char*const kParameterItemCategory3 = - "item_category3"; - -/// Item Category (context-specific) (String). -/// @code -/// let params = [ -/// AnalyticsParameterItemCategory4 : "pants", -/// // ... -/// ] -/// @endcode -static const char*const kParameterItemCategory4 = - "item_category4"; - -/// Item Category (context-specific) (String). -/// @code -/// let params = [ -/// AnalyticsParameterItemCategory5 : "pants", -/// // ... -/// ] -/// @endcode -static const char*const kParameterItemCategory5 = - "item_category5"; - -/// Item ID (context-specific) (String). -/// @code -/// let params = [ -/// AnalyticsParameterItemID : "SKU_12345", -/// // ... -/// ] -/// @endcode -static const char*const kParameterItemID = "item_id"; - -/// The ID of the list in which the item was presented to the -/// user (String). -/// @code -/// let params = [ -/// AnalyticsParameterItemListID : "ABC123", -/// // ... -/// ] -/// @endcode -static const char*const kParameterItemListID = - "item_list_id"; - -/// The name of the list in which the item was presented to the user -/// (String). -/// @code -/// let params = [ -/// AnalyticsParameterItemListName : "Related products", -/// // ... -/// ] -/// @endcode -static const char*const kParameterItemListName = - "item_list_name"; - -/// Item Name (context-specific) (String). -/// @code -/// let params = [ -/// AnalyticsParameterItemName : "jeggings", -/// // ... -/// ] -/// @endcode -static const char*const kParameterItemName = - "item_name"; - -/// Item variant (String). -/// @code -/// let params = [ -/// AnalyticsParameterItemVariant : "Black", -/// // ... -/// ] -/// @endcode -static const char*const kParameterItemVariant = - "item_variant"; - -/// The list of items involved in the transaction expressed as `[[String: -/// Any]]`. -/// @code -/// let params = [ -/// AnalyticsParameterItems : [ -/// [AnalyticsParameterItemName : "jeggings", AnalyticsParameterItemCategory : "pants"], -/// [AnalyticsParameterItemName : "boots", AnalyticsParameterItemCategory : "shoes"], -/// ], -/// ] -/// @endcode -static const char*const kParameterItems = "items"; - -/// Level in game (Int). -/// @code -/// let params = [ -/// AnalyticsParameterLevel : 42, -/// // ... -/// ] -/// @endcode -static const char*const kParameterLevel = "level"; - -/// The name of a level in a game (String). -/// @code -/// let params = [ -/// AnalyticsParameterLevelName : "room_1", -/// // ... -/// ] -/// @endcode -static const char*const kParameterLevelName = - "level_name"; - -/// Location (String). The Google Place ID -/// that corresponds to the associated event. Alternatively, you can supply your own custom -/// Location ID. -/// @code -/// let params = [ -/// AnalyticsParameterLocation : "ChIJiyj437sx3YAR9kUWC8QkLzQ", -/// // ... -/// ] -/// @endcode -static const char*const kParameterLocation = - "location"; - -/// The location associated with the event. Preferred to be the Google -/// Place ID that corresponds to the -/// associated item but could be overridden to a custom location ID -/// string.(String). -/// @code -/// let params = [ -/// AnalyticsParameterLocationID : "ChIJiyj437sx3YAR9kUWC8QkLzQ", -/// // ... -/// ] -/// @endcode -static const char*const kParameterLocationID = - "location_id"; - -/// Marketing Tactic (String). Used to identify the targeting criteria -/// applied to a specific campaign. -/// @code -/// let params = [ -/// AnalyticsParameterMarParameter(ketingTactic, "Remarketing"), -/// // ... -/// ] -/// @endcode -static const char*const kParameterMarketingTactic - = "marketing_tactic"; - -/// The advertising or marParameter(keting, cpc, banner, email), push. -/// Highly recommended (String). -/// @code -/// let params = [ -/// AnalyticsParameterMedium : "email", -/// // ... -/// ] -/// @endcode -static const char*const kParameterMedium = "medium"; - -/// A particular approach used in an operation; for example, "facebook" or -/// "email" in the context of a sign_up or login event. (String). -/// @code -/// let params = [ -/// AnalyticsParameterMethod : "google", -/// // ... -/// ] -/// @endcode -static const char*const kParameterMethod = "method"; - -/// Number of nights staying at hotel (Int). -/// @code -/// let params = [ -/// AnalyticsParameterNumberOfNights : 3, -/// // ... -/// ] -/// @endcode -static const char*const kParameterNumberOfNights - = "number_of_nights"; - -/// Number of passengers traveling (Int). -/// @code -/// let params = [ -/// AnalyticsParameterNumberOfPassengers : 11, -/// // ... -/// ] -/// @endcode -static const char*const kParameterNumberOfPassengers - = "number_of_passengers"; - -/// Number of rooms for travel events (Int). -/// @code -/// let params = [ -/// AnalyticsParameterNumberOfRooms : 2, -/// // ... -/// ] -/// @endcode -static const char*const kParameterNumberOfRooms = - "number_of_rooms"; - -/// Flight or Travel origin (String). -/// @code -/// let params = [ -/// AnalyticsParameterOrigin : "Mountain View, CA", -/// // ... -/// ] -/// @endcode -static const char*const kParameterOrigin = "origin"; - -/// The chosen method of payment (String). -/// @code -/// let params = [ -/// AnalyticsParameterPaymentType : "Visa", -/// // ... -/// ] -/// @endcode -static const char*const kParameterPaymentType = - "payment_type"; - -/// Purchase price (Double). -/// @code -/// let params = [ -/// AnalyticsParameterPrice : 1.0, -/// AnalyticsParameterCurrency : "USD", // e.g. $1.00 USD -/// // ... -/// ] -/// @endcode -static const char*const kParameterPrice = "price"; - -/// The ID of a product promotion (String). -/// @code -/// let params = [ -/// AnalyticsParameterPromotionID : "ABC123", -/// // ... -/// ] -/// @endcode -static const char*const kParameterPromotionID = - "promotion_id"; - -/// The name of a product promotion (String). -/// @code -/// let params = [ -/// AnalyticsParameterPromotionName : "Summer Sale", -/// // ... -/// ] -/// @endcode -static const char*const kParameterPromotionName = - "promotion_name"; - -/// Purchase quantity (Int). -/// @code -/// let params = [ -/// AnalyticsParameterQuantity : 1, -/// // ... -/// ] -/// @endcode -static const char*const kParameterQuantity = - "quantity"; - -/// Score in game (Int). -/// @code -/// let params = [ -/// AnalyticsParameterScore : 4200, -/// // ... -/// ] -/// @endcode -static const char*const kParameterScore = "score"; - -/// Current screen class, such as the class name of the UIViewController, -/// logged with screen_view event and added to every event (String). -/// @code -/// let params = [ -/// AnalyticsParameterScreenClass : "LoginViewController", -/// // ... -/// ] -/// @endcode -static const char*const kParameterScreenClass = - "screen_class"; - -/// Current screen name, such as the name of the UIViewController, logged -/// with screen_view event and added to every event (String). -/// @code -/// let params = [ -/// AnalyticsParameterScreenName : "LoginView", -/// // ... -/// ] -/// @endcode -static const char*const kParameterScreenName = - "screen_name"; - -/// The search string/keywords used (String). -/// @code -/// let params = [ -/// AnalyticsParameterSearchTerm : "periodic table", -/// // ... -/// ] -/// @endcode -static const char*const kParameterSearchTerm = - "search_term"; - -/// Shipping cost associated with a transaction (Double). -/// @code -/// let params = [ -/// AnalyticsParameterShipping : 5.99, -/// AnalyticsParameterCurrency : "USD", // e.g. $5.99 USD -/// // ... -/// ] -/// @endcode -static const char*const kParameterShipping = - "shipping"; - -/// The shipping tier (e.g. Ground, Air, Next-day) selected for delivery -/// of the purchased item (String). -/// @code -/// let params = [ -/// AnalyticsParameterShippingTier : "Ground", -/// // ... -/// ] -/// @endcode -static const char*const kParameterShippingTier = - "shipping_tier"; - -/// The origin of your traffic, such as an Ad network (for example, -/// google) or partner (urban airship). Identify the advertiser, site, -/// publication, etc. that is sending traffic to your property. Highly -/// recommended (String). -/// @code -/// let params = [ -/// AnalyticsParameterSource : "InMobi", -/// // ... -/// ] -/// @endcode -static const char*const kParameterSource = "source"; - -/// Source Platform (String). Used to identify the platform responsible -/// for directing traffic to a given Analytics property (e.g., a buying -/// platform where budgets, targeting criteria, etc. are set, a platform -/// for managing organic traffic data, etc.). -/// @code -/// let params = [ -/// AnalyticsParameterSourcePlatform : "sa360", -/// // ... -/// ] -/// @endcode -static const char*const kParameterSourcePlatform = - "source_platform"; - -/// The departure date, check-in date or rental start date for the item. -/// This should be in YYYY-MM-DD format (String). -/// @code -/// let params = [ -/// AnalyticsParameterStartDate : "2015-09-14", -/// // ... -/// ] -/// @endcode -static const char*const kParameterStartDate = - "start_date"; - -/// The result of an operation. Specify 1 to indicate success and 0 to -/// indicate failure (Int). -/// @code -/// let params = [ -/// AnalyticsParameterSuccess : 1, -/// // ... -/// ] -/// @endcode -static const char*const kParameterSuccess = "success"; - -/// Tax cost associated with a transaction (Double). -/// @code -/// let params = [ -/// AnalyticsParameterTax : 2.43, -/// AnalyticsParameterCurrency : "USD", // e.g. $2.43 USD -/// // ... -/// ] -/// @endcode -static const char*const kParameterTax = "tax"; - -/// If you're manually tagging keyword campaigns, you should use utm_term -/// to specify the keyword (String). -/// @code -/// let params = [ -/// AnalyticsParameterTerm : "game", -/// // ... -/// ] -/// @endcode -static const char*const kParameterTerm = "term"; - -/// The unique identifier of a transaction (String). -/// @code -/// let params = [ -/// AnalyticsParameterTransactionID : "T12345", -/// // ... -/// ] -/// @endcode -static const char*const kParameterTransactionID = - "transaction_id"; - -/// Travel class (String). -/// @code -/// let params = [ -/// AnalyticsParameterTravelClass : "business", -/// // ... -/// ] -/// @endcode -static const char*const kParameterTravelClass = - "travel_class"; - -/// A context-specific numeric value which is accumulated automatically -/// for each event type. This is a general purpose parameter that is -/// useful for accumulating a key metric that pertains to an event. -/// Examples include revenue, distance, time and points. Value should be -/// specified as Int or Double. Notes: Values for pre-defined -/// currency-related events (such as @c AnalyticsEventAddToCart) should be -/// supplied using Double and must be accompanied by a @c -/// AnalyticsParameterCurrency parameter. The valid range of accumulated -/// values is [-9,223,372,036,854.77, 9,223,372,036,854.77]. Supplying a -/// non-numeric value, omitting the corresponding @c -/// AnalyticsParameterCurrency parameter, or supplying an invalid -/// currency code for conversion events will cause that -/// conversion to be omitted from reporting. -/// @code -/// let params = [ -/// AnalyticsParameterValue : 3.99, -/// AnalyticsParameterCurrency : "USD", // e.g. $3.99 USD -/// // ... -/// ] -/// @endcode -static const char*const kParameterValue = "value"; - -/// Name of virtual currency type (String). -/// @code -/// let params = [ -/// AnalyticsParameterVirtualCurrencyName : "virtual_currency_name", -/// // ... -/// ] -/// @endcode -static const char*const kParameterVirtualCurrencyName - = "virtual_currency_name"; -/// @} - -} // namespace analytics -} // namespace firebase - -#endif // FIREBASE_ANALYTICS_CLIENT_CPP_INCLUDE_FIREBASE_ANALYTICS_PARAMETER_NAMES_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/analytics/user_property_names.h b/packages/firebase_core/firebase_core/firebase_core/firebase/analytics/user_property_names.h deleted file mode 100644 index 155fea86e6f9..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/analytics/user_property_names.h +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright 2023 Google Inc. All Rights Reserved. - -#ifndef FIREBASE_ANALYTICS_CLIENT_CPP_INCLUDE_FIREBASE_ANALYTICS_USER_PROPERTY_NAMES_H_ -#define FIREBASE_ANALYTICS_CLIENT_CPP_INCLUDE_FIREBASE_ANALYTICS_USER_PROPERTY_NAMES_H_ - -/// @brief Namespace that encompasses all Firebase APIs. -namespace firebase { -/// @brief Firebase Analytics API. -namespace analytics { - - - -/// @defgroup user_property_names Analytics User Properties -/// -/// Predefined user property names. -/// -/// A UserProperty is an attribute that describes the app-user. By -/// supplying UserProperties, you can later analyze different behaviors of -/// various segments of your userbase. You may supply up to 25 unique -/// UserProperties per app, and you can use the name and value of your -/// choosing for each one. UserProperty names can be up to 24 characters -/// long, may only contain alphanumeric characters and underscores ("_"), -/// and must start with an alphabetic character. UserProperty values can -/// be up to 36 characters long. The "firebase_", "google_", and "ga_" -/// prefixes are reserved and should not be used. -/// @{ - - -/// Indicates whether events logged by Google Analytics can be used to -/// personalize ads for the user. Set to "YES" to enable, or "NO" to -/// disable. Default is enabled. See the -/// documentation for -/// more details and information about related settings. -/// -/// @code -/// Analytics.setUserProperty("NO", forName: AnalyticsUserPropertyAllowAdPersonalizationSignals) -/// @endcode -static const char*const kUserPropertyAllowAdPersonalizationSignals - = "allow_personalized_ads"; - -/// The method used to sign in. For example, "google", "facebook" or -/// "twitter". -static const char*const kUserPropertySignUpMethod - = "sign_up_method"; -/// @} - -} // namespace analytics -} // namespace firebase - -#endif // FIREBASE_ANALYTICS_CLIENT_CPP_INCLUDE_FIREBASE_ANALYTICS_USER_PROPERTY_NAMES_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/app.h b/packages/firebase_core/firebase_core/firebase_core/firebase/app.h deleted file mode 100644 index 0501f38ac0c8..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/app.h +++ /dev/null @@ -1,787 +0,0 @@ -/* - * Copyright 2016 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_APP_SRC_INCLUDE_FIREBASE_APP_H_ -#define FIREBASE_APP_SRC_INCLUDE_FIREBASE_APP_H_ - -#include "firebase/internal/platform.h" - -#if FIREBASE_PLATFORM_ANDROID -#include -#endif // FIREBASE_PLATFORM_ANDROID - -#include -#include -#include - -#if FIREBASE_PLATFORM_IOS || FIREBASE_PLATFORM_TVOS -#ifdef __OBJC__ -@class FIRApp; -#endif // __OBJC__ -#endif // FIREBASE_PLATFORM_IOS - -namespace firebase { - -#ifdef FIREBASE_LINUX_BUILD_CONFIG_STRING -// Check to see if the shared object compiler string matches the input -void CheckCompilerString(const char* input); -#endif // FIREBASE_LINUX_BUILD_CONFIG_STRING - -// Predeclarations. -#ifdef INTERNAL_EXPERIMENTAL -namespace internal { -class FunctionRegistry; -} // namespace internal -#endif // INTERNAL_EXPERIMENTAL - -#ifdef INTERNAL_EXPERIMENTAL -#if FIREBASE_PLATFORM_DESKTOP -namespace heartbeat { -class HeartbeatController; // forward declaration -} // namespace heartbeat -#endif // FIREBASE_PLATFORM_DESKTOP -#endif // INTERNAL_EXPERIMENTAL - -namespace internal { -class AppInternal; -} // namespace internal - -/// @brief Reports whether a Firebase module initialized successfully. -enum InitResult { - /// The given library was successfully initialized. - kInitResultSuccess = 0, - - /// The given library failed to initialize due to a missing dependency. - /// - /// On Android, this typically means that Google Play services is not - /// available and the library requires it. - /// @if cpp_examples - /// Use google_play_services::CheckAvailability() and - /// google_play_services::MakeAvailable() to resolve this issue. - /// @endif - /// - /// @if swig_examples - /// Use FirebaseApp.CheckDependencies() and - /// FirebaseApp.FixDependenciesAsync() to resolve this issue. - /// @endif - /// - /// - /// Also, on Android, this value can be returned if the Java dependencies of a - /// Firebase component are not included in the application, causing - /// initialization to fail. This means that the application's build - /// environment is not configured correctly. To resolve the problem, - /// see the SDK setup documentation for the set of Java dependencies (AARs) - /// required for the component that failed to initialize. - kInitResultFailedMissingDependency -}; - -/// @brief Default name for firebase::App() objects. -extern const char* const kDefaultAppName; - -/// @brief Options that control the creation of a Firebase App. -/// @if cpp_examples -/// @see firebase::App -/// @endif -/// -/// @if swig_examples -/// @see FirebaseApp -/// @endif -/// -class AppOptions { - friend class App; - - public: - /// @brief Create AppOptions. - /// - /// @if cpp_examples - /// To create a firebase::App object, the Firebase application identifier - /// and API key should be set using set_app_id() and set_api_key() - /// respectively. - /// - /// @see firebase::App::Create(). - /// @endif - /// - /// @if swig_examples - /// To create a FirebaseApp object, the Firebase application identifier - /// and API key should be set using AppId and ApiKey respectively. - /// - /// @see FirebaseApp.Create(). - /// @endif - /// - AppOptions() {} - - /// Set the Firebase app ID used to uniquely identify an instance of an app. - /// - /// This is the mobilesdk_app_id in the Android google-services.json config - /// file or GOOGLE_APP_ID in the GoogleService-Info.plist. - /// - /// This only needs to be specified if your application does not include - /// google-services.json or GoogleService-Info.plist in its resources. - void set_app_id(const char* id) { app_id_ = id; } - - /// Retrieves the app ID. - /// - /// @if cpp_examples - /// @see set_app_id(). - /// @endif - /// - /// - /// @xmlonly - /// - /// Gets or sets the App Id. - /// - /// This is the mobilesdk_app_id in the Android google-services.json config - /// file or GOOGLE_APP_ID in the GoogleService-Info.plist. - /// - /// This only needs to be specified if your application does not include - /// google-services.json or GoogleService-Info.plist in its resources. - /// - /// @endxmlonly - /// - const char* app_id() const { return app_id_.c_str(); } - - /// API key used to authenticate requests from your app. - /// - /// For example, "AIzaSyDdVgKwhZl0sTTTLZ7iTmt1r3N2cJLnaDk" used to identify - /// your app to Google servers. - /// - /// This only needs to be specified if your application does not include - /// google-services.json or GoogleService-Info.plist in its resources. - void set_api_key(const char* key) { api_key_ = key; } - - /// Get the API key. - /// - /// @if cpp_examples - /// @see set_api_key(). - /// @endif - /// - /// - /// @xmlonly - /// - /// Gets or sets the API key used to authenticate requests from your app. - /// - /// For example, \"AIzaSyDdVgKwhZl0sTTTLZ7iTmt1r3N2cJLnaDk\" used to identify - /// your app to Google servers. - /// - /// This only needs to be specified if your application does not include - /// google-services.json or GoogleService-Info.plist in its resources. - /// - /// @endxmlonly - /// - const char* api_key() const { return api_key_.c_str(); } - - /// Set the Firebase Cloud Messaging sender ID. - /// - /// For example "012345678901", used to configure Firebase Cloud Messaging. - /// - /// This only needs to be specified if your application does not include - /// google-services.json or GoogleService-Info.plist in its resources. - void set_messaging_sender_id(const char* sender_id) { - fcm_sender_id_ = sender_id; - } - - /// Get the Firebase Cloud Messaging sender ID. - /// - /// @if cpp_examples - /// @see set_messaging_sender_id(). - /// @endif - /// - /// - /// @xmlonly - /// - /// Gets or sets the messaging sender Id. - /// - /// This only needs to be specified if your application does not include - /// google-services.json or GoogleService-Info.plist in its resources. - /// - /// @endxmlonly - /// - const char* messaging_sender_id() const { return fcm_sender_id_.c_str(); } - - /// Set the database root URL, e.g. @"http://abc-xyz-123.firebaseio.com". - void set_database_url(const char* url) { database_url_ = url; } - - /// Get database root URL, e.g. @"http://abc-xyz-123.firebaseio.com". - /// - /// - /// @xmlonly - /// - /// Gets or sets the database root URL, e.g. - /// @\"http://abc-xyz-123.firebaseio.com\". - /// - /// @endxmlonly - /// - const char* database_url() const { return database_url_.c_str(); } - - /// @cond FIREBASE_APP_INTERNAL - - /// Set the tracking ID for Google Analytics, e.g. @"UA-12345678-1". - void set_ga_tracking_id(const char* id) { ga_tracking_id_ = id; } - - /// Get the tracking ID for Google Analytics, - /// - /// @if cpp_examples - /// @see set_ga_tracking_id(). - /// @endif - /// - const char* ga_tracking_id() const { return ga_tracking_id_.c_str(); } - - /// @endcond - - /// Set the Google Cloud Storage bucket name, - /// e.g. @\"abc-xyz-123.storage.firebase.com\". - void set_storage_bucket(const char* bucket) { storage_bucket_ = bucket; } - - /// Get the Google Cloud Storage bucket name, - /// @see set_storage_bucket(). - /// - /// @xmlonly - /// - /// Gets or sets the Google Cloud Storage bucket name, e.g. - /// @\"abc-xyz-123.storage.firebase.com\". - /// - /// @endxmlonly - /// - const char* storage_bucket() const { return storage_bucket_.c_str(); } - - /// Set the Google Cloud project ID. - void set_project_id(const char* project) { project_id_ = project; } - - /// Get the Google Cloud project ID. - /// - /// This is the project_id in the Android google-services.json config - /// file or PROJECT_ID in the GoogleService-Info.plist. - /// - /// @xmlonly - /// - /// Gets the Google Cloud project ID. - /// - /// This is the project_id in the Android google-services.json config - /// file or PROJECT_ID in the GoogleService-Info.plist. - /// - /// @endxmlonly - /// - const char* project_id() const { return project_id_.c_str(); } - -#ifdef INTERNAL_EXPERIMENTAL - /// @brief set the iOS client ID. - /// - /// This is the clientID in the GoogleService-Info.plist. - void set_client_id(const char* client_id) { client_id_ = client_id; } - - /// @brief Get the iOS client ID. - /// - /// This is the client_id in the GoogleService-Info.plist. - const char* client_id() const { return client_id_.c_str(); } -#endif // INTERNAL_EXPERIMENTAL - -#ifdef INTERNAL_EXPERIMENTAL - /// @brief Set the Android or iOS client project name. - /// - /// This is the project_name in the Android google-services.json config - /// file or BUNDLE_ID in the GoogleService-Info.plist. - void set_package_name(const char* package_name) { - package_name_ = package_name; - } - - /// @brief Get the Android or iOS client project name. - /// - /// This is the project_name in the Android google-services.json config - /// file or BUNDLE_ID in the GoogleService-Info.plist. - const char* package_name() const { return package_name_.c_str(); } -#endif // INTERNAL_EXPERIMENTAL - - /// @brief Load options from a config string. - /// - /// @param[in] config A JSON string that contains Firebase configuration i.e. - /// the content of the downloaded google-services.json file. - /// @param[out] options Optional: If provided, load options into it. - /// - /// @returns An instance containing the loaded options if successful. - /// If the options argument to this function is null, this method returns an - /// AppOptions instance allocated from the heap. - static AppOptions* LoadFromJsonConfig(const char* config, - AppOptions* options = nullptr); - -#if INTERNAL_EXPERIMENTAL - /// @brief Determine whether the specified options match this set of options. - /// - /// Fields of this object that are empty are ignored in the comparison. - /// - /// @param[in] options Options to compare with. - bool operator==(const AppOptions& options) const { - return (package_name_.empty() || package_name_ == options.package_name_) && - (api_key_.empty() || api_key_ == options.api_key_) && - (app_id_.empty() || app_id_ == options.app_id_) && - (database_url_.empty() || database_url_ == options.database_url_) && - (ga_tracking_id_.empty() || - ga_tracking_id_ == options.ga_tracking_id_) && - (fcm_sender_id_.empty() || - fcm_sender_id_ == options.fcm_sender_id_) && - (storage_bucket_.empty() || - storage_bucket_ == options.storage_bucket_) && - (project_id_.empty() || project_id_ == options.project_id_); - } -#endif // INTERNAL_EXPERIMENTAL - -#if INTERNAL_EXPERIMENTAL - /// @brief Determine whether the specified options don't match this set of - /// options. - /// - /// Fields of this object that are empty are ignored in the comparison. - /// - /// @param[in] options Options to compare with. - bool operator!=(const AppOptions& options) const { - return !operator==(options); - } -#endif // INTERNAL_EXPERIMENTAL - -#if INTERNAL_EXPERIMENTAL -#if FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) - /// @brief Load default options from the resource file. - /// - /// @param[in] jni_env JNI environment required to allow Firebase services - /// to interact with the Android framework. - /// @param[in] activity JNI reference to the Android activity, required to - /// allow Firebase services to interact with the Android application. - /// @param options Options to populate from a resource file. - /// - /// @return An instance containing the loaded options if successful. - /// If the options argument to this function is null, this method returns an - /// AppOptions instance allocated from the heap.. - static AppOptions* LoadDefault(AppOptions* options, JNIEnv* jni_env, - jobject activity); -#endif // FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) - -#if !FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) - /// @brief Load default options from the resource file. - /// - /// @param options Options to populate from a resource file. - /// - /// @return An instance containing the loaded options if successful. - /// If the options argument to this function is null, this method returns an - /// AppOptions instance allocated from the heap. - static AppOptions* LoadDefault(AppOptions* options); -#endif // !FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) -#endif // INTERNAL_EXPERIMENTAL - -#if INTERNAL_EXPERIMENTAL -#if FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) - /// @brief Attempt to populate required options with default values if not - /// specified. - /// - /// @param[in] jni_env JNI environment required to allow Firebase services - /// to interact with the Android framework. - /// @param[in] activity JNI reference to the Android activity, required to - /// allow Firebase services to interact with the Android application. - /// - /// @return true if successful, false otherwise. - bool PopulateRequiredWithDefaults(JNIEnv* jni_env, jobject activity); -#endif // FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) - -#if !FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) - /// @brief Attempt to populate required options with default values if not - /// specified. - /// - /// @return true if successful, false otherwise. - bool PopulateRequiredWithDefaults(); -#endif // !FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) -#endif // INTERNAL_EXPERIMENTAL - - /// @cond FIREBASE_APP_INTERNAL - private: - /// Application package name (e.g Android package name or iOS bundle ID). - std::string package_name_; - /// API key used to communicate with Google Servers. - std::string api_key_; - /// ID of the app. - std::string app_id_; - /// ClientID of the app. - std::string client_id_; - /// Database root URL. - std::string database_url_; - /// Google analytics tracking ID. - std::string ga_tracking_id_; - /// FCM sender ID. - std::string fcm_sender_id_; - /// Google Cloud Storage bucket name. - std::string storage_bucket_; - /// Google Cloud project ID. - std::string project_id_; - /// @endcond -}; - -/// @brief Firebase application object. -/// -/// @if cpp_examples -/// firebase::App acts as a conduit for communication between all Firebase -/// services used by an application. -/// -/// For example: -/// @code -/// #if defined(__ANDROID__) -/// firebase::App::Create(firebase::AppOptions(), jni_env, activity); -/// #else -/// firebase::App::Create(firebase::AppOptions()); -/// #endif // defined(__ANDROID__) -/// @endcode -/// @endif -/// -/// @if swig_examples -/// FirebaseApp acts as a conduit for communication between all Firebase -/// services used by an application. A default instance is created -/// automatically, based on settings in your Firebase configuration file, -/// and all of the Firebase APIs connect with it automatically. -/// @endif -class App { - public: - ~App(); - -#if !FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) - /// @brief Initializes the default firebase::App with default options. - /// - /// @note This method is specific to non-Android implementations. - /// - /// @return New App instance, the App should not be destroyed for the - /// lifetime of the application. If default options can't be loaded this - /// will return null. - static App* Create(); -#endif // !FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) - -#ifndef SWIG -// -// For Unity, we actually use the simpler, iOS version for both platforms -// -#if FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) - /// @brief Initializes the default firebase::App with default options. - /// - /// @note This method is specific to the Android implementation. - /// - /// @param[in] jni_env JNI environment required to allow Firebase services - /// to interact with the Android framework. - /// @param[in] activity JNI reference to the Android activity, required to - /// allow Firebase services to interact with the Android application. - /// - /// @return New App instance. The App should not be destroyed for the - /// lifetime of the application. If default options can't be loaded this - /// will return null. - static App* Create(JNIEnv* jni_env, jobject activity); -#endif // FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) -#endif // SWIG - -#if !FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) - /// @brief Initializes the default firebase::App with the given options. - /// - /// @note This method is specific to non-Android implementations. - /// - /// Options are copied at initialization time, so changes to the object are - /// ignored. - /// @param[in] options Options that control the creation of the App. - /// - /// @return New App instance, the App should not be destroyed for the - /// lifetime of the application. - static App* Create(const AppOptions& options); -#endif // !FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) - -#ifndef SWIG -// -// For Unity, we actually use the simpler, iOS version for both platforms -// -#if FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) - /// @brief Initializes the default firebase::App with the given options. - /// - /// @note This method is specific to the Android implementation. - /// - /// Options are copied at initialization time, so changes to the object are - /// ignored. - /// @param[in] options Options that control the creation of the App. - /// @param[in] jni_env JNI environment required to allow Firebase services - /// to interact with the Android framework. - /// @param[in] activity JNI reference to the Android activity, required to - /// allow Firebase services to interact with the Android application. - /// - /// @return New App instance. The App should not be destroyed for the - /// lifetime of the application. - static App* Create(const AppOptions& options, JNIEnv* jni_env, - jobject activity); -#endif // FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) -#endif // SWIG - -#if !FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) - /// @brief Initializes a firebase::App with the given options that operates - /// on the named app. - /// - /// @note This method is specific to non-Android implementations. - /// - /// Options are copied at initialization time, so changes to the object are - /// ignored. - /// @param[in] options Options that control the creation of the App. - /// @param[in] name Name of this App instance. This is only required when - /// one application uses multiple App instances. - /// - /// @return New App instance, the App should not be destroyed for the - /// lifetime of the application. - static App* Create(const AppOptions& options, const char* name); -#endif // !FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) - -#ifndef SWIG -// -// For Unity, we actually use the simpler iOS version for both platforms -// -#if FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) - /// @brief Initializes a firebase::App with the given options that operates - /// on the named app. - /// - /// @note This method is specific to the Android implementation. - /// - /// Options are copied at initialization time, so changes to the object are - /// ignored. - /// @param[in] options Options that control the creation of the App. - /// @param[in] name Name of this App instance. This is only required when - /// one application uses multiple App instances. - /// @param[in] jni_env JNI environment required to allow Firebase services - /// to interact with the Android framework. - /// @param[in] activity JNI reference to the Android activity, required to - /// allow Firebase services to interact with the Android application. - /// - /// @return New App instance. The App should not be destroyed for the - /// lifetime of the application. - static App* Create(const AppOptions& options, const char* name, - JNIEnv* jni_env, jobject activity); -#endif // FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) -#endif // SWIG - - /// Get the default App, or nullptr if none has been created. - static App* GetInstance(); - - /// Get the App with the given name, or nullptr if none have been created. - static App* GetInstance(const char* name); - -#ifndef SWIG -// -// Unity doesn't need the JNI from here, it has its method to access JNI. -// -#if FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) - /// Get Java virtual machine, retrieved from the initial JNI environment. - /// @note This method is specific to the Android implementation. - /// - /// @return JNI Java virtual machine object. - JavaVM* java_vm() const; - /// Get JNI environment, needed for performing JNI calls, set on creation. - /// This is not trivial as the correct environment needs to retrieved per - /// thread. - /// @note This method is specific to the Android implementation. - /// - /// @return JNI environment object. - JNIEnv* GetJNIEnv() const; - /// Get a global reference to the Android activity provided to the App on - /// creation. Also serves as the Context needed for Firebase calls. - /// @note This method is specific to the Android implementation. - /// - /// @return Global JNI reference to the Android activity used to create - /// the App. The reference count of the returned object is not increased. - jobject activity() const { return activity_; } -#endif // FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) -#endif // SWIG - - /// Get the name of this App instance. - /// - /// @return The name of this App instance. If a name wasn't provided via - /// Create(), this returns @ref kDefaultAppName. - /// - /// @xmlonly - /// - /// Get the name of this FirebaseApp instance. - /// If a name wasn't provided via Create(), this will match @ref DefaultName. - /// - /// @endxmlonly - /// - const char* name() const { return name_.c_str(); } - - /// Get options the App was created with. - /// - /// @return Options used to create the App. - /// - /// @xmlonly - /// - /// @brief Get the AppOptions the FirebaseApp was created with. - /// @return AppOptions used to create the FirebaseApp. - /// - /// @endxmlonly - /// - const AppOptions& options() const { return options_; } - -#ifdef INTERNAL_EXPERIMENTAL - /// Sets whether automatic data collection is enabled for all products. - /// - /// By default, automatic data collection is enabled. To disable automatic - /// data collection in your mobile app, add to your Android application's - /// manifest: - /// - /// @if NOT_DOXYGEN - /// - /// @else - /// @code - /// <meta-data android:name="firebase_data_collection_default_enabled" - /// android:value="false" /> - /// @endcode - /// @endif - /// - /// or on iOS to your Info.plist: - /// - /// @if NOT_DOXYGEN - /// FirebaseDataCollectionDefaultEnabled - /// - /// @else - /// @code - /// <key>FirebaseDataCollectionDefaultEnabled</key> - /// <false/> - /// @endcode - /// @endif - /// - /// Once your mobile app is set to disable automatic data collection, you can - /// ask users to consent to data collection, and then enable it after their - /// approval by calling this method. - /// - /// This value is persisted across runs of the app so that it can be set once - /// when users have consented to collection. - /// - /// @param enabled Whether or not to enable automatic data collection. - void SetDataCollectionDefaultEnabled(bool enabled); - - /// Gets whether automatic data collection is enabled for all - /// products. Defaults to true unless - /// "firebase_data_collection_default_enabled" is set to false in your - /// Android manifest and FirebaseDataCollectionDefaultEnabled is set to NO - /// in your iOS app's Info.plist. - /// - /// @return Whether or not automatic data collection is enabled for all - /// products. - bool IsDataCollectionDefaultEnabled() const; -#endif // INTERNAL_EXPERIMENTAL -#ifdef SWIG - void SetDataCollectionDefaultEnabled(bool enabled); - bool IsDataCollectionDefaultEnabled() const; -#endif // SWIG - -#ifdef INTERNAL_EXPERIMENTAL - // This is only visible to SWIG and internal users of firebase::App. - /// Get the initialization results of modules that were initialized when - /// creating this app. - /// - /// @return Initialization results of modules indexed by module name. - const std::map& init_results() const { - return init_results_; - } - - // Returns a pointer to the function registry, used by components to expose - // methods to one another without introducing linkage dependencies. - internal::FunctionRegistry* function_registry(); - - /// @brief Register a library which utilizes the Firebase C++ SDK. - /// - /// @param library Name of the library to register as a user of the Firebase - /// C++ SDK. - /// @param version Version of the library being registered. - static void RegisterLibrary(const char* library, const char* version); - - // Internal method to retrieve the combined string of registered libraries. - static const char* GetUserAgent(); - - // On desktop, when App.Create() is invoked without parameters, it looks for a - // file named 'google-services-desktop.json', to load parameters from. - // This function sets the location to search in. - // Note - when setting this, make sure to end the path with the appropriate - // path separator! - static void SetDefaultConfigPath(const char* path); -#endif // INTERNAL_EXPERIMENTAL - -#ifdef INTERNAL_EXPERIMENTAL -#if FIREBASE_PLATFORM_DESKTOP - // These methods are only visible to SWIG and internal users of firebase::App. - - /// Logs a heartbeat using the internal HeartbeatController. - void LogHeartbeat() const; - - /// Get a pointer to the HeartbeatController associated with this app. - std::shared_ptr GetHeartbeatController() - const; -#endif // FIREBASE_PLATFORM_DESKTOP -#endif // INTERNAL_EXPERIMENTAL - -#ifdef INTERNAL_EXPERIMENTAL -#if FIREBASE_PLATFORM_ANDROID - /// Get the platform specific app implementation referenced by this object. - /// - /// @return Global reference to the FirebaseApp. The returned reference - /// most be deleted after use. - jobject GetPlatformApp() const; -#elif FIREBASE_PLATFORM_IOS || FIREBASE_PLATFORM_TVOS -#ifdef __OBJC__ - /// Get the platform specific app implementation referenced by this object. - /// - /// @return Reference to the FIRApp object owned by this app. - FIRApp* GetPlatformApp() const; -#endif // __OBJC__ -#endif // FIREBASE_PLATFORM_ANDROID, FIREBASE_PLATFORM_IOS, - // FIREBASE_PLATFORM_TVOS -#endif // INTERNAL_EXPERIMENTAL - - private: - /// Construct the object. - App() - : -#if FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) - activity_(nullptr), -#endif - internal_(nullptr) { - Initialize(); - -#ifdef FIREBASE_LINUX_BUILD_CONFIG_STRING - CheckCompilerString(FIREBASE_LINUX_BUILD_CONFIG_STRING); -#endif // FIREBASE_LINUX_BUILD_CONFIG_STRING - } - - /// Initialize internal implementation - void Initialize(); - -#ifndef SWIG -// -// Unity doesn't need the JNI from here, it has its method to access JNI. -// -#if FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) - /// Android activity. - /// @note This is specific to Android. - jobject activity_; -#endif // FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) -#endif // SWIG - - /// Name of the App instance. - std::string name_; - /// Options used to create this App instance. - AppOptions options_; - /// Module initialization results. - std::map init_results_; - /// Pointer to other internal data used by this instance. - internal::AppInternal* internal_; - - /// @endcond -}; - -} // namespace firebase - -#endif // FIREBASE_APP_SRC_INCLUDE_FIREBASE_APP_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/auth.h b/packages/firebase_core/firebase_core/firebase_core/firebase/auth.h deleted file mode 100644 index 408c34ea9006..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/auth.h +++ /dev/null @@ -1,939 +0,0 @@ -/* - * Copyright 2016 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_AUTH_SRC_INCLUDE_FIREBASE_AUTH_H_ -#define FIREBASE_AUTH_SRC_INCLUDE_FIREBASE_AUTH_H_ - -#include - -#include "firebase/app.h" -#include "firebase/auth/user.h" -#include "firebase/future.h" -#include "firebase/internal/common.h" - -#if !defined(DOXYGEN) -#ifndef SWIG -FIREBASE_APP_REGISTER_CALLBACKS_REFERENCE(auth) -#endif // SWIG -#endif // !defined(DOXYGEN) - -namespace firebase { - -/// @brief Firebase Authentication API. -/// -/// Firebase Authentication provides backend services to securely authenticate -/// users. It can authenticate users using passwords and federated identity -/// provider credentials, and it can integrate with a custom auth backend. -namespace auth { - -// Predeclarations. -struct AuthData; -class AuthStateListener; -class IdTokenListener; -class PhoneAuthProvider; -struct AuthCompletionHandle; -class FederatedAuthProvider; -class FederatedOAuthProvider; -struct SignInResult; - -/// @brief Firebase authentication object. -/// -/// -/// @if swig_examples -/// Firebase.Auth.FirebaseAuth is the gateway to the Firebase authentication -/// API. With it, you can reference @ref Firebase.Auth.FirebaseAuth objects to -/// manage user accounts and credentials. -/// -/// Each @ref Firebase.FirebaseApp has up to one Firebase.Auth.FirebaseAuth -/// class. You acquire the Firebase.Auth.FirebaseAuth class through the static -/// function @ref Firebase.Auth.FirebaseAuth.GetAuth. -/// -/// For example: -/// @code{.cs} -/// // Get the Auth class for your App. -/// Firebase.Auth.FirebaseAuth auth = Firebase.Auth.FirebaseAuth.GetAuth(app); -/// -/// // Request anonymous sign-in and wait until asynchronous call completes. -/// auth.SignInAnonymouslyAsync().ContinueWith((authTask) => { -/// // Print sign in results. -/// if (authTask.IsCanceled) { -/// DebugLog("Sign-in canceled."); -/// } else if (authTask.IsFaulted) { -/// DebugLog("Sign-in encountered an error."); -/// DebugLog(authTask.Exception.ToString()); -/// } else if (authTask.IsCompleted) { -/// Firebase.Auth.User user = authTask.Result; -/// DebugLog(String.Format("Signed in as {0} user.", -/// user.Anonymous ? "an anonymous" : "a non-anonymous")); -/// DebugLog("Signing out."); -/// auth.SignOut(); -/// }); -/// @endcode -/// @endif -/// -/// @if cpp_examples -/// -/// firebase::auth::Auth is the gateway to the Firebase authentication API. -/// With it, you can reference @ref firebase::auth::User objects to manage user -/// accounts and credentials. -/// -/// Each @ref firebase::App has up to one firebase::auth::Auth class. You -/// acquire the firebase::auth::Auth class through the static function -/// @ref firebase::auth::Auth::GetAuth. -/// -/// For example: -/// @code{.cpp} -/// -/// // Get the Auth class for your App. -/// firebase::auth::Auth* auth = firebase::auth::Auth::GetAuth(app); -/// -/// // Request anonymous sign-in and wait until asynchronous call completes. -/// firebase::Future sign_in_future = -/// auth->SignInAnonymously(); -/// while(sign_in_future.status() == firebase::kFutureStatusPending) { -/// // when polling, like this, make sure you service your platform's -/// // message loop -/// // see https://github.com/firebase/quickstart-cpp for a sample -/// ProcessEvents(300); -/// std::cout << "Signing in...\n"; -/// } -/// -/// const firebase::auth::AuthError error = -/// static_cast(sign_in_future.error()); -/// if (error != firebase::auth::kAuthErrorNone) { -/// std::cout << "Sign in failed with error '" -/// << sign_in_future.error_message() << "'\n"; -/// } else { -/// firebase::auth::User* user = *sign_in_future.result(); -/// // is_anonymous from Anonymous -/// std::cout << "Signed in as " -/// << (user->is_anonymous() ? "an anonymous" : "a non-anonymous") -/// << " user\n"; -/// } -/// @endcode -/// @endif -class Auth { - public: - /// @brief Results of calls @ref FetchProvidersForEmail. - /// - /// - /// @if swig_examples - /// @see FirebaseAuth.FetchProvidersForEmailAsync(). - /// @endif - /// - struct FetchProvidersResult { - /// The IDPs (identity providers) that can be used for `email`. - /// An array of length `num_providers` of null-terminated strings. - /// - /// The C# doc string is in the SWIG file because nested structs are - /// causing problems b/35780150 - /// - std::vector providers; - }; - - ~Auth(); - - /// Synchronously gets the cached current user, or nullptr if there is none. - /// @note This function may block and wait until the Auth instance finishes - /// loading the saved user's state. This should only happen for a short - /// period of time after the Auth instance is created. - /// - /// @xmlonly - /// - /// Synchronously gets the cached current user, or null if there is none. - /// @note This function may block and wait until the Auth instance finishes - /// loading the saved user's state. This should only happen for a short - /// period of time after the Auth instance is created. - /// - /// @endxmlonly - /// - User* current_user(); - - /// The current user language code. This can be set to the app’s current - /// language by calling set_language_code. The string must be a language code - /// that follows BCP 47. This will return an empty string if the app default - /// language code is being used. - std::string language_code() const; - - /// Sets the user-facing language code for auth operations that can be - /// internationalized, such as FirebaseUser.sendEmailVerification(). This - /// language code should follow the conventions defined by the IETF in BCP 47. - void set_language_code(const char* language_code); - - /// Sets the user-facing language code to be the default app language. This - /// uses a language associated with the device's locale data. On desktop - /// this will set the language code to the Firebase service's default. You - /// may subsequently customize the language code again by invoking - /// set_language_code(). - void UseAppLanguage(); - - // ----- Providers ------------------------------------------------------- - /// Asynchronously requests the IDPs (identity providers) that can be used - /// for the given email address. - /// - /// Useful for an "identifier-first" login flow. - /// - /// @if cpp_examples - /// The following sample code illustrates a possible login screen - /// that allows the user to pick an identity provider. - /// @code{.cpp} - /// // This function is called every frame to display the login screen. - /// // Returns the identity provider name, or "" if none selected. - /// const char* DisplayIdentityProviders(firebase::auth::Auth& auth, - /// const char* email) { - /// // Get results of most recent call to FetchProvidersForEmail(). - /// firebase::Future future = - /// auth.FetchProvidersForEmailLastResult(); - /// const firebase::auth::Auth::FetchProvidersResult* result = - /// future.result(); - /// - /// // Header. - /// ShowTextBox("Sign in %s", email); - /// - /// // Fetch providers from the server if we need to. - /// const bool refetch = - /// future.status() == firebase::kFutureStatusInvalid || - /// (result != nullptr && strcmp(email, result->email.c_str()) != 0); - /// if (refetch) { - /// auth.FetchProvidersForEmail(email); - /// } - /// - /// // Show a waiting icon if we're waiting for the asynchronous call to - /// // complete. - /// if (future.status() != firebase::kFutureStatusComplete) { - /// ShowImage("waiting icon"); - /// return ""; - /// } - /// - /// // Show error code if the call failed. - /// if (future.error() != firebase::auth::kAuthErrorNone) { - /// ShowTextBox("Error fetching providers: %s", future.error_message()); - /// } - /// - /// // Show a button for each provider available to this email. - /// // Return the provider for the button that's pressed. - /// for (size_t i = 0; i < result->providers.size(); ++i) { - /// const bool selected = ShowTextButton(result->providers[i].c_str()); - /// if (selected) return result->providers[i].c_str(); - /// } - /// return ""; - /// } - /// @endcode - /// @endif - Future FetchProvidersForEmail(const char* email); - - /// Get results of the most recent call to @ref FetchProvidersForEmail. - Future FetchProvidersForEmailLastResult() const; - - // ----- Sign In --------------------------------------------------------- - /// Asynchronously logs into Firebase with the given Auth token. - /// - /// An error is returned, if the token is invalid, expired or otherwise - /// not accepted by the server. - Future SignInWithCustomToken(const char* token); - - /// Get results of the most recent call to @ref SignInWithCustomToken. - Future SignInWithCustomTokenLastResult() const; - - /// Convenience method for @ref SignInAndRetrieveDataWithCredential that - /// doesn't return additional identity provider data. - Future SignInWithCredential(const Credential& credential); - - /// Get results of the most recent call to @ref SignInWithCredential. - Future SignInWithCredentialLastResult() const; - - /// Sign-in a user authenticated via a federated auth provider. - /// - /// @param[in] provider Contains information on the provider to authenticate - /// with. - /// - /// @return A Future with the result of the sign-in request. - /// - /// @note: This operation is supported only on iOS, tvOS and Android - /// platforms. On other platforms this method will return a Future with a - /// preset error code: kAuthErrorUnimplemented. - Future SignInWithProvider(FederatedAuthProvider* provider); - - /// Asynchronously logs into Firebase with the given credentials. - /// - /// For example, the credential could wrap a Facebook login access token or - /// a Twitter token/token-secret pair. - /// - /// The SignInResult contains both a reference to the User (which can be null - /// if the sign in failed), and AdditionalUserInfo, which holds details - /// specific to the Identity Provider used to sign in. - /// - /// An error is returned if the token is invalid, expired, or otherwise not - /// accepted by the server. - Future SignInAndRetrieveDataWithCredential( - const Credential& credential); - - /// Get results of the most recent call to - /// @ref SignInAndRetrieveDataWithCredential. - Future SignInAndRetrieveDataWithCredentialLastResult() const; - - /// Asynchronously creates and becomes an anonymous user. - /// If there is already an anonymous user signed in, that user will be - /// returned instead. - /// If there is any other existing user, that user will be signed out. - /// - /// - /// @if swig_examples - /// @code{.cs} - /// bool SignIn(Firebase.Auth.FirebaseAuth auth) { - /// auth.SignInAnonymouslyAsync().ContinueWith((authTask) => { - /// if (authTask.IsCanceled) { - /// DebugLog("Anonymous sign in canceled."); - /// } else if (authTask.IsFaulted) { - /// DebugLog("Anonymous sign in encountered an error."); - /// DebugLog(authTask.Exception.ToString()); - /// } else if (authTask.IsCompleted) { - /// DebugLog("Anonymous sign in successful!"); - /// } - /// }); - /// } - /// @endcode - /// @endif - /// - /// @if cpp_examples - /// The following sample code illustrates the sign-in flow that might be - /// used by a game or some other program with a regular (for example, 30Hz) - /// update loop. - /// - /// The sample calls SignIn() every frame. We don’t maintain our own - /// Futures but instead call SignInAnonymouslyLastResult() to get the Future - /// of our most recent call. - /// - /// @code{.cpp} - /// // Try to ensure that we get logged in. - /// // This function is called every frame. - /// bool SignIn(firebase::auth::Auth& auth) { - /// // Grab the result of the latest sign-in attempt. - /// firebase::Future future = - /// auth.SignInAnonymouslyLastResult(); - /// - /// // If we're in a state where we can try to sign in, do so. - /// if (future.status() == firebase::kFutureStatusInvalid || - /// (future.status() == firebase::kFutureStatusComplete && - /// future.error() != firebase::auth::kAuthErrorNone)) { - /// auth.SignInAnonymously(); - /// } - /// - /// // We're signed in if the most recent result was successful. - /// return future.status() == firebase::kFutureStatusComplete && - /// future.error() == firebase::auth::kAuthErrorNone; - /// } - /// @endcode - /// @endif - Future SignInAnonymously(); - - /// Get results of the most recent call to @ref SignInAnonymously. - Future SignInAnonymouslyLastResult() const; - - /// Signs in using provided email address and password. - /// An error is returned if the password is wrong or otherwise not accepted - /// by the server. - Future SignInWithEmailAndPassword(const char* email, - const char* password); - - /// Get results of the most recent call to @ref SignInWithEmailAndPassword. - Future SignInWithEmailAndPasswordLastResult() const; - - /// Creates, and on success, logs in a user with the given email address - /// and password. - /// - /// An error is returned when account creation is unsuccessful - /// (due to another existing account, invalid password, etc.). - Future CreateUserWithEmailAndPassword(const char* email, - const char* password); - - /// Get results of the most recent call to - /// @ref CreateUserWithEmailAndPassword. - Future CreateUserWithEmailAndPasswordLastResult() const; - - /// Removes any existing authentication credentials from this client. - /// This function always succeeds. - void SignOut(); - - // ----- Password Reset ------------------------------------------------- - /// Initiates a password reset for the given email address. - /// - /// If the email address is not registered, then the returned task has a - /// status of IsFaulted. - /// - /// - /// @if swig_examples - /// @code{.cs} - /// void ResetPassword(string email) { - /// auth.SendPasswordResetEmail(email).ContinueWith((authTask) => { - /// if (authTask.IsCanceled) { - /// DebugLog("Password reset was canceled."); - /// } else if (authTask.IsFaulted) { - /// DebugLog("Password reset encountered an error."); - /// DebugLog(authTask.Exception.ToString()); - /// } else if (authTask.IsCompleted) { - /// DebugLog("Password reset successful!"); - /// } - /// }); - /// } - /// @endcode - /// @endif - /// - /// @if cpp_examples - /// The following sample code illustrating a possible password reset flow. - /// Like in the Anonymous Sign-In example above, the ResetPasswordScreen() - /// function is called once per frame (say 30 times per second). - /// - /// No state is persisted by the caller in this example. The state of the - /// most recent calls are instead accessed through calls to functions like - /// auth.SendPasswordResetEmailLastResult(). - /// @code{.cpp} - /// const char* ImageNameForStatus(const firebase::FutureBase& future) { - /// assert(future.status() != firebase::kFutureStatusInvalid); - /// return future.status() == firebase::kFutureStatusPending - /// ? "waiting icon" - /// : future.error() == firebase::auth::kAuthErrorNone - /// ? "checkmark icon" - /// : "x mark icon"; - /// } - /// - /// // This function is called once per frame. - /// void ResetPasswordScreen(firebase::auth::Auth& auth) { - /// // Gather email address. - /// // ShowInputBox() returns a value when `enter` is pressed. - /// const std::string email = ShowInputBox("Enter e-mail"); - /// if (email != "") { - /// auth.SendPasswordResetEmail(email.c_str()); - /// } - /// - /// // Show checkmark, X-mark, or waiting icon beside the - /// // email input box, to indicate if email has been sent. - /// firebase::Future send_future = - /// auth.SendPasswordResetEmailLastResult(); - /// ShowImage(ImageNameForStatus(send_future)); - /// - /// // Display error message if the e-mail could not be sent. - /// if (send_future.status() == firebase::kFutureStatusComplete && - /// send_future.error() != firebase::auth::kAuthErrorNone) { - /// ShowTextBox(send_future.error_message()); - /// } - /// } - /// @endcode - /// @endif - Future SendPasswordResetEmail(const char* email); - - /// Get results of the most recent call to @ref SendPasswordResetEmail. - Future SendPasswordResetEmailLastResult() const; - -#ifndef SWIG - /// @brief Registers a listener to changes in the authentication state. - /// - /// There can be more than one listener registered at the same time. - /// The listeners are called asynchronously, possibly on a different thread. - /// - /// Authentication state changes are: - /// - Right after the listener has been registered - /// - When a user signs in - /// - When the current user signs out - /// - When the current user changes - /// - /// It is a recommended practice to always listen to sign-out events, as you - /// may want to prompt the user to sign in again and maybe restrict the - /// information or actions they have access to. - /// - /// Use RemoveAuthStateListener to unregister a listener. - /// - /// @note The caller owns `listener` and is responsible for destroying it. - /// When `listener` is destroyed, or when @ref Auth is destroyed, - /// RemoveAuthStateListener is called automatically. - void AddAuthStateListener(AuthStateListener* listener); - - /// @brief Unregisters a listener of authentication changes. - /// - /// Listener must previously been added with AddAuthStateListener. - /// - /// Note that listeners unregister themselves automatically when they - /// are destroyed, and the Auth class unregisters its listeners when the - /// Auth class itself is destroyed, so this function does not normally need - /// to be called explicitly. - void RemoveAuthStateListener(AuthStateListener* listener); - - /// @brief Registers a listener to changes in the ID token state. - /// - /// There can be more than one listener registered at the same time. - /// The listeners are called asynchronously, possibly on a different thread. - /// - /// Authentication state changes are: - /// - Right after the listener has been registered - /// - When a user signs in - /// - When the current user signs out - /// - When the current user changes - /// - When there is a change in the current user's token - /// - /// Use RemoveIdTokenListener to unregister a listener. - /// - /// @note The caller owns `listener` and is responsible for destroying it. - /// When `listener` is destroyed, or when @ref Auth is destroyed, - /// RemoveIdTokenListener is called automatically. - void AddIdTokenListener(IdTokenListener* listener); - - /// @brief Unregisters a listener of ID token changes. - /// - /// Listener must previously been added with AddIdTokenListener. - /// - /// Note that listeners unregister themselves automatically when they - /// are destroyed, and the Auth class unregisters its listeners when the - /// Auth class itself is destroyed, so this function does not normally need - /// to be called explicitly. - void RemoveIdTokenListener(IdTokenListener* listener); -#endif // not SWIG - - /// Gets the App this auth object is connected to. - App& app(); - - /// Returns the Auth object for an App. Creates the Auth if required. - /// - /// To get the Auth object for the default app, use, - /// GetAuth(GetDefaultFirebaseApp()); - /// - /// If the library Auth fails to initialize, init_result_out will be - /// written with the result status (if a pointer is given). - /// - /// @param[in] app The App to use for the Auth object. - /// @param[out] init_result_out Optional: If provided, write the init result - /// here. Will be set to kInitResultSuccess if initialization succeeded, or - /// kInitResultFailedMissingDependency on Android if Google Play services is - /// not available on the current device. - static Auth* GetAuth(App* app, InitResult* init_result_out = nullptr); - - private: - /// @cond FIREBASE_APP_INTERNAL - friend class ::firebase::App; - friend class ::firebase::auth::PhoneAuthProvider; - friend class IdTokenRefreshListener; - friend class IdTokenRefreshThread; - friend class UserDataPersist; - friend class UserDesktopTest; - friend class AuthDesktopTest; - - friend void EnableTokenAutoRefresh(AuthData* authData); - friend void DisableTokenAutoRefresh(AuthData* authData); - friend void ResetTokenRefreshCounter(AuthData* authData); - friend void LogHeartbeat(Auth* auth); - /// @endcond - - // Find Auth instance using App. Return null if the instance does not exist. - static Auth* FindAuth(App* app); - - // Provides access to the auth token for the current user. Returns the - // current user's auth token, or an empty string, if there isn't one. - // Note that this can potentially return an expired token from the cache. - static bool GetAuthTokenForRegistry(App* app, void* /*unused*/, void* out); - - // Provides asynchronous access to the auth token for the current user. Allow - // the caller to force-refresh the token. Even without force-refresh, this - // ensure the future contain a fresh current user's auth token. This function - // returns invalid future if user data is not available. - static bool GetAuthTokenAsyncForRegistry(App* app, void* force_refresh, - void* out_future); - - // Provides access to the current user's uid, equivalent to calling - // this->current_user()->uid(). Returns the current user's uid or an empty - // string, if there isn't one. The out pointer is expected to point to an - // instance of std::string. - static bool GetCurrentUserUidForRegistry(App* app, void* /*unused*/, - void* out); - - // Starts and stops a thread to ensure that the cached auth token is never - // kept long enough for it to expire. Refcounted, so multiple classes can - // register this without causing problems. - static bool StartTokenRefreshThreadForRegistry(App* app, void* /*unused*/, - void* /*unused*/); - static bool StopTokenRefreshThreadForRegistry(App* app, void* /*unused*/, - void* /*unused*/); - - // Adds an indirect auth state listener implemented as a callback and a - // context object. - // - // @param callback a function pointer that takes a single void* argument and - // returns void (i.e. it has type void (*)(void*)). - // @param context a pointer to an arbitrary object that Auth will pass to - // the callback when the auth state changes. - static bool AddAuthStateListenerForRegistry(App* app, void* callback, - void* context); - - // Removes the indirect auth state listener that was added with the same - // arguments. - static bool RemoveAuthStateListenerForRegistry(App* app, void* callback, - void* context); - - // Init and Destroy the platform specific auth data. - void InitPlatformAuth(AuthData* const auth_data); - void DestroyPlatformAuth(AuthData* const auth_data); - - // Call GetAuth() to create an Auth object. - // Constructors and destructors don't make any external calls. - // They just initialize and deinitialize internal variables. - Auth(App* app, void* auth_impl); - - // Delete the internal AuthData object. - void DeleteInternal(); - - // This class uses the pimpl mechanism to avoid exposing platform-dependent - // implementation. - AuthData* auth_data_; -}; - -#ifndef SWIG -/// @brief Listener called when there is a change in the authentication state. -/// -/// Override base class method to handle authentication state changes. -/// Methods are invoked asynchronously and may be invoked on other threads. -class AuthStateListener { - public: - /// @note: Destruction of the listener automatically calls - /// RemoveAuthStateListener() from the Auths this listener is registered with, - /// if those Auths have not yet been destroyed. - virtual ~AuthStateListener(); - - /// Called when the authentication state of `auth` changes. - /// - Right after the listener has been registered - /// - When a user is signed in - /// - When the current user is signed out - /// - When the current user changes - /// - /// @param[in] auth Disambiguates which @ref Auth instance the event - /// corresponds to, in the case where you are using more than one at the same - /// time. - virtual void OnAuthStateChanged(Auth* auth) = 0; - - private: - /// @cond FIREBASE_APP_INTERNAL - friend class Auth; - /// @endcond - - /// The Auths with which this listener has been registered. - std::vector auths_; -}; -#endif // not SWIG - -#ifndef SWIG -/// @brief Listener called when there is a change in the ID token. -/// -/// Override base class method to handle ID token changes. -/// Methods are invoked asynchronously and may be invoked on other threads. -class IdTokenListener { - public: - /// @note: Destruction of the listener automatically calls - /// RemoveIdTokenListener() from the Auths this listener is registered with, - /// if those Auths have not yet been destroyed. - virtual ~IdTokenListener(); - - /// Called when there is a change in the current user's token. - /// - Right after the listener has been registered - /// - When a user signs in - /// - When the current user signs out - /// - When the current user changes - /// - When there is a change in the current user's token - /// - /// @param[in] auth Disambiguates which @ref Auth instance the event - /// corresponds to, in the case where you are using more than one at the same - /// time. - virtual void OnIdTokenChanged(Auth* auth) = 0; - - private: - /// @cond FIREBASE_APP_INTERNAL - friend class Auth; - /// @endcond - - /// The Auths with which this listener has been registered. - std::vector auths_; -}; - -#endif // not SWIG - -/// @brief Used to authenticate with Federated Auth Providers. -/// -/// The federated auth provider implementation may facilitate multiple provider -/// types in the future, with support for OAuth to start. -class FederatedAuthProvider { - public: -#ifdef INTERNAL_EXPERIMENTAL -#ifndef SWIG - /// @brief Contains resulting information of a user authenticated by a - /// Federated Auth Provider. This information will be used by the internal - /// implementation to construct a corresponding User object. - struct AuthenticatedUserData { - /// The unique ID identifies the IdP account. - const char* uid; - - /// [opt] The email of the account. - const char* email; - - /// Whether the sign-in email is verified. - bool is_email_verified; - - /// [opt] The display name for the account. - const char* display_name; - - /// [opt] The username for the account. - const char* user_name; - - /// [opt] The photo Url for the account, if one exists. - const char* photo_url; - - /// The linked provider ID (e.g. "google.com" for the Google provider). - const char* provider_id; - - /// A Firebase Auth ID token for the authenticated user. - const char* access_token; - - /// A Firebase Auth refresh token for the authenticated user. - const char* refresh_token; - - /// [opt] IdP user profile data corresponding to the provided credential. - std::map raw_user_info; - - /// The number of seconds in which the ID token expires. - uint64_t token_expires_in_seconds; - }; - - /// @brief Handlers for client applications to facilitate federated auth - /// requests on non-mobile systems. - template - class Handler { - public: - virtual ~Handler() {} - - /// @brief Application sign-in handler. - /// - /// The application must implement this method to handle federated auth user - /// sign-in requests on non-mobile systems. - /// - /// @param[in] provider_data Contains information on the provider to - /// authenticate with. - /// @param[in] completion_handle Internal data pertaining to this operation - /// which must be passed to SignInComplete once the handler has completed - /// the sign in operation. - /// - /// @see Auth#SignInWithProvider - /// @see SignInComplete - virtual void OnSignIn(const T& provider_data, - AuthCompletionHandle* completion_handle) = 0; - - /// Completion for OnSignIn events. - /// - /// Invoke this method once the corresponding OnSignIn has been fulfilled. - /// This method will trigger the associated Future previously - /// returned from the Auth::SignInWithProvider method. - /// - /// @param[in] completion_handle The handle provided to the application's - /// FederatedAuthProvider::Handler::OnSignIn method. - /// @param[in] user_data The application's resulting Firebase user - /// values following the authorization request. - /// @param[in] auth_error The enumerated status code of the authorization - /// request. - /// @param[in] error_message An optional error message to be set in the - /// Future. - /// - /// @see OnSignIn - /// @see Auth::SignInWithProvider - void SignInComplete(AuthCompletionHandle* completion_handle, - const AuthenticatedUserData& user_data, - AuthError auth_error, const char* error_message); - - /// @brief Application user account link handler. - /// - /// The application must implement this method to handle federated auth user - /// link requests on non-mobile systems. - /// - /// @param[in] provider_data Contains information on the provider to - /// authenticate with. - /// @param[in] completion_handle Internal data pertaining to this operation - /// which must be passed to LinkComplete once the handler has completed the - /// user link operation. - /// - /// @see User#LinkWithProvider - virtual void OnLink(const T& provider_data, - AuthCompletionHandle* completion_handle) = 0; - - /// Completion for non-mobile user authorization handlers. - /// - /// Invoke this method once the OnLine process has been fulfilled. This - /// method will trigger the associated Future previously - /// returned from an invocation of User::LinkWithProvider. - /// - /// @param[in] completion_handle The handle provided to the - /// application's FederatedAuthProvider::Handler::OnLink method. - /// @param[in] user_data The application's resulting Firebase user - /// values following the user link request. - /// @param[in] auth_error The enumerated status code of the user link - /// request. - /// @param[in] error_message An optional error message to be set in the - /// Future. - /// - /// @see OnLink - /// @see User#LinkWithProvider - void LinkComplete(AuthCompletionHandle* completion_handle, - const AuthenticatedUserData& user_data, - AuthError auth_error, const char* error_message); - - /// @brief Application user re-authentication handler. - /// - /// The application must implement this method to handle federated auth user - /// re-authentication requests on non-mobile systems. - /// - /// @param[in] provider_data Contains information on the provider to - /// authenticate with. - /// @param[in] completion_handle Internal data pertaining to this operation - /// which must be passed to ReauthenticateComplete once the handler has - /// completed the reauthentication operation. - /// - /// @see User#ReauthenticateWithProviderComplete - virtual void OnReauthenticate(const T& provider_data, - AuthCompletionHandle* completion_handle) = 0; - - /// Completion for non-mobile user authorization handlers. - /// - /// Invoke this method once the OnReauthenticate process has been - /// fulfilled. This method will trigger the associated Future - /// previously returned from an invocation of - /// User::ReauthenticateWithProvider. - /// - /// @param[in] completion_handle The handle provided to the application's - /// FederatedAuthProvider::Handler::OnReauthenticate method. - /// @param[in] user_data The application's resulting Firebase user - /// values following the user re-authentication request. - /// @param[in] auth_error The enumerated status code of the reauthentication - /// request. - /// @param[in] error_message An optional error message to be set in the - /// Future. - /// - /// @see OnReauthenticate - /// @see User#ReuthenticateWithProvider - void ReauthenticateComplete(AuthCompletionHandle* completion_handle, - const AuthenticatedUserData& user_data, - AuthError auth_error, - const char* error_message); - }; -#endif // not SWIG -#endif // INTERNAL_EXPERIMENTAL - - FederatedAuthProvider() {} - virtual ~FederatedAuthProvider() {} - - private: - friend class ::firebase::auth::Auth; - friend class ::firebase::auth::User; - virtual Future SignIn(AuthData* auth_data) = 0; - virtual Future Link(AuthData* auth_data) = 0; - virtual Future Reauthenticate(AuthData* auth_data) = 0; -}; - -/// @brief Authenticates with Federated OAuth Providers via the -/// firebase::auth::Auth and firebase::auth::User classes. -/// -/// Once configured with a provider id, and with OAuth scope and OAuth custom -/// parameters via an FedeartedOAuthProviderData structure, an object of -/// this class may be used via Auth::SignInWithProvider to sign-in users, or via -/// User::LinkWithProvider and User::ReauthenticateWithProvider for cross -/// account linking and user reauthentication, respectively. -class FederatedOAuthProvider : public FederatedAuthProvider { - public: -#ifdef INTERNAL_EXPERIMENTAL -#ifndef SWIG - /// @brief A FederatedAuthProvider typed specifically for OAuth Authentication - /// handling. - /// - /// To be used on non-mobile environments for custom OAuth implementations and - /// UI flows. - typedef FederatedAuthProvider::Handler - AuthHandler; -#endif // !SWIG -#endif // INTERNAL_EXPERIMENTAL - - /// Constructs an unconfigured provider. - FederatedOAuthProvider(); - - /// Constructs a FederatedOAuthProvider preconfigured with provider data. - /// - /// @param[in] provider_data Contains the federated provider id and OAuth - /// scopes and OAuth custom parameters required for user authentication and - /// user linking. - explicit FederatedOAuthProvider( - const FederatedOAuthProviderData& provider_data); - -#ifdef INTERNAL_EXPERIMENTAL -#ifndef SWIG - /// @brief Constructs a provider with the required information to authenticate - /// using an OAuth Provider. - /// - /// An AuthHandler is required on desktop platforms to facilitate custom - /// implementations of OAuth authentication. The AuthHandler must outlive the - /// instance of this OAuthProvider on desktop systems and is ignored on iOS, - /// tvOS, and Android platforms. - /// - /// @param[in] provider_data Contains information on the provider to - /// authenticate with. - /// @param[in] handler An FederatedOAuthProviderData typed - /// FederatedAuthProvider::Handler which be invoked on non-mobile systems - /// to handle authentication requests. - FederatedOAuthProvider(const FederatedOAuthProviderData& provider_data, - AuthHandler* handler); -#endif // !SWIG -#endif // INTERNAL_EXPERIMENTAL - - ~FederatedOAuthProvider() override; - - /// @brief Configures the provider with OAuth provider information. - /// - /// @param[in] provider_data Contains the federated provider id and OAuth - /// scopes and OAuth custom parameters required for user authentication and - /// user linking. - void SetProviderData(const FederatedOAuthProviderData& provider_data); - -#ifdef INTERNAL_EXPERIMENTAL -#ifndef SWIG - /// @brief Configures the use of an AuthHandler for non-mobile systems. - /// - /// The existence of a handler is required for non-mobile systems, and is - /// ignored on iOS, tvOS and Android platforms. - /// - /// @param[in] handler An FederatedOAuthProviderData typed - /// FederatedAuthProvider::Handler which be invoked on non-mobile systems - /// to handle authentication requests. The handler must outlive the instance - /// of this FederatedOAuthProvider. - void SetAuthHandler(AuthHandler* handler); -#endif // !SWIG -#endif // INTERNAL_EXPERIMENTAL - - private: - friend class ::firebase::auth::Auth; - - Future SignIn(AuthData* auth_data) override; - Future Link(AuthData* auth_data) override; - Future Reauthenticate(AuthData* auth_data) override; - - FederatedOAuthProviderData provider_data_; -#ifdef INTERNAL_EXPERIMENTAL - AuthHandler* handler_; -#endif // INTERNAL_EXPERIMENTAL -}; - -} // namespace auth -} // namespace firebase - -#endif // FIREBASE_AUTH_SRC_INCLUDE_FIREBASE_AUTH_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/auth/credential.h b/packages/firebase_core/firebase_core/firebase_core/firebase/auth/credential.h deleted file mode 100644 index a179d199b67a..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/auth/credential.h +++ /dev/null @@ -1,633 +0,0 @@ -/* - * Copyright 2016 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_AUTH_SRC_INCLUDE_FIREBASE_AUTH_CREDENTIAL_H_ -#define FIREBASE_AUTH_SRC_INCLUDE_FIREBASE_AUTH_CREDENTIAL_H_ - -#include - -#include - -#include "firebase/auth/types.h" -#include "firebase/internal/common.h" - -namespace firebase { - -// Predeclarations. -class App; - -/// @cond FIREBASE_APP_INTERNAL -template -class Future; -/// @endcond - -namespace auth { - -// Predeclarations. -class Auth; -class User; - -// Opaque internal types. -struct AuthData; -class ForceResendingTokenData; -struct PhoneAuthProviderData; -struct PhoneListenerData; - -/// @brief Authentication credentials for an authentication provider. -/// -/// An authentication provider is a service that allows you to authenticate -/// a user. Firebase provides email/password authentication, but there are also -/// external authentication providers such as Facebook. -class Credential { -#ifndef SWIG - /// @cond FIREBASE_APP_INTERNAL - friend class EmailAuthProvider; - friend class FacebookAuthProvider; - friend class GameCenterAuthProvider; - friend class GitHubAuthProvider; - friend class GoogleAuthProvider; - friend class JniAuthPhoneListener; - friend class MicrosoftAuthProvider; - friend class OAuthProvider; - friend class PhoneAuthProvider; - friend class PlayGamesAuthProvider; - friend class TwitterAuthProvider; - friend class YahooAuthProvider; - friend class ServiceUpdatedCredentialProvider; - /// @endcond -#endif // !SWIG - - private: - /// Should only be created by `Provider` classes. - /// - /// @see EmailAuthProvider::GetCredential() - /// @see FacebookAuthProvider::GetCredential() - /// @see GoogleAuthProvider::GetCredential() - explicit Credential(void* impl) : impl_(impl), error_code_(kAuthErrorNone) {} - - public: - Credential() : impl_(nullptr), error_code_(kAuthErrorNone) {} - ~Credential(); - - /// Copy constructor. - Credential(const Credential& rhs); - - /// Copy a Credential. - Credential& operator=(const Credential& rhs); - - /// Gets the name of the Identification Provider (IDP) for the credential. - /// - /// - /// @xmlonly - /// - /// Gets the name of the Identification Provider (IDP) for the credential. - /// - /// @endxmlonly - /// - std::string provider() const; - - /// Get whether this credential is valid. A credential can be - /// invalid in an error condition, e.g. empty username/password. - /// - /// @returns True if the credential is valid, false otherwise. - bool is_valid() const; - - protected: - /// @cond FIREBASE_APP_INTERNAL - friend class Auth; - friend class User; - - /// Platform-specific implementation. - /// For example, FIRAuthCredential* on iOS. - void* impl_; - - // If not kAuthErrorNone, then use this error code and string to override - // whatever error we would normally return when trying to sign-in with this - // credential. - AuthError error_code_; - std::string error_message_; - /// @endcond -}; - -/// @brief Use email and password to authenticate. -/// -/// Allows developers to use the email and password credentials as they could -/// other auth providers. For example, this can be used to change passwords, -/// log in, etc. -class EmailAuthProvider { - public: - /// Generate a credential from the given email and password. - /// - /// @param email E-mail to generate the credential from. - /// @param password Password to use for the new credential. - /// - /// @returns New Credential. - static Credential GetCredential(const char* email, const char* password); - - /// The string used to identify this provider. - static const char* const kProviderId; -}; - -/// @brief Use an access token provided by Facebook to authenticate. -class FacebookAuthProvider { - public: - /// Generate a credential from the given Facebook token. - /// - /// @param access_token Facebook token to generate the credential from. - /// - /// @returns New Credential. - static Credential GetCredential(const char* access_token); - - /// The string used to identify this provider. - static const char* const kProviderId; -}; - -/// @brief GameCenter (Apple) auth provider -class GameCenterAuthProvider { - public: - /// Generate a credential from GameCenter for the current user. - /// - /// @return a Future that will be fulfilled with the resulting credential. - static Future GetCredential(); - - /// Get the result of the most recent GetCredential() call. - /// - /// @return an object which can be used to retrieve the Credential. - static Future GetCredentialLastResult(); - - /// Tests to see if the current user is signed in to GameCenter. - /// - /// @return true if the user is signed in, false otherwise. - static bool IsPlayerAuthenticated(); - - /// The string used to identify this provider. - static const char* const kProviderId; -}; - -/// @brief Use an access token provided by GitHub to authenticate. -class GitHubAuthProvider { - public: - /// Generate a credential from the given GitHub token. - /// - /// @param token The GitHub OAuth access token. - /// - /// @returns New Credential. - static Credential GetCredential(const char* token); - - /// The string used to identify this provider. - static const char* const kProviderId; -}; - -/// @brief Use an ID token and access token provided by Google to authenticate. -class GoogleAuthProvider { - public: - /// Generate a credential from the given Google ID token and/or access token. - /// - /// @param id_token Google Sign-In ID token. - /// @param access_token Google Sign-In access token. - /// - /// @returns New Credential. - static Credential GetCredential(const char* id_token, - const char* access_token); - - /// The string used to identify this provider. - static const char* const kProviderId; -}; - -/// @brief Use an access token provided by Microsoft to authenticate. -class MicrosoftAuthProvider { - public: - /// The string used to identify this provider. - static const char* const kProviderId; -}; - -/// @brief OAuth2.0+UserInfo auth provider (OIDC compliant and non-compliant). -class OAuthProvider { - public: - /// Generate a credential for an OAuth2 provider. - /// - /// @param provider_id Name of the OAuth2 provider - /// TODO(jsanmiya) add examples. - /// @param id_token The authentication token (OIDC only). - /// @param access_token TODO(jsanmiya) add explanation (currently missing - /// from Android and iOS implementations). - static Credential GetCredential(const char* provider_id, const char* id_token, - const char* access_token); - - /// Generate a credential for an OAuth2 provider. - /// - /// @param provider_id Name of the OAuth2 provider. - /// @param id_token The authentication token (OIDC only). - /// @param raw_nonce The raw nonce associated with the Auth credential being - /// created. - /// @param access_token The access token associated with the Auth credential - /// to be created, if available. This value may be null. - static Credential GetCredential(const char* provider_id, const char* id_token, - const char* raw_nonce, - const char* access_token); -}; - -/// @brief Use phone number text messages to authenticate. -/// -/// Allows developers to use the phone number and SMS verification codes -/// to authenticate a user on a mobile device. -/// -/// This class is not supported on tvOS and Desktop platforms. -/// -/// The verification flow results in a Credential that can be used to, -/// * Sign in to an existing phone number account/sign up with a new -/// phone number -/// * Link a phone number to a current user. This provider will be added to -/// the user. -/// * Update a phone number on an existing user. -/// * Re-authenticate an existing user. This may be needed when a sensitive -/// operation requires the user to be recently logged in. -/// -/// Possible verification flows: -/// (1) User manually enters verification code. -/// @if cpp_examples -/// - App calls @ref VerifyPhoneNumber. -/// - Web verification page is displayed to user where they may need to -/// solve a CAPTCHA. [iOS only]. -/// - Auth server sends the verification code via SMS to the provided -/// phone number. App receives verification id via Listener::OnCodeSent(). -/// - User receives SMS and enters verification code in app's GUI. -/// - App uses user's verification code to call -/// @ref PhoneAuthProvider::GetCredential. -/// @endif -/// -/// @if swig_examples -/// - App calls @ref VerifyPhoneNumber. -/// - Web verification page is displayed to user where they may need to -/// solve a CAPTCHA. [iOS only]. -/// - Auth server sends the verification code via SMS to the provided -/// phone number. App receives verification id via @ref CodeSent. -/// - User receives SMS and enters verification code in app's GUI. -/// - App uses user's verification code to call -/// @ref PhoneAuthProvider::GetCredential. -/// @endif -/// -/// -/// (2) SMS is automatically retrieved (Android only). -/// - App calls @ref VerifyPhoneNumber with `timeout_ms` > 0. -/// - Auth server sends the verification code via SMS to the provided -/// phone number. -/// - SMS arrives and is automatically retrieved by the operating system. -/// Credential is automatically created and passed to the app via -/// @if cpp_examples -/// Listener::OnVerificationCompleted(). -/// @endif -/// -/// @if swig_examples -/// @ref VerificationCompleted. -/// @endif -/// -/// -/// (3) Phone number is instantly verified (Android only). -/// - App calls @ref VerifyPhoneNumber. -/// - The operating system validates the phone number without having to -/// send an SMS. Credential is automatically created and passed to -/// the app via -/// @if cpp_examples -/// Listener::OnVerificationCompleted(). -/// @endif -/// -/// @if swig_examples -/// @ref VerificationCompleted. -/// @endif -/// -/// -/// @if cpp_examples -/// All three flows can be handled with the example code below. -/// The flow is complete when PhoneVerifier::credential() returns non-NULL. -/// -/// @code{.cpp} -/// class PhoneVerifier : public PhoneAuthProvider::Listener { -/// public: -/// PhoneVerifier(const char* phone_number, -/// PhoneAuthProvider* phone_auth_provider) -/// : display_message_("Sending SMS with verification code"), -/// display_verification_code_input_box_(false), -/// display_resend_sms_button_(false), -/// phone_auth_provider_(phone_auth_provider), -/// phone_number_(phone_number) { -/// SendSms(); -/// } -/// -/// ~PhoneVerifier() override {} -/// -/// void OnVerificationCompleted(Credential credential) override { -/// // Grab `mutex_` for the scope of `lock`. Callbacks can be called on -/// // other threads, so this mutex ensures data access is atomic. -/// MutexLock lock(mutex_); -/// credential_ = credential; -/// } -/// -/// void OnVerificationFailed(const std::string& error) override { -/// MutexLock lock(mutex_); -/// display_message_ = "Verification failed with error: " + error; -/// } -/// -/// void OnCodeSent(const std::string& verification_id, -/// const PhoneAuthProvider::ForceResendingToken& -/// force_resending_token) override { -/// MutexLock lock(mutex_); -/// verification_id_ = verification_id; -/// force_resending_token_ = force_resending_token; -/// -/// display_verification_code_input_box_ = true; -/// display_message_ = "Waiting for SMS"; -/// } -/// -/// void OnCodeAutoRetrievalTimeOut( -/// const std::string& verification_id) override { -/// MutexLock lock(mutex_); -/// display_resend_sms_button_ = true; -/// } -/// -/// // Draw the verification GUI on screen and process input events. -/// void Draw() { -/// MutexLock lock(mutex_); -/// -/// // Draw an informative message describing what's currently happening. -/// ShowTextBox(display_message_.c_str()); -/// -/// // Once the time out expires, display a button to resend the SMS. -/// // If the button is pressed, call VerifyPhoneNumber again using the -/// // force_resending_token_. -/// if (display_resend_sms_button_ && !verification_id_.empty()) { -/// const bool resend_sms = ShowTextButton("Resend SMS"); -/// if (resend_sms) { -/// SendSms(); -/// } -/// } -/// -/// // Once the SMS has been sent, allow the user to enter the SMS -/// // verification code into a text box. When the user has completed -/// // entering it, call GetCredential() to complete the flow. -/// if (display_verification_code_input_box_) { -/// const std::string verification_code = -/// ShowInputBox("Verification code"); -/// if (!verification_code.empty()) { -/// credential_ = phone_auth_provider_->GetCredential( -/// verification_id_.c_str(), verification_code.c_str()); -/// } -/// } -/// } -/// -/// // The phone number verification flow is complete when this returns -/// // non-NULL. -/// Credential* credential() { -/// MutexLock lock(mutex_); -/// return credential_.is_valid() ? &credential_ : nullptr; -/// } -/// -/// private: -/// void SendSms() { -/// static const uint32_t kAutoVerifyTimeOut = 2000; -/// MutexLock lock(mutex_); -/// phone_auth_provider_->VerifyPhoneNumber( -/// phone_number_.c_str(), kAutoVerifyTimeOut, &force_resending_token_, -/// this); -/// display_resend_sms_button_ = false; -/// } -/// -/// // GUI-related variables. -/// std::string display_message_; -/// bool display_verification_code_input_box_; -/// bool display_resend_sms_button_; -/// -/// // Phone flow related variables. -/// PhoneAuthProvider* phone_auth_provider_; -/// std::string phone_number_; -/// std::string verification_id_; -/// PhoneAuthProvider::ForceResendingToken force_resending_token_; -/// Credential credential_; -/// -/// // Callbacks can be called on other threads, so guard them with a mutex. -/// Mutex mutex_; -/// }; -/// @endcode -/// @endif -class PhoneAuthProvider { - public: - /// @brief Token to maintain current phone number verification session. - /// Acquired via @ref Listener::OnCodeSent. Used in @ref VerifyPhoneNumber. - class ForceResendingToken { - public: - /// This token will be invalid until it is assigned a value sent via - /// @ref Listener::OnCodeSent. It can still be passed into - /// @ref VerifyPhoneNumber, but it will be ignored. - ForceResendingToken(); - - /// Make `this` token refer to the same phone session as `rhs`. - ForceResendingToken(const ForceResendingToken& rhs); - - /// Releases internal resources when destructing. - ~ForceResendingToken(); - - /// Make `this` token refer to the same phone session as `rhs`. - ForceResendingToken& operator=(const ForceResendingToken& rhs); - - /// Return true if `rhs` is refers to the same phone number session as - /// `this`. - bool operator==(const ForceResendingToken& rhs) const; - - /// Return true if `rhs` is refers to a different phone number session as - /// `this`. - bool operator!=(const ForceResendingToken& rhs) const; - - private: - friend class JniAuthPhoneListener; - friend class PhoneAuthProvider; - ForceResendingTokenData* data_; - }; - - /// @brief Receive callbacks from @ref VerifyPhoneNumber events. - /// - /// Please see @ref PhoneAuthProvider for a sample implementation. - class Listener { - public: - Listener(); - virtual ~Listener(); - - /// @brief Phone number auto-verification succeeded. - /// - /// Called when, - /// - auto-sms-retrieval has succeeded--flow (2) in @ref PhoneAuthProvider - /// - instant validation has succeeded--flow (3) in @ref PhoneAuthProvider - /// - /// @note This callback is never called on iOS, since iOS does not have - /// auto-validation. It is always called immediately in the stub desktop - /// implementation, however, since it fakes immediate success. - /// - /// @param[in] credential The completed credential from the phone number - /// verification flow. - virtual void OnVerificationCompleted(Credential credential) = 0; - - /// @brief Phone number verification failed with an error. - /// - /// Called when and error occurred doing phone number authentication. - /// For example, - /// - quota exceeded - /// - unknown phone number format - /// - /// @param[in] error A description of the failure. - virtual void OnVerificationFailed(const std::string& error) = 0; - - /// @brief SMS message with verification code sent to phone number. - /// - /// Called immediately after Auth server sends a verification SMS. - /// Once receiving this, you can allow users to manually input the - /// verification code (even if you're also performing auto-verification). - /// For user manual input case, get the SMS verification code from the user - /// and then call @ref GetCredential with the user's code. - /// - /// @param[in] verification_id Pass to @ref GetCredential along with the - /// user-input verification code to complete the phone number verification - /// flow. - /// @param[in] force_resending_token If the user requests that another SMS - /// message be sent, use this when you recall @ref VerifyPhoneNumber. - virtual void OnCodeSent(const std::string& verification_id, - const ForceResendingToken& force_resending_token); - - /// @brief The timeout specified in @ref VerifyPhoneNumber has expired. - /// - /// Called once `auto_verify_time_out_ms` has passed. - /// If using auto SMS retrieval, you can choose to block the UI (do not - /// allow manual input of the verification code) until timeout is hit. - /// - /// @note This callback is called immediately on iOS, since iOS does not - /// have auto-validation. - /// - /// @param[in] verification_id Identify the transaction that has timed out. - virtual void OnCodeAutoRetrievalTimeOut(const std::string& verification_id); - - private: - friend class PhoneAuthProvider; - - /// Back-pointer to the data of the PhoneAuthProvider that - /// @ref VerifyPhoneNumber was called with. Used internally. - PhoneListenerData* data_; - }; - - /// Maximum value of `auto_verify_time_out_ms` in @ref VerifyPhoneNumber. - /// Larger values will be clamped. - /// - /// @deprecated This value is no longer used to clamp - /// `auto_verify_time_out_ms` in VerifyPhoneNumber. The range is - /// determined by the underlying SDK, ex. PhoneAuthOptions.Build - /// in Android SDK - static const uint32_t kMaxTimeoutMs; - - /// Start the phone number authentication operation. - /// - /// @param[in] phone_number The phone number identifier supplied by the user. - /// Its format is normalized on the server, so it can be in any format - /// here. - /// @param[in] auto_verify_time_out_ms The time out for SMS auto retrieval, in - /// miliseconds. Currently SMS auto retrieval is only supported on Android. - /// If 0, do not do SMS auto retrieval. - /// If positive, try to auto-retrieve the SMS verification code. - /// When the time out is exceeded, listener->OnCodeAutoRetrievalTimeOut() - /// is called. - /// @param[in] force_resending_token If NULL, assume this is a new phone - /// number to verify. If not-NULL, bypass the verification session deduping - /// and force resending a new SMS. - /// This token is received in @ref Listener::OnCodeSent. - /// This should only be used when the user presses a Resend SMS button. - /// @param[in,out] listener Class that receives notification whenever an SMS - /// verification event occurs. See sample code at top of class. - void VerifyPhoneNumber(const char* phone_number, - uint32_t auto_verify_time_out_ms, - const ForceResendingToken* force_resending_token, - Listener* listener); - - /// Generate a credential for the given phone number. - /// - /// @param[in] verification_id The id returned when sending the verification - /// code. Sent to the caller via @ref Listener::OnCodeSent. - /// @param[in] verification_code The verification code supplied by the user, - /// most likely by a GUI where the user manually enters the code - /// received in the SMS sent by @ref VerifyPhoneNumber. - /// - /// @returns New Credential. - Credential GetCredential(const char* verification_id, - const char* verification_code); - - /// Return the PhoneAuthProvider for the specified `auth`. - /// - /// @param[in] auth The Auth session for which we want to get a - /// PhoneAuthProvider. - static PhoneAuthProvider& GetInstance(Auth* auth); - - /// The string used to identify this provider. - static const char* const kProviderId; - - private: - friend struct AuthData; - friend class JniAuthPhoneListener; - - // Use @ref GetInstance to access the PhoneAuthProvider. - PhoneAuthProvider(); - - // The PhoneAuthProvider is owned by the Auth class. - ~PhoneAuthProvider(); - - PhoneAuthProviderData* data_; -}; - -/// @brief Use a server auth code provided by Google Play Games to authenticate. -class PlayGamesAuthProvider { - public: - /// Generate a credential from the given Server Auth Code. - /// - /// @param server_auth_code Play Games Sign in Server Auth Code. - /// - /// @return New Credential. - static Credential GetCredential(const char* server_auth_code); - - /// The string used to identify this provider. - static const char* const kProviderId; -}; - -/// @brief Use a token and secret provided by Twitter to authenticate. -class TwitterAuthProvider { - public: - /// Generate a credential from the given Twitter token and password. - /// - /// @param token The Twitter OAuth token. - /// @param secret The Twitter OAuth secret. - /// - /// @return New Credential. - static Credential GetCredential(const char* token, const char* secret); - - /// The string used to identify this provider. - static const char* const kProviderId; -}; - -/// @brief Use an access token provided by Yahoo to authenticate. -class YahooAuthProvider { - public: - /// The string used to identify this provider. - static const char* const kProviderId; -}; - -} // namespace auth -} // namespace firebase - -#endif // FIREBASE_AUTH_SRC_INCLUDE_FIREBASE_AUTH_CREDENTIAL_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/auth/types.h b/packages/firebase_core/firebase_core/firebase_core/firebase/auth/types.h deleted file mode 100644 index 3f141ad3692c..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/auth/types.h +++ /dev/null @@ -1,473 +0,0 @@ -/* - * Copyright 2016 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_AUTH_SRC_INCLUDE_FIREBASE_AUTH_TYPES_H_ -#define FIREBASE_AUTH_SRC_INCLUDE_FIREBASE_AUTH_TYPES_H_ - -#include -#include -#include - -namespace firebase { -namespace auth { - -/// All possible error codes from asynchronous calls. -/// For error details, -/// @if cpp_examples -/// call Future::ErrorMessage(). -/// @endif -/// -/// @if swig_examples -/// use the FirebaseException.Message property. -/// @endif -/// -enum AuthError { - /// Success. - kAuthErrorNone = 0, - - /// Function will be implemented in a later revision of the API. - kAuthErrorUnimplemented = -1, - - /// This indicates an internal error. - /// Common error code for all API Methods. - kAuthErrorFailure = 1, - - /// Indicates a validation error with the custom token. - /// This error originates from "bring your own auth" methods. - kAuthErrorInvalidCustomToken, - - /// Indicates the service account and the API key belong to different - /// projects. - /// Caused by "Bring your own auth" methods. - kAuthErrorCustomTokenMismatch, - - /// Indicates the IDP token or requestUri is invalid. - /// Caused by "Sign in with credential" methods. - kAuthErrorInvalidCredential, - - /// Indicates the user’s account is disabled on the server. - /// Caused by "Sign in with credential" methods. - kAuthErrorUserDisabled, - - /// Indicates an account already exists with the same email address but using - /// different sign-in credentials. Account linking is required. - /// Caused by "Sign in with credential" methods. - kAuthErrorAccountExistsWithDifferentCredentials, - - /// Indicates the administrator disabled sign in with the specified identity - /// provider. - /// Caused by "Set account info" methods. - kAuthErrorOperationNotAllowed, - - /// Indicates the email used to attempt a sign up is already in use. - /// Caused by "Set account info" methods. - kAuthErrorEmailAlreadyInUse, - - /// Indicates the user has attemped to change email or password more than 5 - /// minutes after signing in, and will need to refresh the credentials. - /// Caused by "Set account info" methods. - kAuthErrorRequiresRecentLogin, - - /// Indicates an attempt to link with a credential that has already been - /// linked with a different Firebase account. - /// Caused by "Set account info" methods. - kAuthErrorCredentialAlreadyInUse, - - /// Indicates an invalid email address. - /// Caused by "Sign in with password" methods. - kAuthErrorInvalidEmail, - - /// Indicates the user attempted sign in with a wrong password. - /// Caused by "Sign in with password" methods. - kAuthErrorWrongPassword, - - /// Indicates that too many requests were made to a server method. - /// Common error code for all API methods. - kAuthErrorTooManyRequests, - - /// Indicates the user account was not found. - /// Send password request email error code. - /// Common error code for all API methods. - kAuthErrorUserNotFound, - - /// Indicates an attempt to link a provider to which the account is already - /// linked. - /// Caused by "Link credential" methods. - kAuthErrorProviderAlreadyLinked, - - /// Indicates an attempt to unlink a provider that is not linked. - /// Caused by "Link credential" methods. - kAuthErrorNoSuchProvider, - - /// Indicates user's saved auth credential is invalid, the user needs to sign - /// in again. - /// Caused by requests with an STS id token. - kAuthErrorInvalidUserToken, - - /// Indicates the saved token has expired. - /// For example, the user may have changed account password on another device. - /// The user needs to sign in again on the device that made this request. - /// Caused by requests with an STS id token. - kAuthErrorUserTokenExpired, - - /// Indicates a network error occurred (such as a timeout, interrupted - /// connection, or unreachable host). These types of errors are often - /// recoverable with a retry. - /// Common error code for all API Methods. - kAuthErrorNetworkRequestFailed, - - /// Indicates an invalid API key was supplied in the request. - /// For Android these should no longer occur (as of 2016 v3). - /// Common error code for all API Methods. - kAuthErrorInvalidApiKey, - - /// Indicates the App is not authorized to use Firebase Authentication with - /// the provided API Key. - /// Common error code for all API Methods. - /// On Android this error should no longer occur (as of 2016 v3). - /// Common error code for all API Methods. - kAuthErrorAppNotAuthorized, - - /// Indicates that an attempt was made to reauthenticate with a user which is - /// not the current user. - kAuthErrorUserMismatch, - - /// Indicates an attempt to set a password that is considered too weak. - kAuthErrorWeakPassword, - - /// Internal api usage error code when there is no signed-in user - /// and getAccessToken is called. - /// - /// @note This error is only reported on Android. - kAuthErrorNoSignedInUser, - - /// This can happen when certain methods on App are performed, when the auth - /// API is not loaded. - /// - /// @note This error is only reported on Android. - kAuthErrorApiNotAvailable, - - /// Indicates the out-of-band authentication code is expired. - kAuthErrorExpiredActionCode, - - /// Indicates the out-of-band authentication code is invalid. - kAuthErrorInvalidActionCode, - - /// Indicates that there are invalid parameters in the payload during a - /// "send password reset email" attempt. - kAuthErrorInvalidMessagePayload, - - /// Indicates that an invalid phone number was provided. - /// This is caused when the user is entering a phone number for verification. - kAuthErrorInvalidPhoneNumber, - - /// Indicates that a phone number was not provided during phone number - /// verification. - /// - /// @note This error is iOS-specific. - kAuthErrorMissingPhoneNumber, - - /// Indicates that the recipient email is invalid. - kAuthErrorInvalidRecipientEmail, - - /// Indicates that the sender email is invalid during a "send password reset - /// email" attempt. - kAuthErrorInvalidSender, - - /// Indicates that an invalid verification code was used in the - /// verifyPhoneNumber request. - kAuthErrorInvalidVerificationCode, - - /// Indicates that an invalid verification ID was used in the - /// verifyPhoneNumber request. - kAuthErrorInvalidVerificationId, - - /// Indicates that the phone auth credential was created with an empty - /// verification code. - kAuthErrorMissingVerificationCode, - - /// Indicates that the phone auth credential was created with an empty - /// verification ID. - kAuthErrorMissingVerificationId, - - /// Indicates that an email address was expected but one was not provided. - kAuthErrorMissingEmail, - - /// Represents the error code for when an application attempts to create an - /// email/password account with an empty/null password field. - /// - /// @note This error is only reported on Android. - kAuthErrorMissingPassword, - - /// Indicates that the project's quota for this operation (SMS messages, - /// sign-ins, account creation) has been exceeded. Try again later. - kAuthErrorQuotaExceeded, - - /// Thrown when one or more of the credentials passed to a method fail to - /// identify and/or authenticate the user subject of that operation. Inspect - /// the error message to find out the specific cause. - /// @note This error is only reported on Android. - kAuthErrorRetryPhoneAuth, - - /// Indicates that the SMS code has expired. - kAuthErrorSessionExpired, - - /// Indicates that the app could not be verified by Firebase during phone - /// number authentication. - /// - /// @note This error is iOS-specific. - kAuthErrorAppNotVerified, - - /// Indicates a general failure during the app verification flow. - /// - /// @note This error is iOS-specific. - kAuthErrorAppVerificationFailed, - - /// Indicates that the reCAPTCHA token is not valid. - /// - /// @note This error is iOS and tvOS-specific. - kAuthErrorCaptchaCheckFailed, - - /// Indicates that an invalid APNS device token was used in the verifyClient - /// request. - /// - /// @note This error is iOS and tvOS-specific. - kAuthErrorInvalidAppCredential, - - /// Indicates that the APNS device token is missing in the verifyClient - /// request. - /// - /// @note This error is iOS and tvOS-specific. - kAuthErrorMissingAppCredential, - - /// Indicates that the clientID used to invoke a web flow is invalid. - /// - /// @note This error is iOS and tvOS-specific. - kAuthErrorInvalidClientId, - - /// Indicates that the domain specified in the continue URI is not valid. - /// - /// @note This error is iOS and tvOS-specific. - kAuthErrorInvalidContinueUri, - - /// Indicates that a continue URI was not provided in a request to the backend - /// which requires one. - kAuthErrorMissingContinueUri, - - /// Indicates an error occurred while attempting to access the keychain. - /// Common error code for all API Methods. - /// - /// @note This error is iOS and tvOS-specific. - kAuthErrorKeychainError, - - /// Indicates that the APNs device token could not be obtained. The app may - /// not have set up remote notification correctly, or may have failed to - /// forward the APNs device token to FIRAuth if app delegate swizzling is - /// disabled. - /// - /// @note This error is iOS and tvOS-specific. - kAuthErrorMissingAppToken, - - /// Indicates that the iOS bundle ID is missing when an iOS App Store ID is - /// provided. - /// - /// @note This error is iOS and tvOS-specific. - kAuthErrorMissingIosBundleId, - - /// Indicates that the app fails to forward remote notification to FIRAuth. - /// - /// @note This error is iOS and tvOS-specific. - kAuthErrorNotificationNotForwarded, - - /// Indicates that the domain specified in the continue URL is not white- - /// listed in the Firebase console. - /// - /// @note This error is iOS and tvOS-specific. - kAuthErrorUnauthorizedDomain, - - /// Indicates that an attempt was made to present a new web context while one - /// was already being presented. - kAuthErrorWebContextAlreadyPresented, - - /// Indicates that the URL presentation was cancelled prematurely by the user. - kAuthErrorWebContextCancelled, - - /// Indicates that Dynamic Links in the Firebase Console is not activated. - kAuthErrorDynamicLinkNotActivated, - - /// Indicates that the operation was cancelled. - kAuthErrorCancelled, - - /// Indicates that the provider id given for the web operation is invalid. - kAuthErrorInvalidProviderId, - - /// Indicates that an internal error occurred during a web operation. - kAuthErrorWebInternalError, - - /// Indicates that 3rd party cookies or data are disabled, or that there was - /// a problem with the browser. - kAuthErrorWebStorateUnsupported, - - /// Indicates that the provided tenant ID does not match the Auth instance's - /// tenant ID. - kAuthErrorTenantIdMismatch, - - /// Indicates that a request was made to the backend with an associated tenant - /// ID for an operation that does not support multi-tenancy. - kAuthErrorUnsupportedTenantOperation, - - /// Indicates that an FDL domain used for an out of band code flow is either - /// not configured or is unauthorized for the current project. - kAuthErrorInvalidLinkDomain, - - /// Indicates that credential related request data is invalid. This can occur - /// when there is a project number mismatch (sessionInfo, spatula header, - /// temporary proof), - /// an incorrect temporary proof phone number, or during game center sign in - /// when the user is - /// already signed into a different game center account. - kAuthErrorRejectedCredential, - - /// Indicates that the phone number provided in the MFA sign in flow to be - /// verified does not correspond to a phone second factor for the user. - kAuthErrorPhoneNumberNotFound, - - /// Indicates that a request was made to the backend with an invalid tenant - /// ID. - kAuthErrorInvalidTenantId, - - /// Indicates that a request was made to the backend without a valid client - /// identifier. - kAuthErrorMissingClientIdentifier, - - /// Indicates that a second factor challenge request was made without proof of - /// a successful first factor sign-in. - kAuthErrorMissingMultiFactorSession, - - /// Indicates that a second factor challenge request was made where a second - /// factor identifier was not provided. - kAuthErrorMissingMultiFactorInfo, - - /// Indicates that a second factor challenge request was made containing an - /// invalid proof of first factor sign-in. - kAuthErrorInvalidMultiFactorSession, - - /// Indicates that the user does not have a second factor matching the - /// provided identifier. - kAuthErrorMultiFactorInfoNotFound, - - /// Indicates that a request was made that is restricted to administrators - /// only. - kAuthErrorAdminRestrictedOperation, - - /// Indicates that the user's email must be verified to perform that request. - kAuthErrorUnverifiedEmail, - - /// Indicates that the user is trying to enroll a second factor that already - /// exists on their account. - kAuthErrorSecondFactorAlreadyEnrolled, - - /// Indicates that the user has reached the maximum number of allowed second - /// factors and is attempting to enroll another one. - kAuthErrorMaximumSecondFactorCountExceeded, - - /// Indicates that a user either attempted to enroll in 2FA with an - /// unsupported first factor or is enrolled and attempts a first factor sign - /// in that is not supported for 2FA users. - kAuthErrorUnsupportedFirstFactor, - - /// Indicates that a second factor users attempted to change their email with - /// updateEmail instead of verifyBeforeUpdateEmail. - kAuthErrorEmailChangeNeedsVerification, - -#ifdef INTERNAL_EXPERIMENTAL - /// Indicates that the provided event handler is null or invalid. - kAuthErrorInvalidEventHandler, - - /// Indicates that the federated provider is busy with a previous - /// authorization request. Try again when the previous authorization request - /// completes. - kAuthErrorFederatedProviderAreadyInUse, - - /// Indicates that one or more fields of the provided AuthenticatedUserData - /// are invalid. - kAuthErrorInvalidAuthenticatedUserData, - - /// Indicates that an error occurred during a Federated Auth UI Flow when the - /// user was prompted to enter their credentials. - kAuthErrorFederatedSignInUserInteractionFailure, - - /// Indicates that a request was made with a missing or invalid nonce. - /// This can happen if the hash of the provided raw nonce did not match the - /// hashed nonce in the OIDC ID token payload. - kAuthErrorMissingOrInvalidNonce, - - /// Indicates that the user did not authorize the application during Generic - /// IDP sign-in. - kAuthErrorUserCancelled, - - /// Indicates that a request was made to an unsupported backend endpoint in - /// passthrough mode. - kAuthErrorUnsupportedPassthroughOperation, - - /// Indicates that a token refresh was requested, but neither a refresh token - /// nor a custom token provider is available. - kAuthErrorTokenRefreshUnavailable, - -#endif // INTERNAL_EXEPERIMENTAL -}; - -/// @brief Contains information required to authenticate with a third party -/// provider. -struct FederatedProviderData { - /// @brief contains the id of the provider to be used during sign-in, link, or - /// reauthentication requests. - std::string provider_id; -}; - -/// @brief Contains information to identify an OAuth povider. -struct FederatedOAuthProviderData : FederatedProviderData { - /// Initailizes an empty provider data structure. - FederatedOAuthProviderData() {} - - /// Initializes the provider data structure with a provider id. - explicit FederatedOAuthProviderData(const std::string& provider) { - this->provider_id = provider; - } - -#ifndef SWIG - /// @brief Initializes the provider data structure with the specified provider - /// id, scopes and custom parameters. - FederatedOAuthProviderData( - const std::string& provider, std::vector scopes, - std::map custom_parameters) { - this->provider_id = provider; - this->scopes = scopes; - this->custom_parameters = custom_parameters; - } -#endif - - /// OAuth parmeters which specify which rights of access are being requested. - std::vector scopes; - - /// OAuth parameters which are provided to the federated provider service. - std::map custom_parameters; -}; - -} // namespace auth -} // namespace firebase - -#endif // FIREBASE_AUTH_SRC_INCLUDE_FIREBASE_AUTH_TYPES_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/auth/user.h b/packages/firebase_core/firebase_core/firebase_core/firebase/auth/user.h deleted file mode 100644 index ddd1ba890687..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/auth/user.h +++ /dev/null @@ -1,501 +0,0 @@ -/* - * Copyright 2016 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_AUTH_SRC_INCLUDE_FIREBASE_AUTH_USER_H_ -#define FIREBASE_AUTH_SRC_INCLUDE_FIREBASE_AUTH_USER_H_ - -#include -#include - -#include "firebase/auth/credential.h" -#include "firebase/auth/types.h" -#include "firebase/future.h" -#include "firebase/internal/common.h" -#include "firebase/variant.h" - -namespace firebase { -namespace auth { - -// Predeclarations. -class Auth; -struct AuthData; - -class FederatedAuthProvider; - -/// @brief Interface implemented by each identity provider. -class UserInfoInterface { - public: - virtual ~UserInfoInterface(); - - /// Gets the unique Firebase user ID for the user. - /// - /// @note The user's ID, unique to the Firebase project. - /// Do NOT use this value to authenticate with your backend server, if you - /// have one. - /// @if cpp_examples - /// Use User::GetToken() instead. - /// @endif - /// - /// @if swig_examples - /// Use User.Token instead. - /// @endif - /// @xmlonly - /// - /// Gets the unique Firebase user ID for the user. - /// - /// @note The user's ID, unique to the Firebase project. - /// Do NOT use this value to authenticate with your backend server, if you - /// have one. Use User.Token instead. - /// - /// @endxmlonly - /// - virtual std::string uid() const = 0; - - /// Gets email associated with the user, if any. - /// - /// @xmlonly - /// - /// Gets email associated with the user, if any. - /// - /// @endxmlonly - /// - virtual std::string email() const = 0; - - /// Gets the display name associated with the user, if any. - /// - /// @xmlonly - /// - /// Gets the display name associated with the user, if any. - /// - /// @endxmlonly - /// - virtual std::string display_name() const = 0; - - /// Gets the photo url associated with the user, if any. - /// - /// @xmlonly - /// - /// Gets the photo url associated with the user, if any. - /// - /// @endxmlonly - /// - virtual std::string photo_url() const = 0; - - /// Gets the provider ID for the user (For example, "Facebook"). - /// - /// @xmlonly - /// - /// Gets the provider ID for the user (For example, \"Facebook\"). - /// - /// @endxmlonly - /// - virtual std::string provider_id() const = 0; - - /// Gets the phone number for the user, in E.164 format. - virtual std::string phone_number() const = 0; -}; - -/// @brief Additional user data returned from an identity provider. -struct AdditionalUserInfo { - /// The provider identifier. - std::string provider_id; - - /// The name of the user. - std::string user_name; - - /// Additional identity-provider specific information. - /// Most likely a hierarchical key-value mapping, like a parsed JSON file. - /// Note we use map instead of unordered_map to support older compilers. - std::map profile; - - /// On a nonce-based credential link failure where the user has already linked - /// to the provider, the Firebase auth service may provide an updated - /// Credential. If is_valid returns true on this credential, then it may be - /// passed to a new firebase::auth::Auth::SignInWithCredential request to sign - /// the user in with the provider. - Credential updated_credential; -}; - -/// @brief Metadata corresponding to a Firebase user. -struct UserMetadata { - UserMetadata() : last_sign_in_timestamp(0), creation_timestamp(0) {} - - /// The last sign in UTC timestamp in milliseconds. - /// See https://en.wikipedia.org/wiki/Unix_time for details of UTC. - uint64_t last_sign_in_timestamp; - - /// The Firebase user creation UTC timestamp in milliseconds. - uint64_t creation_timestamp; -}; - -/// @brief Result of operations that can affect authentication state. -struct SignInResult { - SignInResult() : user(NULL) {} - - /// The currently signed-in @ref User, or NULL if there isn't any (i.e. the - /// user is signed out). - User* user; - - /// Identity-provider specific information for the user, if the provider is - /// one of Facebook, GitHub, Google, or Twitter. - AdditionalUserInfo info; - - /// Metadata associated with the Firebase user. - UserMetadata meta; -}; - -/// @brief Firebase user account object. -/// -/// This class allows you to manipulate the profile of a user, link to and -/// unlink from authentication providers, and refresh authentication tokens. -class User : public UserInfoInterface { - public: - /// Parameters to the UpdateUserProfile() function. - /// - /// For fields you don't want to update, pass NULL. - /// For fields you want to reset, pass "". - struct UserProfile { - /// Construct a UserProfile with no display name or photo URL. - UserProfile() : display_name(NULL), photo_url(NULL) {} - - /// User display name. - const char* display_name; - - /// User photo URI. - const char* photo_url; - }; - - ~User(); - - /// The Java Web Token (JWT) that can be used to identify the user to - /// the backend. - /// - /// If a current ID token is still believed to be valid (i.e. it has not yet - /// expired), that token will be returned immediately. - /// A developer may set the optional force_refresh flag to get a new ID token, - /// whether or not the existing token has expired. For example, a developer - /// may use this when they have discovered that the token is invalid for some - /// other reason. - Future GetToken(bool force_refresh); - -#if defined(INTERNAL_EXPERIMENTAL) || defined(SWIG) - /// A "thread safer" version of GetToken. - /// If called by two threads simultaneously, GetToken can return the same - /// pending Future twice. This creates problems if both threads try to set - /// the OnCompletion callback, unaware that there's another copy. - /// GetTokenThreadSafe returns a proxy to the Future if it's still pending, - /// allowing each proxy to have their own callback. - Future GetTokenThreadSafe(bool force_refresh); -#endif // defined(INTERNAL_EXPERIMENTAL) || defined(SWIG) - - /// Get results of the most recent call to @ref GetToken. - Future GetTokenLastResult() const; - - /// Gets the third party profile data associated with this user returned by - /// the authentication server, if any. - /// - /// @xmlonly - /// - /// Gets the third party profile data associated with this user returned by - /// the authentication server, if any. - /// - /// @endxmlonly - /// - const std::vector& provider_data() const; - - /// Sets the email address for the user. - /// - /// May fail if there is already an email/password-based account for the same - /// email address. - Future UpdateEmail(const char* email); - - /// Get results of the most recent call to @ref UpdateEmail. - Future UpdateEmailLastResult() const; - - /// Attempts to change the password for the current user. - /// - /// For an account linked to an Identity Provider (IDP) with no password, - /// this will result in the account becoming an email/password-based account - /// while maintaining the IDP link. May fail if the password is invalid, - /// if there is a conflicting email/password-based account, or if the token - /// has expired. - /// To retrieve fresh tokens, - /// @if cpp_examples - /// call @ref Reauthenticate. - /// @endif - /// - /// @if swig_examples - /// call @ref ReauthenticateAsync. - /// @endif - /// - Future UpdatePassword(const char* password); - - /// Get results of the most recent call to @ref UpdatePassword. - Future UpdatePasswordLastResult() const; - - /// Convenience function for @ref ReauthenticateAndRetrieveData that discards - /// the returned AdditionalUserInfo data. - Future Reauthenticate(const Credential& credential); - - /// Get results of the most recent call to @ref Reauthenticate. - Future ReauthenticateLastResult() const; - - /// Reauthenticate using a credential. - /// - /// @if cpp_examples - /// Some APIs (for example, @ref UpdatePassword, @ref Delete) require that - /// the token used to invoke them be from a recent login attempt. - /// This API takes an existing credential for the user and retrieves fresh - /// tokens, ensuring that the operation can proceed. Developers can call - /// this method prior to calling @ref UpdatePassword() to ensure success. - /// @endif - /// - /// @if swig_examples - /// Some APIs (for example, @ref UpdatePasswordAsync, @ref DeleteAsync) - /// require that the token used to invoke them be from a recent login attempt. - /// This API takes an existing credential for the user and retrieves fresh - /// tokens, ensuring that the operation can proceed. Developers can call - /// this method prior to calling @ref UpdatePasswordAsync() to ensure success. - /// @endif - /// - /// - /// Data from the Identity Provider used to sign-in is returned in the - /// AdditionalUserInfo inside the returned SignInResult. - /// - /// Returns an error if the existing credential is not for this user - /// or if sign-in with that credential failed. - /// @note: The current user may be signed out if this operation fails on - /// Android and desktop platforms. - Future ReauthenticateAndRetrieveData( - const Credential& credential); - - /// Get results of the most recent call to @ref ReauthenticateAndRetrieveData. - Future ReauthenticateAndRetrieveDataLastResult() const; - - /// @brief Re-authenticates the user with a federated auth provider. - /// - /// @param[in] provider Contains information on the auth provider to - /// authenticate with. - /// @return A Future with the result of the re-authentication - /// request. - /// @note: This operation is supported only on iOS, tvOS and Android - /// platforms. On other platforms this method will return a Future with a - /// preset error code: kAuthErrorUnimplemented. - Future ReauthenticateWithProvider( - FederatedAuthProvider* provider) const; - - /// Initiates email verification for the user. - Future SendEmailVerification(); - - /// Get results of the most recent call to @ref SendEmailVerification. - Future SendEmailVerificationLastResult() const; - - /// Updates a subset of user profile information. - Future UpdateUserProfile(const UserProfile& profile); - - /// Get results of the most recent call to @ref UpdateUserProfile. - Future UpdateUserProfileLastResult() const; - - /// Convenience function for @ref ReauthenticateAndRetrieveData that discards - /// the returned @ref AdditionalUserInfo in @ref SignInResult. - Future LinkWithCredential(const Credential& credential); - - /// Get results of the most recent call to @ref LinkWithCredential. - Future LinkWithCredentialLastResult() const; - - /// Links the user with the given 3rd party credentials. - /// - /// For example, a Facebook login access token, a Twitter token/token-secret - /// pair. - /// Status will be an error if the token is invalid, expired, or otherwise - /// not accepted by the server as well as if the given 3rd party - /// user id is already linked with another user account or if the current user - /// is already linked with another id from the same provider. - /// - /// Data from the Identity Provider used to sign-in is returned in the - /// @ref AdditionalUserInfo inside @ref SignInResult. - Future LinkAndRetrieveDataWithCredential( - const Credential& credential); - - /// Get results of the most recent call to - /// @ref LinkAndRetrieveDataWithCredential. - Future LinkAndRetrieveDataWithCredentialLastResult() const; - - /// Links this user with a federated auth provider. - /// - /// @param[in] provider Contains information on the auth provider to link - /// with. - /// @return A Future with the user data result of the link - /// request. - /// - /// @note: This operation is supported only on iOS, tvOS and Android - /// platforms. On other platforms this method will return a Future with a - /// preset error code: kAuthErrorUnimplemented. - Future LinkWithProvider(FederatedAuthProvider* provider) const; - - /// Unlinks the current user from the provider specified. - /// Status will be an error if the user is not linked to the given provider. - Future Unlink(const char* provider); - - /// Get results of the most recent call to @ref Unlink. - Future UnlinkLastResult() const; - - /// Updates the currently linked phone number on the user. - /// This is useful when a user wants to change their phone number. It is a - /// shortcut to calling Unlink(phone_credential.provider().c_str()) and then - /// LinkWithCredential(phone_credential). - /// `credential` must have been created with @ref PhoneAuthProvider. - Future UpdatePhoneNumberCredential(const Credential& credential); - - /// Get results of the most recent call to @ref UpdatePhoneNumberCredential. - Future UpdatePhoneNumberCredentialLastResult() const; - - /// Refreshes the data for this user. - /// - /// For example, the attached providers, email address, display name, etc. - Future Reload(); - - /// Get results of the most recent call to @ref Reload. - Future ReloadLastResult() const; - - /// Deletes the user account. - Future Delete(); - - /// Get results of the most recent call to @ref Delete. - Future DeleteLastResult() const; - - /// Gets the metadata for this user account. - UserMetadata metadata() const; - - /// Returns true if the email address associated with this user has been - /// verified. - /// - /// @xmlonly - /// - /// True if the email address associated with this user has been verified. - /// - /// @endxmlonly - /// - bool is_email_verified() const; - - /// Returns true if user signed in anonymously. - /// - /// @xmlonly - /// - /// True if user signed in anonymously. - /// - /// @endxmlonly - /// - bool is_anonymous() const; - - /// Gets the unique Firebase user ID for the user. - /// - /// @note The user's ID, unique to the Firebase project. - /// Do NOT use this value to authenticate with your backend server, if you - /// have one. - /// @if cpp_examples - /// Use User::GetToken() instead. - /// @endif - /// - /// @if swig_examples - /// Use User.Token instead. - /// @endif - /// @xmlonly - /// - /// Gets the unique Firebase user ID for the user. - /// - /// @note The user's ID, unique to the Firebase project. - /// Do NOT use this value to authenticate with your backend server, if you - /// have one. Use User.Token instead. - /// - /// @endxmlonly - /// - virtual std::string uid() const; - - /// Gets email associated with the user, if any. - /// - /// @xmlonly - /// - /// Gets email associated with the user, if any. - /// - /// @endxmlonly - /// - virtual std::string email() const; - - /// Gets the display name associated with the user, if any. - /// - /// @xmlonly - /// - /// Gets the display name associated with the user, if any. - /// - /// @endxmlonly - /// - virtual std::string display_name() const; - - /// Gets the photo url associated with the user, if any. - /// - /// @xmlonly - /// - /// Gets the photo url associated with the user, if any. - /// - /// @endxmlonly - /// - virtual std::string photo_url() const; - - /// Gets the provider ID for the user (For example, "Facebook"). - /// - /// @xmlonly - /// - /// Gets the provider ID for the user (For example, \"Facebook\"). - /// - /// @endxmlonly - /// - virtual std::string provider_id() const; - - /// Gets the phone number for the user, in E.164 format. - virtual std::string phone_number() const; - - private: - /// @cond FIREBASE_APP_INTERNAL - friend struct AuthData; - // Only exists in AuthData. Access via @ref Auth::CurrentUser(). - explicit User(AuthData* auth_data) : auth_data_(auth_data) {} - - // Disable copy constructor. - User(const User&) = delete; - // Disable copy operator. - User& operator=(const User&) = delete; - /// @endcond - -#if defined(INTERNAL_EXPERIMENTAL) - // Doxygen should not make docs for this function. - /// @cond FIREBASE_APP_INTERNAL - friend class IdTokenRefreshThread; - friend class IdTokenRefreshListener; - friend class Auth; - Future GetTokenInternal(const bool force_refresh, - const int future_identifier); - /// @endcond -#endif // defined(INTERNAL_EXPERIMENTAL) - - // Use the pimpl mechanism to hide data details in the cpp files. - AuthData* auth_data_; -}; - -} // namespace auth -} // namespace firebase - -#endif // FIREBASE_AUTH_SRC_INCLUDE_FIREBASE_AUTH_USER_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/database.h b/packages/firebase_core/firebase_core/firebase_core/firebase/database.h deleted file mode 100644 index d0dc904c107b..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/database.h +++ /dev/null @@ -1,199 +0,0 @@ -// Copyright 2016 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_H_ -#define FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_H_ - -#include "firebase/app.h" -#include "firebase/database/common.h" -#include "firebase/database/data_snapshot.h" -#include "firebase/database/database_reference.h" -#include "firebase/database/disconnection.h" -#include "firebase/database/listener.h" -#include "firebase/database/mutable_data.h" -#include "firebase/database/query.h" -#include "firebase/database/transaction.h" -#include "firebase/internal/common.h" -#include "firebase/log.h" - -namespace firebase { - -/// Namespace for the Firebase Realtime Database C++ SDK. -namespace database { - -namespace internal { -class DatabaseInternal; -} // namespace internal - -class DatabaseReference; - -#ifndef SWIG -/// @brief Entry point for the Firebase Realtime Database C++ SDK. -/// -/// To use the SDK, call firebase::database::Database::GetInstance() to obtain -/// an instance of Database, then use GetReference() to obtain references to -/// child paths within the database. From there you can set data via -/// Query::SetValue(), get data via Query::GetValue(), attach listeners, and -/// more. -#endif // SWIG -class Database { - public: - /// @brief Get an instance of Database corresponding to the given App. - /// - /// Firebase Realtime Database uses firebase::App to communicate with Firebase - /// Authentication to authenticate users to the Database server backend. - /// - /// If you call GetInstance() multiple times with the same App, you will get - /// the same instance of Database. - /// - /// @param[in] app Your instance of firebase::App. Firebase Realtime Database - /// will use this to communicate with Firebase Authentication. - /// @param[out] init_result_out Optional: If provided, write the init result - /// here. Will be set to kInitResultSuccess if initialization succeeded, or - /// kInitResultFailedMissingDependency on Android if Google Play services is - /// not available on the current device. - /// - /// @returns An instance of Database corresponding to the given App. - static Database* GetInstance(::firebase::App* app, - InitResult* init_result_out = nullptr); - - /// @brief Gets an instance of FirebaseDatabase for the specified URL. - /// - /// If you call GetInstance() multiple times with the same App and URL, you - /// will get the same instance of Database. - /// - /// @param[in] app Your instance of firebase::App. Firebase Realtime Database - /// will use this to communicate with Firebase Authentication. - /// @param[in] url The URL of your Firebase Realtime Database. This overrides - /// any url specified in the App options. - /// @param[out] init_result_out Optional: If provided, write the init result - /// here. Will be set to kInitResultSuccess if initialization succeeded, or - /// kInitResultFailedMissingDependency on Android if Google Play services is - /// not available on the current device. - /// - /// @returns An instance of Database corresponding to the given App and URL. - static Database* GetInstance(::firebase::App* app, const char* url, - InitResult* init_result_out = nullptr); - - /// @brief Destructor for the Database object. - /// - /// When deleted, this instance will be removed from the cache of Database - /// objects. If you call GetInstance() in the future with the same App, a new - /// Database instance will be created. - ~Database(); - - /// @brief Get the firebase::App that this Database was created with. - /// - /// @returns The firebase::App this Database was created with. - App* app() const; - - /// @brief Get the URL that this Database was created with. - /// - /// @returns The URL this Database was created with, or an empty string if - /// this Database was created with default parameters. This string will remain - /// valid in memory for the lifetime of this Database. - const char* url() const; - - /// @brief Get a DatabaseReference to the root of the database. - /// - /// @returns A DatabaseReference to the root of the database. - DatabaseReference GetReference() const; - /// @brief Get a DatabaseReference for the specified path. - /// - /// @returns A DatabaseReference to the specified path in the database. - /// If you specified an invalid path, the reference's - /// DatabaseReference::IsValid() will return false. - DatabaseReference GetReference(const char* path) const; - /// @brief Get a DatabaseReference for the provided URL, which must belong to - /// the database URL this instance is already connected to. - /// - /// @returns A DatabaseReference to the specified path in the database. - /// If you specified an invalid path, the reference's - /// DatabaseReference::IsValid() will return false. - DatabaseReference GetReferenceFromUrl(const char* url) const; - - /// @brief Shuts down the connection to the Firebase Realtime Database - /// backend until GoOnline() is called. - void GoOffline(); - - /// @brief Resumes the connection to the Firebase Realtime Database backend - /// after a previous GoOffline() call. - void GoOnline(); - - /// @brief Purge all pending writes to the Firebase Realtime Database server. - /// - /// The Firebase Realtime Database client automatically queues writes and - /// sends them to the server at the earliest opportunity, depending on network - /// connectivity. In some cases (e.g. offline usage) there may be a large - /// number of writes waiting to be sent. Calling this method will purge all - /// outstanding writes so they are abandoned. All writes will be purged, - /// including transactions and onDisconnect() writes. The writes will be - /// rolled back locally, perhaps triggering events for affected event - /// listeners, and the client will not (re-)send them to the Firebase backend. - void PurgeOutstandingWrites(); - - /// @brief Sets whether pending write data will persist between application - /// exits. - /// - /// The Firebase Database client will cache synchronized data and keep track - /// of all writes you've initiated while your application is running. It - /// seamlessly handles intermittent network connections and re-sends write - /// operations when the network connection is restored. However by default - /// your write operations and cached data are only stored in-memory and will - /// be lost when your app restarts. By setting this value to `true`, the data - /// will be persisted to on-device (disk) storage and will thus be available - /// again when the app is restarted (even when there is no network - /// connectivity at that time). - /// - /// @note SetPersistenceEnabled should be called before creating any instances - /// of DatabaseReference, and only needs to be called once per application. - /// - /// @param[in] enabled Set this to true to persist write data to on-device - /// (disk) storage, or false to discard pending writes when the app exists. - void set_persistence_enabled(bool enabled); - - /// Set the log verbosity of this Database instance. - /// - /// The log filtering is cumulative with Firebase App. That is, this library's - /// log messages will only be displayed if they are not filtered out by this - /// library's log level setting and by Firebase App's log level setting. - /// - /// @note On Android this can only be set before any operations have been - /// performed with the object. - /// - /// @param[in] log_level Log level, by default this is set to kLogLevelInfo. - void set_log_level(LogLevel log_level); - - /// Get the log verbosity of this Database instance. - /// - /// @return Get the currently configured logging verbosity. - LogLevel log_level() const; - - private: - friend Database* GetDatabaseInstance(::firebase::App* app, const char* url, - InitResult* init_result_out); - Database(::firebase::App* app, internal::DatabaseInternal* internal); - Database(const Database& src); - Database& operator=(const Database& src); - - // Delete the internal_ data. - void DeleteInternal(); - - internal::DatabaseInternal* internal_; -}; - -} // namespace database -} // namespace firebase - -#endif // FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/database/common.h b/packages/firebase_core/firebase_core/firebase_core/firebase/database/common.h deleted file mode 100644 index 298972784631..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/database/common.h +++ /dev/null @@ -1,83 +0,0 @@ -// Copyright 2016 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_COMMON_H_ -#define FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_COMMON_H_ - -#include "firebase/variant.h" - -namespace firebase { -namespace database { - -/// Error code returned by Firebase Realtime Database C++ functions. -enum Error { - /// The operation was a success, no error occurred. - kErrorNone = 0, - /// The operation had to be aborted due to a network disconnect. - kErrorDisconnected, - /// The supplied auth token has expired. - kErrorExpiredToken, - /// The specified authentication token is invalid. - kErrorInvalidToken, - /// The transaction had too many retries. - kErrorMaxRetries, - /// The operation could not be performed due to a network error. - kErrorNetworkError, - /// The server indicated that this operation failed. - kErrorOperationFailed, - /// The transaction was overridden by a subsequent set. - kErrorOverriddenBySet, - /// This client does not have permission to perform this operation. - kErrorPermissionDenied, - /// The service is unavailable. - kErrorUnavailable, - /// An unknown error occurred. - kErrorUnknownError, - /// The write was canceled locally. - kErrorWriteCanceled, - /// You specified an invalid Variant type for a field. For example, - /// a DatabaseReference's Priority and the keys of a Map must be of - /// scalar type (MutableString, StaticString, Int64, Double). - kErrorInvalidVariantType, - /// An operation that conflicts with this one is already in progress. For - /// example, calling SetValue and SetValueAndPriority on a DatabaseReference - /// is not allowed. - kErrorConflictingOperationInProgress, - /// The transaction was aborted, because the user's DoTransaction function - /// returned kTransactionResultAbort instead of kTransactionResultSuccess. - kErrorTransactionAbortedByUser, -}; - -/// @brief Get the human-readable error message corresponding to an error code. -/// -/// @param[in] error Error code to get the error message for. -/// -/// @returns Statically-allocated string describing the error. -extern const char* GetErrorMessage(Error error); - -/// @brief Get a server-populated value corresponding to the current -/// timestamp. -/// -/// When inserting values into the database, you can use the special value -/// firebase::database::ServerTimestamp() to have the server auto-populate the -/// current timestamp, which is represented as millieconds since the Unix epoch, -/// into the field. -/// -/// @returns A special value that tells the server to use the current timestamp. -const Variant& ServerTimestamp(); - -} // namespace database -} // namespace firebase - -#endif // FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_COMMON_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/database/data_snapshot.h b/packages/firebase_core/firebase_core/firebase_core/firebase/database/data_snapshot.h deleted file mode 100644 index cb83292a792b..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/database/data_snapshot.h +++ /dev/null @@ -1,205 +0,0 @@ -// Copyright 2016 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_DATA_SNAPSHOT_H_ -#define FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_DATA_SNAPSHOT_H_ - -#include - -#include - -#include "firebase/internal/common.h" -#include "firebase/variant.h" - -namespace firebase { -namespace database { -namespace internal { -class Callbacks; -class ChildEventRegistration; -class DataSnapshotInternal; -class DatabaseInternal; -class DatabaseInternalTestMatcherTest; -class DatabaseReferenceInternal; -class QueryInternal; -class Repo; -class ValueEventRegistration; -} // namespace internal - -class Database; -class DatabaseReference; - -#ifndef SWIG -/// A DataSnapshot instance contains data from a Firebase Database location. Any -/// time you read Database data, you receive the data as a DataSnapshot. These -/// are efficiently-generated and cannot be changed. To modify data, -/// use DatabaseReference::SetValue() or DatabaseReference::RunTransaction(). -#endif // SWIG -class DataSnapshot { - public: - /// @brief Default constructor. - /// - /// This DataSnapshot contains nothing and is considered invalid (i.e. - /// is_valid() == false). Use this to construct an empty DataSnapshot that you - /// will later populate with data from a database callback. - DataSnapshot() : internal_(nullptr) {} - -#ifdef INTERNAL_EXPERIMENTAL - explicit DataSnapshot(internal::DataSnapshotInternal* internal); -#endif - - /// @brief Copy constructor. DataSnapshots are immutable, so they can be - /// efficiently copied. - /// - /// @param[in] snapshot DataSnapshot to copy. - DataSnapshot(const DataSnapshot& snapshot); - - /// @brief Copy assignment operator. DataSnapshots are immutable, so they can - /// be efficiently copied. - /// - /// @param[in] snapshot DataSnapshot to copy. - /// - /// @returns Reference to the destination DataSnapshot. - DataSnapshot& operator=(const DataSnapshot& snapshot); - -#if defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) - /// @brief Move constructor. DataSnapshots are immutable, so they can be - /// efficiently moved. - /// - /// @param[in] snapshot DataSnapshot to move into this one. - DataSnapshot(DataSnapshot&& snapshot); - - /// @brief Move assignment operator. DataSnapshots are immutable, so they can - /// be efficiently moved. - /// - /// @param[in] snapshot DataSnapshot to move into this one. - /// - /// @returns Reference to this destination DataSnapshot. - DataSnapshot& operator=(DataSnapshot&& snapshot); -#endif // defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) - - /// Destructor. - ~DataSnapshot(); - - /// @brief Returns true if the data is non-empty. - bool exists() const; - - /// @brief Get a DataSnapshot for the location at the specified relative path. - /// - /// @param[in] path Path relative to this snapshot's location. - /// It only needs to be valid during this call. - /// - /// @returns A DataSnapshot corresponding to specified child location. - DataSnapshot Child(const char* path) const; - - /// @brief Get a DataSnapshot for the location at the specified relative path. - /// - /// @param[in] path Path relative to this snapshot's location. - /// - /// @returns A DataSnapshot corresponding to specified child location. - DataSnapshot Child(const std::string& path) const; - - /// @brief Get all the immediate children of this location. - /// - /// @returns The immediate children of this snapshot. - std::vector children() const; - - /// @brief Get the number of children of this location. - /// - /// @returns The number of immediate children of this snapshot. - size_t children_count() const; - - /// @brief Does this DataSnapshot have any children at all? - /// - /// @returns True if the snapshot has any children, false otherwise. - bool has_children() const; - - /// @brief Get the key name of the source location of this snapshot. - /// - /// @note The returned pointer is only guaranteed to be valid while the - /// DataSnapshot is still in memory. - /// - /// @returns Key name of the source location of this snapshot. - const char* key() const; - - /// @brief Get the key name of the source location of this snapshot. - /// - /// @returns Key name of the source location of this snapshot. - std::string key_string() const; - - /// @brief Get the value of the data contained in this snapshot. - /// - /// @returns The value of the data contained in this location. - Variant value() const; - - /// @brief Get the priority of the data contained in this snapshot. - /// - /// @returns The value of this location's Priority relative to its siblings. - Variant priority() const; - - /// @brief Obtain a DatabaseReference to the source location for this - /// snapshot. - /// - /// @returns A DatabaseReference corresponding to same location as - /// this snapshot. - DatabaseReference GetReference() const; - - /// @brief Does this DataSnapshot have data at a particular location? - /// - /// @param[in] path Path relative to this snapshot's location. - /// The pointer only needs to be valid during this call. - /// - /// @returns True if the snapshot has data at the specified location, false if - /// not. - bool HasChild(const char* path) const; - - /// @brief Does this DataSnapshot have data at a particular location? - /// - /// @param[in] path Path relative to this snapshot's location. - /// - /// @returns True if the snapshot has data at the specified location, false if - /// not. - bool HasChild(const std::string& path) const; - - /// @brief Returns true if this snapshot is valid, false if it is not - /// valid. An invalid snapshot could be returned by a transaction where an - /// error has occurred. - /// - /// @returns true if this snapshot is valid, false if this snapshot is - /// invalid. - bool is_valid() const; - - private: - /// @cond FIREBASE_APP_INTERNAL - friend class internal::Callbacks; - friend class internal::ChildEventRegistration; - friend class internal::DataSnapshotInternal; - friend class internal::DatabaseInternal; - friend class internal::DatabaseInternalTestMatcherTest; - friend class internal::DatabaseReferenceInternal; - friend class internal::QueryInternal; - friend class internal::Repo; - friend class internal::ValueEventRegistration; - /// @endcond - -#ifndef INTERNAL_EXPERIMENTAL - explicit DataSnapshot(internal::DataSnapshotInternal* internal); -#endif - - internal::DataSnapshotInternal* internal_; -}; - -} // namespace database -} // namespace firebase - -#endif // FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_DATA_SNAPSHOT_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/database/database_reference.h b/packages/firebase_core/firebase_core/firebase_core/firebase/database/database_reference.h deleted file mode 100644 index 3e746541a1d5..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/database/database_reference.h +++ /dev/null @@ -1,477 +0,0 @@ -// Copyright 2016 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_DATABASE_REFERENCE_H_ -#define FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_DATABASE_REFERENCE_H_ - -#include -#include - -#include "firebase/database/disconnection.h" -#include "firebase/database/query.h" -#include "firebase/database/transaction.h" -#include "firebase/future.h" -#include "firebase/internal/common.h" -#include "firebase/variant.h" - -namespace firebase { -namespace database { -namespace internal { -class DatabaseInternal; -class DatabaseReferenceInternal; -class Repo; -} // namespace internal - -class DataSnapshot; - -#ifndef SWIG -/// DatabaseReference represents a particular location in your Database and can -/// be used for reading or writing data to that Database location. -/// -/// This class is the starting point for all Database operations. After you've -/// initialized it with a URL, you can use it to read data, write data, and to -/// create new DatabaseReference instances. -#endif // SWIG -class DatabaseReference : public Query { - public: - /// @brief Default constructor. This creates an invalid DatabaseReference. - /// Attempting to perform any operations on this reference will fail unless a - /// valid DatabaseReference has been assigned to it. - DatabaseReference() : Query(), internal_(nullptr) {} - - /// @brief Required virtual destructor. - virtual ~DatabaseReference(); - - /// @brief Copy constructor. It's totally okay (and efficient) to copy - /// DatabaseReference instances, as they simply point to the same location in - /// the database. - /// - /// @param[in] reference DatabaseReference to copy from. - DatabaseReference(const DatabaseReference& reference); - - /// @brief Copy assignment operator. It's totally okay (and efficient) to copy - /// DatabaseReference instances, as they simply point to the same location in - /// the database. - /// - /// @param[in] reference DatabaseReference to copy from. - /// - /// @returns Reference to the destination DatabaseReference. - DatabaseReference& operator=(const DatabaseReference& reference); - -#if defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) - /// @brief Move constructor. Moving is an efficient operation for - /// DatabaseReference instances. - /// - /// @param[in] reference DatabaseReference to move data from. - DatabaseReference(DatabaseReference&& reference); - - /// @brief Move assignment operator. Moving is an efficient operation for - /// DatabaseReference instances. - /// - /// @param[in] reference DatabaseReference to move data from. - /// - /// @returns Reference to the destination DatabaseReference. - DatabaseReference& operator=(DatabaseReference&& reference); -#endif // defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) - - /// @brief Gets the database to which we refer. - /// - /// The pointer will remain valid indefinitely. - /// - /// @returns Firebase Database instance that this DatabaseReference refers to. - Database* database() const; - - /// @brief Gets the string key of this database location. - /// - /// The pointer is only valid while the DatabaseReference remains in memory. - /// - /// @returns String key of this database location, which will remain valid in - /// memory until the DatabaseReference itself goes away. - const char* key() const; - - /// @brief Gets the string key of this database location. - /// - /// @returns String key of this database location. - std::string key_string() const; - - /// @brief Returns true if this reference refers to the root of the database. - /// - /// @returns true if this reference refers to the root of the database, false - /// otherwise. - bool is_root() const; - - /// @brief Returns true if this reference is valid, false if it is not - /// valid. DatabaseReferences constructed with the default constructor - /// are considered invalid. An invalid reference could be returned by - /// Database::GetReference() or Database::GetReferenceFromUrl() if you specify - /// an incorrect location, or calling Query::GetReference() on an invalid - /// query. - /// - /// @returns true if this reference is valid, false if this reference is - /// invalid. - bool is_valid() const override; - - /// @brief Gets the parent of this location, or get this location again if - /// IsRoot(). - /// - /// @returns Parent of this location in the database, unless this location is - /// the root, in which case it returns this same location again. - DatabaseReference GetParent() const; - - /// @brief Gets the root of the database. - /// - /// @returns Root of the database. - DatabaseReference GetRoot() const; - - /// @brief Gets a reference to a location relative to this one. - /// - /// @param[in] path Path relative to this snapshot's location. - /// The pointer only needs to be valid during this call. - /// - /// @returns Child relative to this location. - DatabaseReference Child(const char* path) const; - - /// @brief Gets a reference to a location relative to this one. - /// - /// @param[in] path Path relative to this snapshot's location. - /// - /// @returns Child relative to this location. - DatabaseReference Child(const std::string& path) const; - - /// @brief Automatically generates a child location, create a reference to it, - /// and returns that reference to it. - /// - /// @returns A newly created child, with a unique key. - DatabaseReference PushChild() const; - - /// @brief Removes the value at this location from the database. - /// - /// This is an asynchronous operation which takes time to execute, and uses - /// firebase::Future to return its result. - /// - /// @returns A Future result, which will complete when the operation either - /// succeeds or fails. When the Future is completed, if its Error is - /// kErrorNone, the operation succeeded. - /// - /// @note Only one RemoveValue() should be running on a given database - /// location at the same time. If you need to run multiple operations at once, - /// use RunTransaction(). - Future RemoveValue(); - - /// @brief Gets the result of the most recent call to RemoveValue(); - /// - /// @returns Result of the most recent call to RemoveValue(). - Future RemoveValueLastResult(); - - /// @brief Run a user-supplied callback function (passing in a context), - /// possibly multiple times, to perform an atomic transaction on the database. - /// - /// @see firebase::database::DoTransactionWithContext for more information. - /// - /// @param[in] transaction_function The user-supplied function that will be - /// called, possibly multiple times, to perform the database transaction. - /// @param[in] context User-supplied context that will be passed to the - /// transaction function. - /// @param[in] trigger_local_events If true, events will be triggered for - /// intermediate state changes during the transaction. If false, only the - /// final state will cause events to be triggered. - /// - /// @returns A Future result, which will complete when the transaction either - /// succeeds or fails. When the Future is completed, if its Error is - /// kErrorNone, the operation succeeded and the transaction was committed, and - /// the new value of the data will be returned in the DataSnapshot result. If - /// the Error is kErrorTransactionAbortedByUser, the transaction was aborted - /// because the transaction function returned kTransactionResultAbort, and the - /// old value will be returned in DataSnapshot. Otherwise, if some other error - /// occurred, Error and ErrorMessage will be set and DataSnapshot will be - /// invalid. - /// - /// @note Only one RunTransaction() should be running on a given database - /// location at the same time. - Future RunTransaction( - DoTransactionWithContext transaction_function, void* context, - bool trigger_local_events = true); - -#if defined(FIREBASE_USE_STD_FUNCTION) || defined(DOXYGEN) - /// @brief Run a user-supplied callback, possibly multiple times, to perform - /// an atomic transaction on the database. - /// - /// @see firebase::database::DoTransactionFunction for more information. - /// - /// @param[in] transaction_function The user-supplied function or lambda that - /// will be called, possibly multiple times, to perform the database - /// transaction. - /// @param[in] trigger_local_events If true, events will be triggered for - /// intermediate state changes during the transaction. If false, only the - /// final state will cause events to be triggered. - /// - /// @returns A Future result, which will complete when the transaction either - /// succeeds or fails. When the Future is completed, if its Error is - /// kErrorNone, the operation succeeded and the transaction was committed, and - /// the new value of the data will be returned in the DataSnapshot result. If - /// the Error is kErrorTransactionAbortedByUser, the transaction was aborted - /// because the transaction function returned kTransactionResultAbort, and the - /// old value will be returned in DataSnapshot. Otherwise, if some other error - /// occurred, Error and ErrorMessage will be set and DataSnapshot will be - /// invalid. - /// - /// @note Only one RunTransaction() should be running on a given database - /// location at the same time. - /// - /// @note This version (that accepts an std::function) is not available when - /// using stlport on Android. If you don't wish to use std::function, use the - /// overloaded method that accepts a simple function pointer with a context. - Future RunTransaction( - DoTransactionFunction transaction_function, - bool trigger_local_events = true); -#endif // defined(FIREBASE_USE_STD_FUNCTION) || defined(DOXYGEN) - -#if !defined(FIREBASE_USE_STD_FUNCTION) || defined(DOXYGEN) - /// @brief Run a user-supplied callback function, possibly multiple times, to - /// perform an atomic transaction on the database. - /// - /// @see firebase::database::DoTransaction for more information. - /// - /// @param[in] transaction_function The user-supplied function that will be - /// called, possibly multiple times, to perform the database transaction. - /// @param[in] trigger_local_events If true, events will be triggered for - /// intermediate state changes during the transaction. If false, only the - /// final state will cause events to be triggered. - /// - /// @returns A Future result, which will complete when the transaction either - /// succeeds or fails. When the Future is completed, if its Error is - /// kErrorNone, the operation succeeded and the transaction was committed, and - /// the new value of the data will be returned in the DataSnapshot result. If - /// the Error is kErrorTransactionAbortedByUser, the transaction was aborted - /// because the transaction function returned kTransactionResultAbort, and the - /// old value will be returned in DataSnapshot. Otherwise, if some other error - /// occurred, Error and ErrorMessage will be set and DataSnapshot will be - /// invalid. - /// - /// @note Only one RunTransaction() should be running on a given database - /// location at the same time. - /// - /// @note This version (that accepts a simple function pointer) is only - /// available when using stlport and std::function is not available. - Future RunTransaction(DoTransaction transaction_function, - bool trigger_local_events = true); -#endif // !defined(FIREBASE_USE_STD_FUNCTION) || defined(DOXYGEN) - - /// @brief Get the result of the most recent call to RunTransaction(). - /// - /// @returns Results of the most recent call to RunTransaction(). - Future RunTransactionLastResult(); - - /// @brief Sets the priority of this field, which controls its sort - /// order relative to its siblings. - /// - /// In Firebase, children are sorted in the following order: - /// 1. First, children with no priority. - /// 2. Then, children with numerical priority, sorted numerically in - /// ascending order. - /// 3. Then, remaining children, sorted lexicographically in ascending order - /// of their text priority. - /// - /// Children with the same priority (including no priority) are sorted by - /// key: - /// A. First, children with keys that can be parsed as 32-bit integers, - /// sorted in ascending numerical order of their keys. - /// B. Then, remaining children, sorted in ascending lexicographical order - /// of their keys. - /// - /// This is an asynchronous operation which takes time to execute, and uses - /// firebase::Future to return its result. - /// - /// @param[in] priority Sort priority for this child relative to its siblings. - /// The Variant types accepted are Null, Int64, Double, and String. Other - /// types will return kErrorInvalidVariantType. - /// - /// @returns A Future result, which will complete when the operation either - /// succeeds or fails. When the Future is completed, if its Error is - /// kErrorNone, the operation succeeded. - /// - /// @note Only one SetPriority() should be running on a given database - /// location - /// at the same time. If you need to run multiple operations at once, use - /// RunTransaction(). - Future SetPriority(Variant priority); - - /// @brief Gets the result of the most recent call to SetPriority(). - /// - /// @returns Result of the most recent call to SetPriority(). - Future SetPriorityLastResult(); - - /// @brief Sets the data at this location to the given value. - /// - /// This is an asynchronous operation which takes time to execute, and uses - /// firebase::Future to return its result. - /// - /// @param[in] value The value to set this location to. The Variant's type - /// corresponds to the types accepted by the database JSON: - /// Null: Deletes this location from the database. - /// Int64: Inserts an integer value into this location. - /// Double: Inserts a floating point value into this location. - /// String: Inserts a string into this location. - /// (Accepts both Mutable and Static strings) - /// Vector: Inserts a JSON array into this location. The elements can be any - /// Variant type, including Vector and Map. - /// Map: Inserts a JSON associative array into this location. The keys must - /// be of type String (or Int64/Double which are converted to String). - /// The values can be any Variant type, including Vector and Map. - /// - /// @returns A Future result, which will complete when the operation either - /// succeeds or fails. When the Future is completed, if its Error is - /// kErrorNone, the operation succeeded. - /// - /// @note Only one SetValue() should be running on a given database location - /// at the same time. If you need to run multiple operations at once, use - /// RunTransaction(). - Future SetValue(Variant value); - - /// @brief Gets the result of the most recent call to SetValue(). - /// - /// @returns Result of the most recent call to SetValue(). - Future SetValueLastResult(); - - /// @brief Sets both the data and priority of this location. See SetValue() - /// and SetPriority() for context on the parameters. - /// - /// This is an asynchronous operation which takes time to execute, and uses - /// firebase::Future to return its result. - /// - /// @param[in] value The value to set this location to. See SetValue() for - /// information on the types accepted. - /// @param[in] priority The priority to set this location to. See - /// SetPriority() for information on the types accepted. - /// - /// @returns A Future result, which will complete when the operation either - /// succeeds or fails. When the Future is completed, if its Error is - /// kErrorNone, the operation succeeded. - /// - /// @note Only one SetValueAndPriority() should be running on a given database - /// location at the same time. SetValueAndPriority() can't be used on the same - /// location at the same time as either SetValue() or SetPriority(), and will - /// return kErrorConflictingOperationInProgress if you try. If you need to run - /// multiple operations at once, use RunTransaction(). - Future SetValueAndPriority(Variant value, Variant priority); - - /// @brief Get the result of the most recent call to SetValueAndPriority(). - /// - /// @returns Result of the most recent call to SetValueAndPriority(). - Future SetValueAndPriorityLastResult(); - - /// @brief Updates the specified child keys to the given values. - /// - /// @param[in] values A variant of type Map. The keys are the paths to update - /// and must be of type String (or Int64/Double which are converted to - /// String). The values can be any Variant type. A value of Variant type Null - /// will delete the child. - /// - /// @returns A Future result, which will complete when the operation either - /// succeeds or fails. When the Future is completed, if its Error is - /// kErrorNone, the operation succeeded. - /// - /// @note This method will return kErrorConflictingOperationInProgress if it - /// is run at the same time as SetValue(), SetValueAndPriority(), or - /// RemoveValue() in the same location. - Future UpdateChildren(Variant values); - - /// @brief Updates the specified child keys to the given values. - /// - /// This is an asynchronous operation which takes time to execute, and uses - /// firebase::Future to return its result. - /// - /// @param[in] values The paths to update, and their new child values. A value - /// of type Null will delete that particular child. - /// - /// @returns A Future result, which will complete when the operation either - /// succeeds or fails. When the Future is completed, if its Error is - /// kErrorNone, the operation succeeded. - inline Future UpdateChildren( - const std::map& values) { - return UpdateChildren(Variant(values)); - } - - /// @brief Gets the result of the most recent call to either version of - /// UpdateChildren(). - /// - /// @returns Result of the most recent call to UpdateChildren(). - Future UpdateChildrenLastResult(); - - /// @brief Get the absolute URL of this reference. - /// - /// @returns The absolute URL of the location this reference refers to. - std::string url() const; - - /// @brief Get the disconnect handler, which controls what actions the server - /// will perform to this location's data when this client disconnects. - /// - /// @returns Disconnection handler for this location. You can use this to - /// queue up operations on the server to be performed when the client - /// disconnects. - DisconnectionHandler* OnDisconnect(); - - /// @brief Manually disconnect Firebase Realtime Database from the server, and - /// disable automatic reconnection. This will affect all other instances of - /// DatabaseReference as well. - void GoOffline(); - - /// @brief Manually reestablish connection to the Firebase Realtime Database - /// server and enable automatic reconnection. This will affect all other - /// instances of DatabaseReference as well. - void GoOnline(); - - protected: - /// @cond FIREBASE_APP_INTERNAL - explicit DatabaseReference(internal::DatabaseReferenceInternal* internal); - /// @endcond - - private: - /// @cond FIREBASE_APP_INTERNAL - - // Remove the "Query" cleanup registration (which the base class constructor - // already registered) and replace it with a "DatabaseReference" registration. - // - // This is necessary so that if the instance needs to be cleaned up, the - // correct pointer type will be used to access it. - void SwitchCleanupRegistrationToDatabaseReference(); - - // Remove the "DatabaseReference" cleanup registration and replace it with a - // "Query" one. ~Query() will unregister that one. - void SwitchCleanupRegistrationBackToQuery(); - - friend class DataSnapshot; - friend class Query; - friend class internal::DatabaseInternal; - friend class internal::Repo; - friend bool operator==(const DatabaseReference& lhs, - const DatabaseReference& rhs); - /// @endcond - - internal::DatabaseReferenceInternal* internal_; -}; - -/// @brief Compares two DatabaseReference instances. -/// -/// @param[in] lhs A DatabaseReference. -/// @param[in] rhs A DatabaseReference to compare against. -/// -/// @returns True if the DatabaseReference instances have the same URL. False -/// otherwise. -bool operator==(const DatabaseReference& lhs, const DatabaseReference& rhs); - -} // namespace database -} // namespace firebase - -#endif // FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_DATABASE_REFERENCE_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/database/disconnection.h b/packages/firebase_core/firebase_core/firebase_core/firebase/database/disconnection.h deleted file mode 100644 index b21fa472e629..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/database/disconnection.h +++ /dev/null @@ -1,156 +0,0 @@ -// Copyright 2016 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_DISCONNECTION_H_ -#define FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_DISCONNECTION_H_ - -#include "firebase/future.h" -#include "firebase/internal/common.h" -#include "firebase/variant.h" - -namespace firebase { -namespace database { -namespace internal { -class DatabaseReferenceInternal; -class DisconnectionHandlerInternal; -} // namespace internal - -/// Allows you to register server-side actions to occur when the client -/// disconnects. Each method you call (with the exception of Cancel) will queue -/// up an action on the data that will be performed by the server in the event -/// the client disconnects. To reset this queue, call Cancel(). -/// -/// A DisconnectionHandler is associated with a specific location in the -/// database, as they are obtained by calling DatabaseReference::OnDisconnect(). -class DisconnectionHandler { - public: - ~DisconnectionHandler(); - - /// @brief Cancel any Disconnection operations that are queued up by this - /// handler. When the Future returns, if its Error is kErrorNone, the queue - /// has been cleared on the server. - /// - /// @returns A Future result, which will complete when the operation either - /// succeeds or fails. When the Future is completed, if its Error is - /// kErrorNone, the operation succeeded. - Future Cancel(); - /// @brief Get the result of the most recent call to Cancel(). - /// - /// @returns Result of the most recent call to Cancel(). - Future CancelLastResult(); - - /// @brief Remove the value at the current location when the client - /// disconnects. When the Future returns, if its Error is kErrorNone, the - /// RemoveValue operation has been successfully queued up on the server. - /// - /// @returns A Future result, which will complete when the operation either - /// succeeds or fails. When the Future is completed, if its Error is - /// kErrorNone, the operation succeeded. - Future RemoveValue(); - /// @brief Get the result of the most recent call to RemoveValue(). - /// - /// @returns Result of the most recent call to RemoveValue(). - Future RemoveValueLastResult(); - - /// @brief Set the value of the data at the current location when the client - /// disconnects. When the Future returns, if its Error is kErrorNone, the - /// SetValue operation has been successfully queued up on the server. - /// - /// @param[in] value The value to set this location to when the client - /// disconnects. For information on how the Variant types are used, - /// see firebase::database::DatabaseReference::SetValue(). - /// - /// @returns A Future result, which will complete when the operation either - /// succeeds or fails. When the Future is completed, if its Error is - /// kErrorNone, the operation succeeded. - Future SetValue(Variant value); - /// Get the result of the most recent call to SetValue(). - /// - /// @returns Result of the most recent call to SetValue(). - Future SetValueLastResult(); - - /// @brief Set the value and priority of the data at the current location when - /// the client disconnects. When the Future returns, if its Error is - /// kErrorNone, the SetValue operation has been successfully queued up on the - /// server. - /// - /// @param[in] value The value to set this location to when the client - /// disconnects. For information on how the Variant types are used, - /// see firebase::database::DatabaseReference::SetValue(). - /// @param[in] priority The priority to set this location to when the client - /// disconnects. The Variant types accepted are Null, Int64, Double, and - /// String. For information about how priority is used, see - /// firebase::database::DatabaseReference::SetPriority(). - /// - /// @returns A Future result, which will complete when the operation either - /// succeeds or fails. When the Future is completed, if its Error is - /// kErrorNone, the operation succeeded. - Future SetValueAndPriority(Variant value, Variant priority); - /// @brief Get the result of the most recent call to SetValueAndPriority(). - /// - /// @returns Result of the most recent call to SetValueAndPriority(). - Future SetValueAndPriorityLastResult(); - - /// @brief Updates the specified child keys to the given values when the - /// client disconnects. When the Future returns, if its Error is kErrorNone, - /// the UpdateChildren operation has been successfully queued up by the - /// server. - /// - /// @param[in] values A variant of type Map. The keys are the paths to update - /// and must be of type String (or Int64/Double which are converted to - /// String). The values can be any Variant type. A value of Variant type Null - /// will delete the child. - /// - /// @returns A Future result, which will complete when the operation either - /// succeeds or fails. When the Future is completed, if its Error is - /// kErrorNone, the operation succeeded. - Future UpdateChildren(Variant values); - /// @brief Updates the specified child keys to the given values when the - /// client disconnects. When the Future returns, if its Error is kErrorNone, - /// the UpdateChildren operation has been successfully queued up by the - /// server. - /// - /// @param[in] values The paths to update, and their new child values. A value - /// of type Null will delete that particular child. - /// - /// @returns A Future result, which will complete when the operation either - /// succeeds or fails. When the Future is completed, if its Error is - /// kErrorNone, the operation succeeded. - Future UpdateChildren(const std::map& values) { - return UpdateChildren(Variant(values)); - } - /// @brief Gets the result of the most recent call to either version of - /// UpdateChildren(). - /// - /// @returns Result of the most recent call to UpdateChildren(). - Future UpdateChildrenLastResult(); - - private: - /// @cond FIREBASE_APP_INTERNAL - friend class internal::DatabaseReferenceInternal; - friend class internal::DisconnectionHandlerInternal; - /// @endcond - - /// Call DatabaseReference::OnDisconnect() to get an instance of this class. - explicit DisconnectionHandler( - internal::DisconnectionHandlerInternal* internal); - - /// You can only get the DisconnectHandler for a given reference. - internal::DisconnectionHandlerInternal* internal_; -}; - -} // namespace database -} // namespace firebase - -#endif // FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_DISCONNECTION_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/database/listener.h b/packages/firebase_core/firebase_core/firebase_core/firebase/database/listener.h deleted file mode 100644 index fe13d9299003..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/database/listener.h +++ /dev/null @@ -1,112 +0,0 @@ -// Copyright 2016 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_LISTENER_H_ -#define FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_LISTENER_H_ - -#include "firebase/database/common.h" - -namespace firebase { -namespace database { - -class DataSnapshot; - -/// Value listener interface. Subclasses of this listener class can be -/// used to receive events about data changes at a location. Attach -/// the listener to a location using -/// DatabaseReference::AddValueListener() or -/// Query::AddValueListener(), and OnValueChanged() will be called -/// once immediately, and again when the value changes. -class ValueListener { - public: - virtual ~ValueListener(); - - /// This method will be called with a snapshot of the data at this - /// location each time that data changes. - /// - /// @param[in] snapshot The current data at the location. - virtual void OnValueChanged(const DataSnapshot& snapshot) = 0; - - /// @brief This method will be triggered in the event that this listener - /// either failed at the server, or is removed as a result of the security and - /// Firebase rules. - /// - /// @param[in] error A code corresponding to the error that occurred. - /// @param[in] error_message A description of the error that occurred. - virtual void OnCancelled(const Error& error, const char* error_message) = 0; -}; - -/// Child listener interface. Subclasses of this listener class can be -/// used to receive events about changes in the child locations of a -/// firebase::database::Query or -/// firebase::database::DatabaseReference. Attach the listener to a -/// location with Query::AddChildListener() or -/// DatabaseReference::AddChildListener() and the appropriate method -/// will be triggered when changes occur. -class ChildListener { - public: - virtual ~ChildListener(); - - /// @brief This method is triggered when a new child is added to the location - /// to which this listener was added. - /// - /// @param[in] snapshot An immutable snapshot of the data at the new data at - /// the child location. - /// @param[in] previous_sibling_key The key name of sibling location ordered - /// before the child. This will be nullptr for the first child node of a - /// location. - virtual void OnChildAdded(const DataSnapshot& snapshot, - const char* previous_sibling_key) = 0; - /// @brief This method is triggered when the data at a child location has - /// changed. - /// - /// @param[in] snapshot An immutable snapshot of the data at the new data at - /// the child location. - /// @param[in] previous_sibling_key The key name of sibling location ordered - /// before the child. This will be nullptr for the first child node of a - /// location. - virtual void OnChildChanged(const DataSnapshot& snapshot, - const char* previous_sibling_key) = 0; - /// @brief This method is triggered when a child location's priority changes. - /// See DatabaseReference::SetPriority() for more information on priorities - /// and - /// ordering data. - /// - /// @param[in] snapshot An immutable snapshot of the data at the new data at - /// the child location. - /// @param[in] previous_sibling_key The key name of sibling location ordered - /// before the child. This will be nullptr for the first child node of a - /// location. - virtual void OnChildMoved(const DataSnapshot& snapshot, - const char* previous_sibling_key) = 0; - /// @brief This method is triggered when a child is removed from the location - /// to which this listener was added. - /// - /// @param[in] snapshot An immutable snapshot of the data at the new data at - /// the child location. - virtual void OnChildRemoved(const DataSnapshot& snapshot) = 0; - - /// @brief This method will be triggered in the event that this listener - /// either failed at the server, or is removed as a result of the security and - /// Firebase rules. - /// - /// @param[in] error A code corresponding to the error that occurred. - /// @param[in] error_message A description of the error that occurred. - virtual void OnCancelled(const Error& error, const char* error_message) = 0; -}; - -} // namespace database -} // namespace firebase - -#endif // FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_LISTENER_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/database/mutable_data.h b/packages/firebase_core/firebase_core/firebase_core/firebase/database/mutable_data.h deleted file mode 100644 index cedfa159cca6..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/database/mutable_data.h +++ /dev/null @@ -1,165 +0,0 @@ -// Copyright 2016 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_MUTABLE_DATA_H_ -#define FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_MUTABLE_DATA_H_ - -#include "firebase/internal/common.h" -#include "firebase/variant.h" - -namespace firebase { -namespace database { -namespace internal { -class DatabaseInternal; -class DatabaseReferenceInternal; -class MutableDataInternal; -class Repo; -} // namespace internal - -#ifndef SWIG -/// Instances of this class encapsulate the data and priority at a location. It -/// is used in transactions, and it is intended to be inspected and then updated -/// to the desired data at that location. -#endif // SWIG -class MutableData { - public: -#if defined(FIREBASE_USE_MOVE_OPERATORS) - /// Move constructor - /// Move is more efficient than copy and delete. - MutableData(MutableData&& rhs); - - // MutableData may be moved. - MutableData& operator=(MutableData&& rhs); -#endif // defined(FIREBASE_USE_MOVE_OPERATORS) - - /// Destructor. - ~MutableData(); - - /// @brief Used to obtain a MutableData instance that encapsulates - /// the data and priority at the given relative path. - /// - /// Note that changes made to a child MutableData instance will be visible - /// to the parent and vice versa. - /// - /// @param[in] path Path relative to this snapshot's location. - /// The pointer only needs to be valid during this call. - /// - /// @returns MutableData for the Child relative to this location. The memory - /// will be freed when the Transaction is finished. - MutableData Child(const char* path); - - /// @brief Used to obtain a MutableData instance that encapsulates - /// the data and priority at the given relative path. - /// - /// @param[in] path Path relative to this snapshot's location. - /// - /// @returns MutableData for the Child relative to this location. The memory - /// will be freed when the Transaction is finished. - MutableData Child(const std::string& path); - - /// @brief Get all the immediate children of this location. - /// - /// @returns The immediate children of this location. - std::vector children(); - - /// @brief Get the number of children of this location. - /// - /// @returns The number of immediate children of this location. - size_t children_count(); - - /// @brief Get the key name of the source location of this data. - /// - /// @note The returned pointer is only guaranteed to be valid during the - /// transaction. - /// - /// @returns Key name of the source location of this data. - const char* key() const; - - /// @brief Get the key name of the source location of this data. - /// - /// @returns Key name of the source location of this data. - std::string key_string() const; - - /// @brief Get the value of the data contained at this location. - /// - /// @returns The value of the data contained at this location. - Variant value() const; - - /// @brief Get the priority of the data contained at this snapshot. - /// - /// @returns The value of this location's Priority relative to its siblings. - Variant priority(); - - /// @brief Does this MutableData have data at a particular location? - /// - /// @param[in] path Path relative to this data's location. - /// The pointer only needs to be valid during this call. - /// - /// @returns True if there is data at the specified location, false if not. - bool HasChild(const char* path) const; - - /// @brief Does this MutableData have data at a particular location? - /// - /// @param[in] path Path relative to this data's location. - /// @returns True if there is data at the specified location, false if not. - bool HasChild(const std::string& path) const; - - /// @brief Sets the data at this location to the given value. - /// - /// @param[in] value The value to set this location to. The Variant's type - /// corresponds to the types accepted by the database JSON: - /// Null: Deletes this location from the database. - /// Int64: Inserts an integer value into this location. - /// Double: Inserts a floating point value into this location. - /// String: Inserts a string into this location. - /// (Accepts both Mutable and Static strings) - /// Vector: Inserts a JSON array into this location. The elements can be any - /// Variant type, including Vector and Map. - /// Map: Inserts a JSON associative array into this location. The keys must - /// be of type String (or Int64/Double which are converted to String). - /// The values can be any Variant type, including Vector and Map. - void set_value(const Variant& value); - - /// @brief Sets the priority of this field, which controls its sort - /// order relative to its siblings. - /// - /// @see firebase::database::DatabaseReference::SetPriority() for information - /// on how Priority affects the ordering of a node's children. - /// - /// @param[in] priority Sort priority for this child relative to its siblings. - /// The Variant types accepted are Null, Int64, Double, and String. Other - /// types will return kErrorInvalidVariantType. - void set_priority(const Variant& priority); - - private: - /// @cond FIREBASE_APP_INTERNAL - friend class internal::DatabaseReferenceInternal; - friend class internal::DatabaseInternal; - friend class internal::MutableDataInternal; - friend class internal::Repo; - friend MutableData GetInvalidMutableData(); - /// @endcond - - explicit MutableData(internal::MutableDataInternal* internal); - - MutableData(const MutableData& rhs) = delete; - MutableData& operator=(const MutableData& rhs) = delete; - - internal::MutableDataInternal* internal_; -}; - -} // namespace database -} // namespace firebase - -#endif // FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_MUTABLE_DATA_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/database/query.h b/packages/firebase_core/firebase_core/firebase_core/firebase/database/query.h deleted file mode 100644 index c60707a7ee65..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/database/query.h +++ /dev/null @@ -1,358 +0,0 @@ -// Copyright 2016 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_QUERY_H_ -#define FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_QUERY_H_ - -#include - -#include "firebase/database/listener.h" -#include "firebase/future.h" -#include "firebase/internal/common.h" - -namespace firebase { -namespace database { -namespace internal { -class QueryInternal; -} // namespace internal - -class DatabaseReference; - -#ifndef SWIG -/// The Query class is used for reading data. Listeners can be attached, which -/// will be triggered when the data changes. -#endif // SWIG -class Query { - public: - /// Default constructor. This creates an invalid Query. Attempting to perform - /// any operations on this reference will fail unless a valid Query has been - /// assigned to it. - Query() : internal_(nullptr) {} - - /// Copy constructor. Queries can be copied. Copies exist independently of - /// each other. - Query(const Query& query); - - /// Copy assignment operator. Queries can be copied. Copies exist - /// independently of each other. - Query& operator=(const Query& query); - -#if defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) - /// Move constructor. - Query(Query&& query); - /// Move assignment operator. - Query& operator=(Query&& query); -#endif // defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) - - /// @brief Required virtual destructor. - virtual ~Query(); - - /// @brief Gets the value of the query for the given location a single time. - /// - /// This is an asynchronous operation which takes time to execute, and uses - /// firebase::Future to return its result. - /// - /// @returns A Future result, which will complete when the operation either - /// succeeds or fails. On this Future's completion, if its Error is - /// kErrorNone, the operation succeeded, and the DataSnapshot contains the - /// data in this location. - Future GetValue(); - /// @brief Gets the result of the most recent call to GetValue(). - /// - /// @returns Result of the most recent call to GetValue(). - Future GetValueLastResult(); - - /// @brief Adds a listener that will be called immediately and then again any - /// time the data changes. - /// - /// @param[in] listener A ValueListener instance, which must remain in memory - /// until you remove the listener from the Query. - void AddValueListener(ValueListener* listener); - - /// @brief Removes a listener that was previously added with - /// AddValueListener(). - /// - /// @param[in] listener A ValueListener instance to remove from the - /// Query. After it is removed, you can delete it or attach it to a new - /// location. - /// - /// @note You can remove a ValueListener from a different Query than you added - /// it to, as long as the two Query instances are equivalent. - void RemoveValueListener(ValueListener* listener); - - /// @brief Removes all value listeners that were added with - /// AddValueListener(). - /// - /// @note You can remove ValueListeners from a different Query than you added - /// them to, as long as the two Query instances are equivalent. - void RemoveAllValueListeners(); - - /// @brief Adds a listener that will be called any time a child is added, - /// removed, modified, or reordered. - /// - /// @param[in] listener A ChildListener instance, which must remain in memory - /// until you remove the listener from the Query. - void AddChildListener(ChildListener* listener); - - /// @brief Removes a listener that was previously added with - /// AddChildListener(). - /// - /// @param[in] listener A ChildListener instance to remove from the - /// Query. After it is removed, you can delete it or attach it to a new - /// location. - /// - /// @note You can remove a ChildListener from a different Query than you added - /// it to, as long as the two Query instances are equivalent. - void RemoveChildListener(ChildListener* listener); - - /// @brief Removes all child listeners that were added by AddChildListener(). - /// - /// @note You can remove ChildListeners from a different Query than you added - /// them to, as long as the two Query instances are equivalent. - void RemoveAllChildListeners(); - - /// @brief Gets a DatabaseReference corresponding to the given location. - /// - /// @returns A DatabaseReference corresponding to the same location as the - /// Query, but without any of the ordering or filtering parameters. - DatabaseReference GetReference() const; - - /// @brief Sets whether this location's data should be kept in sync even if - /// there are no active Listeners. - /// - /// By calling SetKeepSynchronized(true) on a given database location, the - /// data for that location will automatically be downloaded and kept in sync, - /// even when no listeners are attached for that location. Additionally, while - /// a location is kept synced, it will not be evicted from the persistent disk - /// cache. - /// - /// @param[in] keep_sync If true, set this location to be synchronized. If - /// false, set it to not be synchronized. - void SetKeepSynchronized(bool keep_sync); - - // The OrderBy* functions are used for two purposes: - // 1. Order the data when getting the list of children. - // 2. When filtering the data using the StartAt* and EndAt* functions further - // below, use the specified ordering. - - /// @brief Gets a query in which child nodes are ordered by the values of the - /// specified path. Any previous OrderBy directive will be replaced in the - /// returned Query. - /// - /// @param[in] path Path to a child node. The value of this node will be used - /// for sorting this query. The pointer you pass in need not remain valid - /// after the call completes. - /// - /// @returns A Query in this same location, with the children are sorted by - /// the value of their own child specified here. - Query OrderByChild(const char* path); - /// @brief Gets a query in which child nodes are ordered by the values of the - /// specified path. Any previous OrderBy directive will be replaced in the - /// returned Query. - /// - /// @param[in] path Path to a child node. The value of this node will be used - /// for sorting this query. - /// - /// @returns A Query in this same location, with the children are sorted by - /// the value of their own child specified here. - Query OrderByChild(const std::string& path); - /// @brief Gets a query in which child nodes are ordered by their keys. Any - /// previous OrderBy directive will be replaced in the returned Query. - /// - /// @returns A Query in this same location, with the children are sorted by - /// their key. - Query OrderByKey(); - /// @brief Gets a query in which child nodes are ordered by their priority. - /// Any previous OrderBy directive will be replaced in the returned Query. - /// - /// @returns A Query in this same location, with the children are sorted by - /// their priority. - Query OrderByPriority(); - /// @brief Create a query in which nodes are ordered by their value. - /// - /// @returns A Query in this same location, with the children are sorted by - /// their value. - Query OrderByValue(); - - // The StartAt, EndAt, and EqualTo functions are used to limit which child - // nodes are returned when iterating through the current location. - - /// @brief Get a Query constrained to nodes with the given sort value or - /// higher. - /// - /// This method is used to generate a reference to a limited view of the data - /// at this location. The Query returned will only refer to child nodes with a - /// value greater than or equal to the given value, using the given OrderBy - /// directive (or priority as the default). - /// - /// @param[in] order_value The lowest sort value the Query should include. - /// - /// @returns A Query in this same location, filtering out child nodes that - /// have a lower sort value than the sort value specified. - Query StartAt(Variant order_value); - /// @brief Get a Query constrained to nodes with the given sort value or - /// higher, and the given key or higher. - /// - /// This method is used to generate a reference to a limited view of the data - /// at this location. The Query returned will only refer to child nodes with a - /// value greater than or equal to the given value, using the given OrderBy - /// directive (or priority as default), and additionally only child nodes with - /// a key greater than or equal to the given key. - /// - /// Known issue This currently does not work properly on all platforms. - /// Please use StartAt(Variant order_value) instead. - /// - /// @param[in] order_value The lowest sort value the Query should include. - /// @param[in] child_key The lowest key the Query should include. - /// - /// @returns A Query in this same location, filtering out child nodes that - /// have a lower sort value than the sort value specified, or a lower key than - /// the key specified. - Query StartAt(Variant order_value, const char* child_key); - - /// @brief Get a Query constrained to nodes with the given sort value or - /// lower. - /// - /// This method is used to generate a reference to a limited view of the data - /// at this location. The Query returned will only refer to child nodes with a - /// value less than or equal to the given value, using the given OrderBy - /// directive (or priority as default). - /// - /// @param[in] order_value The highest sort value the Query should refer - /// to. - /// - /// @returns A Query in this same location, filtering out child nodes that - /// have a higher sort value or key than the sort value or key specified. - Query EndAt(Variant order_value); - /// @brief Get a Query constrained to nodes with the given sort value or - /// lower, and the given key or lower. - /// - /// This method is used to generate a reference to a limited view of - /// the data at this location. The Query returned will only refer to child - /// nodes with a value less than or equal to the given value, using the given - /// OrderBy directive (or priority as default), and additionally only child - /// nodes with a key less than or equal to the given key. - /// - /// Known issue This currently does not work properly on all platforms. - /// Please use EndAt(Variant order_value) instead. - /// - /// @param[in] order_value The highest sort value the Query should include. - /// @param[in] child_key The highest key the Query should include. - /// - /// @returns A Query in this same location, filtering out child nodes that - /// have a higher sort value than the sort value specified, or a higher key - /// than the key specified. - Query EndAt(Variant order_value, const char* child_key); - - /// @brief Get a Query constrained to nodes with the exact given sort value. - /// - /// This method is used to create a query constrained to only return child - /// nodes with the given value, using the given OrderBy directive (or priority - /// as default). - /// - /// @param[in] order_value The exact sort value the Query should include. - /// - /// @returns A Query in this same location, filtering out child nodes that - /// have a different sort value than the sort value specified. - Query EqualTo(Variant order_value); - - /// @brief Get a Query constrained to nodes with the exact given sort value, - /// and the exact given key. - /// - /// This method is used to create a query constrained to only return the child - /// node with the given value, using the given OrderBy directive (or priority - /// as default), and the given key. Note that there is at most one such child - /// as child key names are unique. - /// - /// Known issue This currently does not work properly on iOS, tvOS and - /// desktop. Please use EqualTo(Variant order_value) instead. - /// - /// @param[in] order_value The exact sort value the Query should include. - /// @param[in] child_key The exact key the Query should include. - /// - /// @returns A Query in this same location, filtering out child nodes that - /// have a different sort value than the sort value specified, and containing - /// at most one child with the exact key specified. - Query EqualTo(Variant order_value, const char* child_key); - - // The LimitTo* functions are used to limit how many child nodes are returned - // when iterating through the current location. - - /// @brief Gets a Query limited to only the first results. - /// - /// Limits the query to reference only the first N child nodes, using the - /// given OrderBy directive (or priority as default). - /// - /// @param[in] limit Number of children to limit the Query to. - /// - /// @returns A Query in this same location, limited to the specified number of - /// children (taken from the beginning of the sorted list). - Query LimitToFirst(size_t limit); - /// @brief Gets a Query limited to only the last results. - /// - /// @param[in] limit Number of children to limit the Query to. - /// - /// @returns A Query in this same location, limited to the specified number of - /// children (taken from the end of the sorted list). - Query LimitToLast(size_t limit); - - /// @brief Returns true if this query is valid, false if it is not valid. An - /// invalid query could be returned by, say, attempting to OrderBy two - /// different items, or calling OrderByChild() with an empty path, or by - /// constructing a Query with the default constructor. If a Query - /// is invalid, attempting to add more constraints will also result in an - /// invalid Query. - /// - /// @returns true if this query is valid, false if this query is - /// invalid. - virtual bool is_valid() const; - - protected: - /// @cond FIREBASE_APP_INTERNAL - explicit Query(internal::QueryInternal* internal); - void SetInternal(internal::QueryInternal* internal); - void RegisterCleanup(); - void UnregisterCleanup(); - /// @endcond - - private: - /// @cond FIREBASE_APP_INTERNAL - friend bool operator==(const Query& lhs, const Query& rhs); - /// @endcond - - internal::QueryInternal* internal_; -}; - -/// @brief Compares two Query instances. -/// -/// Two Query instances on the same database, in the same location, with the -/// same parameters (OrderBy*, StartAt, EndAt, EqualTo, Limit*) are considered -/// equivalent. -/// -/// Equivalent Queries have a shared pool of ValueListeners and -/// ChildListeners. When listeners are added or removed from one Query -/// instance, it affects all equivalent Query instances. -/// -/// @param[in] lhs The Query to compare against. -/// @param[in] rhs The Query to compare against. -/// -/// @returns True if the Query instances have the same database, the same -/// path, and the same parameters, determined by StartAt(), EndAt(), -/// EqualTo(), and the OrderBy and LimitTo methods. False otherwise. -bool operator==(const Query& lhs, const Query& rhs); - -} // namespace database -} // namespace firebase - -#endif // FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_QUERY_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/database/transaction.h b/packages/firebase_core/firebase_core/firebase_core/firebase/database/transaction.h deleted file mode 100644 index cb2dd33c59e2..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/database/transaction.h +++ /dev/null @@ -1,102 +0,0 @@ -// Copyright 2016 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_TRANSACTION_H_ -#define FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_TRANSACTION_H_ - -#include "firebase/database/common.h" -#include "firebase/database/data_snapshot.h" -#include "firebase/database/mutable_data.h" -#include "firebase/internal/common.h" -#include "firebase/variant.h" - -#if defined(FIREBASE_USE_STD_FUNCTION) -#include -#endif // defined(FIREBASE_USE_STD_FUNCTION) - -namespace firebase { -namespace database { - -/// Specifies whether the transaction succeeded or not. -enum TransactionResult { - /// The transaction was successful, the MutableData was updated. - kTransactionResultSuccess, - /// The transaction did not succeed. Any changes to the MutableData - /// will be discarded. - kTransactionResultAbort, -}; - -/// Your own transaction handler, which the Firebase Realtime Database library -/// may call multiple times to apply changes to the data, and should return -/// success or failure depending on whether it succeeds. - -/// @note This version of the callback is no longer supported (unless you are -/// building for Android with stlport). You should use either one of -/// DoTransactionWithContext (a simple function pointer that accepts context -/// data) or DoTransactionFunction (based on std::function). -/// -/// @see DoTransactionWithContext for more information. -typedef TransactionResult (*DoTransaction)(MutableData* data); - -/// Your own transaction handler, which the Firebase Realtime Database library -/// may call multiple times to apply changes to the data, and should return -/// success or failure depending on whether it succeeds. The context you -/// specified to RunTransaction will be passed into this call. -/// -/// This function will be called, _possibly multiple times_, with the current -/// data at this location. The function is responsible for inspecting that data -/// and modifying it as desired, then returning a TransactionResult specifying -/// either that the MutableData was modified to a desired new state, or that the -/// transaction should be aborted. Whenever this function is called, the -/// MutableData passed in must be modified from scratch. -/// -/// Since this function may be called repeatedly for the same transaction, be -/// extremely careful of any side effects that may be triggered by this -/// function. In addition, this function is called from within the Firebase -/// Realtime Database library's run loop, so care is also required when -/// accessing data that may be in use by other threads in your application. -/// -/// Best practices for this function are to ONLY rely on the data passed in. -/// -/// @param[in] data Mutable data, which the callback can edit. -/// @param[in] context Context pointer, passed verbatim to the callback. -/// -/// @returns The callback should return kTransactionResultSuccess if the data -/// was modified, or kTransactionResultAbort if it was unable to modify the -/// data. If the callback returns kTransactionResultAbort, the RunTransaction() -/// call will return the kErrorTransactionAbortedByUser error code. -/// -/// @note If you want a callback to be triggered when the transaction is -/// finished, you can use the Future value returned by the method -/// running the transaction, and call Future::OnCompletion() to register a -/// callback to be called when the transaction either succeeds or fails. -/// -/// @see DoTransaction for more information. -typedef TransactionResult (*DoTransactionWithContext)(MutableData* data, - void* context); - -#if defined(FIREBASE_USE_STD_FUNCTION) || defined(DOXYGEN) -/// Your own transaction handler function or lambda, which the Firebase Realtime -/// Database library may call multiple times to apply changes to the data, and -/// should return success or failure depending on whether it succeeds. -/// -/// @see DoTransactionWithContext for more information. -typedef std::function - DoTransactionFunction; -#endif // defined(FIREBASE_USE_STD_FUNCTION) || defined(DOXYGEN) - -} // namespace database -} // namespace firebase - -#endif // FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_TRANSACTION_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/dynamic_links.h b/packages/firebase_core/firebase_core/firebase_core/firebase/dynamic_links.h deleted file mode 100644 index 7a96de679f62..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/dynamic_links.h +++ /dev/null @@ -1,117 +0,0 @@ -// Copyright 2017 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef FIREBASE_DYNAMIC_LINKS_SRC_INCLUDE_FIREBASE_DYNAMIC_LINKS_H_ -#define FIREBASE_DYNAMIC_LINKS_SRC_INCLUDE_FIREBASE_DYNAMIC_LINKS_H_ - -#include - -#include "firebase/app.h" -#include "firebase/internal/common.h" - -#if !defined(DOXYGEN) && !defined(SWIG) -FIREBASE_APP_REGISTER_CALLBACKS_REFERENCE(dynamic_links) -#endif // !defined(DOXYGEN) && !defined(SWIG) - -namespace firebase { - -/// @brief Firebase Dynamic Links API. -/// -/// Firebase Dynamic Links is a cross-platform solution for generating and -/// receiving links, whether or not the app is already installed. -namespace dynamic_links { - -#ifndef SWIG -/// @brief Error code used by Futures returned by this API. -enum ErrorCode { - kErrorCodeSuccess = 0, - kErrorCodeFailed, -}; -#endif // SWIG - -/// @brief Enum describing the strength of a dynamic links match. -/// -/// This version is local to dynamic links; there is a similar enum in invites -/// and another internal version in app. -enum LinkMatchStrength { - /// No match has been achieved - kLinkMatchStrengthNoMatch = 0, - - /// The match between the Dynamic Link and device is not perfect. You should - /// not reveal any personal information related to the Dynamic Link. - kLinkMatchStrengthWeakMatch, - - /// The match between the Dynamic Link and this device has a high confidence, - /// but there is a small possibility of error. - kLinkMatchStrengthStrongMatch, - - /// The match between the Dynamic Link and the device is exact. You may - /// safely reveal any personal information related to this Dynamic Link. - kLinkMatchStrengthPerfectMatch -}; - -/// @brief The received Dynamic Link. -struct DynamicLink { - /// The URL that was passed to the app. - std::string url; - /// The match strength of the dynamic link. - LinkMatchStrength match_strength; -}; - -/// @brief Base class used to receive Dynamic Links. -class Listener { - public: - virtual ~Listener(); - - /// Called on the client when a dynamic link arrives. - /// - /// @param[in] dynamic_link The data describing the Dynamic Link. - virtual void OnDynamicLinkReceived(const DynamicLink* dynamic_link) = 0; -}; - -/// @brief Initialize Firebase Dynamic Links. -/// -/// After Initialize is called, the implementation may call functions on the -/// Listener provided at any time. -/// -/// @param[in] app The Firebase App object for this application. -/// @param[in] listener A Listener object that receives Dynamic Links. -/// -/// @return kInitResultSuccess if initialization succeeded, or -/// kInitResultFailedMissingDependency on Android if Google Play services is -/// not available on the current device. -InitResult Initialize(const App& app, Listener* listener); - -/// @brief Terminate Firebase Dynamic Links. -void Terminate(); - -/// @brief Set the listener for receiving Dynamic Links. -/// -/// @param[in] listener A Listener object that receives Dynamic Links. -/// -/// @return Pointer to the previously set listener. -Listener* SetListener(Listener* listener); - -/// Fetch any pending dynamic links. Each pending link will trigger a call to -/// the registered Listener class. -/// -/// This function is implicitly called on initialization. On iOS this is called -/// automatically when the app gains focus, but on Android this needs to be -/// called manually. -void Fetch(); - -} // namespace dynamic_links -} // namespace firebase - -#endif // FIREBASE_DYNAMIC_LINKS_SRC_INCLUDE_FIREBASE_DYNAMIC_LINKS_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/dynamic_links/components.h b/packages/firebase_core/firebase_core/firebase_core/firebase/dynamic_links/components.h deleted file mode 100644 index 7a8e8fa1a44b..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/dynamic_links/components.h +++ /dev/null @@ -1,336 +0,0 @@ -// Copyright 2017 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef FIREBASE_DYNAMIC_LINKS_SRC_INCLUDE_FIREBASE_DYNAMIC_LINKS_COMPONENTS_H_ -#define FIREBASE_DYNAMIC_LINKS_SRC_INCLUDE_FIREBASE_DYNAMIC_LINKS_COMPONENTS_H_ - -#include -#include -#include - -#include "firebase/future.h" - -namespace firebase { - -namespace dynamic_links { - -/// @brief Google Analytics Parameters. -/// -/// Note that the strings used by the struct are not copied, as so must -/// either be statically allocated, or must persist in memory until the -/// DynamicLinkComponents that uses them goes out of scope. -struct GoogleAnalyticsParameters { - /// Constructs an empty set of Google Analytics parameters. - GoogleAnalyticsParameters() - : source(nullptr), - medium(nullptr), - campaign(nullptr), - term(nullptr), - content(nullptr) {} - - /// The campaign source; used to identify a search engine, newsletter, - /// or other source. - const char* source; - /// The campaign medium; used to identify a medium such as email or - /// cost-per-click (cpc). - const char* medium; - /// The campaign name; The individual campaign name, slogan, promo code, etc. - /// for a product. - const char* campaign; - /// The campaign term; used with paid search to supply the keywords for ads. - const char* term; - /// The campaign content; used for A/B testing and content-targeted ads to - /// differentiate ads or links that point to the same URL. - const char* content; -}; - -/// @brief iOS Parameters. -/// -/// Note that the strings used by the struct are not copied, as so must -/// either be statically allocated, or must persist in memory until the -/// DynamicLinkComponents that uses them goes out of scope. -struct IOSParameters { - /// Constructs a set of IOS parameters with the given bundle id. - /// - /// @param bundle_id_ The parameters ID of the iOS app to use to open the - /// link. - IOSParameters(const char* bundle_id_) - : bundle_id(bundle_id_), - fallback_url(nullptr), - custom_scheme(nullptr), - ipad_fallback_url(nullptr), - ipad_bundle_id(nullptr), - app_store_id(nullptr), - minimum_version(nullptr) {} - - /// Constructs an empty set of IOS parameters. - IOSParameters() - : bundle_id(nullptr), - fallback_url(nullptr), - custom_scheme(nullptr), - ipad_fallback_url(nullptr), - ipad_bundle_id(nullptr), - app_store_id(nullptr), - minimum_version(nullptr) {} - - /// The parameters ID of the iOS app to use to open the link. The app must be - /// connected to your project from the Overview page of the Firebase console. - /// Note this field is required. - const char* bundle_id; - /// The link to open on iOS if the app is not installed. - /// - /// Specify this to do something other than install your app from the - /// App Store when the app isn't installed, such as open the mobile - /// web version of the content, or display a promotional page for your app. - const char* fallback_url; - /// The app's custom URL scheme, if defined to be something other than your - /// app's parameters ID. - const char* custom_scheme; - /// The link to open on iPad if the app is not installed. - /// - /// Overrides fallback_url when on iPad. - const char* ipad_fallback_url; - /// The iPad parameters ID of the app. - const char* ipad_bundle_id; - /// The App Store ID, used to send users to the App Store when the app isn't - /// installed. - const char* app_store_id; - /// The minimum version of your app that can open the link. - const char* minimum_version; -}; - -/// @brief iTunes Connect App Analytics Parameters. -/// -/// Note that the strings used by the struct are not copied, as so must -/// either be statically allocated, or must persist in memory until the -/// DynamicLinkComponents that uses them goes out of scope. -struct ITunesConnectAnalyticsParameters { - /// Constructs an empty set of ITunes Connect Analytics parameters. - ITunesConnectAnalyticsParameters() - : provider_token(nullptr), - affiliate_token(nullptr), - campaign_token(nullptr) {} - - /// The provider token that enables analytics for Dynamic Links from - /// within iTunes Connect. - const char* provider_token; - /// The affiliate token used to create affiliate-coded links. - const char* affiliate_token; - /// The campaign token that developers can add to any link in order to - /// track sales from a specific marketing campaign. - const char* campaign_token; -}; - -/// @brief Android Parameters. -/// -/// Note that the strings used by the struct are not copied, as so must -/// either be statically allocated, or must persist in memory until the -/// DynamicLinkComponents that uses them goes out of scope. -struct AndroidParameters { - /// Constructs a set of Android parameters with the given package name. - /// - /// The package name of the Android app to use to open the link. - AndroidParameters(const char* package_name_) - : package_name(package_name_), - fallback_url(nullptr), - minimum_version(0) {} - - /// Constructs an empty set of Android parameters. - AndroidParameters() - : package_name(nullptr), fallback_url(nullptr), minimum_version(0) {} - - /// The package name of the Android app to use to open the link. The app - /// must be connected to your project from the Overview page of the Firebase - /// console. - /// Note this field is required. - const char* package_name; - /// The link to open when the app isn't installed. - /// - /// Specify this to do something other than install your app from the - /// Play Store when the app isn't installed, such as open the mobile web - /// version of the content, or display a promotional page for your app. - const char* fallback_url; - /// The versionCode of the minimum version of your app that can open the link. - int minimum_version; -}; - -/// @brief Social meta-tag Parameters. -/// -/// Note that the strings used by the struct are not copied, as so must -/// either be statically allocated, or must persist in memory until the -/// DynamicLinkComponents that uses them goes out of scope. -struct SocialMetaTagParameters { - /// Constructs an empty set of Social meta-tag parameters. - SocialMetaTagParameters() - : title(nullptr), description(nullptr), image_url(nullptr) {} - - /// The title to use when the Dynamic Link is shared in a social post. - const char* title; - /// The description to use when the Dynamic Link is shared in a social post. - const char* description; - /// The URL to an image related to this link. - const char* image_url; -}; - -/// @brief The desired path length for shortened Dynamic Link URLs. -enum PathLength { - /// Uses the server-default for the path length. - /// See https://goo.gl/8yDAqC for more information. - kPathLengthDefault = 0, - /// Typical short link for non-sensitive links. - kPathLengthShort, - /// Short link that uses a very long path to make it more difficult to - /// guess. Useful for sensitive links. - kPathLengthUnguessable, -}; - -/// @brief Additional options for Dynamic Link creation. -struct DynamicLinkOptions { - /// Constructs an empty set of Dynamic Link options. - DynamicLinkOptions() : path_length(kPathLengthDefault) {} - - /// The desired path length for shortened Dynamic Link URLs. - PathLength path_length; -}; - -/// @brief The returned value from creating a Dynamic Link. -struct GeneratedDynamicLink { - /// The Dynamic Link value. - std::string url; - /// Information about potential warnings on link creation. - /// - /// Usually presence of warnings means parameter format errors, parameter - /// value errors, or missing parameters. - std::vector warnings; - /// If non-empty, the cause of the Dynamic Link generation failure. - std::string error; -}; - -/// @brief The information needed to generate a Dynamic Link. -/// -/// Note that the strings used by the struct are not copied, as so must -/// either be statically allocated, or must persist in memory until this -/// struct goes out of scope. -struct DynamicLinkComponents { - /// The link your app will open. - /// You can specify any URL your app can handle, such as a link to your - /// app's content, or a URL that initiates some - /// app-specific logic such as crediting the user with a coupon, or - /// displaying a specific welcome screen. This link must be a well-formatted - /// URL, be properly URL-encoded, and use the HTTP or HTTPS scheme. - /// Note, this field is required. - const char* link; - /// The domain (of the form "https://xyz.app.goo.gl") to use for this Dynamic - /// Link. You can find this value in the Dynamic Links section of the Firebase - /// console. - /// - /// If you have set up custom domains on your project, set this to your - /// project's custom domain as listed in the Firebase console. - /// - /// Only https:// links are supported. - /// - /// Note, this field is required. - const char* domain_uri_prefix; - /// The Google Analytics parameters. - GoogleAnalyticsParameters* google_analytics_parameters; - /// The iOS parameters. - IOSParameters* ios_parameters; - /// The iTunes Connect App Analytics parameters. - ITunesConnectAnalyticsParameters* itunes_connect_analytics_parameters; - /// The Android parameters. - AndroidParameters* android_parameters; - /// The social meta-tag parameters. - SocialMetaTagParameters* social_meta_tag_parameters; - - /// Default constructor, initializes all fields to null. - DynamicLinkComponents() - : link(nullptr), - domain_uri_prefix(nullptr), - google_analytics_parameters(nullptr), - ios_parameters(nullptr), - itunes_connect_analytics_parameters(nullptr), - android_parameters(nullptr), - social_meta_tag_parameters(nullptr) {} - - /// Constructor that initializes with the given link and domain. - /// - /// @param link_ The link your app will open. - /// @param domain_uri_prefix_ The domain (of the form - /// "https://xyz.app.goo.gl") to use for this Dynamic Link. You can find this - /// value in the Dynamic Links section of the Firebase console. If you have - /// set up custom domains on your project, set this to your project's custom - /// domain as listed in the Firebase console. Note: If you do not specify - /// "https://" as the URI scheme, it will be added. - DynamicLinkComponents(const char* link_, const char* domain_uri_prefix_) - : link(link_), - domain_uri_prefix(domain_uri_prefix_), - google_analytics_parameters(nullptr), - ios_parameters(nullptr), - itunes_connect_analytics_parameters(nullptr), - android_parameters(nullptr), - social_meta_tag_parameters(nullptr) { - // For backwards compatibility with dynamic_link_domain, if - // domain_uri_prefix doesn't start with "https://", add it. - static const char kHttpsPrefix[] = "https://"; - static const size_t kHttpsPrefixLength = sizeof(kHttpsPrefix) - 1; - if (strncmp(domain_uri_prefix, kHttpsPrefix, kHttpsPrefixLength) != 0) { - domain_uri_prefix_with_scheme = - std::string(kHttpsPrefix) + domain_uri_prefix; - domain_uri_prefix = domain_uri_prefix_with_scheme.c_str(); - } - } - -#ifndef INTERNAL_EXPERIMENTAL - - private: -#endif // INTERNAL_EXPERIMENTAL - std::string domain_uri_prefix_with_scheme; -}; - -/// Creates a long Dynamic Link from the given parameters. -GeneratedDynamicLink GetLongLink(const DynamicLinkComponents& components); - -/// Creates a shortened Dynamic Link from the given parameters. -/// @param components: Settings used to configure the behavior for the link. -Future GetShortLink( - const DynamicLinkComponents& components); - -/// Creates a shortened Dynamic Link from the given parameters. -/// @param components: Settings used to configure the behavior for the link. -/// @param options: Additional options for Dynamic Link shortening, indicating -/// whether or not to produce an unguessable or shortest possible link. -/// No references to the options object will be retained after the call. -Future GetShortLink( - const DynamicLinkComponents& components, const DynamicLinkOptions& options); - -/// Creates a shortened Dynamic Link from a given long Dynamic Link. -/// @param long_dynamic_link A link previously generated from GetLongLink. -Future GetShortLink(const char* long_dynamic_link); - -/// Creates a shortened Dynamic Link from a given long Dynamic Link. -/// @param long_dynamic_link: A link previously generated from GetLongLink. -/// @param options: Additional options for Dynamic Link shortening, indicating -/// whether or not to produce an unguessable or shortest possible link. -/// No references to the options object will be retained after the call. -Future GetShortLink(const char* long_dynamic_link, - const DynamicLinkOptions& options); - -/// Get the (possibly still pending) results of the most recent GetShortUrl -/// call. -Future GetShortLinkLastResult(); - -} // namespace dynamic_links -} // namespace firebase - -#endif // FIREBASE_DYNAMIC_LINKS_SRC_INCLUDE_FIREBASE_DYNAMIC_LINKS_COMPONENTS_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore.h deleted file mode 100644 index c35de11b4d1a..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore.h +++ /dev/null @@ -1,458 +0,0 @@ -/* - * Copyright 2018 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_H_ -#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_H_ - -#include -#include - -#include "firebase/internal/common.h" - -#include "firebase/app.h" -#include "firebase/future.h" -#include "firebase/log.h" -// Include *all* the public headers to make sure including just "firestore.h" is -// sufficient for users. -#include "firebase/firestore/collection_reference.h" -#include "firebase/firestore/document_change.h" -#include "firebase/firestore/document_reference.h" -#include "firebase/firestore/document_snapshot.h" -#include "firebase/firestore/field_path.h" -#include "firebase/firestore/field_value.h" -#include "firebase/firestore/firestore_errors.h" -#include "firebase/firestore/geo_point.h" -#include "firebase/firestore/listener_registration.h" -#include "firebase/firestore/load_bundle_task_progress.h" -#include "firebase/firestore/map_field_value.h" -#include "firebase/firestore/metadata_changes.h" -#include "firebase/firestore/query.h" -#include "firebase/firestore/query_snapshot.h" -#include "firebase/firestore/set_options.h" -#include "firebase/firestore/settings.h" -#include "firebase/firestore/snapshot_metadata.h" -#include "firebase/firestore/source.h" -#include "firebase/firestore/timestamp.h" -#include "firebase/firestore/transaction.h" -#include "firebase/firestore/transaction_options.h" -#include "firebase/firestore/write_batch.h" - -namespace firebase { -/** - * @brief Cloud Firestore API. - * - * Cloud Firestore is a flexible, scalable database for mobile, web, and server - * development from Firebase and Google Cloud Platform. - */ -namespace firestore { - -class FirestoreInternal; - -namespace csharp { - -class ApiHeaders; -class TransactionManager; - -} // namespace csharp - -/** - * @brief Entry point for the Firebase Firestore C++ SDK. - * - * To use the SDK, call firebase::firestore::Firestore::GetInstance() to obtain - * an instance of Firestore, then use Collection() or Document() to obtain - * references to child paths within the database. From there, you can set data - * via CollectionReference::Add() and DocumentReference::Set(), or get data via - * CollectionReference::Get() and DocumentReference::Get(), attach listeners, - * and more. - * - * @note Firestore classes are not meant to be subclassed except for use in test - * mocks. Subclassing is not supported in production code and new SDK releases - * may break code that does so. - */ -class Firestore { - public: - /** - * @brief Returns an instance of Firestore corresponding to the given App. - * - * Firebase Firestore uses firebase::App to communicate with Firebase - * Authentication to authenticate users to the Firestore server backend. - * - * If you call GetInstance() multiple times with the same App, you will get - * the same instance of Firestore. - * - * @param[in] app Your instance of firebase::App. Firebase Firestore will use - * this to communicate with Firebase Authentication. - * @param[out] init_result_out If provided, the initialization result will be - * written here. Will be set to firebase::kInitResultSuccess if initialization - * succeeded, or firebase::kInitResultFailedMissingDependency on Android if - * Google Play services is not available on the current device. - * - * @return An instance of Firestore corresponding to the given App. - */ - static Firestore* GetInstance(::firebase::App* app, - InitResult* init_result_out = nullptr); - - /** - * @brief Returns an instance of Firestore corresponding to the default App. - * - * Firebase Firestore uses the default App to communicate with Firebase - * Authentication to authenticate users to the Firestore server backend. - * - * If you call GetInstance() multiple times, you will get the same instance. - * - * @param[out] init_result_out If provided, the initialization result will be - * written here. Will be set to firebase::kInitResultSuccess if initialization - * succeeded, or firebase::kInitResultFailedMissingDependency on Android if - * Google Play services is not available on the current device. - * - * @return An instance of Firestore corresponding to the default App. - */ - static Firestore* GetInstance(InitResult* init_result_out = nullptr); - - /** - * @brief Destructor for the Firestore object. - * - * When deleted, this instance will be removed from the cache of Firestore - * objects. If you call GetInstance() in the future with the same App, a new - * Firestore instance will be created. - */ - virtual ~Firestore(); - - /** - * Deleted copy constructor; Firestore must be created with - * Firestore::GetInstance(). - */ - Firestore(const Firestore& src) = delete; - - /** - * Deleted copy assignment operator; Firestore must be created with - * Firestore::GetInstance(). - */ - Firestore& operator=(const Firestore& src) = delete; - - /** - * @brief Returns the firebase::App that this Firestore was created with. - * - * @return The firebase::App this Firestore was created with. - */ - virtual const App* app() const; - - /** - * @brief Returns the firebase::App that this Firestore was created with. - * - * @return The firebase::App this Firestore was created with. - */ - virtual App* app(); - - /** - * @brief Returns a CollectionReference instance that refers to the - * collection at the specified path within the database. - * - * @param[in] collection_path A slash-separated path to a collection. - * - * @return The CollectionReference instance. - */ - virtual CollectionReference Collection(const char* collection_path) const; - - /** - * @brief Returns a CollectionReference instance that refers to the - * collection at the specified path within the database. - * - * @param[in] collection_path A slash-separated path to a collection. - * - * @return The CollectionReference instance. - */ - virtual CollectionReference Collection( - const std::string& collection_path) const; - - /** - * @brief Returns a DocumentReference instance that refers to the document at - * the specified path within the database. - * - * @param[in] document_path A slash-separated path to a document. - * @return The DocumentReference instance. - */ - virtual DocumentReference Document(const char* document_path) const; - - /** - * @brief Returns a DocumentReference instance that refers to the document at - * the specified path within the database. - * - * @param[in] document_path A slash-separated path to a document. - * - * @return The DocumentReference instance. - */ - virtual DocumentReference Document(const std::string& document_path) const; - - /** - * @brief Returns a Query instance that includes all documents in the - * database that are contained in a collection or subcollection with the - * given collection_id. - * - * @param[in] collection_id Identifies the collections to query over. Every - * collection or subcollection with this ID as the last segment of its path - * will be included. Cannot contain a slash. - * - * @return The Query instance. - */ - virtual Query CollectionGroup(const char* collection_id) const; - - /** - * @brief Returns a Query instance that includes all documents in the - * database that are contained in a collection or subcollection with the - * given collection_id. - * - * @param[in] collection_id Identifies the collections to query over. Every - * collection or subcollection with this ID as the last segment of its path - * will be included. Cannot contain a slash. - * - * @return The Query instance. - */ - virtual Query CollectionGroup(const std::string& collection_id) const; - - /** Returns the settings used by this Firestore object. */ - virtual Settings settings() const; - - /** Sets any custom settings used to configure this Firestore object. */ - virtual void set_settings(Settings settings); - - /** - * Creates a write batch, used for performing multiple writes as a single - * atomic operation. - * - * Unlike transactions, write batches are persisted offline and therefore are - * preferable when you don't need to condition your writes on read data. - * - * @return The created WriteBatch object. - */ - virtual WriteBatch batch() const; - - /** - * Executes the given update and then attempts to commit the changes applied - * within the transaction. If any document read within the transaction has - * changed, the update function will be retried. If it fails to commit after - * 5 attempts, the transaction will fail. - * - * @param update function or lambda to execute within the transaction context. - * The string reference parameter can be used to set the error message. - * - * @return A Future that will be resolved when the transaction finishes. - */ - virtual Future RunTransaction( - std::function update); - - /** - * Executes the given update and then attempts to commit the changes applied - * within the transaction. If any document read within the transaction has - * changed, the update function will be retried. If it fails to commit after - * the `max_attempts` specified in the given `TransactionOptions`, the - * transaction will fail. - * - * @param options The transaction options for controlling execution. - * @param update function or lambda to execute within the transaction context. - * The string reference parameter can be used to set the error message. - * - * @return A Future that will be resolved when the transaction finishes. - */ - virtual Future RunTransaction( - TransactionOptions options, - std::function update); - - /** - * Sets the log verbosity of all Firestore instances. - * - * The default verbosity level is `kLogLevelInfo`. - * - * @param[in] log_level The desired verbosity. - */ - static void set_log_level(LogLevel log_level); - - /** - * Disables network access for this instance. While the network is disabled, - * any snapshot listeners or Get() calls will return results from cache, and - * any write operations will be queued until network usage is re-enabled via a - * call to EnableNetwork(). - * - * If the network was already disabled, calling `DisableNetwork()` again is - * a no-op. - */ - virtual Future DisableNetwork(); - - /** - * Re-enables network usage for this instance after a prior call to - * DisableNetwork(). - * - * If the network is currently enabled, calling `EnableNetwork()` is a no-op. - */ - virtual Future EnableNetwork(); - - /** - * Terminates this `Firestore` instance. - * - * After calling `Terminate()`, only the `ClearPersistence()` method may be - * used. Calling any other methods will result in an error. - * - * To restart after termination, simply create a new instance of `Firestore` - * with `Firestore::GetInstance()`. - * - * `Terminate()` does not cancel any pending writes and any tasks that are - * awaiting a response from the server will not be resolved. The next time you - * start this instance, it will resume attempting to send these writes to the - * server. - * - * Note: under normal circumstances, calling `Terminate()` is not required. - * This method is useful only when you want to force this instance to release - * all of its resources or in combination with `ClearPersistence()` to ensure - * that all local state is destroyed between test runs. - * - * @return A `Future` that is resolved when the instance has been successfully - * terminated. - */ - virtual Future Terminate(); - - /** - * Waits until all currently pending writes for the active user have been - * acknowledged by the backend. - * - * The returned future is resolved immediately without error if there are no - * outstanding writes. Otherwise, the future is resolved when all previously - * issued writes (including those written in a previous app session) have been - * acknowledged by the backend. The future does not wait for writes that were - * added after the method is called. If you wish to wait for additional - * writes, you have to call `WaitForPendingWrites` again. - * - * Any outstanding `WaitForPendingWrites` futures are resolved with an - * error during user change. - */ - virtual Future WaitForPendingWrites(); - - /** - * Clears the persistent storage. This includes pending writes and cached - * documents. - * - * Must be called while the Firestore instance is not started (after the app - * is shut down or when the app is first initialized). On startup, this method - * must be called before other methods (other than `settings()` and - * `set_settings()`). If the Firestore instance is still running, the function - * will complete with an error code of `FailedPrecondition`. - * - * Note: `ClearPersistence()` is primarily intended to help write - * reliable tests that use Firestore. It uses the most efficient mechanism - * possible for dropping existing data but does not attempt to securely - * overwrite or otherwise make cached data unrecoverable. For applications - * that are sensitive to the disclosure of cache data in between user sessions - * we strongly recommend not to enable persistence in the first place. - */ - virtual Future ClearPersistence(); - - /** - * Attaches a listener for a snapshots-in-sync event. Server-generated - * updates and local changes can affect multiple snapshot listeners. - * The snapshots-in-sync event indicates that all listeners affected by - * a given change have fired. - * - * NOTE: The snapshots-in-sync event only indicates that listeners are - * in sync with each other, but does not relate to whether those - * snapshots are in sync with the server. Use `SnapshotMetadata` in the - * individual listeners to determine if a snapshot is from the cache or - * the server. - * - * @param callback A callback to be called every time all snapshot - * listeners are in sync with each other. - * @return A `ListenerRegistration` object that can be used to remove the - * listener. - */ - virtual ListenerRegistration AddSnapshotsInSyncListener( - std::function callback); - - /** - * Loads a Firestore bundle into the local cache. - * - * @param bundle A string containing the bundle to be loaded. - * @return A `Future` that is resolved when the loading is either completed - * or aborted due to an error. - */ - virtual Future LoadBundle(const std::string& bundle); - - /** - * Loads a Firestore bundle into the local cache, with the provided callback - * executed for progress updates. - * - * @param bundle A string containing the bundle to be loaded. - * @param progress_callback A callback that is called with progress - * updates, and completion or error updates. - * @return A `Future` that is resolved when the loading is either completed - * or aborted due to an error. - */ - virtual Future LoadBundle( - const std::string& bundle, - std::function progress_callback); - - /** - * Reads a Firestore `Query` from the local cache, identified by the given - * name. - * - * Named queries are packaged into bundles on the server side (along with the - * resulting documents) and loaded into local cache using `LoadBundle`. Once - * in the local cache, you can use this method to extract a query by name. - * - * If a query cannot be found, the returned future will complete with its - * `error()` set to a non-zero error code. - * - * @param query_name The name of the query to read from saved bundles. - */ - virtual Future NamedQuery(const std::string& query_name); - - protected: - /** - * Default constructor, to be used only for mocking `Firestore`. - */ - Firestore() = default; - - private: - friend class FieldValueInternal; - friend class FirestoreInternal; - friend class Wrapper; - friend struct ConverterImpl; - friend class FirestoreIntegrationTest; - friend class IncludesTest; - template - friend struct CleanupFn; - - friend class csharp::ApiHeaders; - friend class csharp::TransactionManager; - - explicit Firestore(::firebase::App* app); - explicit Firestore(FirestoreInternal* internal); - - static Firestore* CreateFirestore(::firebase::App* app, - FirestoreInternal* internal, - InitResult* init_result_out); - static Firestore* AddFirestoreToCache(Firestore* firestore, - InitResult* init_result_out); - - static void SetClientLanguage(const std::string& language_token); - - // Delete the internal_ data. - void DeleteInternal(); - - mutable FirestoreInternal* internal_ = nullptr; -}; - -} // namespace firestore -} // namespace firebase - -#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/collection_reference.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/collection_reference.h deleted file mode 100644 index 3d9d4de2ee7f..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/collection_reference.h +++ /dev/null @@ -1,183 +0,0 @@ -/* - * Copyright 2018 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_COLLECTION_REFERENCE_H_ -#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_COLLECTION_REFERENCE_H_ - -#include - -#include "firebase/firestore/map_field_value.h" -#include "firebase/firestore/query.h" - -namespace firebase { - -/// @cond FIREBASE_APP_INTERNAL -template -class Future; -/// @endcond - -namespace firestore { - -class CollectionReferenceInternal; -class DocumentReference; - -/** - * @brief A CollectionReference can be used for adding documents, getting - * document references, and querying for documents (using the methods inherited - * from `Query`). - * - * @note Firestore classes are not meant to be subclassed except for use in test - * mocks. Subclassing is not supported in production code and new SDK releases - * may break code that does so. - */ -class CollectionReference : public Query { - public: - /** - * @brief Creates an invalid CollectionReference that has to be reassigned - * before it can be used. - * - * Calling any member function on an invalid CollectionReference will be - * a no-op. If the function returns a value, it will return a zero, empty, or - * invalid value, depending on the type of the value. - */ - CollectionReference(); - - /** - * @brief Copy constructor. - * - * `CollectionReference` can be efficiently copied because it simply refers to - * a location in the database. - * - * @param[in] other `CollectionReference` to copy from. - */ - CollectionReference(const CollectionReference& other); - - /** - * @brief Move constructor. - * - * Moving is more efficient than copying for a `CollectionReference`. After - * being moved from, a `CollectionReference` is equivalent to its - * default-constructed state. - * - * @param[in] other `CollectionReference` to move data from. - */ - CollectionReference(CollectionReference&& other); - - /** - * @brief Copy assignment operator. - * - * `CollectionReference` can be efficiently copied because it simply refers to - * a location in the database. - * - * @param[in] other `CollectionReference` to copy from. - * - * @return Reference to the destination `CollectionReference`. - */ - CollectionReference& operator=(const CollectionReference& other); - - /** - * @brief Move assignment operator. - * - * Moving is more efficient than copying for a `CollectionReference`. After - * being moved from, a `CollectionReference` is equivalent to its - * default-constructed state. - * - * @param[in] other `CollectionReference` to move data from. - * - * @return Reference to the destination `CollectionReference`. - */ - CollectionReference& operator=(CollectionReference&& other); - - /** - * @brief Gets the ID of the referenced collection. - * - * @return The ID as a std::string. - */ - virtual const std::string& id() const; - - /** - * @brief Returns the path of this collection (relative to the root of the - * database) as a slash-separated string. - * - * @return The path as a std::string. - */ - virtual std::string path() const; - - /** - * @brief Gets a DocumentReference to the document that contains this - * collection. - * - * @return The DocumentReference that contains this collection if this is a - * subcollection. If this is a root collection, returns an invalid - * DocumentReference (`DocumentReference::is_valid()` will return false). - */ - virtual DocumentReference Parent() const; - - /** - * @brief Returns a DocumentReference that points to a new document with an - * auto-generated ID within this collection. - * - * @return A DocumentReference pointing to the new document. - */ - virtual DocumentReference Document() const; - - /** - * @brief Gets a DocumentReference instance that refers to the document at the - * specified path within this collection. - * - * @param[in] document_path A slash-separated relative path to a document. - * The pointer only needs to be valid during this call. - * - * @return The DocumentReference instance. - */ - virtual DocumentReference Document(const char* document_path) const; - - /** - * @brief Gets a DocumentReference instance that refers to the document at the - * specified path within this collection. - * - * @param[in] document_path A slash-separated relative path to a document. - * - * @return The DocumentReference instance. - */ - virtual DocumentReference Document(const std::string& document_path) const; - - /** - * @brief Adds a new document to this collection with the specified data, - * assigning it a document ID automatically. - * - * @param data A map containing the data for the new document. - * - * @return A Future that will be resolved with the DocumentReference of the - * newly created document. - */ - virtual Future Add(const MapFieldValue& data); - - private: - friend class DocumentReference; - friend class DocumentReferenceInternal; - friend class FirestoreInternal; - friend struct ConverterImpl; - - explicit CollectionReference(CollectionReferenceInternal* internal); - - CollectionReferenceInternal* internal() const; -}; - -} // namespace firestore -} // namespace firebase - -#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_COLLECTION_REFERENCE_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/document_change.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/document_change.h deleted file mode 100644 index fbef011d290f..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/document_change.h +++ /dev/null @@ -1,203 +0,0 @@ -/* - * Copyright 2018 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_DOCUMENT_CHANGE_H_ -#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_DOCUMENT_CHANGE_H_ - -#include - -namespace firebase { -namespace firestore { - -class DocumentChangeInternal; -class DocumentSnapshot; - -/** - * @brief A DocumentChange represents a change to the documents matching - * a query. - * - * DocumentChange contains the document affected and the type of change that - * occurred (added, modified, or removed). - * - * @note Firestore classes are not meant to be subclassed except for use in test - * mocks. Subclassing is not supported in production code and new SDK releases - * may break code that does so. - */ -class DocumentChange { - public: - /** - * An enumeration of snapshot diff types. - */ - enum class Type { - /** - * Indicates a new document was added to the set of documents matching the - * query. - */ - kAdded, - - /** - * Indicates a document within the query was modified. - */ - kModified, - - /** - * Indicates a document within the query was removed (either deleted or no - * longer matches the query). - */ - kRemoved, - }; - - /** - * The sentinel index used as a return value to indicate no matches. - */ -#if defined(ANDROID) - // Older NDK (r16b) fails to define this properly. Fix this when support for - // the older NDK is removed. - static const std::size_t npos; -#else - static constexpr std::size_t npos = static_cast(-1); -#endif // defined(ANDROID) - - /** - * @brief Creates an invalid DocumentChange that has to be reassigned before - * it can be used. - * - * Calling any member function on an invalid DocumentChange will be a no-op. - * If the function returns a value, it will return a zero, empty, or invalid - * value, depending on the type of the value. - */ - DocumentChange(); - - /** - * @brief Copy constructor. - * - * `DocumentChange` is immutable and can be efficiently copied (no deep copy - * is performed). - * - * @param[in] other `DocumentChange` to copy from. - */ - DocumentChange(const DocumentChange& other); - - /** - * @brief Move constructor. - * - * Moving is more efficient than copying for a `DocumentChange`. After being - * moved from, a `DocumentChange` is equivalent to its default-constructed - * state. - * - * @param[in] other `DocumentChange` to move data from. - */ - DocumentChange(DocumentChange&& other); - - virtual ~DocumentChange(); - - /** - * @brief Copy assignment operator. - * - * `DocumentChange` is immutable and can be efficiently copied (no deep copy - * is performed). - * - * @param[in] other `DocumentChange` to copy from. - * - * @return Reference to the destination `DocumentChange`. - */ - DocumentChange& operator=(const DocumentChange& other); - - /** - * @brief Move assignment operator. - * - * Moving is more efficient than copying for a `DocumentChange`. After being - * moved from, a `DocumentChange` is equivalent to its default-constructed - * state. - * - * @param[in] other `DocumentChange` to move data from. - * - * @return Reference to the destination `DocumentChange`. - */ - DocumentChange& operator=(DocumentChange&& other); - - /** - * Returns the type of change that occurred (added, modified, or removed). - */ - virtual Type type() const; - - /** - * @brief The document affected by this change. - * - * Returns the newly added or modified document if this DocumentChange is for - * an updated document. Returns the deleted document if this document change - * represents a removal. - */ - virtual DocumentSnapshot document() const; - - /** - * The index of the changed document in the result set immediately prior to - * this DocumentChange (that is, supposing that all prior DocumentChange - * objects have been applied). Returns DocumentChange::npos for 'added' - * events. - */ - virtual std::size_t old_index() const; - - /** - * The index of the changed document in the result set immediately after this - * DocumentChange (that is, supposing that all prior DocumentChange objects - * and the current DocumentChange object have been applied). Returns - * DocumentChange::npos for 'removed' events. - */ - virtual std::size_t new_index() const; - - /** - * @brief Returns true if this `DocumentChange` is valid, false if it is - * not valid. An invalid `DocumentChange` could be the result of: - * - Creating a `DocumentChange` using the default constructor. - * - Moving from the `DocumentChange`. - * - Deleting your Firestore instance, which will invalidate all the - * `DocumentChange` instances associated with it. - * - * @return true if this `DocumentChange` is valid, false if this - * `DocumentChange` is invalid. - */ - bool is_valid() const { return internal_ != nullptr; } - - private: - std::size_t Hash() const; - - friend bool operator==(const DocumentChange& lhs, const DocumentChange& rhs); - friend std::size_t DocumentChangeHash(const DocumentChange& change); - - friend class FirestoreInternal; - friend class Wrapper; - friend struct ConverterImpl; - template - friend struct CleanupFn; - - explicit DocumentChange(DocumentChangeInternal* internal); - - mutable DocumentChangeInternal* internal_ = nullptr; -}; - -/** Checks `lhs` and `rhs` for equality. */ -bool operator==(const DocumentChange& lhs, const DocumentChange& rhs); - -/** Checks `lhs` and `rhs` for inequality. */ -inline bool operator!=(const DocumentChange& lhs, const DocumentChange& rhs) { - return !(lhs == rhs); -} - -} // namespace firestore -} // namespace firebase - -#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_DOCUMENT_CHANGE_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/document_reference.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/document_reference.h deleted file mode 100644 index d0f82cf42d73..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/document_reference.h +++ /dev/null @@ -1,351 +0,0 @@ -/* - * Copyright 2018 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_DOCUMENT_REFERENCE_H_ -#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_DOCUMENT_REFERENCE_H_ - -#include -#include -#include - -#include "firebase/internal/common.h" - -#include "firebase/firestore/firestore_errors.h" -#include "firebase/firestore/map_field_value.h" -#include "firebase/firestore/metadata_changes.h" -#include "firebase/firestore/set_options.h" -#include "firebase/firestore/source.h" - -namespace firebase { - -/// @cond FIREBASE_APP_INTERNAL -template -class Future; -/// @endcond - -namespace firestore { - -class CollectionReference; -class DocumentReferenceInternal; -class DocumentSnapshot; -template -class EventListener; -class Firestore; -class ListenerRegistration; - -/** - * @brief A DocumentReference refers to a document location in a Firestore - * database and can be used to write, read, or listen to the location. - * - * There may or may not exist a document at the referenced location. - * A DocumentReference can also be used to create a CollectionReference to - * a subcollection. - * - * Create a DocumentReference via `Firestore::Document(const std::string& - * path)`. - * - * @note Firestore classes are not meant to be subclassed except for use in test - * mocks. Subclassing is not supported in production code and new SDK releases - * may break code that does so. - */ -class DocumentReference { - public: - /** - * @brief Creates an invalid DocumentReference that has to be reassigned - * before it can be used. - * - * Calling any member function on an invalid DocumentReference will be - * a no-op. If the function returns a value, it will return a zero, empty, or - * invalid value, depending on the type of the value. - */ - DocumentReference(); - - /** - * @brief Copy constructor. - * - * `DocumentReference` can be efficiently copied because it simply refers to - * a location in the database. - * - * @param[in] other `DocumentReference` to copy from. - */ - DocumentReference(const DocumentReference& other); - - /** - * @brief Move constructor. - * - * Moving is more efficient than copying for a `DocumentReference`. After - * being moved from, a `DocumentReference` is equivalent to its - * default-constructed state. - * - * @param[in] other `DocumentReference` to move data from. - */ - DocumentReference(DocumentReference&& other); - - virtual ~DocumentReference(); - - /** - * @brief Copy assignment operator. - * - * `DocumentReference` can be efficiently copied because it simply refers to - * a location in the database. - * - * @param[in] other `DocumentReference` to copy from. - * - * @return Reference to the destination `DocumentReference`. - */ - DocumentReference& operator=(const DocumentReference& other); - - /** - * @brief Move assignment operator. - * - * Moving is more efficient than copying for a `DocumentReference`. After - * being moved from, a `DocumentReference` is equivalent to its - * default-constructed state. - * - * @param[in] other `DocumentReference` to move data from. - * - * @return Reference to the destination `DocumentReference`. - */ - DocumentReference& operator=(DocumentReference&& other); - - /** - * @brief Returns the Firestore instance associated with this document - * reference. - * - * The pointer will remain valid indefinitely. - * - * @return Firebase Firestore instance that this DocumentReference refers to. - */ - virtual const Firestore* firestore() const; - - /** - * @brief Returns the Firestore instance associated with this document - * reference. - * - * The pointer will remain valid indefinitely. - * - * @return Firebase Firestore instance that this DocumentReference refers to. - */ - virtual Firestore* firestore(); - - /** - * @brief Returns the string ID of this document location. - * - * @return String ID of this document location. - */ - virtual const std::string& id() const; - - /** - * @brief Returns the path of this document (relative to the root of the - * database) as a slash-separated string. - * - * @return String path of this document location. - */ - virtual std::string path() const; - - /** - * @brief Returns a CollectionReference to the collection that contains this - * document. - */ - virtual CollectionReference Parent() const; - - /** - * @brief Returns a CollectionReference instance that refers to the - * subcollection at the specified path relative to this document. - * - * @param[in] collection_path A slash-separated relative path to a - * subcollection. The pointer only needs to be valid during this call. - * - * @return The CollectionReference instance. - */ - virtual CollectionReference Collection(const char* collection_path) const; - - /** - * @brief Returns a CollectionReference instance that refers to the - * subcollection at the specified path relative to this document. - * - * @param[in] collection_path A slash-separated relative path to a - * subcollection. - * - * @return The CollectionReference instance. - */ - virtual CollectionReference Collection( - const std::string& collection_path) const; - - /** - * @brief Reads the document referenced by this DocumentReference. - * - * By default, Get() attempts to provide up-to-date data when possible by - * waiting for data from the server, but it may return cached data or fail if - * you are offline and the server cannot be reached. This behavior can be - * altered via the Source parameter. - * - * @param[in] source A value to configure the get behavior (optional). - * - * @return A Future that will be resolved with the contents of the Document at - * this DocumentReference. - */ - virtual Future Get(Source source = Source::kDefault) const; - - /** - * @brief Writes to the document referred to by this DocumentReference. - * - * If the document does not yet exist, it will be created. If you pass - * SetOptions, the provided data can be merged into an existing document. - * - * @param[in] data A map of the fields and values to write to the document. - * @param[in] options An object to configure the Set() behavior (optional). - * - * @return A Future that will be resolved when the write finishes. - */ - virtual Future Set(const MapFieldValue& data, - const SetOptions& options = SetOptions()); - - /** - * @brief Updates fields in the document referred to by this - * DocumentReference. - * - * If no document exists yet, the update will fail. - * - * @param[in] data A map of field / value pairs to update. Fields can contain - * dots to reference nested fields within the document. - * - * @return A Future that will be resolved when the client is online and the - * commit has completed against the server. The future will not resolve when - * the device is offline, though local changes will be visible immediately. - */ - virtual Future Update(const MapFieldValue& data); - - /** - * @brief Updates fields in the document referred to by this - * DocumentReference. - * - * If no document exists yet, the update will fail. - * - * @param[in] data A map from FieldPath to FieldValue to update. - * - * @return A Future that will be resolved when the client is online and the - * commit has completed against the server. The future will not resolve when - * the device is offline, though local changes will be visible immediately. - */ - virtual Future Update(const MapFieldPathValue& data); - - /** - * @brief Removes the document referred to by this DocumentReference. - * - * @return A Future that will be resolved when the delete completes. - */ - virtual Future Delete(); - - /** - * @brief Starts listening to the document referenced by this - * DocumentReference. - * - * @param[in] callback The std::function to call. When this function is - * called, snapshot value is valid if and only if error is Error::kErrorOk. - * The std::string is an error message; the value may be empty if an error - * message is not available. - * - * @return A registration object that can be used to remove the listener. - */ - virtual ListenerRegistration AddSnapshotListener( - std::function - callback); - - /** - * @brief Starts listening to the document referenced by this - * DocumentReference. - * - * @param[in] metadata_changes Indicates whether metadata-only changes (that - * is, only DocumentSnapshot::metadata() changed) should trigger snapshot - * events. - * @param[in] callback The std::function to call. When this function is - * called, snapshot value is valid if and only if error is Error::kErrorOk. - * The std::string is an error message; the value may be empty if an error - * message is not available. - * - * @return A registration object that can be used to remove the listener. - */ - virtual ListenerRegistration AddSnapshotListener( - MetadataChanges metadata_changes, - std::function - callback); - - /** - * @brief Returns true if this `DocumentReference` is valid, false if it is - * not valid. An invalid `DocumentReference` could be the result of: - * - Creating a `DocumentReference` using the default constructor. - * - Moving from the `DocumentReference`. - * - Calling `CollectionReference::Parent()` on a `CollectionReference` that - * is not a subcollection. - * - Deleting your Firestore instance, which will invalidate all the - * `DocumentReference` instances associated with it. - * - * @return true if this `DocumentReference` is valid, false if this - * `DocumentReference` is invalid. - */ - bool is_valid() const { return internal_ != nullptr; } - - /** - * Returns a string representation of this `DocumentReference` for - * logging/debugging purposes. - * - * @note the exact string representation is unspecified and subject to - * change; don't rely on the format of the string. - */ - std::string ToString() const; - - /** - * Outputs the string representation of this `DocumentReference` to the given - * stream. - * - * @see `ToString()` for comments on the representation format. - */ - friend std::ostream& operator<<(std::ostream& out, - const DocumentReference& reference); - - private: - friend bool operator==(const DocumentReference& lhs, - const DocumentReference& rhs); - - friend class CollectionReferenceInternal; - friend class DocumentSnapshotInternal; - friend class FieldValueInternal; - friend class FirestoreInternal; - friend class TransactionInternal; - friend class WriteBatchInternal; - friend struct ConverterImpl; - template - friend struct CleanupFn; - - explicit DocumentReference(DocumentReferenceInternal* internal); - - mutable DocumentReferenceInternal* internal_ = nullptr; -}; - -/** Checks `lhs` and `rhs` for equality. */ -bool operator==(const DocumentReference& lhs, const DocumentReference& rhs); - -/** Checks `lhs` and `rhs` for inequality. */ -inline bool operator!=(const DocumentReference& lhs, - const DocumentReference& rhs) { - return !(lhs == rhs); -} - -} // namespace firestore -} // namespace firebase - -#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_DOCUMENT_REFERENCE_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/document_snapshot.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/document_snapshot.h deleted file mode 100644 index 7617eb5d1412..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/document_snapshot.h +++ /dev/null @@ -1,297 +0,0 @@ -/* - * Copyright 2018 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_DOCUMENT_SNAPSHOT_H_ -#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_DOCUMENT_SNAPSHOT_H_ - -#include -#include - -#include "firebase/firestore/map_field_value.h" -#include "firebase/firestore/snapshot_metadata.h" - -namespace firebase { -namespace firestore { - -class DocumentReference; -class DocumentSnapshotInternal; -class FieldPath; -class FieldValue; -class Firestore; - -/** - * @brief A DocumentSnapshot contains data read from a document in your - * Firestore database. - * - * The data can be extracted with the GetData() method, or by using - * Get() to access a specific field. For a DocumentSnapshot that points to - * a non-existing document, any data access will cause a failed assertion. You - * can use the exists() method to explicitly verify a document's existence. - * - * @note Firestore classes are not meant to be subclassed except for use in test - * mocks. Subclassing is not supported in production code and new SDK releases - * may break code that does so. - */ -class DocumentSnapshot { - public: - /** - * Controls the return value for server timestamps that have not yet been set - * to their final value. - */ - enum class ServerTimestampBehavior { - /** - * Return Null for server timestamps that have not yet been set to their - * final value. - */ - kNone = 0, - - /** - * Return local estimates for server timestamps that have not yet been set - * to their final value. This estimate will likely differ from the final - * value and may cause these pending values to change once the server result - * becomes available. - */ - kEstimate, - - /** - * Return the previous value for server timestamps that have not yet been - * set to their final value. - */ - kPrevious, - - /** The default behavior, which is equivalent to specifying kNone. */ - // - // Note, SWIG renaming mechanism doesn't properly handle initializing an - // enum constant with another enum constant (e.g., in expression `kFoo = - // kBar` only `kFoo` will be renamed, leaving `kBar` as is, leading to - // compilation errors). - // - kDefault = 0, - }; - - /** - * @brief Creates an invalid DocumentSnapshot that has to be reassigned before - * it can be used. - * - * Calling any member function on an invalid DocumentSnapshot will be a no-op. - * If the function returns a value, it will return a zero, empty, or invalid - * value, depending on the type of the value. - */ - DocumentSnapshot(); - - /** - * @brief Copy constructor. - * - * `DocumentSnapshot` is immutable and can be efficiently copied (no deep copy - * is performed). - * - * @param[in] other `DocumentSnapshot` to copy from. - */ - DocumentSnapshot(const DocumentSnapshot& other); - - /** - * @brief Move constructor. - * - * Moving is more efficient than copying for a `DocumentSnapshot`. After being - * moved from, a `DocumentSnapshot` is equivalent to its default-constructed - * state. - * - * @param[in] other `DocumentSnapshot` to move data from. - */ - DocumentSnapshot(DocumentSnapshot&& other); - - virtual ~DocumentSnapshot(); - - /** - * @brief Copy assignment operator. - * - * `DocumentSnapshot` is immutable and can be efficiently copied (no deep copy - * is performed). - * - * @param[in] other `DocumentSnapshot` to copy from. - * - * @return Reference to the destination `DocumentSnapshot`. - */ - DocumentSnapshot& operator=(const DocumentSnapshot& other); - - /** - * @brief Move assignment operator. - * - * Moving is more efficient than copying for a `DocumentSnapshot`. After being - * moved from, a `DocumentSnapshot` is equivalent to its default-constructed - * state. - * - * @param[in] other `DocumentSnapshot` to move data from. - * - * @return Reference to the destination `DocumentSnapshot`. - */ - DocumentSnapshot& operator=(DocumentSnapshot&& other); - - /** - * @brief Returns the string ID of the document for which this - * DocumentSnapshot contains data. - * - * @return String ID of this document location. - */ - virtual const std::string& id() const; - - /** - * @brief Returns the document location for which this DocumentSnapshot - * contains data. - * - * @return DocumentReference of this document location. - */ - virtual DocumentReference reference() const; - - /** - * @brief Returns the metadata about this snapshot concerning its source and - * if it has local modifications. - * - * @return SnapshotMetadata about this snapshot. - */ - virtual SnapshotMetadata metadata() const; - - /** - * @brief Explicitly verify a document's existence. - * - * @return True if the document exists in this snapshot. - */ - virtual bool exists() const; - - /** - * @brief Retrieves all fields in the document as a map of FieldValues. - * - * @param stb Configures how server timestamps that have not yet - * been set to their final value are returned from the snapshot (optional). - * - * @return A map containing all fields in the document, or an empty map if the - * document doesn't exist. - */ - virtual MapFieldValue GetData( - ServerTimestampBehavior stb = ServerTimestampBehavior::kDefault) const; - - /** - * @brief Retrieves a specific field from the document. - * - * @param field String ID of the field to retrieve. The pointer only needs to - * be valid during this call. - * @param stb Configures how server timestamps that have not yet been set to - * their final value are returned from the snapshot (optional). - * - * @return The value contained in the field. If the field does not exist in - * the document, then a `FieldValue` instance with `is_valid() == false` will - * be returned. - */ - virtual FieldValue Get( - const char* field, - ServerTimestampBehavior stb = ServerTimestampBehavior::kDefault) const; - - /** - * @brief Retrieves a specific field from the document. - * - * @param field String ID of the field to retrieve. - * @param stb Configures how server timestamps that have not yet been set to - * their final value are returned from the snapshot (optional). - * - * @return The value contained in the field. If the field does not exist in - * the document, then a `FieldValue` instance with `is_valid() == false` will - * be returned. - */ - virtual FieldValue Get( - const std::string& field, - ServerTimestampBehavior stb = ServerTimestampBehavior::kDefault) const; - - /** - * @brief Retrieves a specific field from the document. - * - * @param field Path of the field to retrieve. - * @param stb Configures how server timestamps that have not yet been set to - * their final value are returned from the snapshot (optional). - * - * @return The value contained in the field. If the field does not exist in - * the document, then a `FieldValue` instance with `is_valid() == false` will - * be returned. - */ - virtual FieldValue Get( - const FieldPath& field, - ServerTimestampBehavior stb = ServerTimestampBehavior::kDefault) const; - - /** - * @brief Returns true if this `DocumentSnapshot` is valid, false if it is - * not valid. An invalid `DocumentSnapshot` could be the result of: - * - Creating a `DocumentSnapshot` with the default constructor. - * - Moving from the `DocumentSnapshot`. - * - Deleting your Firestore instance, which will invalidate all the - * `DocumentSnapshot` instances associated with it. - * - * @return true if this `DocumentSnapshot` is valid, false if this - * `DocumentSnapshot` is invalid. - */ - bool is_valid() const { return internal_ != nullptr; } - - /** - * Returns a string representation of this `DocumentSnapshot` for - * logging/debugging purposes. - * - * @note the exact string representation is unspecified and subject to - * change; don't rely on the format of the string. - */ - std::string ToString() const; - - /** - * Outputs the string representation of this `DocumentSnapshot` to the given - * stream. - * - * @see `ToString()` for comments on the representation format. - */ - friend std::ostream& operator<<(std::ostream& out, - const DocumentSnapshot& document); - - private: - std::size_t Hash() const; - - friend bool operator==(const DocumentSnapshot& lhs, - const DocumentSnapshot& rhs); - friend std::size_t DocumentSnapshotHash(const DocumentSnapshot& snapshot); - - friend class DocumentChangeInternal; - friend class EventListenerInternal; - friend class FirestoreInternal; - friend class QueryInternal; - friend class TransactionInternal; - friend class Wrapper; - friend struct ConverterImpl; - template - friend struct CleanupFn; - - explicit DocumentSnapshot(DocumentSnapshotInternal* internal); - - mutable DocumentSnapshotInternal* internal_ = nullptr; -}; - -/** Checks `lhs` and `rhs` for equality. */ -bool operator==(const DocumentSnapshot& lhs, const DocumentSnapshot& rhs); - -/** Checks `lhs` and `rhs` for inequality. */ -inline bool operator!=(const DocumentSnapshot& lhs, - const DocumentSnapshot& rhs) { - return !(lhs == rhs); -} - -} // namespace firestore -} // namespace firebase - -#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_DOCUMENT_SNAPSHOT_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/field_path.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/field_path.h deleted file mode 100644 index d09dec641140..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/field_path.h +++ /dev/null @@ -1,205 +0,0 @@ -/* - * Copyright 2018 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_FIELD_PATH_H_ -#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_FIELD_PATH_H_ - -#include -#include -#include -#include - -namespace firebase { -namespace firestore { - -#if !defined(__ANDROID__) - -namespace model { -class FieldPath; -} // namespace model - -#else - -class FieldPathPortable; - -#endif // !defined(__ANDROID__) - -/** - * @brief A FieldPath refers to a field in a document. - * - * The path may consist of a single field name (referring to a top level field - * in the document) or a list of field names (referring to a nested field in the - * document). - */ -class FieldPath final { - public: - /** - * @brief Creates an invalid FieldPath that has to be reassigned before it can - * be used. - * - * Calling any member function on an invalid FieldPath will be a no-op. If the - * function returns a value, it will return a zero, empty, or invalid value, - * depending on the type of the value. - */ - FieldPath(); - - /** - * Creates a FieldPath from the provided field names. If more than one field - * name is provided, the path will point to a nested field in a document. - * - * @param field_names A list of field names. - */ - FieldPath(std::initializer_list field_names); - - /** - * Creates a FieldPath from the provided field names. If more than one field - * name is provided, the path will point to a nested field in a document. - * - * @param field_names A vector of field names. - */ - FieldPath(const std::vector& field_names); - - /** - * @brief Copy constructor. - * - * This performs a deep copy, creating an independent instance. - * - * @param[in] other `FieldPath` to copy from. - */ - FieldPath(const FieldPath& other); - - /** - * @brief Move constructor. - * - * Moving is more efficient than copying for `FieldPath`. After being moved - * from, `FieldPath` is in a valid but unspecified state. - * - * @param[in] other `FieldPath` to move data from. - */ - FieldPath(FieldPath&& other) noexcept; - - ~FieldPath(); - - /** - * @brief Copy assignment operator. - * - * This performs a deep copy, creating an independent instance. - * - * @param[in] other `FieldPath` to copy from. - * - * @return Reference to the destination `FieldPath`. - */ - FieldPath& operator=(const FieldPath& other); - - /** - * @brief Move assignment operator. - * - * Moving is more efficient than copying for `FieldPath`. After being moved - * from, `FieldPath` is in a valid but unspecified state. - * - * @param[in] other `FieldPath` to move data from. - * - * @return Reference to the destination `FieldPath`. - */ - FieldPath& operator=(FieldPath&& other) noexcept; - - /** - * A special sentinel FieldPath to refer to the ID of a document. It can be - * used in queries to sort or filter by the document ID. - */ - static FieldPath DocumentId(); - - /** - * @brief Returns true if this `FieldPath` is valid, false if it is not valid. - * An invalid `FieldPath` could be the result of: - * - Creating a `FieldPath` using the default constructor. - * - Moving from the `FieldPath`. - * - * @return true if this `FieldPath` is valid, false if this `FieldPath` is - * invalid. - */ - bool is_valid() const { return internal_ != nullptr; } - - /** - * Returns a string representation of this `FieldPath` for - * logging/debugging purposes. - * - * @note the exact string representation is unspecified and subject to - * change; don't rely on the format of the string. - */ - std::string ToString() const; - - /** - * Outputs the string representation of this `FieldPath` to the given - * stream. - * - * @see `ToString()` for comments on the representation format. - */ - friend std::ostream& operator<<(std::ostream& out, const FieldPath& path); - - private: - // The type of the internal object that implements the public interface. -#if !defined(SWIG) -#if !defined(__ANDROID__) - using FieldPathInternal = ::firebase::firestore::model::FieldPath; -#else - using FieldPathInternal = ::firebase::firestore::FieldPathPortable; -#endif // !defined(__ANDROID__) -#endif // !defined(SWIG) - - friend bool operator==(const FieldPath& lhs, const FieldPath& rhs); - friend bool operator!=(const FieldPath& lhs, const FieldPath& rhs); - friend struct std::hash; - - friend class DocumentSnapshot; // For access to `FromDotSeparatedString` - friend class Query; - friend class QueryInternal; - friend class SetOptions; // For access to `FromDotSeparatedString` - friend class FieldPathConverter; - friend struct ConverterImpl; - - explicit FieldPath(FieldPathInternal* internal); - - static FieldPathInternal* InternalFromSegments( - std::vector field_names); - - static FieldPath FromDotSeparatedString(const std::string& path); - - FieldPathInternal* internal_ = nullptr; -}; - -} // namespace firestore -} // namespace firebase - -#if !defined(SWIG) -namespace std { -/** - * A convenient specialization of std::hash for FieldPath. - */ -template <> -struct hash { - /** - * Calculates the hash of the argument. - * - * Note: specialization of `std::hash` is provided for convenience only. The - * implementation is subject to change. - */ - size_t operator()(const firebase::firestore::FieldPath& field_path) const; -}; -} // namespace std -#endif // !defined(SWIG) - -#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_FIELD_PATH_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/field_value.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/field_value.h deleted file mode 100644 index e66814104ed7..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/field_value.h +++ /dev/null @@ -1,436 +0,0 @@ -/* - * Copyright 2018 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_FIELD_VALUE_H_ -#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_FIELD_VALUE_H_ - -#include -#include -#include -#include -#include - -#include "firebase/firestore/map_field_value.h" -#include "firebase/internal/type_traits.h" - -namespace firebase { - -class Timestamp; - -namespace firestore { - -class DocumentReference; -class FieldValueInternal; -class GeoPoint; - -/** - * @brief A field value represents variant datatypes as stored by Firestore. - * - * FieldValue can be used when reading a particular field with - * DocumentSnapshot::Get() or fields with DocumentSnapshot::GetData(). When - * writing document fields with DocumentReference::Set() or - * DocumentReference::Update(), it can also represent sentinel values in - * addition to real data values. - * - * For a non-sentinel instance, you can check whether it is of a particular type - * with is_foo() and get the value with foo_value(), where foo can be one of - * null, boolean, integer, double, timestamp, string, blob, reference, - * geo_point, array or map. If the instance is not of type foo, the call to - * foo_value() will fail (and cause a crash). - */ -class FieldValue final { - // Helper aliases for `Increment` member functions. - // Qualifying `is_integer` is to prevent ambiguity with the - // `FieldValue::is_integer` member function. - // Note: normally, `enable_if::type` would be included in the alias, but such - // a declaration breaks SWIG (presumably, SWIG cannot handle `typename` within - // an alias template). - template - using EnableIfIntegral = enable_if<::firebase::is_integer::value, int>; - template - using EnableIfFloatingPoint = enable_if::value, int>; - - public: - /** - * The enumeration of all valid runtime types of FieldValue. - */ - enum class Type { - kNull, - kBoolean, - kInteger, - kDouble, - kTimestamp, - kString, - kBlob, - kReference, - kGeoPoint, - kArray, - kMap, - // Below are sentinel types. Sentinel types can be passed to Firestore - // methods as arguments, but are never returned from Firestore. - kDelete, - kServerTimestamp, - kArrayUnion, - kArrayRemove, - kIncrementInteger, - kIncrementDouble, - }; - - /** - * @brief Creates an invalid FieldValue that has to be reassigned before it - * can be used. - * - * Calling any member function on an invalid FieldValue will be a no-op. If - * the function returns a value, it will return a zero, empty, or invalid - * value, depending on the type of the value. - */ - FieldValue(); - - /** - * @brief Copy constructor. - * - * `FieldValue` is immutable and can be efficiently copied (no deep copy is - * performed). - * - * @param[in] other `FieldValue` to copy from. - */ - FieldValue(const FieldValue& other); - - /** - * @brief Move constructor. - * - * Moving is more efficient than copying for a `FieldValue`. After being moved - * from, a `FieldValue` is equivalent to its default-constructed state. - * - * @param[in] other `FieldValue` to move data from. - */ - FieldValue(FieldValue&& other) noexcept; - - ~FieldValue(); - - /** - * @brief Copy assignment operator. - * - * `FieldValue` is immutable and can be efficiently copied (no deep copy is - * performed). - * - * @param[in] other `FieldValue` to copy from. - * - * @return Reference to the destination `FieldValue`. - */ - FieldValue& operator=(const FieldValue& other); - - /** - * @brief Move assignment operator. - * - * Moving is more efficient than copying for a `FieldValue`. After being moved - * from, a `FieldValue` is equivalent to its default-constructed state. - * - * @param[in] other `FieldValue` to move data from. - * - * @return Reference to the destination `FieldValue`. - */ - FieldValue& operator=(FieldValue&& other) noexcept; - - /** - * @brief Constructs a FieldValue containing the given boolean value. - */ - static FieldValue Boolean(bool value); - - /** - * @brief Constructs a FieldValue containing the given 64-bit integer value. - */ - static FieldValue Integer(int64_t value); - - /** - * @brief Constructs a FieldValue containing the given double-precision - * floating point value. - */ - static FieldValue Double(double value); - - /** - * @brief Constructs a FieldValue containing the given Timestamp value. - */ - static FieldValue Timestamp(Timestamp value); - - /** - * @brief Constructs a FieldValue containing the given std::string value. - */ - static FieldValue String(std::string value); - - /** - * @brief Constructs a FieldValue containing the given blob value of given - * size. `value` is copied into the returned FieldValue. - */ - static FieldValue Blob(const uint8_t* value, size_t size); - - /** - * @brief Constructs a FieldValue containing the given reference value. - */ - static FieldValue Reference(DocumentReference value); - - /** - * @brief Constructs a FieldValue containing the given GeoPoint value. - */ - static FieldValue GeoPoint(GeoPoint value); - - /** - * @brief Constructs a FieldValue containing the given FieldValue vector - * value. - */ - static FieldValue Array(std::vector value); - - /** - * @brief Constructs a FieldValue containing the given FieldValue map value. - */ - static FieldValue Map(MapFieldValue value); - - /** @brief Gets the current type contained in this FieldValue. */ - Type type() const; - - /** @brief Gets whether this FieldValue is currently null. */ - bool is_null() const { return type() == Type::kNull; } - - /** @brief Gets whether this FieldValue contains a boolean value. */ - bool is_boolean() const { return type() == Type::kBoolean; } - - /** @brief Gets whether this FieldValue contains an integer value. */ - bool is_integer() const { return type() == Type::kInteger; } - - /** @brief Gets whether this FieldValue contains a double value. */ - bool is_double() const { return type() == Type::kDouble; } - - /** @brief Gets whether this FieldValue contains a timestamp. */ - bool is_timestamp() const { return type() == Type::kTimestamp; } - - /** @brief Gets whether this FieldValue contains a string. */ - bool is_string() const { return type() == Type::kString; } - - /** @brief Gets whether this FieldValue contains a blob. */ - bool is_blob() const { return type() == Type::kBlob; } - - /** - * @brief Gets whether this FieldValue contains a reference to a document in - * the same Firestore. - */ - bool is_reference() const { return type() == Type::kReference; } - - /** @brief Gets whether this FieldValue contains a GeoPoint. */ - bool is_geo_point() const { return type() == Type::kGeoPoint; } - - /** @brief Gets whether this FieldValue contains an array of FieldValues. */ - bool is_array() const { return type() == Type::kArray; } - - /** @brief Gets whether this FieldValue contains a map of std::string to - * FieldValue. */ - bool is_map() const { return type() == Type::kMap; } - - /** @brief Gets the boolean value contained in this FieldValue. */ - bool boolean_value() const; - - /** @brief Gets the integer value contained in this FieldValue. */ - int64_t integer_value() const; - - /** @brief Gets the double value contained in this FieldValue. */ - double double_value() const; - - /** @brief Gets the timestamp value contained in this FieldValue. */ - class Timestamp timestamp_value() const; - - /** @brief Gets the string value contained in this FieldValue. */ - std::string string_value() const; - - /** @brief Gets the blob value contained in this FieldValue. */ - const uint8_t* blob_value() const; - - /** @brief Gets the blob size contained in this FieldValue. */ - size_t blob_size() const; - - /** @brief Gets the DocumentReference contained in this FieldValue. */ - DocumentReference reference_value() const; - - /** @brief Gets the GeoPoint value contained in this FieldValue. */ - class GeoPoint geo_point_value() const; - - /** @brief Gets the vector of FieldValues contained in this FieldValue. */ - std::vector array_value() const; - - /** - * @brief Gets the map of string to FieldValue contained in this FieldValue. - */ - MapFieldValue map_value() const; - - /** - * @brief Returns `true` if this `FieldValue` is valid, `false` if it is not - * valid. An invalid `FieldValue` could be the result of: - * - Creating a `FieldValue` using the default constructor. - * - Moving from the `FieldValue`. - * - Calling `DocumentSnapshot::Get(field)` for a field that does not exist - * in the document. - * - * @return `true` if this `FieldValue` is valid, `false` if this `FieldValue` - * is invalid. - */ - bool is_valid() const { return internal_ != nullptr; } - - /** @brief Constructs a null. */ - static FieldValue Null(); - - /** - * @brief Returns a sentinel for use with Update() to mark a field for - * deletion. - */ - static FieldValue Delete(); - - /** - * Returns a sentinel that can be used with Set() or Update() to include - * a server-generated timestamp in the written data. - */ - static FieldValue ServerTimestamp(); - - /** - * Returns a special value that can be used with Set() or Update() that tells - * the server to union the given elements with any array value that already - * exists on the server. Each specified element that doesn't already exist in - * the array will be added to the end. If the field being modified is not - * already an array, it will be overwritten with an array containing exactly - * the specified elements. - * - * @param elements The elements to union into the array. - * @return The FieldValue sentinel for use in a call to Set() or Update(). - */ - static FieldValue ArrayUnion(std::vector elements); - - /** - * Returns a special value that can be used with Set() or Update() that tells - * the server to remove the given elements from any array value that already - * exists on the server. All instances of each element specified will be - * removed from the array. If the field being modified is not already an - * array, it will be overwritten with an empty array. - * - * @param elements The elements to remove from the array. - * @return The FieldValue sentinel for use in a call to Set() or Update(). - */ - static FieldValue ArrayRemove(std::vector elements); - - /** - * Returns a special value that can be used with `Set()` or `Update()` that - * tells the server to increment the field's current value by the given - * integer value. - * - * If the current field value is an integer, possible integer overflows are - * resolved to `LONG_MAX` or `LONG_MIN`. If the current field value is a - * double, both values will be interpreted as doubles and the arithmetic will - * follow IEEE 754 semantics. - * - * If field is not an integer or a double, or if the field does not yet exist, - * the transformation will set the field to the given value. - * - * @param by_value The integer value to increment by. Should be an integer - * type not larger than `int64_t`. - * @return The FieldValue sentinel for use in a call to `Set()` or `Update().` - */ - template ::type = 0> - static FieldValue Increment(T by_value) { - // Note: Doxygen will run into trouble if this function's definition is - // moved outside the class body. - static_assert( - (std::numeric_limits::max)() <= - (std::numeric_limits::max)(), - "The integer type you provided is larger than can fit in an int64_t. " - "If you are sure the value will not be truncated, please explicitly " - "cast to int64_t before passing it to FieldValue::Increment()."); - return IntegerIncrement(static_cast(by_value)); - } - - /** - * Returns a special value that can be used with `Set()` or `Update()` that - * tells the server to increment the field's current value by the given - * floating point value. - * - * If the current field value is an integer, possible integer overflows are - * resolved to `LONG_MAX` or `LONG_MIN`. If the current field value is a - * double, both values will be interpreted as doubles and the arithmetic will - * follow IEEE 754 semantics. - * - * If field is not an integer or a double, or if the field does not yet exist, - * the transformation will set the field to the given value. - * - * @param by_value The double value to increment by. Should be a floating - * point type no larger than `double`. - * @return The FieldValue sentinel for use in a call to `Set()` or `Update().` - */ - template ::type = 0> - static FieldValue Increment(T by_value) { - // Note: Doxygen will run into trouble if this function's definition is - // moved outside the class body. - static_assert( - (std::numeric_limits::max)() <= (std::numeric_limits::max)(), - "The floating point type you provided is larger than can fit in a " - "double. If you are sure the value will not be truncated, please " - "explicitly cast to double before passing it to " - "FieldValue::Increment()."); - return DoubleIncrement(static_cast(by_value)); - } - - /** - * Returns a string representation of this `FieldValue` for logging/debugging - * purposes. - * - * @note the exact string representation is unspecified and subject to - * change; don't rely on the format of the string. - */ - std::string ToString() const; - - /** - * Outputs the string representation of this `FieldValue` to the given stream. - * - * @see `ToString()` for comments on the representation format. - */ - friend std::ostream& operator<<(std::ostream& out, const FieldValue& value); - - private: - friend class DocumentReferenceInternal; - friend class DocumentSnapshotInternal; - friend class FieldValueInternal; - friend class FirestoreInternal; - friend class QueryInternal; - friend class TransactionInternal; - friend class Wrapper; - friend class WriteBatchInternal; - friend struct ConverterImpl; - friend bool operator==(const FieldValue& lhs, const FieldValue& rhs); - - explicit FieldValue(FieldValueInternal* internal); - - static FieldValue IntegerIncrement(int64_t by_value); - static FieldValue DoubleIncrement(double by_value); - - FieldValueInternal* internal_ = nullptr; -}; - -/** Checks `lhs` and `rhs` for equality. */ -bool operator==(const FieldValue& lhs, const FieldValue& rhs); - -/** Checks `lhs` and `rhs` for inequality. */ -inline bool operator!=(const FieldValue& lhs, const FieldValue& rhs) { - return !(lhs == rhs); -} - -} // namespace firestore -} // namespace firebase - -#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_FIELD_VALUE_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/firestore_errors.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/firestore_errors.h deleted file mode 100644 index 6af214a08df1..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/firestore_errors.h +++ /dev/null @@ -1,116 +0,0 @@ -/* - * Copyright 2018 Google - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIRESTORE_CORE_INCLUDE_FIREBASE_FIRESTORE_FIRESTORE_ERRORS_H_ -#define FIRESTORE_CORE_INCLUDE_FIREBASE_FIRESTORE_FIRESTORE_ERRORS_H_ - -namespace firebase { -namespace firestore { - -/** - * Error codes used by Cloud Firestore. - * - * The codes are in sync across Firestore SDKs on various platforms. - */ -enum Error { - /** The operation completed successfully. */ - // Note: NSError objects will never have a code with this value. - kErrorOk = 0, - - kErrorNone = 0, - - /** The operation was cancelled (typically by the caller). */ - kErrorCancelled = 1, - - /** Unknown error or an error from a different error domain. */ - kErrorUnknown = 2, - - /** - * Client specified an invalid argument. Note that this differs from - * FailedPrecondition. InvalidArgument indicates arguments that are - * problematic regardless of the state of the system (e.g., an invalid field - * name). - */ - kErrorInvalidArgument = 3, - - /** - * Deadline expired before operation could complete. For operations that - * change the state of the system, this error may be returned even if the - * operation has completed successfully. For example, a successful response - * from a server could have been delayed long enough for the deadline to - * expire. - */ - kErrorDeadlineExceeded = 4, - - /** Some requested document was not found. */ - kErrorNotFound = 5, - - /** Some document that we attempted to create already exists. */ - kErrorAlreadyExists = 6, - - /** The caller does not have permission to execute the specified operation. */ - kErrorPermissionDenied = 7, - - /** - * Some resource has been exhausted, perhaps a per-user quota, or perhaps the - * entire file system is out of space. - */ - kErrorResourceExhausted = 8, - - /** - * Operation was rejected because the system is not in a state required for - * the operation's execution. - */ - kErrorFailedPrecondition = 9, - - /** - * The operation was aborted, typically due to a concurrency issue like - * transaction aborts, etc. - */ - kErrorAborted = 10, - - /** Operation was attempted past the valid range. */ - kErrorOutOfRange = 11, - - /** Operation is not implemented or not supported/enabled. */ - kErrorUnimplemented = 12, - - /** - * Internal errors. Means some invariants expected by underlying system has - * been broken. If you see one of these errors, something is very broken. - */ - kErrorInternal = 13, - - /** - * The service is currently unavailable. This is a most likely a transient - * condition and may be corrected by retrying with a backoff. - */ - kErrorUnavailable = 14, - - /** Unrecoverable data loss or corruption. */ - kErrorDataLoss = 15, - - /** - * The request does not have valid authentication credentials for the - * operation. - */ - kErrorUnauthenticated = 16 -}; - -} // namespace firestore -} // namespace firebase - -#endif // FIRESTORE_CORE_INCLUDE_FIREBASE_FIRESTORE_FIRESTORE_ERRORS_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/firestore_version.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/firestore_version.h deleted file mode 100644 index 627ead9e3ae7..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/firestore_version.h +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright 2018 Google - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIRESTORE_CORE_INCLUDE_FIREBASE_FIRESTORE_FIRESTORE_VERSION_H_ -#define FIRESTORE_CORE_INCLUDE_FIREBASE_FIRESTORE_FIRESTORE_VERSION_H_ - -namespace firebase { -namespace firestore { - -/** Version string for the Firebase Firestore SDK. */ -extern const char* const kFirestoreVersionString; - -} // namespace firestore -} // namespace firebase - -#endif // FIRESTORE_CORE_INCLUDE_FIREBASE_FIRESTORE_FIRESTORE_VERSION_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/geo_point.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/geo_point.h deleted file mode 100644 index ac56e74a4515..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/geo_point.h +++ /dev/null @@ -1,120 +0,0 @@ -/* - * Copyright 2018 Google - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIRESTORE_CORE_INCLUDE_FIREBASE_FIRESTORE_GEO_POINT_H_ -#define FIRESTORE_CORE_INCLUDE_FIREBASE_FIRESTORE_GEO_POINT_H_ - -#include -#include - -namespace firebase { -namespace firestore { - -/** - * An immutable object representing a geographical point in Firestore. The point - * is represented as a latitude/longitude pair. - * - * Latitude values are in the range of [-90, 90]. - * Longitude values are in the range of [-180, 180]. - */ -class GeoPoint { - public: - /** Creates a `GeoPoint` with both latitude and longitude set to 0. */ - GeoPoint() = default; - - /** - * Creates a `GeoPoint` from the provided latitude and longitude values. - * - * @param latitude The latitude as number of degrees between -90 and 90. - * @param longitude The longitude as number of degrees between -180 and 180. - */ - GeoPoint(double latitude, double longitude); - - /** Copy constructor, `GeoPoint` is trivially copyable. */ - GeoPoint(const GeoPoint& other) = default; - - /** Move constructor, equivalent to copying. */ - GeoPoint(GeoPoint&& other) = default; - - /** Copy assignment operator, `GeoPoint` is trivially copyable. */ - GeoPoint& operator=(const GeoPoint& other) = default; - - /** Move assignment operator, equivalent to copying. */ - GeoPoint& operator=(GeoPoint&& other) = default; - - /** Returns the latitude value of this `GeoPoint`. */ - double latitude() const { - return latitude_; - } - - /** Returns the latitude value of this `GeoPoint`. */ - double longitude() const { - return longitude_; - } - - /** - * Returns a string representation of this `GeoPoint` for logging/debugging - * purposes. - * - * @note: the exact string representation is unspecified and subject to - * change; don't rely on the format of the string. - */ - std::string ToString() const; - - /** - * Outputs the string representation of this `GeoPoint` to the given stream. - * - * @see `ToString()` for comments on the representation format. - */ - friend std::ostream& operator<<(std::ostream& out, const GeoPoint& geo_point); - - private: - double latitude_ = 0.0; - double longitude_ = 0.0; -}; - -/** Checks whether `lhs` and `rhs` are in ascending order. */ -bool operator<(const GeoPoint& lhs, const GeoPoint& rhs); - -/** Checks whether `lhs` and `rhs` are in descending order. */ -inline bool operator>(const GeoPoint& lhs, const GeoPoint& rhs) { - return rhs < lhs; -} - -/** Checks whether `lhs` and `rhs` are in non-ascending order. */ -inline bool operator>=(const GeoPoint& lhs, const GeoPoint& rhs) { - return !(lhs < rhs); -} - -/** Checks whether `lhs` and `rhs` are in non-descending order. */ -inline bool operator<=(const GeoPoint& lhs, const GeoPoint& rhs) { - return !(lhs > rhs); -} - -/** Checks `lhs` and `rhs` for inequality. */ -inline bool operator!=(const GeoPoint& lhs, const GeoPoint& rhs) { - return lhs < rhs || lhs > rhs; -} - -/** Checks `lhs` and `rhs` for equality. */ -inline bool operator==(const GeoPoint& lhs, const GeoPoint& rhs) { - return !(lhs != rhs); -} - -} // namespace firestore -} // namespace firebase - -#endif // FIRESTORE_CORE_INCLUDE_FIREBASE_FIRESTORE_GEO_POINT_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/listener_registration.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/listener_registration.h deleted file mode 100644 index 20487943347f..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/listener_registration.h +++ /dev/null @@ -1,130 +0,0 @@ -/* - * Copyright 2018 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_LISTENER_REGISTRATION_H_ -#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_LISTENER_REGISTRATION_H_ - -namespace firebase { -namespace firestore { - -class FirestoreInternal; -class ListenerRegistrationInternal; - -/** Represents a listener that can be removed by calling Remove(). */ -class ListenerRegistration { - public: - /** - * @brief Creates an invalid ListenerRegistration that has to be reassigned - * before it can be used. - * - * Calling Remove() on an invalid ListenerRegistration is a no-op. - */ - ListenerRegistration(); - - /** - * @brief Copy constructor. - * - * `ListenerRegistration` can be efficiently copied because it simply refers - * to the same underlying listener. If there is more than one copy of - * a `ListenerRegistration`, after calling `Remove` on one of them, the - * listener is removed, and calling `Remove` on any other copies will be - * a no-op. - * - * @param[in] other `ListenerRegistration` to copy from. - */ - ListenerRegistration(const ListenerRegistration& other); - - /** - * @brief Move constructor. - * - * Moving is more efficient than copying for a `ListenerRegistration`. After - * being moved from, a `ListenerRegistration` is equivalent to its - * default-constructed state. - * - * @param[in] other `ListenerRegistration` to move data from. - */ - ListenerRegistration(ListenerRegistration&& other); - - virtual ~ListenerRegistration(); - - /** - * @brief Copy assignment operator. - * - * `ListenerRegistration` can be efficiently copied because it simply refers - * to the same underlying listener. If there is more than one copy of - * a `ListenerRegistration`, after calling `Remove` on one of them, the - * listener is removed, and calling `Remove` on any other copies will be - * a no-op. - * - * @param[in] other `ListenerRegistration` to copy from. - * - * @return Reference to the destination `ListenerRegistration`. - */ - ListenerRegistration& operator=(const ListenerRegistration& other); - - /** - * @brief Move assignment operator. - * - * Moving is more efficient than copying for a `ListenerRegistration`. After - * being moved from, a `ListenerRegistration` is equivalent to its - * default-constructed state. - * - * @param[in] other `ListenerRegistration` to move data from. - * - * @return Reference to the destination `ListenerRegistration`. - */ - ListenerRegistration& operator=(ListenerRegistration&& other); - - /** - * Removes the listener being tracked by this ListenerRegistration. After the - * initial call, subsequent calls have no effect. - */ - virtual void Remove(); - - /** - * @brief Returns true if this `ListenerRegistration` is valid, false if it is - * not valid. An invalid `ListenerRegistration` could be the result of: - * - Creating a `ListenerRegistration` using the default constructor. - * - Moving from the `ListenerRegistration`. - * - Deleting your Firestore instance, which will invalidate all the - * `ListenerRegistration` instances associated with it. - * - * @return true if this `ListenerRegistration` is valid, false if this - * `ListenerRegistration` is invalid. - */ - bool is_valid() const { return internal_ != nullptr; } - - private: - friend class DocumentReferenceInternal; - friend class FirestoreInternal; - friend class ListenerRegistrationInternal; - friend class QueryInternal; - friend struct ConverterImpl; - template - friend struct CleanupFn; - - explicit ListenerRegistration(ListenerRegistrationInternal* internal); - - void Cleanup(); - - FirestoreInternal* firestore_ = nullptr; - mutable ListenerRegistrationInternal* internal_ = nullptr; -}; - -} // namespace firestore -} // namespace firebase - -#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_LISTENER_REGISTRATION_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/load_bundle_task_progress.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/load_bundle_task_progress.h deleted file mode 100644 index be9b235f1205..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/load_bundle_task_progress.h +++ /dev/null @@ -1,101 +0,0 @@ -/* - * Copyright 2021 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_LOAD_BUNDLE_TASK_PROGRESS_H_ -#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_LOAD_BUNDLE_TASK_PROGRESS_H_ - -#include - -namespace firebase { -namespace firestore { - -class LoadBundleTaskProgressInternal; - -/** Represents a progress update or the final state from loading bundles. */ -class LoadBundleTaskProgress { - public: - /** - * Represents the state of bundle loading tasks. - * - * Both `kSuccess` and `kError` are final states: the task will abort - * or complete and there will be no more updates after they are reported. - */ - enum class State { kError, kInProgress, kSuccess }; - - LoadBundleTaskProgress() = default; - /** Construct a LoadBundleTaskProgress with specific state. **/ - LoadBundleTaskProgress(int32_t documents_loaded, - int32_t total_documents, - int64_t bytes_loaded, - int64_t total_bytes, - State state); - - /** Returns how many documents have been loaded. */ - int32_t documents_loaded() const { return documents_loaded_; } - - /** - * Returns the total number of documents in the bundle. Returns 0 if the - * bundle failed to parse. - */ - int32_t total_documents() const { return total_documents_; } - - /** Returns how many bytes have been loaded. */ - int64_t bytes_loaded() const { return bytes_loaded_; } - - /** - * Returns the total number of bytes in the bundle. Returns 0 if the bundle - * failed to parse. - */ - int64_t total_bytes() const { return total_bytes_; } - - /** Returns the current state of the loading progress. */ - State state() const { return state_; } - - private: - friend class EventListenerInternal; - friend class LoadBundleTaskProgressInternal; - friend struct ConverterImpl; - -#if defined(__ANDROID__) - explicit LoadBundleTaskProgress(LoadBundleTaskProgressInternal* internal); -#endif // defined(__ANDROID__) - - int32_t documents_loaded_ = 0; - int32_t total_documents_ = 0; - int64_t bytes_loaded_ = 0; - int64_t total_bytes_ = 0; - State state_ = State::kInProgress; -}; - -/** LoadBundleTaskProgress == comparison operator. **/ -inline bool operator==(const LoadBundleTaskProgress& lhs, - const LoadBundleTaskProgress& rhs) { - return lhs.state() == rhs.state() && - lhs.bytes_loaded() == rhs.bytes_loaded() && - lhs.documents_loaded() == rhs.documents_loaded() && - lhs.total_bytes() == rhs.total_bytes() && - lhs.total_documents() == rhs.total_documents(); -} - -/** LoadBundleTaskProgress != comparison operator. **/ -inline bool operator!=(const LoadBundleTaskProgress& lhs, - const LoadBundleTaskProgress& rhs) { - return !(lhs == rhs); -} - -} // namespace firestore -} // namespace firebase - -#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_LOAD_BUNDLE_TASK_PROGRESS_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/map_field_value.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/map_field_value.h deleted file mode 100644 index 8c67c05a1088..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/map_field_value.h +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright 2018 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_MAP_FIELD_VALUE_H_ -#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_MAP_FIELD_VALUE_H_ - -#include -#include - -namespace firebase { -namespace firestore { - -class FieldPath; -class FieldValue; - -/** @brief A map of `FieldValue`s indexed by stringified field paths. */ -using MapFieldValue = std::unordered_map; -/** @brief A map of `FieldValue`s indexed by field paths. */ -using MapFieldPathValue = std::unordered_map; - -} // namespace firestore -} // namespace firebase - -#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_MAP_FIELD_VALUE_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/metadata_changes.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/metadata_changes.h deleted file mode 100644 index 13f9abe48427..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/metadata_changes.h +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright 2018 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_METADATA_CHANGES_H_ -#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_METADATA_CHANGES_H_ - -namespace firebase { -namespace firestore { - -/** - * Indicates whether metadata-only changes (that is, - * DocumentSnapshot::metadata() or QuerySnapshot::metadata() changed) should - * trigger snapshot events. - */ -enum class MetadataChanges { - /** Snapshot events will not be triggered by metadata-only changes. */ - kExclude, - - /** - * Snapshot events will be triggered by any changes, including metadata-only - * changes. - */ - kInclude, -}; - -} // namespace firestore -} // namespace firebase -#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_METADATA_CHANGES_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/query.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/query.h deleted file mode 100644 index d2e73400cee6..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/query.h +++ /dev/null @@ -1,683 +0,0 @@ -/* - * Copyright 2018 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_QUERY_H_ -#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_QUERY_H_ - -#include -#include -#include -#include -#include - -#include "firebase/internal/common.h" - -#include "firebase/firestore/firestore_errors.h" -#include "firebase/firestore/metadata_changes.h" -#include "firebase/firestore/source.h" - -namespace firebase { -/// @cond FIREBASE_APP_INTERNAL -template -class Future; -/// @endcond - -namespace firestore { - -class DocumentSnapshot; -template -class EventListener; -class FieldPath; -class FieldValue; -class ListenerRegistration; -class Firestore; -class QueryInternal; -class QuerySnapshot; - -/** - * @brief A Query which you can read or listen to. - * - * You can also construct refined Query objects by adding filters and ordering. - * - * You cannot construct a valid Query directly; use CollectionReference - * methods that return a Query instead. - * - * @note Firestore classes are not meant to be subclassed except for use in test - * mocks. Subclassing is not supported in production code and new SDK releases - * may break code that does so. - */ -class Query { - public: - /** - * An enum for the direction of a sort. - */ - enum class Direction { - kAscending, - kDescending, - }; - - /** - * @brief Creates an invalid Query that has to be reassigned before it can be - * used. - * - * Calling any member function on an invalid Query will be a no-op. If the - * function returns a value, it will return a zero, empty, or invalid value, - * depending on the type of the value. - */ - Query(); - - /** - * @brief Copy constructor. - * - * `Query` is immutable and can be efficiently copied (no deep copy is - * performed). - * - * @param[in] other `Query` to copy from. - */ - Query(const Query& other); - - /** - * @brief Move constructor. - * - * Moving is more efficient than copying for a `Query`. After being moved - * from, a `Query` is equivalent to its default-constructed state. - * - * @param[in] other `Query` to move data from. - */ - Query(Query&& other); - - virtual ~Query(); - - /** - * @brief Copy assignment operator. - * - * `Query` is immutable and can be efficiently copied (no deep copy is - * performed). - * - * @param[in] other `Query` to copy from. - * - * @return Reference to the destination `Query`. - */ - Query& operator=(const Query& other); - - /** - * @brief Move assignment operator. - * - * Moving is more efficient than copying for a `Query`. After being moved - * from, a `Query` is equivalent to its default-constructed state. - * - * @param[in] other `Query` to move data from. - * - * @return Reference to the destination `Query`. - */ - Query& operator=(Query&& other); - - /** - * @brief Returns the Firestore instance associated with this query. - * - * The pointer will remain valid indefinitely. - * - * @return Firebase Firestore instance that this Query refers to. - */ - virtual const Firestore* firestore() const; - - /** - * @brief Returns the Firestore instance associated with this query. - * - * The pointer will remain valid indefinitely. - * - * @return Firebase Firestore instance that this Query refers to. - */ - virtual Firestore* firestore(); - - /** - * @brief Creates and returns a new Query with the additional filter that - * documents must contain the specified field and the value should be equal to - * the specified value. - * - * @param[in] field The name of the field to compare. - * @param[in] value The value for comparison. - * - * @return The created Query. - */ - virtual Query WhereEqualTo(const std::string& field, - const FieldValue& value) const; - - /** - * @brief Creates and returns a new Query with the additional filter that - * documents must contain the specified field and the value should be equal to - * the specified value. - * - * @param[in] field The path of the field to compare. - * @param[in] value The value for comparison. - * - * @return The created Query. - */ - virtual Query WhereEqualTo(const FieldPath& field, - const FieldValue& value) const; - - /** - * @brief Creates and returns a new Query with the additional filter that - * documents must contain the specified field and the value does not equal the - * specified value. - * - * A Query can have only one `WhereNotEqualTo()` filter, and it cannot be - * combined with `WhereNotIn()`. - * - * @param[in] field The name of the field to compare. - * @param[in] value The value for comparison. - * - * @return The created Query. - */ - virtual Query WhereNotEqualTo(const std::string& field, - const FieldValue& value) const; - - /** - * @brief Creates and returns a new Query with the additional filter that - * documents must contain the specified field and the value does not equal the - * specified value. - * - * A Query can have only one `WhereNotEqualTo()` filter, and it cannot be - * combined with `WhereNotIn()`. - * - * @param[in] field The path of the field to compare. - * @param[in] value The value for comparison. - * - * @return The created Query. - */ - virtual Query WhereNotEqualTo(const FieldPath& field, - const FieldValue& value) const; - - /** - * @brief Creates and returns a new Query with the additional filter that - * documents must contain the specified field and the value should be less - * than the specified value. - * - * @param[in] field The name of the field to compare. - * @param[in] value The value for comparison. - * - * @return The created Query. - */ - virtual Query WhereLessThan(const std::string& field, - const FieldValue& value) const; - - /** - * @brief Creates and returns a new Query with the additional filter that - * documents must contain the specified field and the value should be less - * than the specified value. - * - * @param[in] field The path of the field to compare. - * @param[in] value The value for comparison. - * - * @return The created Query. - */ - virtual Query WhereLessThan(const FieldPath& field, - const FieldValue& value) const; - - /** - * @brief Creates and returns a new Query with the additional filter that - * documents must contain the specified field and the value should be less - * than or equal to the specified value. - * - * @param[in] field The name of the field to compare. - * @param[in] value The value for comparison. - * - * @return The created Query. - */ - virtual Query WhereLessThanOrEqualTo(const std::string& field, - const FieldValue& value) const; - - /** - * @brief Creates and returns a new Query with the additional filter that - * documents must contain the specified field and the value should be less - * than or equal to the specified value. - * - * @param[in] field The path of the field to compare. - * @param[in] value The value for comparison. - * - * @return The created Query. - */ - virtual Query WhereLessThanOrEqualTo(const FieldPath& field, - const FieldValue& value) const; - - /** - * @brief Creates and returns a new Query with the additional filter that - * documents must contain the specified field and the value should be greater - * than the specified value. - * - * @param[in] field The name of the field to compare. - * @param[in] value The value for comparison. - * - * @return The created Query. - */ - virtual Query WhereGreaterThan(const std::string& field, - const FieldValue& value) const; - - /** - * @brief Creates and returns a new Query with the additional filter that - * documents must contain the specified field and the value should be greater - * than the specified value. - * - * @param[in] field The path of the field to compare. - * @param[in] value The value for comparison. - * - * @return The created Query. - */ - virtual Query WhereGreaterThan(const FieldPath& field, - const FieldValue& value) const; - - /** - * @brief Creates and returns a new Query with the additional filter that - * documents must contain the specified field and the value should be greater - * than or equal to the specified value. - * - * @param[in] field The name of the field to compare. - * @param[in] value The value for comparison. - * - * @return The created Query. - */ - virtual Query WhereGreaterThanOrEqualTo(const std::string& field, - const FieldValue& value) const; - - /** - * @brief Creates and returns a new Query with the additional filter that - * documents must contain the specified field and the value should be greater - * than or equal to the specified value. - * - * @param[in] field The path of the field to compare. - * @param[in] value The value for comparison. - * - * @return The created Query. - */ - virtual Query WhereGreaterThanOrEqualTo(const FieldPath& field, - const FieldValue& value) const; - - /** - * @brief Creates and returns a new Query with the additional filter that - * documents must contain the specified field, the value must be an array, and - * that the array must contain the provided value. - * - * A Query can have only one `WhereArrayContains()` filter and it cannot be - * combined with `WhereArrayContainsAny()` or `WhereIn()`. - * - * @param[in] field The name of the field containing an array to search. - * @param[in] value The value that must be contained in the array. - * - * @return The created Query. - */ - virtual Query WhereArrayContains(const std::string& field, - const FieldValue& value) const; - - /** - * @brief Creates and returns a new Query with the additional filter that - * documents must contain the specified field, the value must be an array, and - * that the array must contain the provided value. - * - * A Query can have only one `WhereArrayContains()` filter and it cannot be - * combined with `WhereArrayContainsAny()` or `WhereIn()`. - * - * @param[in] field The path of the field containing an array to search. - * @param[in] value The value that must be contained in the array. - * - * @return The created Query. - */ - virtual Query WhereArrayContains(const FieldPath& field, - const FieldValue& value) const; - - /** - * @brief Creates and returns a new Query with the additional filter that - * documents must contain the specified field, the value must be an array, and - * that the array must contain at least one value from the provided list. - * - * A Query can have only one `WhereArrayContainsAny()` filter and it cannot be - * combined with `WhereArrayContains()` or `WhereIn()`. - * - * @param[in] field The name of the field containing an array to search. - * @param[in] values The list that contains the values to match. - * - * @return The created Query. - */ - virtual Query WhereArrayContainsAny( - const std::string& field, const std::vector& values) const; - - /** - * @brief Creates and returns a new Query with the additional filter that - * documents must contain the specified field, the value must be an array, and - * that the array must contain at least one value from the provided list. - * - * A Query can have only one `WhereArrayContainsAny()` filter and it cannot be - * combined with` WhereArrayContains()` or `WhereIn()`. - * - * @param[in] field The path of the field containing an array to search. - * @param[in] values The list that contains the values to match. - * - * @return The created Query. - */ - virtual Query WhereArrayContainsAny( - const FieldPath& field, const std::vector& values) const; - - /** - * @brief Creates and returns a new Query with the additional filter that - * documents must contain the specified field and the value must equal one of - * the values from the provided list. - * - * A Query can have only one `WhereIn()` filter and it cannot be - * combined with `WhereArrayContainsAny()`. - * - * @param[in] field The name of the field containing an array to search. - * @param[in] values The list that contains the values to match. - * - * @return The created Query. - */ - virtual Query WhereIn(const std::string& field, - const std::vector& values) const; - - /** - * @brief Creates and returns a new Query with the additional filter that - * documents must contain the specified field and the value must equal one of - * the values from the provided list. - * - * A Query can have only one `WhereIn()` filter and it cannot be - * combined with `WhereArrayContainsAny()`. - * - * @param[in] field The path of the field containing an array to search. - * @param[in] values The list that contains the values to match. - * - * @return The created Query. - */ - virtual Query WhereIn(const FieldPath& field, - const std::vector& values) const; - - /** - * @brief Creates and returns a new Query with the additional filter that - * documents must contain the specified field and the value must not equal any - * of the values from the provided list. - * - * One special case is that `WhereNotIn` cannot match `FieldValue::Null()` - * values. To query for documents where a field exists and is - * `FieldValue::Null()`, use `WhereNotEqualTo`, which can handle this special - * case. - * - * A `Query` can have only one `WhereNotIn()` filter, and it cannot be - * combined with `WhereArrayContains()`, `WhereArrayContainsAny()`, - * `WhereIn()`, or `WhereNotEqualTo()`. - * - * @param[in] field The name of the field containing an array to search. - * @param[in] values The list that contains the values to match. - * - * @return The created Query. - */ - virtual Query WhereNotIn(const std::string& field, - const std::vector& values) const; - - /** - * @brief Creates and returns a new Query with the additional filter that - * documents must contain the specified field and the value must not equal any - * of the values from the provided list. - * - * One special case is that `WhereNotIn` cannot match `FieldValue::Null()` - * values. To query for documents where a field exists and is - * `FieldValue::Null()`, use `WhereNotEqualTo`, which can handle this special - * case. - * - * A `Query` can have only one `WhereNotIn()` filter, and it cannot be - * combined with `WhereArrayContains()`, `WhereArrayContainsAny()`, - * `WhereIn()`, or `WhereNotEqualTo()`. - * - * @param[in] field The path of the field containing an array to search. - * @param[in] values The list that contains the values to match. - * - * @return The created Query. - */ - virtual Query WhereNotIn(const FieldPath& field, - const std::vector& values) const; - - /** - * @brief Creates and returns a new Query that's additionally sorted by the - * specified field. - * - * @param[in] field The field to sort by. - * @param[in] direction The direction to sort (optional). If not specified, - * order will be ascending. - * - * @return The created Query. - */ - virtual Query OrderBy(const std::string& field, - Direction direction = Direction::kAscending) const; - - /** - * @brief Creates and returns a new Query that's additionally sorted by the - * specified field. - * - * @param[in] field The field to sort by. - * @param[in] direction The direction to sort (optional). If not specified, - * order will be ascending. - * - * @return The created Query. - */ - virtual Query OrderBy(const FieldPath& field, - Direction direction = Direction::kAscending) const; - - /** - * @brief Creates and returns a new Query that only returns the first matching - * documents up to the specified number. - * - * @param[in] limit A non-negative integer to specify the maximum number of - * items to return. - * - * @return The created Query. - */ - virtual Query Limit(int32_t limit) const; - - /** - * @brief Creates and returns a new Query that only returns the last matching - * documents up to the specified number. - * - * @param[in] limit A non-negative integer to specify the maximum number of - * items to return. - * - * @return The created Query. - */ - virtual Query LimitToLast(int32_t limit) const; - - /** - * @brief Creates and returns a new Query that starts at the provided document - * (inclusive). The starting position is relative to the order of the query. - * The document must contain all of the fields provided in the order by of - * this query. - * - * @param[in] snapshot The snapshot of the document to start at. - * - * @return The created Query. - */ - virtual Query StartAt(const DocumentSnapshot& snapshot) const; - - /** - * @brief Creates and returns a new Query that starts at the provided fields - * relative to the order of the query. The order of the field values must - * match the order of the order by clauses of the query. - * - * @param[in] values The field values to start this query at, in order of the - * query's order by. - * - * @return The created Query. - */ - virtual Query StartAt(const std::vector& values) const; - - /** - * @brief Creates and returns a new Query that starts after the provided - * document (inclusive). The starting position is relative to the order of the - * query. The document must contain all of the fields provided in the order by - * of this query. - * - * @param[in] snapshot The snapshot of the document to start after. - * - * @return The created Query. - */ - virtual Query StartAfter(const DocumentSnapshot& snapshot) const; - - /** - * @brief Creates and returns a new Query that starts after the provided - * fields relative to the order of the query. The order of the field values - * must match the order of the order by clauses of the query. - * - * @param[in] values The field values to start this query after, in order of - * the query's order by. - * - * @return The created Query. - */ - virtual Query StartAfter(const std::vector& values) const; - - /** - * @brief Creates and returns a new Query that ends before the provided - * document (inclusive). The end position is relative to the order of the - * query. The document must contain all of the fields provided in the order by - * of this query. - * - * @param[in] snapshot The snapshot of the document to end before. - * - * @return The created Query. - */ - virtual Query EndBefore(const DocumentSnapshot& snapshot) const; - - /** - * @brief Creates and returns a new Query that ends before the provided fields - * relative to the order of the query. The order of the field values must - * match the order of the order by clauses of the query. - * - * @param[in] values The field values to end this query before, in order of - * the query's order by. - * - * @return The created Query. - */ - virtual Query EndBefore(const std::vector& values) const; - - /** - * @brief Creates and returns a new Query that ends at the provided document - * (inclusive). The end position is relative to the order of the query. The - * document must contain all of the fields provided in the order by of this - * query. - * - * @param[in] snapshot The snapshot of the document to end at. - * - * @return The created Query. - */ - virtual Query EndAt(const DocumentSnapshot& snapshot) const; - - /** - * @brief Creates and returns a new Query that ends at the provided fields - * relative to the order of the query. The order of the field values must - * match the order of the order by clauses of the query. - * - * @param[in] values The field values to end this query at, in order of the - * query's order by. - * - * @return The created Query. - */ - virtual Query EndAt(const std::vector& values) const; - - /** - * @brief Executes the query and returns the results as a QuerySnapshot. - * - * By default, Get() attempts to provide up-to-date data when possible by - * waiting for data from the server, but it may return cached data or fail if - * you are offline and the server cannot be reached. This behavior can be - * altered via the Source parameter. - * - * @param[in] source A value to configure the get behavior (optional). - * - * @return A Future that will be resolved with the results of the Query. - */ - virtual Future Get(Source source = Source::kDefault) const; - - /** - * @brief Starts listening to the QuerySnapshot events referenced by this - * query. - * - * @param[in] callback The std::function to call. When this function is - * called, snapshot value is valid if and only if error is Error::kErrorOk. - * The std::string is an error message; the value may be empty if an error - * message is not available. - * - * @return A registration object that can be used to remove the listener. - */ - virtual ListenerRegistration AddSnapshotListener( - std::function - callback); - - /** - * @brief Starts listening to the QuerySnapshot events referenced by this - * query. - * - * @param[in] metadata_changes Indicates whether metadata-only changes (that - * is, only DocumentSnapshot::metadata() changed) should trigger snapshot - * events. - * @param[in] callback The std::function to call. When this function is - * called, snapshot value is valid if and only if error is Error::kErrorOk. - * The std::string is an error message; the value may be empty if an error - * message is not available. - * - * @return A registration object that can be used to remove the listener. - */ - virtual ListenerRegistration AddSnapshotListener( - MetadataChanges metadata_changes, - std::function - callback); - - /** - * @brief Returns true if this `Query` is valid, false if it is not valid. An - * invalid `Query` could be the result of: - * - Creating a `Query` using the default constructor. - * - Moving from the `Query`. - * - Deleting your Firestore instance, which will invalidate all the `Query` - * instances associated with it. - * - * @return true if this `Query` is valid, false if this `Query` is invalid. - */ - bool is_valid() const { return internal_ != nullptr; } - - private: - size_t Hash() const; - - friend bool operator==(const Query& lhs, const Query& rhs); - friend size_t QueryHash(const Query& query); - - friend class FirestoreInternal; - friend class QueryInternal; - friend class QuerySnapshotInternal; - friend struct ConverterImpl; - template - friend struct CleanupFn; - // For access to the constructor and to `internal_`. - friend class CollectionReference; - - explicit Query(QueryInternal* internal); - - mutable QueryInternal* internal_ = nullptr; -}; - -/** Checks `lhs` and `rhs` for equality. */ -bool operator==(const Query& lhs, const Query& rhs); - -/** Checks `lhs` and `rhs` for inequality. */ -inline bool operator!=(const Query& lhs, const Query& rhs) { - return !(lhs == rhs); -} - -} // namespace firestore -} // namespace firebase - -#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_QUERY_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/query_snapshot.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/query_snapshot.h deleted file mode 100644 index 2dcf7aaf5239..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/query_snapshot.h +++ /dev/null @@ -1,194 +0,0 @@ -/* - * Copyright 2018 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_QUERY_SNAPSHOT_H_ -#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_QUERY_SNAPSHOT_H_ - -#include -#include - -#include "firebase/firestore/metadata_changes.h" -#include "firebase/firestore/snapshot_metadata.h" - -namespace firebase { -namespace firestore { - -class DocumentChange; -class DocumentSnapshot; -class Query; -class QuerySnapshotInternal; - -/** - * @brief A QuerySnapshot contains zero or more DocumentSnapshot objects. - * - * QuerySnapshot can be iterated using a range-based for loop, and its size can - * be inspected with empty() and size(). - * - * @note Firestore classes are not meant to be subclassed except for use in test - * mocks. Subclassing is not supported in production code and new SDK releases - * may break code that does so. - */ -class QuerySnapshot { - public: - /** - * @brief Creates an invalid QuerySnapshot that has to be reassigned before it - * can be used. - * - * Calling any member function on an invalid QuerySnapshot will be a no-op. If - * the function returns a value, it will return a zero, empty, or invalid - * value, depending on the type of the value. - */ - QuerySnapshot(); - - /** - * @brief Copy constructor. - * - * `QuerySnapshot` is immutable and can be efficiently copied (no deep copy is - * performed). - * - * @param[in] other `QuerySnapshot` to copy from. - */ - QuerySnapshot(const QuerySnapshot& other); - - /** - * @brief Move constructor. - * - * Moving is more efficient than copying for a `QuerySnapshot`. After being - * moved from, a `QuerySnapshot` is equivalent to its default-constructed - * state. - * - * @param[in] other `QuerySnapshot` to move data from. - */ - QuerySnapshot(QuerySnapshot&& other); - - virtual ~QuerySnapshot(); - - /** - * @brief Copy assignment operator. - * - * `QuerySnapshot` is immutable and can be efficiently copied (no deep copy is - * performed). - * - * @param[in] other `QuerySnapshot` to copy from. - * - * @return Reference to the destination `QuerySnapshot`. - */ - QuerySnapshot& operator=(const QuerySnapshot& other); - - /** - * @brief Move assignment operator. - * - * Moving is more efficient than copying for a `QuerySnapshot`. After being - * moved from, a `QuerySnapshot` is equivalent to its default-constructed - * state. - * - * @param[in] other `QuerySnapshot` to move data from. - * - * @return Reference to the destination `QuerySnapshot`. - */ - QuerySnapshot& operator=(QuerySnapshot&& other); - - /** - * @brief The query from which you got this QuerySnapshot. - */ - virtual Query query() const; - - /** - * @brief Metadata about this snapshot, concerning its source and if it has - * local modifications. - * - * @return The metadata for this document snapshot. - */ - virtual SnapshotMetadata metadata() const; - - /** - * @brief The list of documents that changed since the last snapshot. - * - * If it's the first snapshot, all documents will be in the list as added - * changes. Documents with changes only to their metadata will not be - * included. - * - * @param[in] metadata_changes Indicates whether metadata-only changes (that - * is, only QuerySnapshot::metadata() changed) should be included. - * - * @return The list of document changes since the last snapshot. - */ - virtual std::vector DocumentChanges( - MetadataChanges metadata_changes = MetadataChanges::kExclude) const; - - /** - * @brief The list of documents in this QuerySnapshot in order of the query. - * - * @return The list of documents. - */ - virtual std::vector documents() const; - - /** - * @brief Checks the emptiness of the QuerySnapshot. - * - * @return True if there are no documents in the QuerySnapshot. - */ - bool empty() const { return size() == 0; } - - /** - * @brief Checks the size of the QuerySnapshot. - * - * @return The number of documents in the QuerySnapshot. - */ - virtual std::size_t size() const; - - /** - * @brief Returns true if this `QuerySnapshot` is valid, false if it is not - * valid. An invalid `QuerySnapshot` could be the result of: - * - Creating a `QuerySnapshot` using the default constructor. - * - Moving from the `QuerySnapshot`. - * - Deleting your Firestore instance, which will invalidate all the - * `QuerySnapshot` instances associated with it. - * - * @return true if this `QuerySnapshot` is valid, false if this - * `QuerySnapshot` is invalid. - */ - bool is_valid() const { return internal_ != nullptr; } - - private: - std::size_t Hash() const; - - friend bool operator==(const QuerySnapshot& lhs, const QuerySnapshot& rhs); - friend std::size_t QuerySnapshotHash(const QuerySnapshot& snapshot); - - friend class EventListenerInternal; - friend class FirestoreInternal; - friend struct ConverterImpl; - template - friend struct CleanupFn; - - explicit QuerySnapshot(QuerySnapshotInternal* internal); - - mutable QuerySnapshotInternal* internal_ = nullptr; -}; - -/** Checks `lhs` and `rhs` for equality. */ -bool operator==(const QuerySnapshot& lhs, const QuerySnapshot& rhs); - -/** Checks `lhs` and `rhs` for inequality. */ -inline bool operator!=(const QuerySnapshot& lhs, const QuerySnapshot& rhs) { - return !(lhs == rhs); -} - -} // namespace firestore -} // namespace firebase - -#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_QUERY_SNAPSHOT_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/set_options.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/set_options.h deleted file mode 100644 index bf21b07a0c45..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/set_options.h +++ /dev/null @@ -1,161 +0,0 @@ -/* - * Copyright 2018 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_SET_OPTIONS_H_ -#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_SET_OPTIONS_H_ - -#include -#include -#include - -#include "firebase/firestore/field_path.h" - -namespace firebase { -namespace firestore { - -/** - * @brief An options object that configures the behavior of Set() calls. - * - * By providing the SetOptions objects returned by Merge(), the Set() methods in - * DocumentReference, WriteBatch and Transaction can be configured to perform - * granular merges instead of overwriting the target documents in their - * entirety. - */ -class SetOptions final { - public: - /** The enumeration of all types of SetOptions. */ - enum class Type { - /** Overwrites the whole document. */ - kOverwrite, - - /** - * Replaces the values specified in the call parameter while leaves omitted - * fields untouched. - */ - kMergeAll, - - /** - * Replaces the values of the fields explicitly specified in the call - * parameter. - */ - kMergeSpecific, - }; - - /** - * Creates SetOptions with overwrite semantics. - */ - SetOptions() = default; - - /** - * @brief Copy constructor. - * - * This performs a deep copy, creating an independent instance. - * - * @param[in] other `SetOptions` to copy from. - */ - SetOptions(const SetOptions& other) = default; - - /** - * @brief Move constructor. - * - * Moving is more efficient than copying for `SetOptions`. After being moved - * from, `SetOptions` is in a valid but unspecified state. - * - * @param[in] other `SetOptions` to move data from. - */ - SetOptions(SetOptions&& other) = default; - - ~SetOptions(); - - /** - * @brief Copy assignment operator. - * - * This performs a deep copy, creating an independent instance. - * - * @param[in] other `SetOptions` to copy from. - * - * @return Reference to the destination `SetOptions`. - */ - SetOptions& operator=(const SetOptions& other) = default; - - /** - * @brief Move assignment operator. - * - * Moving is more efficient than copying for `SetOptions`. After being moved - * from, `SetOptions` is in a valid but unspecified state. - * - * @param[in] other `SetOptions` to move data from. - * - * @return Reference to the destination `SetOptions`. - */ - SetOptions& operator=(SetOptions&& other) = default; - - /** - * Returns an instance that can be used to change the behavior of Set() calls - * to only replace the values specified in its data argument. Fields omitted - * from the Set() call will remain untouched. - */ - static SetOptions Merge(); - - /** - * Returns an instance that can be used to change the behavior of Set() calls - * to only replace the given fields. Any field that is not specified in - * `fields` is ignored and remains untouched. - * - * It is an error to pass a SetOptions object to a Set() call that is missing - * a value for any of the fields specified here. - * - * @param fields The list of fields to merge. Fields can contain dots to - * reference nested fields within the document. - */ - static SetOptions MergeFields(const std::vector& fields); - - /** - * Returns an instance that can be used to change the behavior of Set() calls - * to only replace the given fields. Any field that is not specified in - * `fields` is ignored and remains untouched. - * - * It is an error to pass a SetOptions object to a Set() call that is missing - * a value for any of the fields specified here in its to data argument. - * - * @param fields The list of fields to merge. - */ - static SetOptions MergeFieldPaths(const std::vector& fields); - - private: - friend bool operator==(const SetOptions& lhs, const SetOptions& rhs); - friend class SetOptionsInternal; - - SetOptions(Type type, std::unordered_set fields); - - Type type_ = Type::kOverwrite; - std::unordered_set fields_; -}; - -/** Checks `lhs` and `rhs` for equality. */ -inline bool operator==(const SetOptions& lhs, const SetOptions& rhs) { - return lhs.type_ == rhs.type_ && lhs.fields_ == rhs.fields_; -} - -/** Checks `lhs` and `rhs` for inequality. */ -inline bool operator!=(const SetOptions& lhs, const SetOptions& rhs) { - return !(lhs == rhs); -} - -} // namespace firestore -} // namespace firebase - -#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_SET_OPTIONS_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/settings.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/settings.h deleted file mode 100644 index 8169d9f594e8..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/settings.h +++ /dev/null @@ -1,247 +0,0 @@ -/* - * Copyright 2018 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_SETTINGS_H_ -#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_SETTINGS_H_ - -#if defined(__OBJC__) -#include -#endif - -#include -#include -#include -#include - -namespace firebase { -namespace firestore { - -#if !defined(__ANDROID__) -// -// This declaration is guarded by a preprocessor macro because it causes -// problems with name lookup on Android. Android implementation of the public -// API extensively uses function calls of the form `util::Foo` which are -// expected to resolve to `::firebase::util::Foo`. As soon as namespace -// `::firebase::firestore::util` becomes visible, it shadows `::firebase::util` -// (within `::firebase::firestore`), so now all those calls fail to compile -// because they are interpreted as referring to -// `::firebase::firestore::util::Foo`, which doesn't exist. Changing existing -// code is impractical because such usages are numerous. -// -namespace util { -class Executor; -} -#endif - -class FirestoreInternal; - -/** Settings used to configure a Firestore instance. */ -class Settings final { - public: - /** - * Constant to use with `set_cache_size_bytes` to disable garbage collection. - */ - static constexpr int64_t kCacheSizeUnlimited = -1; - - /** - * @brief Creates the default settings. - */ - Settings(); - - /** - * @brief Copy constructor. - * - * This performs a deep copy, creating an independent instance. - * - * @param[in] other `Settings` to copy from. - */ - Settings(const Settings& other) = default; - - /** - * @brief Move constructor. - * - * Moving is more efficient than copying for `Settings`. After being moved - * from, `Settings` is in a valid but unspecified state. - * - * @param[in] other `Settings` to move data from. - */ - Settings(Settings&& other) = default; - - /** - * @brief Copy assignment operator. - * - * This performs a deep copy, creating an independent instance. - * - * @param[in] other `Settings` to copy from. - * - * @return Reference to the destination `Settings`. - */ - Settings& operator=(const Settings& other) = default; - - /** - * @brief Move assignment operator. - * - * Moving is more efficient than copying for `Settings`. After being moved - * from, `Settings` is in a valid but unspecified state. - * - * @param[in] other `Settings` to move data from. - * - * @return Reference to the destination `Settings`. - */ - Settings& operator=(Settings&& other) = default; - - /** - * Gets the host of the Firestore backend to connect to. - */ - const std::string& host() const { return host_; } - - /** - * Returns whether to use SSL when communicating. - */ - bool is_ssl_enabled() const { return ssl_enabled_; } - - /** - * Returns whether to enable local persistent storage. - */ - bool is_persistence_enabled() const { return persistence_enabled_; } - - /** Returns cache size for on-disk data. */ - int64_t cache_size_bytes() const { return cache_size_bytes_; } - - /** - * Sets the host of the Firestore backend. The default is - * "firestore.googleapis.com". - * - * @param host The host string. - */ - void set_host(std::string host); - - /** - * Enables or disables SSL for communication. - * - * @param enabled Set true to enable SSL for communication. - */ - void set_ssl_enabled(bool enabled); - - /** - * Enables or disables local persistent storage. - * - * @param enabled Set true to enable local persistent storage. - */ - void set_persistence_enabled(bool enabled); - - /** - * Sets an approximate cache size threshold for the on-disk data. If the cache - * grows beyond this size, Cloud Firestore will start removing data that - * hasn't been recently used. The size is not a guarantee that the cache will - * stay below that size, only that if the cache exceeds the given size, - * cleanup will be attempted. - * - * By default, collection is enabled with a cache size of 100 MB. The minimum - * value is 1 MB. - */ - void set_cache_size_bytes(int64_t value); - -#if defined(__OBJC__) || defined(DOXYGEN) - /** - * Returns a dispatch queue that Firestore will use to execute callbacks. - * - * The returned dispatch queue is used for all completion handlers and event - * handlers. - * - * If no dispatch queue is explictly set by calling `set_dispatch_queue()` - * then a dedicated "callback queue" will be used; namely, the main thread - * will not be used for callbacks unless expliclty set to do so by a call to - * `set_dispatch_queue()`. - * - * @note This method is only available when `__OBJC__` is defined, such as - * when compiling for iOS or tvOS. - * - * @see `set_dispatch_queue(dispatch_queue_t)` for information on how to - * explicitly set the dispatch queue to use. - */ - dispatch_queue_t dispatch_queue() const; - - /** - * Sets the dispatch queue that Firestore will use to execute callbacks. - * - * The specified dispatch queue will be used for all completion handlers and - * event handlers. - * - * @param queue The dispatch queue to use. - * - * @note This method is only available when `__OBJC__` is defined, such as - * when compiling for iOS or tvOS. - * - * @see `dispatch_queue()` for the "get" counterpart to this method. - */ - void set_dispatch_queue(dispatch_queue_t queue); -#endif // defined(__OBJC__) || defined(DOXYGEN) - - /** - * Returns a string representation of these `Settings` for - * logging/debugging purposes. - * - * @note the exact string representation is unspecified and subject to - * change; don't rely on the format of the string. - */ - std::string ToString() const; - - /** - * Outputs the string representation of these `Settings` to the given - * stream. - * - * @see `ToString()` for comments on the representation format. - */ - friend std::ostream& operator<<(std::ostream& out, const Settings& settings); - - private: - static constexpr int64_t kDefaultCacheSizeBytes = 100 * 1024 * 1024; - - std::string host_; - bool ssl_enabled_ = true; - bool persistence_enabled_ = true; - int64_t cache_size_bytes_ = kDefaultCacheSizeBytes; - - // - // TODO(varconst): fix Android problems and make these declarations - // unconditional. - // -#if !defined(__ANDROID__) - friend class FirestoreInternal; - std::unique_ptr CreateExecutor() const; - - std::shared_ptr executor_; -#endif -}; - -/** Checks `lhs` and `rhs` for equality. */ -inline bool operator==(const Settings& lhs, const Settings& rhs) { - return lhs.host() == rhs.host() && - lhs.is_ssl_enabled() == rhs.is_ssl_enabled() && - lhs.is_persistence_enabled() == rhs.is_persistence_enabled() && - lhs.cache_size_bytes() == rhs.cache_size_bytes(); -} - -/** Checks `lhs` and `rhs` for inequality. */ -inline bool operator!=(const Settings& lhs, const Settings& rhs) { - return !(lhs == rhs); -} - -} // namespace firestore -} // namespace firebase - -#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_SETTINGS_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/snapshot_metadata.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/snapshot_metadata.h deleted file mode 100644 index ce7f3f2b8607..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/snapshot_metadata.h +++ /dev/null @@ -1,159 +0,0 @@ -/* - * Copyright 2018 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_SNAPSHOT_METADATA_H_ -#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_SNAPSHOT_METADATA_H_ - -#include -#include - -namespace firebase { -namespace firestore { - -/** Metadata about a snapshot, describing the state of the snapshot. */ -class SnapshotMetadata final { - public: - /** - * Constructs a SnapshotMetadata that has all of its boolean members set to - * false. - */ - SnapshotMetadata() = default; - - /** - * Constructs a SnapshotMetadata by providing boolean parameters that describe - * the state of the snapshot. - * - * @param has_pending_writes Whether there is any pending write on the - * snapshot. - * @param is_from_cache Whether the snapshot is from cache instead of backend. - */ - SnapshotMetadata(bool has_pending_writes, bool is_from_cache) - : has_pending_writes_(has_pending_writes), - is_from_cache_(is_from_cache) {} - - /** - * @brief Copy constructor. - * - * This performs a deep copy, creating an independent instance. - * - * @note This class is currently trivially copyable, but it is not guaranteed - * to stay that way, and code relying on this might be broken by a future - * release. - * - * @param[in] other `SnapshotMetadata` to copy from. - */ - SnapshotMetadata(const SnapshotMetadata& other) = default; - - /** - * @brief Move constructor, equivalent to copying. - * - * After being moved from, `SnapshotMetadata` is in a valid but unspecified - * state. - * - * @param[in] other `SnapshotMetadata` to move data from. - */ - SnapshotMetadata(SnapshotMetadata&& other) = default; - - /** - * @brief Copy assignment operator. - * - * This performs a deep copy, creating an independent instance. - * - * @note This class is currently trivially copyable, but it is not guaranteed - * to stay that way, and code relying on this might be broken by a future - * release. - * - * @param[in] other `SnapshotMetadata` to copy from. - * - * @return Reference to the destination `SnapshotMetadata`. - */ - SnapshotMetadata& operator=(const SnapshotMetadata& other) = default; - - /** - * @brief Move assignment operator, equivalent to copying. - * - * After being moved from, `SnapshotMetadata` is in a valid but unspecified - * state. - * - * @param[in] other `SnapshotMetadata` to move data from. - * - * @return Reference to the destination `SnapshotMetadata`. - */ - SnapshotMetadata& operator=(SnapshotMetadata&& other) = default; - - /** - * Returns whether the snapshot contains the result of local writes. - * - * @return true if the snapshot contains the result of local writes (for - * example, Set() or Update() calls) that have not yet been committed to the - * backend. If your listener has opted into metadata updates (via - * MetadataChanges::kInclude) you will receive another snapshot with - * has_pending_writes() equal to false once the writes have been committed to - * the backend. - */ - bool has_pending_writes() const { return has_pending_writes_; } - - /** - * Returns whether the snapshot was created from cached data. - * - * @return true if the snapshot was created from cached data rather than - * guaranteed up-to-date server data. If your listener has opted into metadata - * updates (via MetadataChanges::kInclude) you will receive another snapshot - * with is_from_cache() equal to false once the client has received up-to-date - * data from the backend. - */ - bool is_from_cache() const { return is_from_cache_; } - - /** - * Returns a string representation of this `SnapshotMetadata` for - * logging/debugging purposes. - * - * @note the exact string representation is unspecified and subject to - * change; don't rely on the format of the string. - */ - std::string ToString() const; - - /** - * Outputs the string representation of this `SnapshotMetadata` to the given - * stream. - * - * @see `ToString()` for comments on the representation format. - */ - friend std::ostream& operator<<(std::ostream& out, - const SnapshotMetadata& metadata); - - private: - bool has_pending_writes_ = false; - bool is_from_cache_ = false; -}; - -/** Checks `lhs` and `rhs` for equality. */ -inline bool operator==(const SnapshotMetadata& lhs, - const SnapshotMetadata& rhs) { - return lhs.has_pending_writes() == rhs.has_pending_writes() && - lhs.is_from_cache() == rhs.is_from_cache(); -} - -/** Checks `lhs` and `rhs` for inequality. */ -inline bool operator!=(const SnapshotMetadata& lhs, - const SnapshotMetadata& rhs) { - return !(lhs == rhs); -} - -} // namespace firestore -} // namespace firebase - -#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_SNAPSHOT_METADATA_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/source.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/source.h deleted file mode 100644 index 743106d9e578..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/source.h +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright 2018 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_SOURCE_H_ -#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_SOURCE_H_ - -namespace firebase { -namespace firestore { - -/** - * @brief Configures the behavior of DocumentReference::Get() and Query::Get(). - * - * By providing a Source value, these methods can be configured to fetch results - * only from the server, only from the local cache, or attempt to fetch results - * from the server and fall back to the cache (which is the default). - */ -enum class Source { - /** - * Causes Firestore to try to retrieve an up-to-date (server-retrieved) - * snapshot, but fall back to returning cached data if the server can't be - * reached. - */ - kDefault, - - /** - * Causes Firestore to avoid the cache, generating an error if the server - * cannot be reached. Note that the cache will still be updated if the server - * request succeeds. Also note that latency-compensation still takes effect, - * so any pending write operations will be visible in the returned data - * (merged into the server-provided data). - */ - kServer, - - /** - * Causes Firestore to immediately return a value from the cache, ignoring the - * server completely (implying that the returned value may be stale with - * respect to the value on the server). If there is no data in the cache to - * satisfy the DocumentReference::Get() call will return an error and - * Query::Get() will return an empty QuerySnapshot with no documents. - */ - kCache, -}; - -} // namespace firestore -} // namespace firebase -#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_SOURCE_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/timestamp.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/timestamp.h deleted file mode 100644 index e806bb87c136..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/timestamp.h +++ /dev/null @@ -1,252 +0,0 @@ -/* - * Copyright 2018 Google - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIRESTORE_CORE_INCLUDE_FIREBASE_FIRESTORE_TIMESTAMP_H_ -#define FIRESTORE_CORE_INCLUDE_FIREBASE_FIRESTORE_TIMESTAMP_H_ - -#include -#include -#include -#include - -#if !defined(_STLPORT_VERSION) -#include // NOLINT(build/c++11) -#endif // !defined(_STLPORT_VERSION) - -namespace firebase { - -/** - * A Timestamp represents a point in time independent of any time zone or - * calendar, represented as seconds and fractions of seconds at nanosecond - * resolution in UTC Epoch time. It is encoded using the Proleptic Gregorian - * Calendar which extends the Gregorian calendar backwards to year one. It is - * encoded assuming all minutes are 60 seconds long, i.e. leap seconds are - * "smeared" so that no leap second table is needed for interpretation. Range is - * from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.999999999Z. - * - * @see - * https://github.com/google/protobuf/blob/master/src/google/protobuf/timestamp.proto - */ -class Timestamp { - public: - /** - * Creates a new timestamp representing the epoch (with seconds and - * nanoseconds set to 0). - */ - Timestamp() = default; - - /** - * Creates a new timestamp. - * - * @param seconds The number of seconds of UTC time since Unix epoch - * 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to - * 9999-12-31T23:59:59Z inclusive; otherwise, assertion failure will be - * triggered. - * @param nanoseconds The non-negative fractions of a second at nanosecond - * resolution. Negative second values with fractions must still have - * non-negative nanoseconds values that count forward in time. Must be - * from 0 to 999,999,999 inclusive; otherwise, assertion failure will be - * triggered. - */ - Timestamp(int64_t seconds, int32_t nanoseconds); - - /** Copy constructor, `Timestamp` is trivially copyable. */ - Timestamp(const Timestamp& other) = default; - - /** Move constructor, equivalent to copying. */ - Timestamp(Timestamp&& other) = default; - - /** Copy assignment operator, `Timestamp` is trivially copyable. */ - Timestamp& operator=(const Timestamp& other) = default; - - /** Move assignment operator, equivalent to copying. */ - Timestamp& operator=(Timestamp&& other) = default; - - /** - * Creates a new timestamp with the current date. - * - * The precision is up to nanoseconds, depending on the system clock. - * - * @return a new timestamp representing the current date. - */ - static Timestamp Now(); - - /** - * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z. - */ - int64_t seconds() const { - return seconds_; - } - - /** - * The non-negative fractions of a second at nanosecond resolution. Negative - * second values with fractions still have non-negative nanoseconds values - * that count forward in time. - */ - int32_t nanoseconds() const { - return nanoseconds_; - } - - /** - * Converts `time_t` to a `Timestamp`. - * - * @param seconds_since_unix_epoch - * @parblock - * The number of seconds of UTC time since Unix epoch - * 1970-01-01T00:00:00Z. Can be negative to represent dates before the - * epoch. Must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z - * inclusive; otherwise, assertion failure will be triggered. - * - * Note that while the epoch of `time_t` is unspecified, it's usually Unix - * epoch. If this assumption is broken, this function will produce - * incorrect results. - * @endparblock - * - * @return a new timestamp with the given number of seconds and zero - * nanoseconds. - */ - static Timestamp FromTimeT(time_t seconds_since_unix_epoch); - -#if !defined(_STLPORT_VERSION) - /** - * Converts `std::chrono::time_point` to a `Timestamp`. - * - * @param time_point - * @parblock - * The time point with system clock's epoch, which is - * presumed to be Unix epoch 1970-01-01T00:00:00Z. Can be negative to - * represent dates before the epoch. Must be from 0001-01-01T00:00:00Z to - * 9999-12-31T23:59:59Z inclusive; otherwise, assertion failure will be - * triggered. - * - * Note that while the epoch of `std::chrono::system_clock` is - * unspecified, it's usually Unix epoch. If this assumption is broken, - * this constructor will produce incorrect results. - * @endparblock - */ - static Timestamp FromTimePoint( - std::chrono::time_point time_point); - - /** - * Converts this `Timestamp` to a `time_point`. - * - * Important: if overflow would occur, the returned value will be the maximum - * or minimum value that `Duration` can hold. Note in particular that `long - * long` is insufficient to hold the full range of `Timestamp` values with - * nanosecond precision (which is why `Duration` defaults to `microseconds`). - */ - template - std::chrono::time_point ToTimePoint() const; -#endif // !defined(_STLPORT_VERSION) - - /** - * Returns a string representation of this `Timestamp` for logging/debugging - * purposes. - * - * @note: the exact string representation is unspecified and subject to - * change; don't rely on the format of the string. - */ - std::string ToString() const; - - /** - * Outputs the string representation of this `Timestamp` to the given stream. - * - * @see `ToString()` for comments on the representation format. - */ - friend std::ostream& operator<<(std::ostream& out, - const Timestamp& timestamp); - - private: - // Checks that the number of seconds is within the supported date range, and - // that nanoseconds satisfy 0 <= ns <= 1second. - void ValidateBounds() const; - - int64_t seconds_ = 0; - int32_t nanoseconds_ = 0; -}; - -/** Checks whether `lhs` and `rhs` are in ascending order. */ -inline bool operator<(const Timestamp& lhs, const Timestamp& rhs) { - return lhs.seconds() < rhs.seconds() || - (lhs.seconds() == rhs.seconds() && - lhs.nanoseconds() < rhs.nanoseconds()); -} - -/** Checks whether `lhs` and `rhs` are in descending order. */ -inline bool operator>(const Timestamp& lhs, const Timestamp& rhs) { - return rhs < lhs; -} - -/** Checks whether `lhs` and `rhs` are in non-ascending order. */ -inline bool operator>=(const Timestamp& lhs, const Timestamp& rhs) { - return !(lhs < rhs); -} - -/** Checks whether `lhs` and `rhs` are in non-descending order. */ -inline bool operator<=(const Timestamp& lhs, const Timestamp& rhs) { - return !(lhs > rhs); -} - -/** Checks `lhs` and `rhs` for inequality. */ -inline bool operator!=(const Timestamp& lhs, const Timestamp& rhs) { - return lhs < rhs || lhs > rhs; -} - -/** Checks `lhs` and `rhs` for equality. */ -inline bool operator==(const Timestamp& lhs, const Timestamp& rhs) { - return !(lhs != rhs); -} - -#if !defined(_STLPORT_VERSION) - -// Make sure the header compiles even when included after `` without -// `NOMINMAX` defined. `push/pop_macro` pragmas are supported by Visual Studio -// as well as Clang and GCC. -#pragma push_macro("min") -#pragma push_macro("max") -#undef min -#undef max - -template -std::chrono::time_point Timestamp::ToTimePoint() const { - namespace chr = std::chrono; - using TimePoint = chr::time_point; - - // Saturate on overflow - const auto max_seconds = chr::duration_cast(Duration::max()); - if (seconds_ > 0 && max_seconds.count() <= seconds_) { - return TimePoint{Duration::max()}; - } - const auto min_seconds = chr::duration_cast(Duration::min()); - if (seconds_ < 0 && min_seconds.count() >= seconds_) { - return TimePoint{Duration::min()}; - } - - const auto seconds = chr::duration_cast(chr::seconds(seconds_)); - const auto nanoseconds = - chr::duration_cast(chr::nanoseconds(nanoseconds_)); - return TimePoint{seconds + nanoseconds}; -} - -#pragma pop_macro("max") -#pragma pop_macro("min") - -#endif // !defined(_STLPORT_VERSION) - -} // namespace firebase - -#endif // FIRESTORE_CORE_INCLUDE_FIREBASE_FIRESTORE_TIMESTAMP_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/transaction.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/transaction.h deleted file mode 100644 index af78e0a2fb70..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/transaction.h +++ /dev/null @@ -1,143 +0,0 @@ -/* - * Copyright 2018 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_TRANSACTION_H_ -#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_TRANSACTION_H_ - -#include - -#include "firebase/firestore/firestore_errors.h" -#include "firebase/firestore/map_field_value.h" -#include "firebase/firestore/set_options.h" - -namespace firebase { -namespace firestore { - -class DocumentReference; -class DocumentSnapshot; -class TransactionInternal; - -/** - * @brief Transaction provides methods to read and write data within - * a transaction. - * - * You cannot create a `Transaction` directly; use `Firestore::RunTransaction()` - * function instead. - * - * @note Firestore classes are not meant to be subclassed except for use in test - * mocks. Subclassing is not supported in production code and new SDK releases - * may break code that does so. - */ -class Transaction { - public: - /** Destructor. */ - virtual ~Transaction(); - - /** - * @brief Deleted copy constructor. - * - * A `Transaction` object is only valid for the duration of the callback you - * pass to `Firestore::RunTransaction()` and cannot be copied. - */ - Transaction(const Transaction& other) = delete; - - /** - * @brief Deleted copy assignment operator. - * - * A `Transaction` object is only valid for the duration of the callback you - * pass to `Firestore::RunTransaction()` and cannot be copied. - */ - Transaction& operator=(const Transaction& other) = delete; - - /** - * @brief Writes to the document referred to by the provided reference. - * - * If the document does not yet exist, it will be created. If you pass - * SetOptions, the provided data can be merged into an existing document. - * - * @param[in] document The DocumentReference to overwrite. - * @param[in] data A map of the fields and values to write to the document. - * @param[in] options An object to configure the Set() behavior (optional). - */ - virtual void Set(const DocumentReference& document, - const MapFieldValue& data, - const SetOptions& options = SetOptions()); - - /** - * Updates fields in the document referred to by the provided reference. If no - * document exists yet, the update will fail. - * - * @param[in] document The DocumentReference to update. - * @param[in] data A map of field / value pairs to update. Fields can contain - * dots to reference nested fields within the document. - */ - virtual void Update(const DocumentReference& document, - const MapFieldValue& data); - - /** - * Updates fields in the document referred to by the provided reference. If no - * document exists yet, the update will fail. - * - * @param[in] document The DocumentReference to update. - * @param[in] data A map from FieldPath to FieldValue to update. - */ - virtual void Update(const DocumentReference& document, - const MapFieldPathValue& data); - - /** - * Deletes the document referred to by the provided reference. - * - * @param[in] document The DocumentReference to delete. - */ - virtual void Delete(const DocumentReference& document); - - /** - * Reads the document referred by the provided reference. - * - * @param[in] document The DocumentReference to read. - * @param[out] error_code An out parameter to capture an error, if one - * occurred. - * @param[out] error_message An out parameter to capture error message, if - * any. - * @return The contents of the document at this DocumentReference or invalid - * DocumentSnapshot if there is any error. - */ - virtual DocumentSnapshot Get(const DocumentReference& document, - Error* error_code, - std::string* error_message); - - protected: - /** - * Default constructor, to be used only for mocking a `Transaction`. - */ - Transaction() = default; - - private: - friend class FirestoreInternal; - friend class TransactionInternal; - friend struct ConverterImpl; - template - friend struct CleanupFn; - - explicit Transaction(TransactionInternal* internal); - - mutable TransactionInternal* internal_ = nullptr; -}; - -} // namespace firestore -} // namespace firebase - -#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_TRANSACTION_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/transaction_options.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/transaction_options.h deleted file mode 100644 index 9433578879b3..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/transaction_options.h +++ /dev/null @@ -1,137 +0,0 @@ -/* - * Copyright 2022 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_TRANSACTION_OPTIONS_H_ -#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_TRANSACTION_OPTIONS_H_ - -#include -#include -#include - -namespace firebase { -namespace firestore { - -/** - * Options to customize transaction behavior for `Firestore.runTransaction()`. - */ -class TransactionOptions final { - public: - /** - * @brief Creates the default `TransactionOptions`. - */ - TransactionOptions() = default; - - /** - * @brief Copy constructor. - * - * This performs a deep copy, creating an independent instance. - * - * @param[in] other `TransactionOptions` to copy from. - */ - TransactionOptions(const TransactionOptions& other) = default; - - /** - * @brief Move constructor. - * - * Moving is not any more efficient than copying for `TransactionOptions` - * because this class is trivially copyable; however, future additions to this - * class may make it not trivially copyable, at which point moving would be - * more efficient than copying. After being moved from, `TransactionOptions` - * is in a valid but unspecified state. - * - * @param[in] other `TransactionOptions` to move data from. - */ - TransactionOptions(TransactionOptions&& other) = default; - - /** - * @brief Copy assignment operator. - * - * This performs a deep copy, creating an independent instance. - * - * @param[in] other `TransactionOptions` to copy from. - * - * @return Reference to the destination `TransactionOptions`. - */ - TransactionOptions& operator=(const TransactionOptions& other) = default; - - /** - * @brief Move assignment operator. - * - * Moving is not any more efficient than copying for `TransactionOptions` - * because this class is trivially copyable; however, future additions to this - * class may make it not trivially copyable, at which point moving would be - * more efficient than copying. After being moved from, `TransactionOptions` - * is in a valid but unspecified state. - * - * @param[in] other `TransactionOptions` to move data from. - * - * @return Reference to the destination `TransactionOptions`. - */ - TransactionOptions& operator=(TransactionOptions&& other) = default; - - /** - * @brief Gets the maximum number of attempts to commit, after which the - * transaction fails. - * - * The default value is 5. - */ - int32_t max_attempts() const { return max_attempts_; } - - /** - * @brief Sets the maximum number of attempts to commit, after which the - * transaction fails. - * - * The default value is 5. - * - * @param[in] max_attempts The maximum number of attempts; must be greater - * than zero. - */ - void set_max_attempts(int32_t max_attempts); - - /** - * Returns a string representation of this `TransactionOptions` object for - * logging/debugging purposes. - * - * @note the exact string representation is unspecified and subject to - * change; don't rely on the format of the string. - */ - std::string ToString() const; - - /** - * Outputs the string representation of this `TransactionOptions` object to - * the given stream. - * - * @see `ToString()` for comments on the representation format. - */ - friend std::ostream& operator<<(std::ostream&, const TransactionOptions&); - - private: - int32_t max_attempts_ = 5; -}; - -/** Compares two `TransactionOptions` objects for equality. */ -bool operator==(const TransactionOptions&, const TransactionOptions&); - -/** Compares two `TransactionOptions` objects for inequality. */ -inline bool operator!=(const TransactionOptions& lhs, - const TransactionOptions& rhs) { - return !(lhs == rhs); -} - -} // namespace firestore -} // namespace firebase - -#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_TRANSACTION_OPTIONS_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/write_batch.h b/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/write_batch.h deleted file mode 100644 index 1e92cd693516..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/firestore/write_batch.h +++ /dev/null @@ -1,188 +0,0 @@ -/* - * Copyright 2018 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_WRITE_BATCH_H_ -#define FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_WRITE_BATCH_H_ - -#include "firebase/firestore/map_field_value.h" -#include "firebase/firestore/set_options.h" - -namespace firebase { - -/// @cond FIREBASE_APP_INTERNAL -template -class Future; -/// @endcond - -namespace firestore { - -class DocumentReference; -class WriteBatchInternal; - -/** - * @brief A write batch is used to perform multiple writes as a single atomic - * unit. - * - * A WriteBatch object provides methods for adding writes to the write batch. - * None of the writes will be committed (or visible locally) until Commit() is - * called. - * - * Unlike transactions, write batches are persisted offline and therefore are - * preferable when you don't need to condition your writes on read data. - * - * @note Firestore classes are not meant to be subclassed except for use in test - * mocks. Subclassing is not supported in production code and new SDK releases - * may break code that does so. - */ -class WriteBatch { - public: - /** - * @brief Creates an invalid WriteBatch that has to be reassigned before it - * can be used. - * - * Calling any member function on an invalid WriteBatch will be a no-op. If - * the function returns a value, it will return a zero, empty, or invalid - * value, depending on the type of the value. - */ - WriteBatch(); - - /** - * @brief Copy constructor. - * - * This performs a deep copy, creating an independent instance. - * - * @param[in] other `WriteBatch` to copy from. - */ - WriteBatch(const WriteBatch& other); - - /** - * @brief Move constructor. - * - * Moving is more efficient than copying for a `WriteBatch`. After being moved - * from, a `WriteBatch` is equivalent to its default-constructed state. - * - * @param[in] other `WriteBatch` to move data from. - */ - WriteBatch(WriteBatch&& other); - - virtual ~WriteBatch(); - - /** - * @brief Copy assignment operator. - * - * This performs a deep copy, creating an independent instance. - * - * @param[in] other `WriteBatch` to copy from. - * - * @return Reference to the destination `WriteBatch`. - */ - WriteBatch& operator=(const WriteBatch& other); - - /** - * @brief Move assignment operator. - * - * Moving is more efficient than copying for a `WriteBatch`. After being moved - * from, a `WriteBatch` is equivalent to its default-constructed state. - * - * @param[in] other `WriteBatch` to move data from. - * - * @return Reference to the destination `WriteBatch`. - */ - WriteBatch& operator=(WriteBatch&& other); - - /** - * @brief Writes to the document referred to by the provided reference. - * - * If the document does not yet exist, it will be created. If you pass - * SetOptions, the provided data can be merged into an existing document. - * - * @param document The DocumentReference to write to. - * @param data A map of the fields and values to write to the document. - * @param[in] options An object to configure the Set() behavior (optional). - * - * @return This WriteBatch instance. Used for chaining method calls. - */ - virtual WriteBatch& Set(const DocumentReference& document, - const MapFieldValue& data, - const SetOptions& options = SetOptions()); - - /** - * Updates fields in the document referred to by the provided reference. If no - * document exists yet, the update will fail. - * - * @param document The DocumentReference to update. - * @param data A map of field / value pairs to update. Fields can contain dots - * to reference nested fields within the document. - * @return This WriteBatch instance. Used for chaining method calls. - */ - virtual WriteBatch& Update(const DocumentReference& document, - const MapFieldValue& data); - - /** - * Updates fields in the document referred to by the provided reference. If no - * document exists yet, the update will fail. - * - * @param document The DocumentReference to update. - * @param data A map from FieldPath to FieldValue to update. - * @return This WriteBatch instance. Used for chaining method calls. - */ - virtual WriteBatch& Update(const DocumentReference& document, - const MapFieldPathValue& data); - - /** - * Deletes the document referred to by the provided reference. - * - * @param document The DocumentReference to delete. - * @return This WriteBatch instance. Used for chaining method calls. - */ - virtual WriteBatch& Delete(const DocumentReference& document); - - /** - * Commits all of the writes in this write batch as a single atomic unit. - * - * @return A Future that will be resolved when the write finishes. - */ - virtual Future Commit(); - - /** - * @brief Returns true if this `WriteBatch` is valid, false if it is not - * valid. An invalid `WriteBatch` could be the result of: - * - Creating a `WriteBatch` using the default constructor. - * - Moving from the `WriteBatch`. - * - Deleting your Firestore instance, which will invalidate all the - * `WriteBatch` instances associated with it. - * - * @return true if this `WriteBatch` is valid, false if this `WriteBatch` is - * invalid. - */ - bool is_valid() const { return internal_ != nullptr; } - - private: - friend class FirestoreInternal; - friend class WriteBatchInternal; - friend struct ConverterImpl; - template - friend struct CleanupFn; - - explicit WriteBatch(WriteBatchInternal* internal); - - mutable WriteBatchInternal* internal_ = nullptr; -}; - -} // namespace firestore -} // namespace firebase - -#endif // FIREBASE_FIRESTORE_SRC_INCLUDE_FIREBASE_FIRESTORE_WRITE_BATCH_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/functions.h b/packages/firebase_core/firebase_core/firebase_core/firebase/functions.h deleted file mode 100644 index 500a05cc7ae9..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/functions.h +++ /dev/null @@ -1,115 +0,0 @@ -// Copyright 2017 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef FIREBASE_FUNCTIONS_SRC_INCLUDE_FIREBASE_FUNCTIONS_H_ -#define FIREBASE_FUNCTIONS_SRC_INCLUDE_FIREBASE_FUNCTIONS_H_ - -#include - -#include "firebase/app.h" -#include "firebase/functions/callable_reference.h" -#include "firebase/functions/callable_result.h" -#include "firebase/functions/common.h" - -namespace firebase { - -/// Namespace for the Firebase C++ SDK for Cloud Functions. -namespace functions { - -/// @cond FIREBASE_APP_INTERNAL -namespace internal { -class FunctionsInternal; -} // namespace internal -/// @endcond - -class FunctionsReference; - -#ifndef SWIG -/// @brief Entry point for the Firebase C++ SDK for Cloud Functions. -/// -/// To use the SDK, call firebase::functions::Functions::GetInstance() to -/// obtain an instance of Functions, then use GetHttpsCallable() to obtain -/// references to callable functions. From there you can call them with -/// CallableReference::Call(). -#endif // SWIG -class Functions { - public: - /// @brief Destructor. You may delete an instance of Functions when - /// you are finished using it, to shut down the Functions library. - ~Functions(); - - /// @brief Get an instance of Functions corresponding to the given App. - /// - /// Cloud Functions uses firebase::App to communicate with Firebase - /// Authentication to authenticate users to the server backend. - /// - /// @param[in] app An instance of firebase::App. Cloud Functions will use - /// this to communicate with Firebase Authentication. - /// @param[out] init_result_out Optional: If provided, write the init result - /// here. Will be set to kInitResultSuccess if initialization succeeded, or - /// kInitResultFailedMissingDependency on Android if Google Play services is - /// not available on the current device. - /// - /// @returns An instance of Functions corresponding to the given App. - static Functions* GetInstance(::firebase::App* app, - InitResult* init_result_out = nullptr); - - /// @brief Get an instance of Functions corresponding to the given App. - /// - /// Cloud Functions uses firebase::App to communicate with Firebase - /// Authentication to authenticate users to the server backend. - /// - /// @param[in] app An instance of firebase::App. Cloud Functions will use - /// this to communicate with Firebase Authentication. - /// @param[in] region The region to call functions in. - /// @param[out] init_result_out Optional: If provided, write the init result - /// here. Will be set to kInitResultSuccess if initialization succeeded, or - /// kInitResultFailedMissingDependency on Android if Google Play services is - /// not available on the current device. - /// - /// @returns An instance of Functions corresponding to the given App. - static Functions* GetInstance(::firebase::App* app, const char* region, - InitResult* init_result_out = nullptr); - - /// @brief Get the firebase::App that this Functions was created with. - /// - /// @returns The firebase::App this Functions was created with. - ::firebase::App* app(); - - /// @brief Get a FunctionsReference for the specified path. - HttpsCallableReference GetHttpsCallable(const char* name) const; - - /// @brief Get a FunctionsReference for the specified URL. - HttpsCallableReference GetHttpsCallableFromURL(const char* url) const; - - /// @brief Sets an origin for a Cloud Functions emulator to use. - void UseFunctionsEmulator(const char* origin); - - private: - /// @cond FIREBASE_APP_INTERNAL - Functions(::firebase::App* app, const char* region); - Functions(const Functions& src); - Functions& operator=(const Functions& src); - - // Delete the internal_ data. - void DeleteInternal(); - - internal::FunctionsInternal* internal_; - /// @endcond -}; - -} // namespace functions -} // namespace firebase - -#endif // FIREBASE_FUNCTIONS_SRC_INCLUDE_FIREBASE_FUNCTIONS_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/functions/callable_reference.h b/packages/firebase_core/firebase_core/firebase_core/firebase/functions/callable_reference.h deleted file mode 100644 index 9641c23564df..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/functions/callable_reference.h +++ /dev/null @@ -1,124 +0,0 @@ -// Copyright 2017 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef FIREBASE_FUNCTIONS_SRC_INCLUDE_FIREBASE_FUNCTIONS_CALLABLE_REFERENCE_H_ -#define FIREBASE_FUNCTIONS_SRC_INCLUDE_FIREBASE_FUNCTIONS_CALLABLE_REFERENCE_H_ - -#include -#include - -#include "firebase/future.h" -#include "firebase/internal/common.h" - -namespace firebase { -class Variant; - -namespace functions { -class Functions; -class HttpsCallableResult; - -/// @cond FIREBASE_APP_INTERNAL -namespace internal { -class HttpsCallableReferenceInternal; -} // namespace internal -/// @endcond - -#ifndef SWIG -/// Represents a reference to a Cloud Functions object. -/// Developers can call HTTPS Callable Functions. -#endif // SWIG -class HttpsCallableReference { - public: - /// @brief Default constructor. This creates an invalid - /// HttpsCallableReference. Attempting to perform any operations on this - /// reference will fail unless a valid HttpsCallableReference has been - /// assigned to it. - HttpsCallableReference() : internal_(nullptr) {} - - ~HttpsCallableReference(); - - /// @brief Copy constructor. It's totally okay (and efficient) to copy - /// HttpsCallableReference instances, as they simply point to the same - /// location. - /// - /// @param[in] reference HttpsCallableReference to copy from. - HttpsCallableReference(const HttpsCallableReference& reference); - - /// @brief Copy assignment operator. It's totally okay (and efficient) to copy - /// HttpsCallableReference instances, as they simply point to the same - /// location. - /// - /// @param[in] reference HttpsCallableReference to copy from. - /// - /// @returns Reference to the destination HttpsCallableReference. - HttpsCallableReference& operator=(const HttpsCallableReference& reference); - -#if defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) - /// @brief Move constructor. Moving is an efficient operation for - /// HttpsCallableReference instances. - /// - /// @param[in] other HttpsCallableReference to move data from. - HttpsCallableReference(HttpsCallableReference&& other); - - /// @brief Move assignment operator. Moving is an efficient operation for - /// HttpsCallableReference instances. - /// - /// @param[in] other HttpsCallableReference to move data from. - /// - /// @returns Reference to the destination HttpsCallableReference. - HttpsCallableReference& operator=(HttpsCallableReference&& other); -#endif // defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) - - /// @brief Gets the firebase::functions::Functions instance to which we refer. - /// - /// The pointer will remain valid indefinitely. - /// - /// @returns The firebase::functions::Functions instance that this - /// HttpsCallableReference refers to. - Functions* functions(); - - /// @brief Calls the function. - /// - /// @returns The result of the call; - Future Call(); - - /// @brief Calls the function. - /// - /// @param[in] data The params to pass to the function. - /// @returns The result of the call; - Future Call(const Variant& data); - - /// @brief Returns true if this HttpsCallableReference is valid, false if it - /// is not valid. An invalid HttpsCallableReference indicates that the - /// reference is uninitialized (created with the default constructor) or that - /// there was an error retrieving the reference. - /// - /// @returns true if this HttpsCallableReference is valid, false if this - /// HttpsCallableReference is invalid. - bool is_valid() const; - - private: - /// @cond FIREBASE_APP_INTERNAL - friend class Functions; - - HttpsCallableReference(internal::HttpsCallableReferenceInternal* internal); - - internal::HttpsCallableReferenceInternal* internal_; - /// @endcond -}; - -} // namespace functions -} // namespace firebase - -#endif // FIREBASE_FUNCTIONS_SRC_INCLUDE_FIREBASE_FUNCTIONS_CALLABLE_REFERENCE_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/functions/callable_result.h b/packages/firebase_core/firebase_core/firebase_core/firebase/functions/callable_result.h deleted file mode 100644 index 5186377ae828..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/functions/callable_result.h +++ /dev/null @@ -1,96 +0,0 @@ -// Copyright 2018 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef FIREBASE_FUNCTIONS_SRC_INCLUDE_FIREBASE_FUNCTIONS_CALLABLE_RESULT_H_ -#define FIREBASE_FUNCTIONS_SRC_INCLUDE_FIREBASE_FUNCTIONS_CALLABLE_RESULT_H_ - -#include "firebase/functions/common.h" -#include "firebase/variant.h" - -namespace firebase { -namespace functions { - -/// @cond FIREBASE_APP_INTERNAL -namespace internal { -class HttpsCallableReferenceInternal; -} -/// @endcond - -/// An HttpsCallableResult contains the result of calling an HttpsCallable. -class HttpsCallableResult { - public: - /// @brief Creates an HttpsCallableResult with null data. - HttpsCallableResult() {} - - ~HttpsCallableResult() {} - - /// @brief Copy constructor. Copying is as efficient as copying a Variant. - /// - /// @param[in] other HttpsCallableResult to copy data from. - HttpsCallableResult(const HttpsCallableResult& other) : data_(other.data_) {} - - /// @brief Assignment operator. Copying is as efficient as copying a Variant. - /// - /// @param[in] other HttpsCallableResult to copy data from. - /// - /// @returns Reference to the destination HttpsCallableResult. - HttpsCallableResult& operator=(const HttpsCallableResult& other) { - data_ = other.data_; - return *this; - } - -#if defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) - /// @brief Move constructor. Moving is an efficient operation for - /// HttpsCallableResult instances. - /// - /// @param[in] other HttpsCallableResult to move data from. - HttpsCallableResult(HttpsCallableResult&& other) { - data_ = std::move(other.data_); - } - - /// @brief Move assignment operator. Moving is an efficient operation for - /// HttpsCallableResult instances. - /// - /// @param[in] other HttpsCallableResult to move data from. - /// - /// @returns Reference to the destination HttpsCallableResult. - HttpsCallableResult& operator=(HttpsCallableResult&& other) { - data_ = std::move(other.data_); - return *this; - } - -#endif // defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) - - /// @brief Returns the data that is the result of a Call. - /// - /// @returns The variant containing the data. - const Variant& data() const { return data_; } - - private: - /// @cond FIREBASE_APP_INTERNAL - // Only functions are allowed to construct results. - friend class ::firebase::functions::internal::HttpsCallableReferenceInternal; - HttpsCallableResult(const Variant& data) : data_(data) {} -#if defined(FIREBASE_USE_MOVE_OPERATORS) - HttpsCallableResult(Variant&& data) : data_(std::move(data)) {} -#endif // defined(FIREBASE_USE_MOVE_OPERATORS) - - Variant data_; - /// @endcond -}; - -} // namespace functions -} // namespace firebase - -#endif // FIREBASE_FUNCTIONS_SRC_INCLUDE_FIREBASE_FUNCTIONS_CALLABLE_RESULT_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/functions/common.h b/packages/firebase_core/firebase_core/firebase_core/firebase/functions/common.h deleted file mode 100644 index 143dc8257618..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/functions/common.h +++ /dev/null @@ -1,202 +0,0 @@ -// Copyright 2017 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef FIREBASE_FUNCTIONS_SRC_INCLUDE_FIREBASE_FUNCTIONS_COMMON_H_ -#define FIREBASE_FUNCTIONS_SRC_INCLUDE_FIREBASE_FUNCTIONS_COMMON_H_ - -#include "firebase/variant.h" - -namespace firebase { -namespace functions { - -/// Error code returned by Cloud Functions C++ functions. -/// Standard gRPC error codes, as defined in: -/// https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto -enum Error { -#ifdef INTERNAL_EXPERIMENTAL -// LINT.IfChange -#endif // INTERNAL_EXPERIMENTAL - - // Not an error; returned on success - // - // HTTP Mapping: 200 OK - kErrorNone = 0, - - // The operation was cancelled, typically by the caller. - // - // HTTP Mapping: 499 Client Closed Request - kErrorCancelled = 1, - - // Unknown error. For example, this error may be returned when - // a `Status` value received from another address space belongs to - // an error space that is not known in this address space. Also - // errors raised by APIs that do not return enough error information - // may be converted to this error. - // - // HTTP Mapping: 500 Internal Server Error - kErrorUnknown = 2, - - // The client specified an invalid argument. Note that this differs - // from `FAILED_PRECONDITION`. `INVALID_ARGUMENT` indicates arguments - // that are problematic regardless of the state of the system - // (e.g., a malformed file name). - // - // HTTP Mapping: 400 Bad Request - kErrorInvalidArgument = 3, - - // The deadline expired before the operation could complete. For operations - // that change the state of the system, this error may be returned - // even if the operation has completed successfully. For example, a - // successful response from a server could have been delayed long - // enough for the deadline to expire. - // - // HTTP Mapping: 504 Gateway Timeout - kErrorDeadlineExceeded = 4, - - // Some requested entity (e.g., file or directory) was not found. - // - // Note to server developers: if a request is denied for an entire class - // of users, such as gradual feature rollout or undocumented whitelist, - // `NOT_FOUND` may be used. If a request is denied for some users within - // a class of users, such as user-based access control, `PERMISSION_DENIED` - // must be used. - // - // HTTP Mapping: 404 Not Found - kErrorNotFound = 5, - - // The entity that a client attempted to create (e.g., file or directory) - // already exists. - // - // HTTP Mapping: 409 Conflict - kErrorAlreadyExists = 6, - - // The caller does not have permission to execute the specified - // operation. `PERMISSION_DENIED` must not be used for rejections - // caused by exhausting some resource (use `RESOURCE_EXHAUSTED` - // instead for those errors). `PERMISSION_DENIED` must not be - // used if the caller can not be identified (use `UNAUTHENTICATED` - // instead for those errors). This error code does not imply the - // request is valid or the requested entity exists or satisfies - // other pre-conditions. - // - // HTTP Mapping: 403 Forbidden - kErrorPermissionDenied = 7, - - // The request does not have valid authentication credentials for the - // operation. - // - // HTTP Mapping: 401 Unauthorized - kErrorUnauthenticated = 16, - - // Some resource has been exhausted, perhaps a per-user quota, or - // perhaps the entire file system is out of space. - // - // HTTP Mapping: 429 Too Many Requests - kErrorResourceExhausted = 8, - - // The operation was rejected because the system is not in a state - // required for the operation's execution. For example, the directory - // to be deleted is non-empty, an rmdir operation is applied to - // a non-directory, etc. - // - // Service implementors can use the following guidelines to decide - // between `FAILED_PRECONDITION`, `ABORTED`, and `UNAVAILABLE`: - // (a) Use `UNAVAILABLE` if the client can retry just the failing call. - // (b) Use `ABORTED` if the client should retry at a higher level - // (e.g., when a client-specified test-and-set fails, indicating the - // client should restart a read-modify-write sequence). - // (c) Use `FAILED_PRECONDITION` if the client should not retry until - // the system state has been explicitly fixed. E.g., if an "rmdir" - // fails because the directory is non-empty, `FAILED_PRECONDITION` - // should be returned since the client should not retry unless - // the files are deleted from the directory. - // - // HTTP Mapping: 400 Bad Request - kErrorFailedPrecondition = 9, - - // The operation was aborted, typically due to a concurrency issue such as - // a sequencer check failure or transaction abort. - // - // See the guidelines above for deciding between `FAILED_PRECONDITION`, - // `ABORTED`, and `UNAVAILABLE`. - // - // HTTP Mapping: 409 Conflict - kErrorAborted = 10, - - // The operation was attempted past the valid range. E.g., seeking or - // reading past end-of-file. - // - // Unlike `INVALID_ARGUMENT`, this error indicates a problem that may - // be fixed if the system state changes. For example, a 32-bit file - // system will generate `INVALID_ARGUMENT` if asked to read at an - // offset that is not in the range [0,2^32-1], but it will generate - // `OUT_OF_RANGE` if asked to read from an offset past the current - // file size. - // - // There is a fair bit of overlap between `FAILED_PRECONDITION` and - // `OUT_OF_RANGE`. We recommend using `OUT_OF_RANGE` (the more specific - // error) when it applies so that callers who are iterating through - // a space can easily look for an `OUT_OF_RANGE` error to detect when - // they are done. - // - // HTTP Mapping: 400 Bad Request - kErrorOutOfRange = 11, - - // The operation is not implemented or is not supported/enabled in this - // service. - // - // HTTP Mapping: 501 Not Implemented - kErrorUnimplemented = 12, - - // Internal errors. This means that some invariants expected by the - // underlying system have been broken. This error code is reserved - // for serious errors. - // - // HTTP Mapping: 500 Internal Server Error - kErrorInternal = 13, - - // The service is currently unavailable. This is most likely a - // transient condition, which can be corrected by retrying with - // a backoff. - // - // See the guidelines above for deciding between `FAILED_PRECONDITION`, - // `ABORTED`, and `UNAVAILABLE`. - // - // HTTP Mapping: 503 Service Unavailable - kErrorUnavailable = 14, - - // Unrecoverable data loss or corruption. - // - // HTTP Mapping: 500 Internal Server Error - kErrorDataLoss = 15, - -}; - -#ifdef INTERNAL_EXPERIMENTAL -/// @cond FIREBASE_APP_INTERNAL -namespace internal { - -// Get the human-readable error message corresponding to an error code. -// -// Returns a statically-allocated string describing the error code you pass in. -const char* GetErrorMessage(Error error); - -} // namespace internal -/// @endcond -#endif // INTERNAL_EXPERIMENTAL - -} // namespace functions -} // namespace firebase - -#endif // FIREBASE_FUNCTIONS_SRC_INCLUDE_FIREBASE_FUNCTIONS_COMMON_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/future.h b/packages/firebase_core/firebase_core/firebase_core/firebase/future.h deleted file mode 100644 index 0d09fc079a32..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/future.h +++ /dev/null @@ -1,533 +0,0 @@ -/* - * Copyright 2016 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_APP_SRC_INCLUDE_FIREBASE_FUTURE_H_ -#define FIREBASE_APP_SRC_INCLUDE_FIREBASE_FUTURE_H_ - -#include -#include - -#include - -#include "firebase/internal/common.h" -#include "firebase/internal/mutex.h" - -#ifdef FIREBASE_USE_STD_FUNCTION -#include -#endif - -namespace firebase { - -// Predeclarations. -/// @cond FIREBASE_APP_INTERNAL -namespace detail { -class FutureApiInterface; -class CompletionCallbackHandle; -} // namespace detail -/// @endcond - -/// Asynchronous call status. -enum FutureStatus { - /// Results are ready. - kFutureStatusComplete, - - /// Result is still being processed. - kFutureStatusPending, - - /// No result is pending. - /// FutureBase::Release() or move operator was called. - kFutureStatusInvalid -}; - -/// Handle that the API uses to identify an asynchronous call. -/// The exact interpretation of the handle is up to the API. -typedef uintptr_t FutureHandleId; - -/// Class that provides more context to FutureHandleId, which allows the -/// underlying API to track handles, perform reference counting, etc. -class FutureHandle { - public: - /// @cond FIREBASE_APP_INTERNAL - FutureHandle(); - explicit FutureHandle(FutureHandleId id) : FutureHandle(id, nullptr) {} - FutureHandle(FutureHandleId id, detail::FutureApiInterface* api); - ~FutureHandle(); - - // Copy constructor and assignment operator. - FutureHandle(const FutureHandle& rhs); - FutureHandle& operator=(const FutureHandle& rhs); - -#if defined(FIREBASE_USE_MOVE_OPERATORS) - // Move constructor and assignment operator. - FutureHandle(FutureHandle&& rhs) noexcept; - FutureHandle& operator=(FutureHandle&& rhs) noexcept; -#endif // defined(FIREBASE_USE_MOVE_OPERATORS) - - // Comparison operators. - bool operator!=(const FutureHandle& rhs) const { return !(*this == rhs); } - bool operator==(const FutureHandle& rhs) const { - // Only compare IDs, since the API is irrelevant (comparison will only occur - // within the context of a single API anyway). - return id() == rhs.id(); - } - - FutureHandleId id() const { return id_; } - detail::FutureApiInterface* api() const { return api_; } - - // Detach from the FutureApi. This handle will no longer increment the - // Future's reference count. This is mainly used for testing, so that you can - // still look up the Future based on its handle's ID without affecting the - // reference count yourself. - void Detach(); - - // Called by CleanupNotifier when the API is being deleted. At this point we - // can ignore all of the reference counts since all Future data is about to be - // deleted anyway. - void Cleanup() { api_ = nullptr; } - - private: - FutureHandleId id_; - detail::FutureApiInterface* api_; - /// @endcond -}; - -/// @brief Type-independent return type of asynchronous calls. -/// -/// @see Future for code samples. -/// -/// @cond FIREBASE_APP_INTERNAL -/// Notes: -/// - Futures have pointers back to the API, but the API does not maintain -/// pointers to its Futures. Therefore, all Futures must be destroyed -/// *before* the API is destroyed. -/// - Futures can be moved or copied. Call results are reference counted, -/// and are destroyed when they are no longer referenced by any Futures. -/// - The actual `Status`, `Error`, and `Result` values are kept inside the -/// API. This makes synchronization and data management easier. -/// -/// WARNING: This class should remain POD (plain old data). It should not have -/// virtual methods. Nor should the derived Future class add any -/// data. Internally, we static_cast FutureBase to Future, -/// so the underlying data should remain the same. -/// @endcond -class FutureBase { - public: - /// Function pointer for a completion callback. When we call this, we will - /// send the completed future, along with the user data that you specified - /// when you set up the callback. - typedef void (*CompletionCallback)(const FutureBase& result_data, - void* user_data); - -#if defined(INTERNAL_EXPERIMENTAL) - /// Handle, representing a completion callback, that can be passed to - /// RemoveOnCompletion. - using CompletionCallbackHandle = detail::CompletionCallbackHandle; -#endif - - /// Construct an untyped future. - FutureBase(); - - /// @cond FIREBASE_APP_INTERNAL - - /// Construct an untyped future using the specified API and handle. - /// - /// @param api API class used to provide the future implementation. - /// @param handle Handle to the future. - FutureBase(detail::FutureApiInterface* api, const FutureHandle& handle); - - /// @endcond - - ~FutureBase(); - - /// Copy constructor and operator. - /// Increment the reference count when creating a copy of the future. - FutureBase(const FutureBase& rhs); - - /// Copy an untyped future. - FutureBase& operator=(const FutureBase& rhs); - -#if defined(FIREBASE_USE_MOVE_OPERATORS) - /// Move constructor and operator. - /// Move is more efficient than copy and delete because we don't touch the - /// reference counting in the API. - FutureBase(FutureBase&& rhs) noexcept; - - /// Copy an untyped future. - FutureBase& operator=(FutureBase&& rhs) noexcept; -#endif // defined(FIREBASE_USE_MOVE_OPERATORS) - - /// Explicitly release the internal resources for a future. - /// Future will become invalid. - void Release(); - - /// Completion status of the asynchronous call. - FutureStatus status() const; - - /// When status() is firebase::kFutureStatusComplete, returns the API-defined - /// error code. Otherwise, return value is undefined. - int error() const; - - /// When status() is firebase::kFutureStatusComplete, returns the API-defined - /// error message, as human-readable text, or an empty string if the API does - /// not provide a human readable description of the error. - /// - /// @note The returned pointer is only valid for the lifetime of the Future - /// or its copies. - const char* error_message() const; - - /// Result of the asynchronous call, or nullptr if the result is still - /// pending. Cast is required since GetFutureResult() returns void*. - const void* result_void() const; - -#if defined(INTERNAL_EXPERIMENTAL) - /// Special timeout value indicating an infinite timeout. - /// - /// Passing this value to FutureBase::Wait() or Future::Await() will cause - /// those methods to wait until the future is complete. - /// - /// @Warning It is inadvisable to use this from code that could be called - /// from an event loop. - static const int kWaitTimeoutInfinite; - - /// Block (i.e. suspend the current thread) until either the future is - /// completed or the specified timeout period (in milliseconds) has elapsed. - /// If `timeout_milliseconds` is `kWaitTimeoutInfinite`, then the timeout - /// period is treated as being infinite, i.e. this will block until the - /// future is completed. - /// - /// @return True if the future completed, or - /// false if the timeout period elapsed before the future completed. - bool Wait(int timeout_milliseconds) const; -#endif // defined(INTERNAL_EXPERIMENTAL) - - /// Register a single callback that will be called at most once, when the - /// future is completed. - /// - /// If you call any OnCompletion() method more than once on the same future, - /// only the most recent callback you registered with OnCompletion() will be - /// called. -#if defined(INTERNAL_EXPERIMENTAL) - /// However completions registered with AddCompletion() will still be - /// called even if there is a subsequent call to OnCompletion(). - /// - /// When the future completes, first the most recent callback registered with - /// OnCompletion(), if any, will be called; then all callbacks registered with - /// AddCompletion() will be called, in the order that they were registered. -#endif - /// - /// When your callback is called, the user_data that you supplied here will be - /// passed back as the second parameter. - /// - /// @param[in] callback Function pointer to your callback. - /// @param[in] user_data Optional user data. We will pass this back to your - /// callback. - void OnCompletion(CompletionCallback callback, void* user_data) const; - -#if defined(FIREBASE_USE_STD_FUNCTION) || defined(DOXYGEN) - /// Register a single callback that will be called at most once, when the - /// future is completed. - /// - /// If you call any OnCompletion() method more than once on the same future, - /// only the most recent callback you registered with OnCompletion() will be - /// called. -#if defined(INTERNAL_EXPERIMENTAL) - /// However completions registered with AddCompletion() will still be - /// called even if there is a subsequent call to OnCompletion(). - /// - /// When the future completes, first the most recent callback registered with - /// OnCompletion(), if any, will be called; then all callbacks registered with - /// AddCompletion() will be called, in the order that they were registered. -#endif - /// - /// @param[in] callback Function or lambda to call. - /// - /// @note This method is not available when using STLPort on Android, as - /// `std::function` is not supported on STLPort. - void OnCompletion(std::function callback) const; -#endif // defined(FIREBASE_USE_STD_FUNCTION) || defined(DOXYGEN) - -#if defined(INTERNAL_EXPERIMENTAL) - /// Like OnCompletion, but allows adding multiple callbacks. - /// - /// If you call AddCompletion() more than once, all of the completions that - /// you register will be called, when the future is completed. However, any - /// callbacks which were subsequently removed by calling RemoveOnCompletion - /// will not be called. - /// - /// When the future completes, first the most recent callback registered with - /// OnCompletion(), if any, will be called; then all callbacks registered with - /// AddCompletion() will be called, in the order that they were registered. - /// - /// @param[in] callback Function pointer to your callback. - /// @param[in] user_data Optional user data. We will pass this back to your - /// callback. - /// @return A handle that can be passed to RemoveOnCompletion. - CompletionCallbackHandle AddOnCompletion(CompletionCallback callback, - void* user_data) const; - -#if defined(FIREBASE_USE_STD_FUNCTION) || defined(DOXYGEN) - /// Like OnCompletion, but allows adding multiple callbacks. - /// - /// If you call AddCompletion() more than once, all of the completions that - /// you register will be called, when the future is completed. However, any - /// callbacks which were subsequently removed by calling RemoveOnCompletion - /// will not be called. - /// - /// When the future completes, first the most recent callback registered with - /// OnCompletion(), if any, will be called; then all callbacks registered with - /// AddCompletion() will be called, in the order that they were registered. - /// - /// @param[in] callback Function or lambda to call. - /// @return A handle that can be passed to RemoveOnCompletion. - /// - /// @note This method is not available when using STLPort on Android, as - /// `std::function` is not supported on STLPort. - CompletionCallbackHandle AddOnCompletion( - std::function callback) const; - -#endif // defined(FIREBASE_USE_STD_FUNCTION) || defined(DOXYGEN) - - /// Unregisters a callback that was previously registered with - /// AddOnCompletion. - /// - /// @param[in] completion_handle The return value of a previous call to - /// AddOnCompletion. - void RemoveOnCompletion(CompletionCallbackHandle completion_handle) const; -#endif // defined(INTERNAL_EXPERIMENTAL) - - /// Returns true if the two Futures reference the same result. - bool operator==(const FutureBase& rhs) const { - MutexLock lock(mutex_); - return api_ == rhs.api_ && handle_ == rhs.handle_; - } - - /// Returns true if the two Futures reference different results. - bool operator!=(const FutureBase& rhs) const { return !operator==(rhs); } - -#if defined(INTERNAL_EXPERIMENTAL) - /// Returns the API-specific handle. Should only be called by the API. - FutureHandle GetHandle() const { - MutexLock lock(mutex_); - return handle_; - } -#endif // defined(INTERNAL_EXPERIMENTAL) - - protected: - /// @cond FIREBASE_APP_INTERNAL - - mutable Mutex mutex_; - - /// Backpointer to the issuing API class. - /// Set to nullptr when Future is invalidated. - detail::FutureApiInterface* api_; - - /// API-specified handle type. - FutureHandle handle_; - - /// @endcond -}; - -/// @brief Type-specific version of FutureBase. -/// -/// The Firebase C++ SDK uses this class to return results from asynchronous -/// operations. All Firebase C++ functions and method calls that operate -/// asynchronously return a Future, and provide a "LastResult" function to -/// retrieve the most recent Future result. -/// -/// @code -/// // You can retrieve the Future from the function call directly, like this: -/// Future< SampleResultType > future = firebase::SampleAsyncOperation(); -/// -/// // Or you can retrieve it later, like this: -/// firebase::SampleAsyncOperation(); -/// // [...] -/// Future< SampleResultType > future = -/// firebase::SampleAsyncOperationLastResult(); -/// @endcode -/// -/// When you have a Future from an asynchronous operation, it will eventually -/// complete. Once it is complete, you can check for errors (a nonzero error() -/// means an error occurred) and get the result data if no error occurred by -/// calling result(). -/// -/// There are two ways to find out that a Future has completed. You can poll -/// its status(), or set an OnCompletion() callback: -/// -/// @code -/// // Check whether the status is kFutureStatusComplete. -/// if (future.status() == firebase::kFutureStatusComplete) { -/// if (future.error() == 0) { -/// DoSomethingWithResultData(future.result()); -/// } -/// else { -/// LogMessage("Error %d: %s", future.error(), future.error_message()); -/// } -/// } -/// -/// // Or, set an OnCompletion callback, which accepts a C++11 lambda or -/// // function pointer. You can pass your own user data to the callback. In -/// // most cases, the callback will be running in a different thread, so take -/// // care to make sure your code is thread-safe. -/// future.OnCompletion([](const Future< SampleResultType >& completed_future, -/// void* user_data) { -/// // We are probably in a different thread right now. -/// if (completed_future.error() == 0) { -/// DoSomethingWithResultData(completed_future.result()); -/// } -/// else { -/// LogMessage("Error %d: %s", -/// completed_future.error(), -/// completed_future.error_message()); -/// } -/// }, user_data); -/// @endcode -/// -/// @tparam ResultType The type of this Future's result. -// -// WARNING: This class should not have virtual methods or data members. -// See the warning in FutureBase for further details. -template -class Future : public FutureBase { - public: - /// Function pointer for a completion callback. When we call this, we will - /// send the completed future, along with the user data that you specified - /// when you set up the callback. - typedef void (*TypedCompletionCallback)(const Future& result_data, - void* user_data); - - /// Construct a future. - Future() {} - - /// @cond FIREBASE_APP_INTERNAL - - /// Construct a future using the specified API and handle. - /// - /// @param api API class used to provide the future implementation. - /// @param handle Handle to the future. - Future(detail::FutureApiInterface* api, const FutureHandle& handle) - : FutureBase(api, handle) {} - - /// @endcond - - /// Result of the asynchronous call, or nullptr if the result is still - /// pending. Allows the API to provide a type-specific interface. - /// - const ResultType* result() const { - return static_cast(result_void()); - } - -#if defined(INTERNAL_EXPERIMENTAL) - /// Waits (blocks) until either the future is completed, or the specified - /// timeout period (in milliseconds) has elapsed, then returns the result of - /// the asynchronous call. - /// - /// This is a convenience method that calls Wait() and then returns result(). - /// - /// If `timeout_milliseconds` is `kWaitTimeoutInfinite`, then the timeout - /// period is treated as being infinite, i.e. this will block until the - /// future is completed. - const ResultType* Await(int timeout_milliseconds) const { - Wait(timeout_milliseconds); - return result(); - } -#endif // defined(INTERNAL_EXPERIMENTAL) - - /// Register a single callback that will be called at most once, when the - /// future is completed. - /// - /// If you call any OnCompletion() method more than once on the same future, - /// only the most recent callback you registered will be called. - /// - /// When your callback is called, the user_data that you supplied here will be - /// passed back as the second parameter. - /// - /// @param[in] callback Function pointer to your callback. - /// @param[in] user_data Optional user data. We will pass this back to your - /// callback. - /// - /// @note This is the same callback as FutureBase::OnCompletion(), so you - /// can't expect to set both and have both run; again, only the most recently - /// registered one will run. - inline void OnCompletion(TypedCompletionCallback callback, - void* user_data) const; - -#if defined(FIREBASE_USE_STD_FUNCTION) || defined(DOXYGEN) - /// Register a single callback that will be called at most once, when the - /// future is completed. - /// - /// If you call any OnCompletion() method more than once on the same future, - /// only the most recent callback you registered will be called. - /// - /// @param[in] callback Function or lambda to call. - /// - /// @note This method is not available when using STLPort on Android, as - /// `std::function` is not supported on STLPort. - /// - /// @note This is the same callback as FutureBase::OnCompletion(), so you - /// can't expect to set both and have both run; again, only the most recently - /// registered one will run. - inline void OnCompletion( - std::function&)> callback) const; -#endif // defined(FIREBASE_USE_STD_FUNCTION) || defined(DOXYGEN) - -#if defined(INTERNAL_EXPERIMENTAL) - /// Like OnCompletion, but allows adding multiple callbacks. - /// - /// If you call AddCompletion() more than once, all of the completions that - /// you register will be called, when the future is completed. However, any - /// callbacks which were subsequently removed by calling RemoveOnCompletion - /// will not be called. - /// - /// When the future completes, first the most recent callback registered with - /// OnCompletion(), if any, will be called; then all callbacks registered with - /// AddCompletion() will be called, in the order that they were registered. - /// - /// @param[in] callback Function pointer to your callback. - /// @param[in] user_data Optional user data. We will pass this back to your - /// callback. - /// @return A handle that can be passed to RemoveOnCompletion. - inline CompletionCallbackHandle AddOnCompletion( - TypedCompletionCallback callback, void* user_data) const; - -#if defined(FIREBASE_USE_STD_FUNCTION) || defined(DOXYGEN) - /// Like OnCompletion, but allows adding multiple callbacks. - /// - /// If you call AddCompletion() more than once, all of the completions that - /// you register will be called, when the future is completed. However, any - /// callbacks which were subsequently removed by calling RemoveOnCompletion - /// will not be called. - /// - /// When the future completes, first the most recent callback registered with - /// OnCompletion(), if any, will be called; then all callbacks registered with - /// AddCompletion() will be called, in the order that they were registered. - /// - /// @param[in] callback Function or lambda to call. - /// @return A handle that can be passed to RemoveOnCompletion. - /// - /// @note This method is not available when using STLPort on Android, as - /// `std::function` is not supported on STLPort. - inline CompletionCallbackHandle AddOnCompletion( - std::function&)> callback) const; -#endif // defined(FIREBASE_USE_STD_FUNCTION) || defined(DOXYGEN) -#endif // defined(INTERNAL_EXPERIMENTAL) -}; - -} // namespace firebase - -// Include the inline implementation. -#include "firebase/internal/future_impl.h" - -#endif // FIREBASE_APP_SRC_INCLUDE_FIREBASE_FUTURE_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/gma.h b/packages/firebase_core/firebase_core/firebase_core/firebase/gma.h deleted file mode 100644 index b7da2cf569b9..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/gma.h +++ /dev/null @@ -1,207 +0,0 @@ -/* - * Copyright 2021 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_GMA_SRC_INCLUDE_FIREBASE_GMA_H_ -#define FIREBASE_GMA_SRC_INCLUDE_FIREBASE_GMA_H_ - -#include "firebase/internal/platform.h" - -#if FIREBASE_PLATFORM_ANDROID -#include -#endif // FIREBASE_PLATFORM_ANDROID - -#include - -#include "firebase/app.h" -#include "firebase/gma/ad_view.h" -#include "firebase/gma/interstitial_ad.h" -#include "firebase/gma/rewarded_ad.h" -#include "firebase/gma/types.h" -#include "firebase/internal/common.h" - -#if !defined(DOXYGEN) && !defined(SWIG) -FIREBASE_APP_REGISTER_CALLBACKS_REFERENCE(gma) -#endif // !defined(DOXYGEN) && !defined(SWIG) - -namespace firebase { -// In the GMA docs, link to firebase::Future in the Firebase C++ docs. -#if defined(DOXYGEN_ADMOB) -/// @brief The Google Mobile Ads C++ SDK uses this class to return results from -/// asynchronous operations. All C++ functions and method calls that operate -/// asynchronously return a %Future, and provide a "LastResult" -/// function to retrieve the most recent %Future result. -/// -/// The Google Mobile Ads C++ SDK uses this class from the Firebase C++ SDK to -/// return results from asynchronous operations. For more information, see the -/// Firebase -/// C++ SDK documentation. -template -class Future { - // Empty class (used for documentation only). -}; -#endif // defined(DOXYGEN_ADMOB) - -/// @brief API for Google Mobile Ads with Firebase. -/// -/// The GMA API allows you to load and display mobile ads using the Google -/// Mobile Ads SDK. Each ad format has its own header file. -namespace gma { - -/// Initializes Google Mobile Ads (GMA) via Firebase. -/// -/// @param[in] app The Firebase app for which to initialize mobile ads. -/// -/// @param[out] init_result_out Optional: If provided, write the basic init -/// result here. kInitResultSuccess if initialization succeeded, or -/// kInitResultFailedMissingDependency on Android if Google Play services is not -/// available on the current device and the Google Mobile Ads SDK requires -/// Google Play services (for example, when using 'play-services-ads-lite'). -/// Note that this does not include the adapter initialization status, which is -/// returned in the Future. -/// -/// @return If init_result_out is kInitResultSuccess, this Future will contain -/// the initialization status of each adapter once initialization is complete. -/// Otherwise, the returned Future will have kFutureStatusInvalid. -Future Initialize( - const ::firebase::App& app, InitResult* init_result_out = nullptr); - -#if FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) -/// Initializes Google Mobile Ads (GMA) without Firebase for Android. -/// -/// The arguments to @ref Initialize are platform-specific so the caller must do -/// something like this: -/// @code -/// #if defined(__ANDROID__) -/// firebase::gma::Initialize(jni_env, activity); -/// #else -/// firebase::gma::Initialize(); -/// #endif -/// @endcode -/// -/// @param[in] jni_env JNIEnv pointer. -/// @param[in] activity Activity used to start the application. -/// @param[out] init_result_out Optional: If provided, write the basic init -/// result here. kInitResultSuccess if initialization succeeded, or -/// kInitResultFailedMissingDependency on Android if Google Play services is not -/// available on the current device and the Google Mobile Ads SDK requires -/// Google Play services (for example, when using 'play-services-ads-lite'). -/// Note that this does not include the adapter initialization status, which is -/// returned in the Future. -/// -/// @return If init_result_out is kInitResultSuccess, this Future will contain -/// the initialization status of each adapter once initialization is complete. -/// Otherwise, the returned Future will have kFutureStatusInvalid. -Future Initialize( - JNIEnv* jni_env, jobject activity, InitResult* init_result_out = nullptr); - -#endif // defined(__ANDROID__) || defined(DOXYGEN) -#if !FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) -/// Initializes Google Mobile Ads (GMA) without Firebase for iOS. -/// -/// @param[out] init_result_out Optional: If provided, write the basic init -/// result here. kInitResultSuccess if initialization succeeded, or -/// kInitResultFailedMissingDependency on Android if Google Play services is not -/// available on the current device and the Google Mobile Ads SDK requires -/// Google Play services (for example, when using 'play-services-ads-lite'). -/// Note that this does not include the adapter initialization status, which is -/// returned in the Future. -/// -/// @return If init_result_out is kInitResultSuccess, this Future -/// will contain the initialization status of each adapter once initialization -/// is complete. Otherwise, the returned Future will have -/// kFutureStatusInvalid. -Future Initialize( - InitResult* init_result_out = nullptr); -#endif // !defined(__ANDROID__) || defined(DOXYGEN) - -/// Get the Future returned by a previous call to -/// @ref firebase::gma::Initialize(). -Future InitializeLastResult(); - -/// Get the current adapter initialization status. You can poll this method to -/// check which adapters have been initialized. -AdapterInitializationStatus GetInitializationStatus(); - -/// Disables automated SDK crash reporting on iOS. If not called, the SDK -/// records the original exception handler if available and registers a new -/// exception handler. The new exception handler only reports SDK related -/// exceptions and calls the recorded original exception handler. -/// -/// This method has no effect on Android. -void DisableSDKCrashReporting(); - -/// Disables mediation adapter initialization on iOS during initialization of -/// the GMA SDK. Calling this method may negatively impact your ad -/// performance and should only be called if you will not use GMA SDK -/// controlled mediation during this app session. This method must be called -/// before initializing the GMA SDK or loading ads and has no effect once the -/// SDK has been initialized. -/// -/// This method has no effect on Android. -void DisableMediationInitialization(); - -/// Sets the global @ref RequestConfiguration that will be used for -/// every @ref AdRequest during the app's session. -/// -/// @param[in] request_configuration The request configuration that should be -/// applied to all ad requests. -void SetRequestConfiguration(const RequestConfiguration& request_configuration); - -/// Gets the global RequestConfiguration. -/// -/// @return the currently active @ref RequestConfiguration that's being -/// used for every ad request. -/// @note: on iOS, the -/// @ref RequestConfiguration::tag_for_child_directed_treatment and -/// @ref RequestConfiguration::tag_for_under_age_of_consent fields will be set -/// to RequestConfiguration.kChildDirectedTreatmentUnspecified, and -/// RequestConfiguration.kUnderAgeOfConsentUnspecified, respectfully. -RequestConfiguration GetRequestConfiguration(); - -/// Opens the ad inspector UI. -/// -/// @param[in] parent The platform-specific UI element that will host the -/// ad inspector. For iOS this should be the window's -/// UIViewController. For Android this is the -/// Activity Context which the GMA SDK is running in. -/// @param[in] listener The listener will be invoked when the user closes -/// the ad inspector UI. @ref firebase::gma::Initialize(). must be called -/// prior to this function. -void OpenAdInspector(AdParent parent, AdInspectorClosedListener* listener); - -/// Controls whether the Google Mobile Ads SDK Same App Key is enabled. -/// -/// This function must be invoked after GMA has been initialized. The value set -/// persists across app sessions. The key is enabled by default. -/// -/// This operation is supported on iOS only. This is a no-op on Android -/// systems. -/// -/// @param[in] is_enabled whether the Google Mobile Ads SDK Same App Key is -/// enabled. -void SetIsSameAppKeyEnabled(bool is_enabled); - -/// @brief Terminate GMA. -/// -/// Frees resources associated with GMA that were allocated during -/// @ref firebase::gma::Initialize(). -void Terminate(); - -} // namespace gma -} // namespace firebase - -#endif // FIREBASE_GMA_SRC_INCLUDE_FIREBASE_GMA_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/gma/ad_view.h b/packages/firebase_core/firebase_core/firebase_core/firebase/gma/ad_view.h deleted file mode 100644 index 16916a21665f..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/gma/ad_view.h +++ /dev/null @@ -1,267 +0,0 @@ -/* - * Copyright 2021 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_GMA_SRC_INCLUDE_FIREBASE_GMA_AD_VIEW_H_ -#define FIREBASE_GMA_SRC_INCLUDE_FIREBASE_GMA_AD_VIEW_H_ - -#include "firebase/future.h" -#include "firebase/gma/types.h" -#include "firebase/internal/common.h" - -namespace firebase { -namespace gma { - -namespace internal { -// Forward declaration for platform-specific data, implemented in each library. -class AdViewInternal; -} // namespace internal - -class AdViewBoundingBoxListener; -struct BoundingBox; - -/// @brief Loads and displays Google Mobile Ads AdView ads. -/// -/// Each AdView object corresponds to a single GMA ad placement of a specified -/// size. There are methods to load an ad, move it, show it and hide it, and -/// retrieve the bounds of the ad onscreen. -/// -/// AdView objects provide information about their current state through -/// Futures. Methods like @ref Initialize, @ref LoadAd, and @ref Hide each have -/// a corresponding @ref Future from which the result of the last call can be -/// determined. The two variants of @ref SetPosition share a single result -/// @ref Future, since they're essentially the same action. -/// -/// For example, you could initialize, load, and show an AdView while -/// checking the result of the previous action at each step as follows: -/// -/// @code -/// namespace gma = ::firebase::gma; -/// gma::AdView* ad_view = new gma::AdView(); -/// ad_view->Initialize(ad_parent, "YOUR_AD_UNIT_ID", desired_ad_size) -/// @endcode -/// -/// Then, later: -/// -/// @code -/// if (ad_view->InitializeLastResult().status() == -/// ::firebase::kFutureStatusComplete && -/// ad_view->InitializeLastResult().error() == -/// firebase::gma::kAdErrorCodeNone) { -/// ad_view->LoadAd(your_ad_request); -/// } -/// @endcode -class AdView { - public: - /// The possible screen positions for a @ref AdView, configured via - /// @ref SetPosition. - enum Position { - /// The position isn't one of the predefined screen locations. - kPositionUndefined = -1, - /// Top of the screen, horizontally centered. - kPositionTop = 0, - /// Bottom of the screen, horizontally centered. - kPositionBottom, - /// Top-left corner of the screen. - kPositionTopLeft, - /// Top-right corner of the screen. - kPositionTopRight, - /// Bottom-left corner of the screen. - kPositionBottomLeft, - /// Bottom-right corner of the screen. - kPositionBottomRight, - }; - - /// Creates an uninitialized @ref AdView object. - /// @ref Initialize must be called before the object is used. - AdView(); - - ~AdView(); - - /// Initializes the @ref AdView object. - /// @param[in] parent The platform-specific UI element that will host the ad. - /// @param[in] ad_unit_id The ad unit ID to use when requesting ads. - /// @param[in] size The desired ad size for the ad. - Future Initialize(AdParent parent, const char* ad_unit_id, - const AdSize& size); - - /// Returns a @ref Future that has the status of the last call to - /// @ref Initialize. - Future InitializeLastResult() const; - - /// Begins an asynchronous request for an ad. If successful, the ad will - /// automatically be displayed in the AdView. - /// @param[in] request An AdRequest struct with information about the request - /// to be made (such as targeting info). - Future LoadAd(const AdRequest& request); - - /// Returns a @ref Future containing the status of the last call to - /// @ref LoadAd. - Future LoadAdLastResult() const; - - /// Retrieves the @ref AdView's current onscreen size and location. - /// - /// @return The current size and location. Values are in pixels, and location - /// coordinates originate from the top-left corner of the screen. - BoundingBox bounding_box() const; - - /// Sets an AdListener for this ad view. - /// - /// @param[in] listener An AdListener object which will be invoked - /// when lifecycle events occur on this AdView. - void SetAdListener(AdListener* listener); - - /// Sets a listener to be invoked when the Ad's bounding box - /// changes size or location. - /// - /// @param[in] listener A AdViewBoundingBoxListener object which will be - /// invoked when the ad changes size, shape, or position. - void SetBoundingBoxListener(AdViewBoundingBoxListener* listener); - - /// Sets a listener to be invoked when this ad is estimated to have earned - /// money. - /// - /// @param[in] listener A PaidEventListener object to be invoked when a - /// paid event occurs on the ad. - void SetPaidEventListener(PaidEventListener* listener); - - /// Moves the @ref AdView so that its top-left corner is located at - /// (x, y). Coordinates are in pixels from the top-left corner of the screen. - /// - /// When built for Android, the library will not display an ad on top of or - /// beneath an Activity's status bar. If a call to SetPostion - /// would result in an overlap, the @ref AdView is placed just below the - /// status bar, so no overlap occurs. - /// @param[in] x The desired horizontal coordinate. - /// @param[in] y The desired vertical coordinate. - /// - /// @return a @ref Future which will be completed when this move operation - /// completes. - Future SetPosition(int x, int y); - - /// Moves the @ref AdView so that it's located at the given predefined - /// position. - /// - /// @param[in] position The predefined position to which to move the - /// @ref AdView. - /// - /// @return a @ref Future which will be completed when this move operation - /// completes. - Future SetPosition(Position position); - - /// Returns a @ref Future containing the status of the last call to either - /// version of @ref SetPosition. - Future SetPositionLastResult() const; - - /// Hides the AdView. - Future Hide(); - - /// Returns a @ref Future containing the status of the last call to - /// @ref Hide. - Future HideLastResult() const; - - /// Shows the @ref AdView. - Future Show(); - - /// Returns a @ref Future containing the status of the last call to - /// @ref Show. - Future ShowLastResult() const; - - /// Pauses the @ref AdView. Should be called whenever the C++ engine - /// pauses or the application loses focus. - Future Pause(); - - /// Returns a @ref Future containing the status of the last call to - /// @ref Pause. - Future PauseLastResult() const; - - /// Resumes the @ref AdView after pausing. - Future Resume(); - - /// Returns a @ref Future containing the status of the last call to - /// @ref Resume. - Future ResumeLastResult() const; - - /// Cleans up and deallocates any resources used by the @ref AdView. - /// You must call this asynchronous operation before this object's destructor - /// is invoked or risk leaking device resources. - Future Destroy(); - - /// Returns a @ref Future containing the status of the last call to - /// @ref Destroy. - Future DestroyLastResult() const; - - /// Returns the AdSize of the AdView. - /// - /// @return An @ref AdSize object representing the size of the ad. If this - /// view has not been initialized then the AdSize will be 0,0. - AdSize ad_size() const; - - protected: - /// Pointer to a listener for AdListener events. - AdListener* ad_listener_; - - /// Pointer to a listener for BoundingBox events. - AdViewBoundingBoxListener* ad_view_bounding_box_listener_; - - /// Pointer to a listener for paid events. - PaidEventListener* paid_event_listener_; - - private: - // An internal, platform-specific implementation object that this class uses - // to interact with the Google Mobile Ads SDKs for iOS and Android. - internal::AdViewInternal* internal_; -}; - -/// A listener class that developers can extend and pass to an @ref AdView -/// object's @ref AdView::SetBoundingBoxListener method to be notified of -/// changes to the size of the Ad's bounding box. -class AdViewBoundingBoxListener { - public: - virtual ~AdViewBoundingBoxListener(); - - /// This method is called when the @ref AdView object's bounding box - /// changes. - /// - /// @param[in] ad_view The view whose bounding box changed. - /// @param[in] box The new bounding box. - virtual void OnBoundingBoxChanged(AdView* ad_view, BoundingBox box) = 0; -}; - -/// @brief The screen location and dimensions of an AdView once it has been -/// initialized. -struct BoundingBox { - /// Default constructor which initializes all member variables to 0. - BoundingBox() - : height(0), width(0), x(0), y(0), position(AdView::kPositionUndefined) {} - - /// Height of the ad in pixels. - int height; - /// Width of the ad in pixels. - int width; - /// Horizontal position of the ad in pixels from the left. - int x; - /// Vertical position of the ad in pixels from the top. - int y; - - /// The position of the AdView if one has been set as the target position, or - /// kPositionUndefined otherwise. - AdView::Position position; -}; - -} // namespace gma -} // namespace firebase - -#endif // FIREBASE_GMA_SRC_INCLUDE_FIREBASE_GMA_AD_VIEW_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/gma/interstitial_ad.h b/packages/firebase_core/firebase_core/firebase_core/firebase/gma/interstitial_ad.h deleted file mode 100644 index 4680537178c8..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/gma/interstitial_ad.h +++ /dev/null @@ -1,128 +0,0 @@ -/* - * Copyright 2021 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_GMA_SRC_INCLUDE_FIREBASE_GMA_INTERSTITIAL_AD_H_ -#define FIREBASE_GMA_SRC_INCLUDE_FIREBASE_GMA_INTERSTITIAL_AD_H_ - -#include "firebase/future.h" -#include "firebase/gma/types.h" -#include "firebase/internal/common.h" - -namespace firebase { -namespace gma { - -namespace internal { -// Forward declaration for platform-specific data, implemented in each library. -class InterstitialAdInternal; -} // namespace internal - -/// @brief Loads and displays Google Mobile Ads interstitial ads. -/// -/// @ref InterstitialAd is a single-use object that can load and show a -/// single GMA interstitial ad. -/// -/// InterstitialAd objects provide information about their current state -/// through Futures. @ref Initialize, @ref LoadAd, and @ref Show each have a -/// corresponding @ref Future from which you can determine result of the -/// previous call. -/// -/// Here's how one might initialize, load, and show an interstitial ad while -/// checking against the result of the previous action at each step: -/// -/// @code -/// namespace gma = ::firebase::gma; -/// gma::InterstitialAd* interstitial = new gma::InterstitialAd(); -/// interstitial->Initialize(ad_parent); -/// @endcode -/// -/// Then, later: -/// -/// @code -/// if (interstitial->InitializeLastResult().status() == -/// ::firebase::kFutureStatusComplete && -/// interstitial->InitializeLastResult().error() == -/// firebase::gma::kAdErrorCodeNone) { -/// interstitial->LoadAd( "YOUR_AD_UNIT_ID", my_ad_request); -/// } -/// @endcode -/// -/// And after that: -/// -/// @code -/// if (interstitial->LoadAdLastResult().status() == -/// ::firebase::kFutureStatusComplete && -/// interstitial->LoadAdLastResult().error() == -/// firebase::gma::kAdErrorCodeNone)) { -/// interstitial->Show(); -/// } -/// @endcode -class InterstitialAd { - public: - /// Creates an uninitialized @ref InterstitialAd object. - /// @ref Initialize must be called before the object is used. - InterstitialAd(); - - ~InterstitialAd(); - - /// Initialize the @ref InterstitialAd object. - /// @param[in] parent The platform-specific UI element that will host the ad. - Future Initialize(AdParent parent); - - /// Returns a @ref Future containing the status of the last call to - /// @ref Initialize. - Future InitializeLastResult() const; - - /// Begins an asynchronous request for an ad. - /// - /// @param[in] ad_unit_id The ad unit ID to use in loading the ad. - /// @param[in] request An AdRequest struct with information about the request - /// to be made (such as targeting info). - Future LoadAd(const char* ad_unit_id, const AdRequest& request); - - /// Returns a @ref Future containing the status of the last call to - /// @ref LoadAd. - Future LoadAdLastResult() const; - - /// Shows the @ref InterstitialAd. This should not be called unless an ad has - /// already been loaded. - Future Show(); - - /// Returns a @ref Future containing the status of the last call to - /// @ref Show. - Future ShowLastResult() const; - - /// Sets the @ref FullScreenContentListener for this @ref InterstitialAd. - /// - /// @param[in] listener A valid @ref FullScreenContentListener to receive - /// callbacks. - void SetFullScreenContentListener(FullScreenContentListener* listener); - - /// Registers a callback to be invoked when this ad is estimated to have - /// earned money - /// - /// @param[in] listener A valid @ref PaidEventListener to receive callbacks. - void SetPaidEventListener(PaidEventListener* listener); - - private: - // An internal, platform-specific implementation object that this class uses - // to interact with the Google Mobile Ads SDKs for iOS and Android. - internal::InterstitialAdInternal* internal_; -}; - -} // namespace gma -} // namespace firebase - -#endif // FIREBASE_GMA_SRC_INCLUDE_FIREBASE_GMA_INTERSTITIAL_AD_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/gma/rewarded_ad.h b/packages/firebase_core/firebase_core/firebase_core/firebase/gma/rewarded_ad.h deleted file mode 100644 index a3c5431486d4..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/gma/rewarded_ad.h +++ /dev/null @@ -1,152 +0,0 @@ -/* - * Copyright 2021 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_GMA_SRC_INCLUDE_FIREBASE_GMA_REWARDED_AD_H_ -#define FIREBASE_GMA_SRC_INCLUDE_FIREBASE_GMA_REWARDED_AD_H_ - -#include - -#include "firebase/future.h" -#include "firebase/gma/types.h" -#include "firebase/internal/common.h" - -namespace firebase { -namespace gma { - -namespace internal { -// Forward declaration for platform-specific data, implemented in each library. -class RewardedAdInternal; -} // namespace internal - -/// @brief Loads and displays Google Mobile Ads rewarded ads. -/// -/// @ref RewardedAd is a single-use object that can load and show a -/// single GMA rewarded ad. -/// -/// RewardedAd objects provide information about their current state -/// through Futures. @ref Initialize, @ref LoadAd, and @ref Show each have a -/// corresponding @ref Future from which you can determine result of the -/// previous call. -/// -/// Here's how one might initialize, load, and show an rewarded ad while -/// checking against the result of the previous action at each step: -/// -/// @code -/// namespace gma = ::firebase::gma; -/// gma::RewardedAd* rewarded = new gma::RewardedAd(); -/// rewarded->Initialize(ad_parent); -/// @endcode -/// -/// Then, later: -/// -/// @code -/// if (rewarded->InitializeLastResult().status() == -/// ::firebase::kFutureStatusComplete && -/// rewarded->InitializeLastResult().error() == -/// firebase::gma::kAdErrorCodeNone) { -/// rewarded->LoadAd( "YOUR_AD_UNIT_ID", my_ad_request); -/// } -/// @endcode -/// -/// And after that: -/// -/// @code -/// if (rewarded->LoadAdLastResult().status() == -/// ::firebase::kFutureStatusComplete && -/// rewarded->LoadAdLastResult().error() == -/// firebase::gma::kAdErrorCodeNone)) { -/// rewarded->Show(&my_user_earned_reward_listener); -/// } -/// @endcode -class RewardedAd { - public: - /// Options for RewardedAd server-side verification callbacks. Set options on - /// a RewardedAd object using the @ref SetServerSideVerificationOptions - /// method. - struct ServerSideVerificationOptions { - /// Custom data to be included in server-side verification callbacks. - std::string custom_data; - - /// User id to be used in server-to-server reward callbacks. - std::string user_id; - }; - - /// Creates an uninitialized @ref RewardedAd object. - /// @ref Initialize must be called before the object is used. - RewardedAd(); - - ~RewardedAd(); - - /// Initialize the @ref RewardedAd object. - /// @param[in] parent The platform-specific UI element that will host the ad. - Future Initialize(AdParent parent); - - /// Returns a @ref Future containing the status of the last call to - /// @ref Initialize. - Future InitializeLastResult() const; - - /// Begins an asynchronous request for an ad. - /// - /// @param[in] ad_unit_id The ad unit ID to use in loading the ad. - /// @param[in] request An AdRequest struct with information about the request - /// to be made (such as targeting info). - Future LoadAd(const char* ad_unit_id, const AdRequest& request); - - /// Returns a @ref Future containing the status of the last call to - /// @ref LoadAd. - Future LoadAdLastResult() const; - - /// Shows the @ref RewardedAd. This should not be called unless an ad has - /// already been loaded. - /// - /// @param[in] listener The @ref UserEarnedRewardListener to be notified when - /// user earns a reward. - Future Show(UserEarnedRewardListener* listener); - - /// Returns a @ref Future containing the status of the last call to - /// @ref Show. - Future ShowLastResult() const; - - /// Sets the @ref FullScreenContentListener for this @ref RewardedAd. - /// - /// @param[in] listener A valid @ref FullScreenContentListener to receive - /// callbacks. - void SetFullScreenContentListener(FullScreenContentListener* listener); - - /// Registers a callback to be invoked when this ad is estimated to have - /// earned money - /// - /// @param[in] listener A valid @ref PaidEventListener to receive callbacks. - void SetPaidEventListener(PaidEventListener* listener); - - /// Sets the server side verification options. - /// - /// @param[in] serverSideVerificationOptions A @ref - /// ServerSideVerificationOptions object containing custom data and a user - /// Id. - void SetServerSideVerificationOptions( - const ServerSideVerificationOptions& serverSideVerificationOptions); - - private: - // An internal, platform-specific implementation object that this class uses - // to interact with the Google Mobile Ads SDKs for iOS and Android. - internal::RewardedAdInternal* internal_; -}; - -} // namespace gma -} // namespace firebase - -#endif // FIREBASE_GMA_SRC_INCLUDE_FIREBASE_GMA_REWARDED_AD_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/gma/types.h b/packages/firebase_core/firebase_core/firebase_core/firebase/gma/types.h deleted file mode 100644 index 292ee4138a68..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/gma/types.h +++ /dev/null @@ -1,939 +0,0 @@ -/* - * Copyright 2021 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_GMA_SRC_INCLUDE_FIREBASE_GMA_TYPES_H_ -#define FIREBASE_GMA_SRC_INCLUDE_FIREBASE_GMA_TYPES_H_ - -#include -#include -#include -#include -#include - -#include "firebase/future.h" -#include "firebase/internal/platform.h" - -#if FIREBASE_PLATFORM_ANDROID -#include -#elif FIREBASE_PLATFORM_IOS || FIREBASE_PLATFORM_TVOS -extern "C" { -#include -} // extern "C" -#endif // FIREBASE_PLATFORM_ANDROID, FIREBASE_PLATFORM_IOS, - // FIREBASE_PLATFORM_TVOS - -namespace firebase { -namespace gma { - -struct AdErrorInternal; -struct AdapterResponseInfoInternal; -struct BoundingBox; -struct ResponseInfoInternal; - -class AdapterResponseInfo; -class AdViewBoundingBoxListener; -class GmaInternal; -class AdView; -class InterstitialAd; -class PaidEventListener; -class ResponseInfo; - -namespace internal { -class AdViewInternal; -} - -/// This is a platform specific datatype that is required to create -/// a Google Mobile Ads ad. -/// -/// The following defines the datatype on each platform: -///
    -///
  • Android: A `jobject` which references an Android Activity.
  • -///
  • iOS: An `id` which references an iOS UIView.
  • -///
-#if FIREBASE_PLATFORM_ANDROID -/// An Android Activity from Java. -typedef jobject AdParent; -#elif FIREBASE_PLATFORM_IOS || FIREBASE_PLATFORM_TVOS -/// A pointer to an iOS UIView. -typedef id AdParent; -#else -/// A void pointer for stub classes. -typedef void* AdParent; -#endif // FIREBASE_PLATFORM_ANDROID, FIREBASE_PLATFORM_IOS, - // FIREBASE_PLATFORM_TVOS - -/// Error codes returned by Future::error(). -enum AdErrorCode { - /// Call completed successfully. - kAdErrorCodeNone, - /// The ad has not been fully initialized. - kAdErrorCodeUninitialized, - /// The ad is already initialized (repeat call). - kAdErrorCodeAlreadyInitialized, - /// A call has failed because an ad is currently loading. - kAdErrorCodeLoadInProgress, - /// A call to load an ad has failed due to an internal SDK error. - kAdErrorCodeInternalError, - /// A call to load an ad has failed due to an invalid request. - kAdErrorCodeInvalidRequest, - /// A call to load an ad has failed due to a network error. - kAdErrorCodeNetworkError, - /// A call to load an ad has failed because no ad was available to serve. - kAdErrorCodeNoFill, - /// An attempt has been made to show an ad on an Android Activity that has - /// no window token (such as one that's not done initializing). - kAdErrorCodeNoWindowToken, - /// An attempt to load an Ad Network extras class for an ad request has - /// failed. - kAdErrorCodeAdNetworkClassLoadError, - /// The ad server experienced a failure processing the request. - kAdErrorCodeServerError, - /// The current device’s OS is below the minimum required version. - kAdErrorCodeOSVersionTooLow, - /// The request was unable to be loaded before being timed out. - kAdErrorCodeTimeout, - /// Will not send request because the interstitial object has already been - /// used. - kAdErrorCodeInterstitialAlreadyUsed, - /// The mediation response was invalid. - kAdErrorCodeMediationDataError, - /// Error finding or creating a mediation ad network adapter. - kAdErrorCodeMediationAdapterError, - /// Attempting to pass an invalid ad size to an adapter. - kAdErrorCodeMediationInvalidAdSize, - /// Invalid argument error. - kAdErrorCodeInvalidArgument, - /// Received invalid response. - kAdErrorCodeReceivedInvalidResponse, - /// Will not send a request because the rewarded ad object has already been - /// used. - kAdErrorCodeRewardedAdAlreadyUsed, - /// A mediation ad network adapter received an ad request, but did not fill. - /// The adapter’s error is included as an underlyingError. - kAdErrorCodeMediationNoFill, - /// Will not send request because the ad object has already been used. - kAdErrorCodeAdAlreadyUsed, - /// Will not send request because the application identifier is missing. - kAdErrorCodeApplicationIdentifierMissing, - /// Android Ad String is invalid. - kAdErrorCodeInvalidAdString, - /// The ad can not be shown when app is not in the foreground. - kAdErrorCodeAppNotInForeground, - /// A mediation adapter failed to show the ad. - kAdErrorCodeMediationShowError, - /// The ad is not ready to be shown. - kAdErrorCodeAdNotReady, - /// Ad is too large for the scene. - kAdErrorCodeAdTooLarge, - /// Attempted to present ad from a non-main thread. This is an internal - /// error which should be reported to support if encountered. - kAdErrorCodeNotMainThread, - /// A debug operation failed because the device is not in test mode. - kAdErrorCodeNotInTestMode, - /// An attempt to load the Ad Inspector failed. - kAdErrorCodeInspectorFailedToLoad, - /// The request to show the Ad Inspector failed because it's already open. - kAdErrorCodeInsepctorAlreadyOpen, - /// Fallback error for any unidentified cases. - kAdErrorCodeUnknown, -}; - -/// A listener for receiving notifications during the lifecycle of a BannerAd. -class AdListener { - public: - virtual ~AdListener(); - - /// Called when a click is recorded for an ad. - virtual void OnAdClicked() {} - - /// Called when the user is about to return to the application after clicking - /// on an ad. - virtual void OnAdClosed() {} - - /// Called when an impression is recorded for an ad. - virtual void OnAdImpression() {} - - /// Called when an ad opens an overlay that covers the screen. - virtual void OnAdOpened() {} -}; - -/// Information about why an ad operation failed. -class AdError { - public: - /// Default Constructor. - AdError(); - - /// Copy Constructor. - AdError(const AdError& ad_error); - - /// Destructor. - virtual ~AdError(); - - /// Assignment operator. - AdError& operator=(const AdError& obj); - - /// Retrieves an AdError which represents the cause of this error. - /// - /// @return a pointer to an adError which represents the cause of this - /// AdError. If there was no cause then nullptr is returned. - std::unique_ptr GetCause() const; - - /// Gets the error's code. - AdErrorCode code() const; - - /// Gets the domain of the error. - const std::string& domain() const; - - /// Gets the message describing the error. - const std::string& message() const; - - /// Gets the ResponseInfo if an error occurred during a loadAd operation. - /// The ResponseInfo will have empty fields if this AdError does not - /// represent an error stemming from a load ad operation. - const ResponseInfo& response_info() const; - - /// Returns a log friendly string version of this object. - virtual const std::string& ToString() const; - - /// A domain string which represents an undefined error domain. - /// - /// The GMA SDK returns this domain for domain() method invocations when - /// converting error information from legacy mediation adapter callbacks. - static const char* const kUndefinedDomain; - - private: - friend class AdapterResponseInfo; - friend class GmaInternal; - friend class AdView; - friend class InterstitialAd; - - /// Constructor used when building results in Ad event callbacks. - explicit AdError(const AdErrorInternal& ad_error_internal); - - // Collection of response from adapters if this Result is due to a loadAd - // operation. - ResponseInfo* response_info_; - - // An internal, platform-specific implementation object that this class uses - // to interact with the Google Mobile Ads SDKs for iOS and Android. - AdErrorInternal* internal_; -}; - -/// Information about an ad response. -class ResponseInfo { - public: - /// Constructor creates an uninitialized ResponseInfo. - ResponseInfo(); - - /// Gets the AdapterResponseInfo objects for the ad response. - /// - /// @return a vector of AdapterResponseInfo objects containing metadata for - /// each adapter included in the ad response. - const std::vector& adapter_responses() const { - return adapter_responses_; - } - - /// A class name that identifies the ad network that returned the ad. - /// Returns an empty string if the ad failed to load. - const std::string& mediation_adapter_class_name() const { - return mediation_adapter_class_name_; - } - - /// Gets the response ID string for the loaded ad. Returns an empty - /// string if the ad fails to load. - const std::string& response_id() const { return response_id_; } - - /// Gets a log friendly string version of this object. - const std::string& ToString() const { return to_string_; } - - private: - friend class AdError; - friend class GmaInternal; - - explicit ResponseInfo(const ResponseInfoInternal& internal); - - std::vector adapter_responses_; - std::string mediation_adapter_class_name_; - std::string response_id_; - std::string to_string_; -}; - -/// Information about the result of an ad operation. -class AdResult { - public: - /// Default Constructor. - AdResult(); - - /// Constructor. - explicit AdResult(const AdError& ad_error); - - /// Destructor. - virtual ~AdResult(); - - /// Returns true if the operation was successful. - bool is_successful() const; - - /// An object representing an error which occurred during an ad operation. - /// If the @ref AdResult::is_successful() returned true, then the - /// @ref AdError object returned via this method will contain no contextual - /// information. - const AdError& ad_error() const; - - /// For debugging and logging purposes, successfully loaded ads provide a - /// ResponseInfo object which contains information about the adapter which - /// loaded the ad. If the ad failed to load then the object returned from - /// this method will have default values. Information about the error - /// should be retrieved via @ref AdResult::ad_error() instead. - const ResponseInfo& response_info() const; - - private: - friend class GmaInternal; - - /// Constructor invoked upon successful ad load. This contains response - /// information from the adapter which loaded the ad. - explicit AdResult(const ResponseInfo& response_info); - - /// Denotes if the @ref AdResult represents a success or an error. - bool is_successful_; - - /// Information about the error. Will be a default-constructed @ref AdError - /// if this result represents a success. - AdError ad_error_; - - /// Information from the adapter which loaded the ad. - ResponseInfo response_info_; -}; - -/// A snapshot of a mediation adapter's initialization status. -class AdapterStatus { - public: - AdapterStatus() : is_initialized_(false), latency_(0) {} - - /// Detailed description of the status. - /// - /// This method should only be used for informational purposes, such as - /// logging. Use @ref is_initialized to make logical decisions regarding an - /// adapter's status. - const std::string& description() const { return description_; } - - /// Returns the adapter's initialization state. - bool is_initialized() const { return is_initialized_; } - - /// The adapter's initialization latency in milliseconds. - /// 0 if initialization has not yet ended. - int latency() const { return latency_; } - -#if !defined(DOXYGEN) - // Equality operator for testing. - bool operator==(const AdapterStatus& rhs) const { - return (description() == rhs.description() && - is_initialized() == rhs.is_initialized() && - latency() == rhs.latency()); - } -#endif // !defined(DOXYGEN) - - private: - friend class GmaInternal; - std::string description_; - bool is_initialized_; - int latency_; -}; - -/// An immutable snapshot of the GMA SDK’s initialization status, categorized -/// by mediation adapter. -class AdapterInitializationStatus { - public: - /// Initialization status of each known ad network, keyed by its adapter's - /// class name. - std::map GetAdapterStatusMap() const { - return adapter_status_map_; - } -#if !defined(DOXYGEN) - // Equality operator for testing. - bool operator==(const AdapterInitializationStatus& rhs) const { - return (GetAdapterStatusMap() == rhs.GetAdapterStatusMap()); - } -#endif // !defined(DOXYGEN) - - private: - friend class GmaInternal; - std::map adapter_status_map_; -}; - -/// Listener to be invoked when the Ad Inspector has been closed. -class AdInspectorClosedListener { - public: - virtual ~AdInspectorClosedListener(); - - /// Called when the user clicked the ad. The AdResult contains the status of - /// the operation, including details of the error if one occurred. - virtual void OnAdInspectorClosed(const AdResult& ad_result) = 0; -}; - -/// @brief Response information for an individual ad network contained within -/// a @ref ResponseInfo object. -class AdapterResponseInfo { - public: - /// Destructor - ~AdapterResponseInfo(); - - /// @brief Information about the result including whether an error - /// occurred, and any contextual information about that error. - /// - /// @return the error that occurred while rendering the ad. If no error - /// occurred then the AdResult's successful method will return true. - AdResult ad_result() const { return ad_result_; } - - /// Returns a string representation of a class name that identifies the ad - /// network adapter. - const std::string& adapter_class_name() const { return adapter_class_name_; } - - /// Amount of time the ad network spent loading an ad. - /// - /// @return number of milliseconds the network spent loading an ad. This value - /// is 0 if the network did not make a load attempt. - int64_t latency_in_millis() const { return latency_; } - - /// A log friendly string version of this object. - const std::string& ToString() const { return to_string_; } - - private: - friend class ResponseInfo; - - /// Constructs an Adapter Response Info Object. - explicit AdapterResponseInfo(const AdapterResponseInfoInternal& internal); - - AdResult ad_result_; - std::string adapter_class_name_; - int64_t latency_; - std::string to_string_; -}; - -/// The size of a banner ad. -class AdSize { - public: - /// Denotes the orientation of the AdSize. - enum Orientation { - /// AdSize should reflect the current orientation of the device. - kOrientationCurrent = 0, - - /// AdSize will be adaptively formatted in Landscape mode. - kOrientationLandscape, - - /// AdSize will be adaptively formatted in Portrait mode. - kOrientationPortrait - }; - - /// Denotes the type size object that the @ref AdSize represents. - enum Type { - /// The standard AdSize type of a set height and width. - kTypeStandard = 0, - - /// An adaptive size anchored to a portion of the screen. - kTypeAnchoredAdaptive, - - /// An adaptive size intended to be embedded in scrollable content. - kTypeInlineAdaptive, - }; - - /// Mobile Marketing Association (MMA) banner ad size (320x50 - /// density-independent pixels). - static const AdSize kBanner; - - /// Interactive Advertising Bureau (IAB) full banner ad size - /// (468x60 density-independent pixels). - static const AdSize kFullBanner; - - /// Taller version of kBanner. Typically 320x100. - static const AdSize kLargeBanner; - - /// Interactive Advertising Bureau (IAB) leaderboard ad size - /// (728x90 density-independent pixels). - static const AdSize kLeaderboard; - - /// Interactive Advertising Bureau (IAB) medium rectangle ad size - /// (300x250 density-independent pixels). - static const AdSize kMediumRectangle; - - /// Creates a new AdSize. - /// - /// @param[in] width The width of the ad in density-independent pixels. - /// @param[in] height The height of the ad in density-independent pixels. - AdSize(uint32_t width, uint32_t height); - - /// @brief Creates an AdSize with the given width and a Google-optimized - /// height to create a banner ad in landscape mode. - /// - /// @param[in] width The width of the ad in density-independent pixels. - /// - /// @return an AdSize with the given width and a Google-optimized height - /// to create a banner ad. The size returned will have an aspect ratio - /// similar to BANNER, suitable for anchoring near the top or bottom of - /// your app. The exact size of the ad returned can be retrieved by calling - /// @ref AdView::ad_size once the ad has been loaded. - static AdSize GetLandscapeAnchoredAdaptiveBannerAdSize(uint32_t width); - - /// @brief Creates an AdSize with the given width and a Google-optimized - /// height to create a banner ad in portrait mode. - /// - /// @param[in] width The width of the ad in density-independent pixels. - /// - /// @return an AdSize with the given width and a Google-optimized height - /// to create a banner ad. The size returned will have an aspect ratio - /// similar to BANNER, suitable for anchoring near the top or bottom - /// of your app. The exact size of the ad returned can be retrieved by - /// calling @ref AdView::ad_size once the ad has been loaded. - static AdSize GetPortraitAnchoredAdaptiveBannerAdSize(uint32_t width); - - /// @brief Creates an AdSize with the given width and a Google-optimized - /// height to create a banner ad given the current orientation. - /// - /// @param[in] width The width of the ad in density-independent pixels. - /// - /// @return an AdSize with the given width and a Google-optimized height - /// to create a banner ad. The size returned will have an aspect ratio - /// similar to AdSize, suitable for anchoring near the top or bottom of - /// your app. The exact size of the ad returned can be retrieved by calling - /// @ref AdView::ad_size once the ad has been loaded. - static AdSize GetCurrentOrientationAnchoredAdaptiveBannerAdSize( - uint32_t width); - - /// @brief This ad size is most suitable for banner ads given a maximum - /// height. - /// - /// This AdSize allows Google servers to choose an optimal ad size with - /// a height less than or equal to the max height given in - /// - /// @param[in] width The width of the ad in density-independent pixels. - /// @param[in] max_height The maximum height that a loaded ad will have. Must - /// be - /// at least 32 dp, but a maxHeight of 50 dp or higher is recommended. - /// - /// @return an AdSize with the given width and a height that is always 0. - /// The exact size of the ad returned can be retrieved by calling - /// @ref AdView::ad_size once the ad has been loaded. - static AdSize GetInlineAdaptiveBannerAdSize(int width, int max_height); - - /// @brief Creates an AdSize with the given width and the device’s - /// landscape height. - /// - /// This ad size allows Google servers to choose an optimal ad size with - /// a height less than or equal to the height of the screen in landscape - /// orientation. - /// - /// @param[in] width The width of the ad in density-independent pixels. - /// - /// @return an AdSize with the given width and a height that is always 0. - /// The exact size of the ad returned can be retrieved by calling - /// @ref AdView::ad_size once the ad has been loaded. - static AdSize GetLandscapeInlineAdaptiveBannerAdSize(int width); - - /// @brief Creates an AdSize with the given width and the device’s - /// portrait height. - /// - /// This ad size allows Google servers to choose an optimal ad size with - /// a height less than or equal to the height of the screen in portrait - /// orientation. - /// - /// @param[in] width The width of the ad in density-independent pixels. - /// - /// @return an AdSize with the given width and a height that is always 0. - /// The exact size of the ad returned can be retrieved by calling - /// @ref AdView::ad_size once the ad has been loaded. - static AdSize GetPortraitInlineAdaptiveBannerAdSize(int width); - - /// @brief A convenience method to return an inline adaptive banner ad size - /// given the current interface orientation. - /// - /// This AdSize allows Google servers to choose an optimal ad size with a - /// height less than or equal to the height of the screen in the requested - /// orientation. - /// - /// @param[in] width The width of the ad in density-independent pixels. - /// - /// @return an AdSize with the given width and a height that is always 0. - /// The exact size of the ad returned can be retrieved by calling - /// @ref AdView::ad_size once the ad has been loaded. - static AdSize GetCurrentOrientationInlineAdaptiveBannerAdSize(int width); - - /// Comparison operator. - /// - /// @return true if `rhs` refers to the same AdSize as `this`. - bool operator==(const AdSize& rhs) const; - - /// Comparison operator. - /// - /// @returns true if `rhs` refers to a different AdSize as `this`. - bool operator!=(const AdSize& rhs) const; - - /// The width of the region represented by this AdSize. Value is in - /// density-independent pixels. - uint32_t width() const { return width_; } - - /// The height of the region represented by this AdSize. Value is in - /// density-independent pixels. - uint32_t height() const { return height_; } - - /// The AdSize orientation. - Orientation orientation() const { return orientation_; } - - /// The AdSize type, either standard size or adaptive. - Type type() const { return type_; } - - private: - friend class firebase::gma::internal::AdViewInternal; - - /// Returns an Anchor Adpative AdSize Object given a width and orientation. - static AdSize GetAnchoredAdaptiveBannerAdSize(uint32_t width, - Orientation orientation); - - /// Returns true if the AdSize parameter is equivalient to this AdSize object. - bool is_equal(const AdSize& ad_size) const; - - /// Denotes the orientation for anchored adaptive AdSize objects. - Orientation orientation_; - - /// Advertisement width in platform-indepenent pixels. - uint32_t width_; - - /// Advertisement width in platform-indepenent pixels. - uint32_t height_; - - /// The type of AdSize (standard or adaptive) - Type type_; -}; - -/// Contains targeting information used to fetch an ad. -class AdRequest { - public: - /// Creates an @ref AdRequest with no custom configuration. - AdRequest(); - - /// Creates an @ref AdRequest with the optional content URL. - /// - /// When requesting an ad, apps may pass the URL of the content they are - /// serving. This enables keyword targeting to match the ad with the content. - /// - /// The URL is ignored if null or the number of characters exceeds 512. - /// - /// @param[in] content_url the url of the content being viewed. - explicit AdRequest(const char* content_url); - - ~AdRequest(); - - /// The content URL targeting information. - /// - /// @return the content URL for the @ref AdRequest. The string will be empty - /// if no content URL has been configured. - const std::string& content_url() const { return content_url_; } - - /// A Map of adapter class names to their collection of extra parameters, as - /// configured via @ref add_extra. - const std::map >& extras() - const { - return extras_; - } - - /// Keywords which will help GMA to provide targeted ads, as added by - /// @ref add_keyword. - const std::unordered_set& keywords() const { return keywords_; } - - /// Returns the set of neighboring content URLs or an empty set if no URLs - /// were set via @ref add_neighboring_content_urls(). - const std::unordered_set& neighboring_content_urls() const { - return neighboring_content_urls_; - } - - /// Add a network extra for the associated ad mediation adapter. - /// - /// Appends an extra to the corresponding list of extras for the ad mediation - /// adapter. Each ad mediation adapter can have multiple extra strings. - /// - /// @param[in] adapter_class_name the class name of the ad mediation adapter - /// for which to add the extra. - /// @param[in] extra_key a key which will be passed to the corresponding ad - /// mediation adapter. - /// @param[in] extra_value the value associated with extra_key. - void add_extra(const char* adapter_class_name, const char* extra_key, - const char* extra_value); - - /// Adds a keyword for targeting purposes. - /// - /// Multiple keywords may be added via repeated invocations of this method. - /// - /// @param[in] keyword a string that GMA will use to aid in targeting ads. - void add_keyword(const char* keyword); - - /// When requesting an ad, apps may pass the URL of the content they are - /// serving. This enables keyword targeting to match the ad with the content. - /// - /// The URL is ignored if null or the number of characters exceeds 512. - /// - /// @param[in] content_url the url of the content being viewed. - void set_content_url(const char* content_url); - - /// Adds to the list of URLs which represent web content near an ad. - /// - /// Promotes brand safety and allows displayed ads to have an app level - /// rating (MA, T, PG, etc) that is more appropriate to neighboring content. - /// - /// Subsequent invocations append to the existing list. - /// - /// @param[in] neighboring_content_urls neighboring content URLs to be - /// attached to the existing neighboring content URLs. - void add_neighboring_content_urls( - const std::vector& neighboring_content_urls); - - private: - std::string content_url_; - std::map > extras_; - std::unordered_set keywords_; - std::unordered_set neighboring_content_urls_; -}; - -/// Describes a reward credited to a user for interacting with a RewardedAd. -class AdReward { - public: - /// Creates an @ref AdReward. - AdReward(const std::string& type, int64_t amount) - : type_(type), amount_(amount) {} - - /// Returns the reward amount. - int64_t amount() const { return amount_; } - - /// Returns the type of the reward. - const std::string& type() const { return type_; } - - private: - const int64_t amount_; - const std::string type_; -}; - -/// The monetary value earned from an ad. -class AdValue { - public: - /// Allowed constants for @ref precision_type(). - enum PrecisionType { - /// An ad value with unknown precision. - kdValuePrecisionUnknown = 0, - /// An ad value estimated from aggregated data. - kAdValuePrecisionEstimated, - /// A publisher-provided ad value, such as manual CPMs in a mediation group. - kAdValuePrecisionPublisherProvided = 2, - /// The precise value paid for this ad. - kAdValuePrecisionPrecise = 3 - }; - - /// Constructor - AdValue(const char* currency_code, PrecisionType precision_type, - int64_t value_micros) - : currency_code_(currency_code), - precision_type_(precision_type), - value_micros_(value_micros) {} - - /// The value's ISO 4217 currency code. - const std::string& currency_code() const { return currency_code_; } - - /// The precision of the reported ad value. - PrecisionType precision_type() const { return precision_type_; } - - /// The ad's value in micro-units, where 1,000,000 micro-units equal one - /// unit of the currency. - int64_t value_micros() const { return value_micros_; } - - private: - const std::string currency_code_; - const PrecisionType precision_type_; - const int64_t value_micros_; -}; - -/// @brief Listener to be invoked when ads show and dismiss full screen content, -/// such as a fullscreen ad experience or an in-app browser. -class FullScreenContentListener { - public: - virtual ~FullScreenContentListener(); - - /// Called when the user clicked the ad. - virtual void OnAdClicked() {} - - /// Called when the ad dismissed full screen content. - virtual void OnAdDismissedFullScreenContent() {} - - /// Called when the ad failed to show full screen content. - /// - /// @param[in] ad_error An object containing detailed information - /// about the error. - virtual void OnAdFailedToShowFullScreenContent(const AdError& ad_error) {} - - /// Called when an impression is recorded for an ad. - virtual void OnAdImpression() {} - - /// Called when the ad showed the full screen content. - virtual void OnAdShowedFullScreenContent() {} -}; - -/// Listener to be invoked when ads have been estimated to earn money. -class PaidEventListener { - public: - virtual ~PaidEventListener(); - - /// Called when an ad is estimated to have earned money. - virtual void OnPaidEvent(const AdValue& value) {} -}; - -/// @brief Global configuration that will be used for every @ref AdRequest. -/// Set the configuration via @ref SetRequestConfiguration. -struct RequestConfiguration { - /// A maximum ad content rating, which may be configured via - /// @ref max_ad_content_rating. - enum MaxAdContentRating { - /// No content rating has been specified. - kMaxAdContentRatingUnspecified = -1, - - /// Content suitable for general audiences, including families. - kMaxAdContentRatingG, - - /// Content suitable only for mature audiences. - kMaxAdContentRatingMA, - - /// Content suitable for most audiences with parental guidance. - kMaxAdContentRatingPG, - - /// Content suitable for teen and older audiences. - kMaxAdContentRatingT - }; - - /// Specify whether you would like your app to be treated as child-directed - /// for purposes of the Children’s Online Privacy Protection Act (COPPA). - /// Values defined here may be configured via - /// @ref tag_for_child_directed_treatment. - enum TagForChildDirectedTreatment { - /// Indicates that ad requests will include no indication of how you would - /// like your app treated with respect to COPPA. - kChildDirectedTreatmentUnspecified = -1, - - /// Indicates that your app should not be treated as child-directed for - /// purposes of the Children’s Online Privacy Protection Act (COPPA). - kChildDirectedTreatmentFalse, - - /// Indicates that your app should be treated as child-directed for purposes - /// of the Children’s Online Privacy Protection Act (COPPA). - kChildDirectedTreatmentTrue - }; - - /// Configuration values to mark your app to receive treatment for users in - /// the European Economic Area (EEA) under the age of consent. Values defined - /// here should be configured via @ref tag_for_under_age_of_consent. - enum TagForUnderAgeOfConsent { - /// Indicates that the publisher has not specified whether the ad request - /// should receive treatment for users in the European Economic Area (EEA) - /// under the age of consent. - kUnderAgeOfConsentUnspecified = -1, - - /// Indicates the publisher specified that the ad request should not receive - /// treatment for users in the European Economic Area (EEA) under the age of - /// consent. - kUnderAgeOfConsentFalse, - - /// Indicates the publisher specified that the ad request should receive - /// treatment for users in the European Economic Area (EEA) under the age of - /// consent. - kUnderAgeOfConsentTrue - }; - - /// Sets a maximum ad content rating. GMA ads returned for your app will - /// have a content rating at or below that level. - MaxAdContentRating max_ad_content_rating; - - /// @brief Allows you to specify whether you would like your app - /// to be treated as child-directed for purposes of the Children’s Online - /// Privacy Protection Act (COPPA) - - /// http://business.ftc.gov/privacy-and-security/childrens-privacy. - /// - /// If you set this value to - /// RequestConfiguration.kChildDirectedTreatmentTrue, you will indicate - /// that your app should be treated as child-directed for purposes of the - /// Children’s Online Privacy Protection Act (COPPA). - /// - /// If you set this value to - /// RequestConfiguration.kChildDirectedTreatmentFalse, you will indicate - /// that your app should not be treated as child-directed for purposes of the - /// Children’s Online Privacy Protection Act (COPPA). - /// - /// If you do not set this value, or set this value to - /// RequestConfiguration.kChildDirectedTreatmentUnspecified, ad requests will - /// include no indication of how you would like your app treated with respect - /// to COPPA. - /// - /// By setting this value, you certify that this notification is accurate and - /// you are authorized to act on behalf of the owner of the app. You - /// understand that abuse of this setting may result in termination of your - /// Google account. - /// - /// @note: it may take some time for this designation to be fully implemented - /// in applicable Google services. - /// - TagForChildDirectedTreatment tag_for_child_directed_treatment; - - /// This value allows you to mark your app to receive treatment for users in - /// the European Economic Area (EEA) under the age of consent. This feature is - /// designed to help facilitate compliance with the General Data Protection - /// Regulation (GDPR). Note that you may have other legal obligations under - /// GDPR. Please review the European Union's guidance and consult with your - /// own legal counsel. Please remember that Google's tools are designed to - /// facilitate compliance and do not relieve any particular publisher of its - /// obligations under the law. - /// - /// When using this feature, a Tag For Users under the Age of Consent in - /// Europe (TFUA) parameter will be included in all ad requests. This - /// parameter disables personalized advertising, including remarketing, for - /// that specific ad request. It also disables requests to third-party ad - /// vendors, such as ad measurement pixels and third-party ad servers. - /// - /// If you set this value to RequestConfiguration.kUnderAgeOfConsentTrue, you - /// will indicate that you want your app to be handled in a manner suitable - /// for users under the age of consent. - /// - /// If you set this value to RequestConfiguration.kUnderAgeOfConsentFalse, - /// you will indicate that you don't want your app to be handled in a manner - /// suitable for users under the age of consent. - /// - /// If you do not set this value, or set this value to - /// kUnderAgeOfConsentUnspecified, your app will include no indication of how - /// you would like your app to be handled in a manner suitable for users under - /// the age of consent. - TagForUnderAgeOfConsent tag_for_under_age_of_consent; - - /// Sets a list of test device IDs corresponding to test devices which will - /// always request test ads. - std::vector test_device_ids; -}; - -/// Listener to be invoked when the user earned a reward. -class UserEarnedRewardListener { - public: - virtual ~UserEarnedRewardListener(); - /// Called when the user earned a reward. The app is responsible for - /// crediting the user with the reward. - /// - /// @param[in] reward the @ref AdReward that should be granted to the user. - virtual void OnUserEarnedReward(const AdReward& reward) {} -}; - -} // namespace gma -} // namespace firebase - -#endif // FIREBASE_GMA_SRC_INCLUDE_FIREBASE_GMA_TYPES_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/installations.h b/packages/firebase_core/firebase_core/firebase_core/firebase/installations.h deleted file mode 100644 index c9774bc37e73..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/installations.h +++ /dev/null @@ -1,123 +0,0 @@ -// Copyright 2020 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef FIREBASE_INSTALLATIONS_SRC_INCLUDE_FIREBASE_INSTALLATIONS_H_ -#define FIREBASE_INSTALLATIONS_SRC_INCLUDE_FIREBASE_INSTALLATIONS_H_ - -#include -#include - -#include "firebase/app.h" -#include "firebase/future.h" -#include "firebase/internal/common.h" - -/// @brief Namespace that encompasses all Firebase APIs. -namespace firebase { - -namespace installations { - -/// Installations error codes. -enum Error { - kErrorNone = 0, - /// An unknown error occurred. - kErrorUnknown, - /// Installations service cannot be accessed. - kErrorNoAccess, - /// Some of the parameters of the request were invalid. - kErrorInvalidConfiguration, -}; - -namespace internal { -// Implementation specific data for an Installation. -class InstallationsInternal; -} // namespace internal - -/// @brief Installations provides a unique identifier for each app instance and -/// a mechanism to authenticate and authorize actions (for example, sending an -/// FCM message). -/// -/// Provides a unique identifier for a Firebase installation. -/// Provides an auth token for a Firebase installation. -/// Provides a API to perform data deletion for a Firebase -/// installation. -class Installations { - public: - ~Installations(); - - /// @brief Get the App this object is connected to. - /// - /// @return App this object is connected to. - App* app() const { return app_; } - - /// @brief Returns the Installations object for an App creating the - /// Installations if required. - /// - /// @param[in] app The App to create an Installations object from. - /// - /// @return Installations object if successful, nullptr otherwise. - static Installations* GetInstance(App* app); - - /// @brief Returns a stable identifier that uniquely identifies the app - /// installation. - /// - /// @return Unique identifier for the app installation. - Future GetId(); - - /// @brief Get the results of the most recent call to @ref GetId. - Future GetIdLastResult(); - - /// @brief Call to delete this Firebase app installation from the Firebase - /// backend. - Future Delete(); - - /// @brief Get the results of the most recent call to @ref Delete. - Future DeleteLastResult(); - - /// @brief Returns a token that authorizes an Entity to perform an action on - /// behalf of the application identified by installations. - /// - /// This is similar to an OAuth2 token except it applies to the - /// application instance instead of a user. - /// - /// For example, to get a token that can be used to send messages to an - /// application via Firebase Cloud Messaging, set entity to the - /// sender ID, and set scope to "FCM". - /// - /// @param forceRefresh If set true, will always return a new token. - /// - /// @return Returns a valid authentication token for the Firebase - /// installation. - Future GetToken(bool forceRefresh); - - /// @brief Get the results of the most recent call to @ref GetToken. - Future GetTokenLastResult(); - - private: - explicit Installations(App* app); - - static Installations* FindInstallations(App* app); - // Installations internal initialize. - bool InitInternal(); - // Clean up Installations instance. - void DeleteInternal(); - - App* app_; - internal::InstallationsInternal* installations_internal_; -}; - -} // namespace installations - -} // namespace firebase - -#endif // FIREBASE_INSTALLATIONS_SRC_INCLUDE_FIREBASE_INSTALLATIONS_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/internal/common.h b/packages/firebase_core/firebase_core/firebase_core/firebase/internal/common.h deleted file mode 100644 index 2e2878a0bd97..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/internal/common.h +++ /dev/null @@ -1,128 +0,0 @@ -/* - * Copyright 2016 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_APP_SRC_INCLUDE_FIREBASE_INTERNAL_COMMON_H_ -#define FIREBASE_APP_SRC_INCLUDE_FIREBASE_INTERNAL_COMMON_H_ - -// This file contains definitions that configure the SDK. - -// Include a STL header file, othewise _STLPORT_VERSION won't be set. -#include - -// Move operators use rvalue references, which are a C++11 extension. -// Also, Visual Studio 2010 and later actually support move operators despite -// reporting __cplusplus to be 199711L, so explicitly check for that. -// Also, stlport doesn't implement std::move(). -#if (__cplusplus >= 201103L || _MSC_VER >= 1600) && !defined(_STLPORT_VERSION) -#define FIREBASE_USE_MOVE_OPERATORS -#endif - -// stlport doesn't implement std::function. -#if !defined(_STLPORT_VERSION) -#define FIREBASE_USE_STD_FUNCTION -#endif // !defined(_STLPORT_VERSION) - -// stlport doesn't implement std::aligned_storage. -#if defined(_STLPORT_VERSION) -#include - -namespace firebase { -template -struct AlignedStorage { - struct type { - alignas(Alignment) unsigned char data[Length]; - }; -}; -} // namespace firebase -#define FIREBASE_ALIGNED_STORAGE ::firebase::AlignedStorage -#else -#include -#define FIREBASE_ALIGNED_STORAGE std::aligned_storage -#endif // defined(_STLPORT_VERSION) - -// Visual Studio 2013 does not support snprintf, so use streams instead. -#if !(defined(_MSC_VER) && _MSC_VER <= 1800) -#define FIREBASE_USE_SNPRINTF -#endif // !(defined(_MSC_VER) && _MSC_VER <= 1800) - -#if !(defined(_MSC_VER) && _MSC_VER <= 1800) -#define FIREBASE_USE_EXPLICIT_DEFAULT_METHODS -#endif // !(defined(_MSC_VER) && _MSC_VER <= 1800) - -#if !defined(DOXYGEN) && !defined(SWIG) -#if !defined(_WIN32) && !defined(__CYGWIN__) -// Prevent GCC & Clang from stripping a symbol. -#define FIREBASE_APP_KEEP_SYMBOL __attribute__((used)) -#else -// MSVC needs to reference a symbol directly in the application for it to be -// kept in the final executable. In this case, the end user's application -// must include the appropriate Firebase header (e.g firebase/analytics.h) to -// initialize the module. -#define FIREBASE_APP_KEEP_SYMBOL -#endif // !defined(_WIN32) && !defined(__CYGWIN__) - -// Module initializer's name. -// -// This can be used to explicitly include a module initializer in an application -// to prevent the object from being stripped by the linker. The symbol is -// located in the "firebase" namespace so can be referenced using: -// -// ::firebase::FIREBASE_APP_REGISTER_CALLBACKS_REFERENCE_NAME(name) -// -// Where "name" is the module name, for example "analytics". -#define FIREBASE_APP_REGISTER_CALLBACKS_INITIALIZER_NAME(module_name) \ - g_##module_name##_initializer - -// Declare a module initializer variable as a global. -#define FIREBASE_APP_REGISTER_CALLBACKS_INITIALIZER_VARIABLE(module_name) \ - namespace firebase { \ - extern void* FIREBASE_APP_REGISTER_CALLBACKS_INITIALIZER_NAME(module_name); \ - } /* namespace firebase */ - -// Generates code which references a module initializer. -// For example, FIREBASE_APP_REGISTER_REFERENCE(analytics) will register the -// module initializer for the analytics module. -#define FIREBASE_APP_REGISTER_CALLBACKS_REFERENCE(module_name) \ - FIREBASE_APP_REGISTER_CALLBACKS_INITIALIZER_VARIABLE(module_name) \ - namespace firebase { \ - static void* module_name##_ref FIREBASE_APP_KEEP_SYMBOL = \ - &FIREBASE_APP_REGISTER_CALLBACKS_INITIALIZER_NAME(module_name); \ - } /* namespace firebase */ -#endif // !defined(DOXYGEN) && !defined(SWIG) - -#if defined(SWIG) || defined(DOXYGEN) -// SWIG needs to ignore the FIREBASE_DEPRECATED tag. -#define FIREBASE_DEPRECATED -#endif // defined(SWIG) || defined(DOXYGEN) - -#ifndef FIREBASE_DEPRECATED -#ifdef __GNUC__ -#define FIREBASE_DEPRECATED __attribute__((deprecated)) -#elif defined(_MSC_VER) -#define FIREBASE_DEPRECATED __declspec(deprecated) -#else -// We don't know how to mark functions as "deprecated" with this compiler. -#define FIREBASE_DEPRECATED -#endif -#endif // FIREBASE_DEPRECATED - -// Calculates the number of elements in an array. -#define FIREBASE_ARRAYSIZE(x) (sizeof(x) / sizeof((x)[0])) - -// Guaranteed compile time strlen. -#define FIREBASE_STRLEN(s) (FIREBASE_ARRAYSIZE(s) - sizeof((s)[0])) - -#endif // FIREBASE_APP_SRC_INCLUDE_FIREBASE_INTERNAL_COMMON_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/internal/future_impl.h b/packages/firebase_core/firebase_core/firebase_core/firebase/internal/future_impl.h deleted file mode 100644 index 59e7771d010b..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/internal/future_impl.h +++ /dev/null @@ -1,359 +0,0 @@ -/* - * Copyright 2016 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_APP_SRC_INCLUDE_FIREBASE_INTERNAL_FUTURE_IMPL_H_ -#define FIREBASE_APP_SRC_INCLUDE_FIREBASE_INTERNAL_FUTURE_IMPL_H_ - -/// @cond FIREBASE_APP_INTERNAL - -// You shouldn't include future_impl.h directly, since its just the inline -// implementation of the functions in future.h. Include future.h instead. -#include "firebase/future.h" - -#if defined(FIREBASE_USE_MOVE_OPERATORS) -#include -#endif // defined(FIREBASE_USE_MOVE_OPERATORS) - -namespace firebase { - -class ReferenceCountedFutureImpl; - -namespace detail { - -class CompletionCallbackHandle; - -/// Pure-virtual interface that APIs must implement to use Futures. -class FutureApiInterface { - public: - // typedef void FutureCallbackFn(const FutureBase* future); - virtual ~FutureApiInterface(); - - /// Increment the reference count on handle's asynchronous call. - /// Called when the Future is copied. - virtual void ReferenceFuture(const FutureHandle& handle) = 0; - - /// Decrement the reference count on handle's asynchronous call. - /// Called when the Future is destroyed or moved. - /// If the reference count drops to zero, the asynchronous call can be - /// forgotten. - virtual void ReleaseFuture(const FutureHandle& handle) = 0; - - /// Return the status of the asynchronous call. - virtual FutureStatus GetFutureStatus(const FutureHandle& handle) const = 0; - - /// Return the API-specific error. - /// Valid when GetFutureStatus() is kFutureStatusComplete, and undefined - /// otherwise. - virtual int GetFutureError(const FutureHandle& handle) const = 0; - - /// Return the API-specific error, in human-readable form, or "" if no message - /// has been provided. - /// Valid when GetFutureStatus() is kFutureStatusComplete, and undefined - /// otherwise. - virtual const char* GetFutureErrorMessage( - const FutureHandle& handle) const = 0; - - /// Return a pointer to the completed asynchronous result, or NULL if - /// result is still pending. - /// After an asynchronous call is marked complete, the API should not - /// modify the result (especially on a callback thread), since the threads - /// owning the Future can reference the result memory via this function. - virtual const void* GetFutureResult(const FutureHandle& handle) const = 0; - - /// Register a callback that will be called when this future's status is set - /// to Complete. If clear_existing_callbacks is true, then the new callback - /// will replace any existing callbacks, otherwise it will be added to the - /// list of callbacks. - /// - /// The future's result data will be passed back when the callback is - /// called, along with the user_data supplied here. - /// - /// After the callback has been called, if `user_data_delete_fn_ptr` is - /// non-null, then `(*user_data_delete_fn_ptr)(user_data)` will be called. - virtual CompletionCallbackHandle AddCompletionCallback( - const FutureHandle& handle, FutureBase::CompletionCallback callback, - void* user_data, void (*user_data_delete_fn)(void*), - bool clear_existing_callbacks) = 0; - - /// Unregister a callback that was previously registered with - /// `AddCompletionCallback`. - virtual void RemoveCompletionCallback( - const FutureHandle& handle, CompletionCallbackHandle callback_handle) = 0; - -#if defined(FIREBASE_USE_STD_FUNCTION) - /// Register a callback that will be called when this future's status is set - /// to Complete. - /// - /// If `clear_existing_callbacks` is true, then the new callback - /// will replace any existing callbacks, otherwise it will be added to the - /// list of callbacks. - /// - /// The future's result data will be passed back when the callback is - /// called. - /// - /// @return A handle that can be passed to `FutureBase::RemoveCompletion`. - virtual CompletionCallbackHandle AddCompletionCallbackLambda( - const FutureHandle& handle, - std::function callback, - bool clear_existing_callbacks) = 0; -#endif // defined(FIREBASE_USE_STD_FUNCTION) - - /// Register this Future instance to be cleaned up. - virtual void RegisterFutureForCleanup(FutureBase* future) = 0; - - /// Unregister this Future instance from the cleanup list. - virtual void UnregisterFutureForCleanup(FutureBase* future) = 0; -}; - -inline void RegisterForCleanup(FutureApiInterface* api, FutureBase* future) { - if (api != NULL) { // NOLINT - api->RegisterFutureForCleanup(future); - } -} - -inline void UnregisterForCleanup(FutureApiInterface* api, FutureBase* future) { - if (api != NULL) { // NOLINT - api->UnregisterFutureForCleanup(future); - } -} - -class CompletionCallbackHandle { - public: - // Construct a null CompletionCallbackHandle. - CompletionCallbackHandle() - : callback_(nullptr), - user_data_(nullptr), - user_data_delete_fn_(nullptr) {} - - private: - friend class ::firebase::FutureBase; - friend class ::firebase::ReferenceCountedFutureImpl; - CompletionCallbackHandle(FutureBase::CompletionCallback callback, - void* user_data, void (*user_data_delete_fn)(void*)) - : callback_(callback), - user_data_(user_data), - user_data_delete_fn_(user_data_delete_fn) {} - - FutureBase::CompletionCallback callback_; - void* user_data_; - void (*user_data_delete_fn_)(void*); -}; - -} // namespace detail - -template -void Future::OnCompletion(TypedCompletionCallback callback, - void* user_data) const { - FutureBase::OnCompletion(reinterpret_cast(callback), - user_data); -} - -#if defined(FIREBASE_USE_STD_FUNCTION) -template -inline void Future::OnCompletion( - std::function&)> callback) const { - FutureBase::OnCompletion( - *reinterpret_cast*>(&callback)); -} -#endif // defined(FIREBASE_USE_STD_FUNCTION) - -#if defined(INTERNAL_EXPERIMENTAL) -template -FutureBase::CompletionCallbackHandle Future::AddOnCompletion( - TypedCompletionCallback callback, void* user_data) const { - return FutureBase::AddOnCompletion( - reinterpret_cast(callback), user_data); -} - -#if defined(FIREBASE_USE_STD_FUNCTION) -template -inline FutureBase::CompletionCallbackHandle Future::AddOnCompletion( - std::function&)> callback) const { - return FutureBase::AddOnCompletion( - *reinterpret_cast*>(&callback)); -} -#endif // defined(FIREBASE_USE_STD_FUNCTION) - -#endif // defined(INTERNAL_EXPERIMENTAL) - -inline FutureBase::FutureBase() - : mutex_(Mutex::Mode::kModeNonRecursive), - api_(NULL), - handle_(0) {} // NOLINT - -inline FutureBase::FutureBase(detail::FutureApiInterface* api, - const FutureHandle& handle) - : mutex_(Mutex::Mode::kModeNonRecursive), api_(api), handle_(handle) { - api_->ReferenceFuture(handle_); - // Once the FutureBase has reference, we don't need extra handle reference. - handle_.Detach(); - detail::RegisterForCleanup(api_, this); -} - -inline FutureBase::~FutureBase() { Release(); } - -inline FutureBase::FutureBase(const FutureBase& rhs) - : mutex_(Mutex::Mode::kModeNonRecursive), - api_(NULL) // NOLINT -{ // NOLINT - *this = rhs; -} - -inline FutureBase& FutureBase::operator=(const FutureBase& rhs) { - Release(); - - detail::FutureApiInterface* new_api; - FutureHandle new_handle; - { - MutexLock lock(rhs.mutex_); - new_api = rhs.api_; - new_handle = rhs.handle_; - } - - { - MutexLock lock(mutex_); - api_ = new_api; - handle_ = new_handle; - - if (api_ != NULL) { // NOLINT - api_->ReferenceFuture(handle_); - } - detail::RegisterForCleanup(api_, this); - } - - return *this; -} - -#if defined(FIREBASE_USE_MOVE_OPERATORS) -inline FutureBase::FutureBase(FutureBase&& rhs) noexcept - : mutex_(Mutex::Mode::kModeNonRecursive), - api_(NULL) // NOLINT -{ - *this = std::move(rhs); -} - -inline FutureBase& FutureBase::operator=(FutureBase&& rhs) noexcept { - Release(); - - detail::FutureApiInterface* new_api; - FutureHandle new_handle; - { - MutexLock lock(rhs.mutex_); - detail::UnregisterForCleanup(rhs.api_, &rhs); - new_api = rhs.api_; - new_handle = rhs.handle_; - rhs.api_ = NULL; // NOLINT - } - - MutexLock lock(mutex_); - api_ = new_api; - handle_ = new_handle; - detail::RegisterForCleanup(api_, this); - return *this; -} -#endif // defined(FIREBASE_USE_MOVE_OPERATORS) - -inline void FutureBase::Release() { - MutexLock lock(mutex_); - if (api_ != NULL) { // NOLINT - detail::UnregisterForCleanup(api_, this); - api_->ReleaseFuture(handle_); - api_ = NULL; // NOLINT - } -} - -inline FutureStatus FutureBase::status() const { - MutexLock lock(mutex_); - return api_ == NULL ? // NOLINT - kFutureStatusInvalid - : api_->GetFutureStatus(handle_); -} - -inline int FutureBase::error() const { - MutexLock lock(mutex_); - return api_ == NULL ? -1 : api_->GetFutureError(handle_); // NOLINT -} - -inline const char* FutureBase::error_message() const { - MutexLock lock(mutex_); - return api_ == NULL ? NULL : api_->GetFutureErrorMessage(handle_); // NOLINT -} - -inline const void* FutureBase::result_void() const { - MutexLock lock(mutex_); - return api_ == NULL ? NULL : api_->GetFutureResult(handle_); // NOLINT -} - -inline void FutureBase::OnCompletion(CompletionCallback callback, - void* user_data) const { - MutexLock lock(mutex_); - if (api_ != NULL) { // NOLINT - api_->AddCompletionCallback(handle_, callback, user_data, nullptr, - /*clear_existing_callbacks=*/true); - } -} - -#if defined(INTERNAL_EXPERIMENTAL) -inline FutureBase::CompletionCallbackHandle FutureBase::AddOnCompletion( - CompletionCallback callback, void* user_data) const { - MutexLock lock(mutex_); - if (api_ != NULL) { // NOLINT - return api_->AddCompletionCallback(handle_, callback, user_data, nullptr, - /*clear_existing_callbacks=*/false); - } - return CompletionCallbackHandle(); -} - -inline void FutureBase::RemoveOnCompletion( - CompletionCallbackHandle completion_handle) const { - MutexLock lock(mutex_); - if (api_ != NULL) { // NOLINT - api_->RemoveCompletionCallback(handle_, completion_handle); - } -} -#endif // defined(INTERNAL_EXPERIMENTAL) - -#if defined(FIREBASE_USE_STD_FUNCTION) -inline void FutureBase::OnCompletion( - std::function callback) const { - MutexLock lock(mutex_); - if (api_ != NULL) { // NOLINT - api_->AddCompletionCallbackLambda(handle_, callback, - /*clear_existing_callbacks=*/true); - } -} - -#if defined(INTERNAL_EXPERIMENTAL) -inline FutureBase::CompletionCallbackHandle FutureBase::AddOnCompletion( - std::function callback) const { - MutexLock lock(mutex_); - if (api_ != NULL) { // NOLINT - return api_->AddCompletionCallbackLambda( - handle_, callback, - /*clear_existing_callbacks=*/false); - } - return CompletionCallbackHandle(); -} -#endif // defined(INTERNAL__EXPERIMENTAL) - -#endif // defined(FIREBASE_USE_STD_FUNCTION) - -// NOLINTNEXTLINE - allow namespace overridden -} // namespace firebase - -/// @endcond - -#endif // FIREBASE_APP_SRC_INCLUDE_FIREBASE_INTERNAL_FUTURE_IMPL_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/internal/mutex.h b/packages/firebase_core/firebase_core/firebase_core/firebase/internal/mutex.h deleted file mode 100644 index 86f6a45d1b38..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/internal/mutex.h +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Copyright 2016 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_APP_SRC_INCLUDE_FIREBASE_INTERNAL_MUTEX_H_ -#define FIREBASE_APP_SRC_INCLUDE_FIREBASE_INTERNAL_MUTEX_H_ - -#include "firebase/internal/platform.h" - -#if FIREBASE_PLATFORM_WINDOWS -#include -#else -#include -#endif // FIREBASE_PLATFORM_WINDOWS - -namespace firebase { - -#if !defined(DOXYGEN) - -/// @brief A simple synchronization lock. Only one thread at a time can Acquire. -class Mutex { - public: - // Bitfield that describes the mutex configuration. - enum Mode { - kModeNonRecursive = (0 << 0), - kModeRecursive = (1 << 0), - }; - - Mutex() : Mutex(kModeRecursive) {} - - explicit Mutex(Mode mode); - - ~Mutex(); - - // Acquires the lock for this mutex, blocking until it is available. - void Acquire(); - - // Releases the lock for this mutex acquired by a previous `Acquire()` call. - void Release(); - -// Returns the implementation-defined native mutex handle. -// Used by firebase::Thread implementation. -#if FIREBASE_PLATFORM_WINDOWS - HANDLE* native_handle() { return &synchronization_object_; } -#else - pthread_mutex_t* native_handle() { return &mutex_; } -#endif // FIREBASE_PLATFORM_WINDOWS - - private: - Mutex(const Mutex&) = delete; - Mutex& operator=(const Mutex&) = delete; - -#if FIREBASE_PLATFORM_WINDOWS - HANDLE synchronization_object_; - Mode mode_; -#else - pthread_mutex_t mutex_; -#endif // FIREBASE_PLATFORM_WINDOWS -}; - -/// @brief Acquire and hold a /ref Mutex, while in scope. -/// -/// Example usage: -/// \code{.cpp} -/// Mutex syncronization_mutex; -/// void MyFunctionThatRequiresSynchronization() { -/// MutexLock lock(syncronization_mutex); -/// // ... logic ... -/// } -/// \endcode -class MutexLock { - public: - explicit MutexLock(Mutex& mutex) : mutex_(&mutex) { mutex_->Acquire(); } - ~MutexLock() { mutex_->Release(); } - - private: - // Copy is disallowed. - MutexLock(const MutexLock& rhs); // NOLINT - MutexLock& operator=(const MutexLock& rhs); - - Mutex* mutex_; -}; - -#endif // !defined(DOXYGEN) - -} // namespace firebase - -#endif // FIREBASE_APP_SRC_INCLUDE_FIREBASE_INTERNAL_MUTEX_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/internal/platform.h b/packages/firebase_core/firebase_core/firebase_core/firebase/internal/platform.h deleted file mode 100644 index 17d64e32d022..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/internal/platform.h +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Copyright 2019 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_APP_SRC_INCLUDE_FIREBASE_INTERNAL_PLATFORM_H_ -#define FIREBASE_APP_SRC_INCLUDE_FIREBASE_INTERNAL_PLATFORM_H_ - -// This header serts exactly one of these FIREBASE_PLATFORM macros to 1, and the -// rest to 0: -// -// FIREBASE_PLATFORM_ANDROID -// FIREBASE_PLATFORM_IOS -// FIREBASE_PLATFORM_TVOS -// FIREBASE_PLATFORM_OSX -// FIREBASE_PLATFORM_WINDOWS -// FIREBASE_PLATFORM_LINUX -// FIREBASE_PLATFORM_UNKNOWN -// -// You can use e.g. #if FIREBASE_PLATFORM_OSX to conditionally compile code -// after including this header. -// -// It also defines some convenience macros: -// FIREBASE_PLATFORM_DESKTOP (1 on OSX, WINDOWS, and LINUX, 0 otherwise) -// FIREBASE_PLATFORM_MOBILE (1 on IOS and ANDROID, 0 otherwise) - -#define FIREBASE_PLATFORM_ANDROID 0 -#define FIREBASE_PLATFORM_IOS 0 -#define FIREBASE_PLATFORM_TVOS 0 -#define FIREBASE_PLATFORM_OSX 0 -#define FIREBASE_PLATFORM_WINDOWS 0 -#define FIREBASE_PLATFORM_LINUX 0 -#define FIREBASE_PLATFORM_UNKNOWN 0 - -#ifdef __APPLE__ -#include "TargetConditionals.h" -#endif // __APPLE__ - -#if defined(__ANDROID__) -#undef FIREBASE_PLATFORM_ANDROID -#define FIREBASE_PLATFORM_ANDROID 1 -#elif defined(TARGET_OS_IOS) && TARGET_OS_IOS -#undef FIREBASE_PLATFORM_IOS -#define FIREBASE_PLATFORM_IOS 1 -#elif defined(TARGET_OS_TV) && TARGET_OS_TV -#undef FIREBASE_PLATFORM_TVOS -#define FIREBASE_PLATFORM_TVOS 1 -#elif defined(TARGET_OS_OSX) && TARGET_OS_OSX -#undef FIREBASE_PLATFORM_OSX -#define FIREBASE_PLATFORM_OSX 1 -#elif defined(_WIN32) -#undef FIREBASE_PLATFORM_WINDOWS -#define FIREBASE_PLATFORM_WINDOWS 1 -#elif defined(__linux__) -#undef FIREBASE_PLATFORM_LINUX -#define FIREBASE_PLATFORM_LINUX 1 -#else -#undef FIREBASE_PLATFORM_UNKNOWN -#define FIREBASE_PLATFORM_UNKNOWN 1 -#endif - -#if FIREBASE_PLATFORM_LINUX - -// Include std library header to get version defines -#include - -#if defined(__clang__) -#define FIREBASE_COMPILER_CLANG 1 -#elif defined(__GNUC__) -#define FIREBASE_COMPILER_GCC 1 -#endif - -#if defined(_LIBCPP_VERSION) -#define FIREBASE_STANDARD_LIBCPP 1 -#elif defined(__GLIBCXX__) -#define FIREBASE_STANDARD_LIBSTDCPP 1 -#endif - -#if (FIREBASE_COMPILER_CLANG && FIREBASE_STANDARD_LIBCPP) -#define FIREBASE_LINUX_BUILD_CONFIG_STRING "clang_libstdcpp" -#elif (FIREBASE_COMPILER_CLANG && FIREBASE_STANDARD_LIBSTDCPP) -#define FIREBASE_LINUX_BUILD_CONFIG_STRING "clang_libcpp" -#elif (FIREBASE_COMPILER_GCC && FIREBASE_STANDARD_LIBCPP) -#define FIREBASE_LINUX_BUILD_CONFIG_STRING "gcc_libstdcpp" -#elif (FIREBASE_COMPILER_GCC && FIREBASE_STANDARD_LIBSTDCPP) -#define FIREBASE_LINUX_BUILD_CONFIG_STRING "gcc_libcpp" -#else -#error "Unsupported compiler or standard library" -#endif - -#endif // FIREBASE_PLATFORM_LINUX - -#define FIREBASE_PLATFORM_MOBILE \ - (FIREBASE_PLATFORM_IOS || FIREBASE_PLATFORM_ANDROID) -#define FIREBASE_PLATFORM_DESKTOP \ - (FIREBASE_PLATFORM_LINUX || FIREBASE_PLATFORM_WINDOWS || \ - FIREBASE_PLATFORM_OSX) - -#endif // FIREBASE_APP_SRC_INCLUDE_FIREBASE_INTERNAL_PLATFORM_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/internal/type_traits.h b/packages/firebase_core/firebase_core/firebase_core/firebase/internal/type_traits.h deleted file mode 100644 index 7c465ea27c1e..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/internal/type_traits.h +++ /dev/null @@ -1,134 +0,0 @@ -/* - * Copyright 2017 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_APP_SRC_INCLUDE_FIREBASE_INTERNAL_TYPE_TRAITS_H_ -#define FIREBASE_APP_SRC_INCLUDE_FIREBASE_INTERNAL_TYPE_TRAITS_H_ - -#include -#include - -// Doxygen breaks trying to parse this file, and since it is internal logic, -// it doesn't need to be included in the generated documentation. -#ifndef DOXYGEN - -namespace firebase { - -template -struct remove_reference { - typedef T type; -}; - -template -struct remove_reference { - typedef T type; -}; - -template -struct remove_reference { - typedef T type; -}; - -template -struct is_array { - static constexpr bool value = false; -}; - -template -struct is_array { - static constexpr bool value = true; -}; - -template -struct is_array { - static constexpr bool value = true; -}; - -template -struct is_lvalue_reference { - static constexpr bool value = false; -}; - -template -struct is_lvalue_reference { - static constexpr bool value = true; -}; - -// STLPort does include header, but its contents are in `std::tr1` -// namespace. To work around this, use aliases. -// TODO(varconst): all of the reimplementations of traits above can be replaced -// with appropriate aliases. -// TODO(varconst): the traits in this file would be more conformant if they -// inherited from `std::integral_constant`. -#ifdef STLPORT -#define FIREBASE_TYPE_TRAITS_NS std::tr1 -#else -#define FIREBASE_TYPE_TRAITS_NS std -#endif - -template -using decay = FIREBASE_TYPE_TRAITS_NS::decay; - -template -using decay_t = typename decay::type; - -template -using enable_if = FIREBASE_TYPE_TRAITS_NS::enable_if; - -template -using is_floating_point = FIREBASE_TYPE_TRAITS_NS::is_floating_point; - -template -using is_integral = FIREBASE_TYPE_TRAITS_NS::is_integral; - -template -using is_same = FIREBASE_TYPE_TRAITS_NS::is_same; - -template -using integral_constant = FIREBASE_TYPE_TRAITS_NS::integral_constant; - -using true_type = FIREBASE_TYPE_TRAITS_NS::true_type; -using false_type = FIREBASE_TYPE_TRAITS_NS::false_type; - -#undef FIREBASE_TYPE_TRAITS_NS - -// `is_char::value` is true iff `T` is a character type (including `wchar_t` -// and C++11 fixed-width character types). -template -struct is_char { - static constexpr bool value = -#if __cplusplus >= 202002L - is_same::value || -#endif -#if __cplusplus >= 201103L - is_same::value || is_same::value || -#endif - is_same::value || is_same::value || - is_same::value || is_same::value; -}; - -// A subset of `std::is_integral`: excludes `bool` and character types. -template -struct is_integer { - static constexpr bool value = - is_integral::value && !is_same::value && !is_char::value; -}; - -// NOLINTNEXTLINE - allow namespace overridden -} // namespace firebase - -#endif // DOXYGEN - -#endif // FIREBASE_APP_SRC_INCLUDE_FIREBASE_INTERNAL_TYPE_TRAITS_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/log.h b/packages/firebase_core/firebase_core/firebase_core/firebase/log.h deleted file mode 100644 index 3d36ce37dcb3..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/log.h +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright 2016 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_APP_SRC_INCLUDE_FIREBASE_LOG_H_ -#define FIREBASE_APP_SRC_INCLUDE_FIREBASE_LOG_H_ - -/// @brief Namespace that encompasses all Firebase APIs. -namespace firebase { - -/// @brief Levels used when logging messages. -enum LogLevel { - /// Verbose Log Level - kLogLevelVerbose = 0, - /// Debug Log Level - kLogLevelDebug, - /// Info Log Level - kLogLevelInfo, - /// Warning Log Level - kLogLevelWarning, - /// Error Log Level - kLogLevelError, - /// Assert Log Level - kLogLevelAssert, -}; - -/// @brief Sets the logging verbosity. -/// All log messages at or above the specific log level. -/// -/// @param[in] level Log level to display, by default this is set to -/// kLogLevelInfo. -void SetLogLevel(LogLevel level); - -/// @brief Gets the logging verbosity. -/// -/// @return Get the currently configured logging verbosity. -LogLevel GetLogLevel(); - -// NOLINTNEXTLINE - allow namespace overridden -} // namespace firebase - -#endif // FIREBASE_APP_SRC_INCLUDE_FIREBASE_LOG_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/messaging.h b/packages/firebase_core/firebase_core/firebase_core/firebase/messaging.h deleted file mode 100644 index e7c7f5776868..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/messaging.h +++ /dev/null @@ -1,728 +0,0 @@ -// Copyright 2016 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef FIREBASE_MESSAGING_SRC_INCLUDE_FIREBASE_MESSAGING_H_ -#define FIREBASE_MESSAGING_SRC_INCLUDE_FIREBASE_MESSAGING_H_ - -#include - -#include -#include -#include - -#include "firebase/app.h" -#include "firebase/future.h" -#include "firebase/internal/common.h" - -#if !defined(DOXYGEN) && !defined(SWIG) -FIREBASE_APP_REGISTER_CALLBACKS_REFERENCE(messaging) -#endif // !defined(DOXYGEN) && !defined(SWIG) - -namespace firebase { - -/// @brief Firebase Cloud Messaging API. -/// -/// Firebase Cloud Messaging allows you to send data from your server to your -/// users' devices, and receive messages from devices on the same connection -/// if you're using a XMPP server. -/// -/// The FCM service handles all aspects of queueing of messages and delivery -/// to client applications running on target devices. -namespace messaging { - -/// @brief A class to configure the behavior of Firebase Cloud Messaging. -/// -/// This class contains various configuration options that control some of -/// Firebase Cloud Messaging's behavior. -struct MessagingOptions { - /// Default constructor. - MessagingOptions() : suppress_notification_permission_prompt(false) {} - - /// If true, do not display the prompt to the user requesting permission to - /// allow notifications to this app. If the prompt is suppressed in this way, - /// the developer must manually prompt the user for permission at some point - /// in the future using `RequestPermission()`. - /// - /// If this prompt has already been accepted once in the past the prompt will - /// not be displayed again. - /// - /// This option currently only applies to iOS and tvOS. - bool suppress_notification_permission_prompt; -}; - -/// @brief Data structure for parameters that are unique to the Android -/// implementation. -struct AndroidNotificationParams { - /// The channel id that was provided when the message was sent. - std::string channel_id; -}; - -/// Used for messages that display a notification. -/// -/// On android, this requires that the app is using the Play Services client -/// library. -struct Notification { - Notification() : android(nullptr) {} - -#ifndef SWIG - /// Copy constructor. Makes a deep copy of this Message. - Notification(const Notification& other) : android(nullptr) { *this = other; } -#endif // !SWIG - -#ifndef SWIG - /// Copy assignment operator. Makes a deep copy of this Message. - Notification& operator=(const Notification& other) { - this->title = other.title; - this->body = other.body; - this->icon = other.icon; - this->sound = other.sound; - this->tag = other.tag; - this->color = other.color; - this->click_action = other.click_action; - this->body_loc_key = other.body_loc_key; - this->body_loc_args = other.body_loc_args; - this->title_loc_key = other.title_loc_key; - this->title_loc_args = other.title_loc_args; - delete this->android; - if (other.android) { - this->android = new AndroidNotificationParams(*other.android); - } else { - this->android = nullptr; - } - return *this; - } -#endif // !SWIG - - /// Destructor. - ~Notification() { delete android; } - - /// Indicates notification title. This field is not visible on tvOS, iOS - /// phones and tablets. - std::string title; - - /// Indicates notification body text. - std::string body; - - /// Indicates notification icon. Sets value to myicon for drawable resource - /// myicon. - std::string icon; - - /// Indicates a sound to play when the device receives the notification. - /// Supports default, or the filename of a sound resource bundled in the - /// app. - /// - /// Android sound files must reside in /res/raw/, while iOS and tvOS sound - /// files can be in the main bundle of the client app or in the - /// Library/Sounds folder of the app’s data container. - std::string sound; - - /// Indicates the badge on the client app home icon. iOS and tvOS only. - std::string badge; - - /// Indicates whether each notification results in a new entry in the - /// notification drawer on Android. If not set, each request creates a new - /// notification. If set, and a notification with the same tag is already - /// being shown, the new notification replaces the existing one in the - /// notification drawer. - std::string tag; - - /// Indicates color of the icon, expressed in \#rrggbb format. Android only. - std::string color; - - /// The action associated with a user click on the notification. - /// - /// On Android, if this is set, an activity with a matching intent filter is - /// launched when user clicks the notification. - /// - /// If set on iOS or tvOS, corresponds to category in APNS payload. - std::string click_action; - - /// Indicates the key to the body string for localization. - /// - /// On iOS and tvOS, this corresponds to "loc-key" in APNS payload. - /// - /// On Android, use the key in the app's string resources when populating this - /// value. - std::string body_loc_key; - - /// Indicates the string value to replace format specifiers in body string - /// for localization. - /// - /// On iOS and tvOS, this corresponds to "loc-args" in APNS payload. - /// - /// On Android, these are the format arguments for the string resource. For - /// more information, see [Formatting strings][1]. - /// - /// [1]: - /// https://developer.android.com/guide/topics/resources/string-resource.html#FormattingAndStyling - std::vector body_loc_args; - - /// Indicates the key to the title string for localization. - /// - /// On iOS and tvOS, this corresponds to "title-loc-key" in APNS payload. - /// - /// On Android, use the key in the app's string resources when populating this - /// value. - std::string title_loc_key; - - /// Indicates the string value to replace format specifiers in title string - /// for localization. - /// - /// On iOS and tvOS, this corresponds to "title-loc-args" in APNS payload. - /// - /// On Android, these are the format arguments for the string resource. For - /// more information, see [Formatting strings][1]. - /// - /// [1]: - /// https://developer.android.com/guide/topics/resources/string-resource.html#FormattingAndStyling - std::vector title_loc_args; - - /// Parameters that are unique to the Android implementation. - AndroidNotificationParams* android; -}; - -/// @brief Data structure used to send messages to, and receive messages from, -/// cloud messaging. -struct Message { - /// Initialize the message. - Message() - : time_to_live(0), - notification(nullptr), - notification_opened(false), - sent_time(0) {} - - /// Destructor. - ~Message() { delete notification; } - -#ifndef SWIG - /// Copy constructor. Makes a deep copy of this Message. - Message(const Message& other) : notification(nullptr) { *this = other; } -#endif // !SWIG - -#ifndef SWIG - /// Copy assignment operator. Makes a deep copy of this Message. - Message& operator=(const Message& other) { - this->from = other.from; - this->to = other.to; - this->collapse_key = other.collapse_key; - this->data = other.data; - this->raw_data = other.raw_data; - this->message_id = other.message_id; - this->message_type = other.message_type; - this->priority = other.priority; - this->original_priority = other.original_priority; - this->sent_time = other.sent_time; - this->time_to_live = other.time_to_live; - this->error = other.error; - this->error_description = other.error_description; - delete this->notification; - if (other.notification) { - this->notification = new Notification(*other.notification); - } else { - this->notification = nullptr; - } - this->notification_opened = other.notification_opened; - this->link = other.link; - return *this; - } -#endif // !SWIG - - /// Authenticated ID of the sender. This is a project number in most cases. - /// - /// Any value starting with google.com, goog. or gcm. are reserved. - /// - /// This field is only used for downstream messages received through - /// Listener::OnMessage(). - std::string from; - - /// This parameter specifies the recipient of a message. - /// - /// For example it can be a registration token, a topic name, an Instance ID - /// or project ID. - /// - /// PROJECT_ID@gcm.googleapis.com or Instance ID are accepted. - std::string to; - - /// This parameter identifies a group of messages (e.g., with collapse_key: - /// "Updates Available") that can be collapsed, so that only the last message - /// gets sent when delivery can be resumed. This is intended to avoid sending - /// too many of the same messages when the device comes back online or becomes - /// active. - /// - /// Note that there is no guarantee of the order in which messages get sent. - /// - /// Note: A maximum of 4 different collapse keys is allowed at any given time. - /// This means a FCM connection server can simultaneously store 4 different - /// send-to-sync messages per client app. If you exceed this number, there is - /// no guarantee which 4 collapse keys the FCM connection server will keep. - /// - /// This field is only used for downstream messages received through - /// Listener::OnMessage(). - std::string collapse_key; - - /// The metadata, including all original key/value pairs. Includes some of the - /// HTTP headers used when sending the message. `gcm`, `google` and `goog` - /// prefixes are reserved for internal use. - std::map data; - - /// Binary payload. - std::vector raw_data; - - /// Message ID. This can be specified by sender. Internally a hash of the - /// message ID and other elements will be used for storage. The ID must be - /// unique for each topic subscription - using the same ID may result in - /// overriding the original message or duplicate delivery. - std::string message_id; - - /// Equivalent with a content-type. - /// - /// Defined values: - /// - "deleted_messages" - indicates the server had too many messages and - /// dropped some, and the client should sync with his own server. - /// Current limit is 100 messages stored. - /// - "send_event" - indicates an upstream message has been pushed to the - /// FCM server. It does not guarantee the upstream destination received - /// it. - /// Parameters: "message_id" - /// - "send_error" - indicates an upstream message expired, without being - /// sent to the FCM server. - /// Parameters: "message_id" and "error" - /// - /// If this field is missing, the message is a regular message. - /// - /// This field is only used for downstream messages received through - /// Listener::OnMessage(). - std::string message_type; - - /// Sets the priority of the message. Valid values are "normal" and "high." On - /// iOS and tvOS, these correspond to APNs priority 5 and 10. - /// - /// By default, messages are sent with normal priority. Normal priority - /// optimizes the client app's battery consumption, and should be used unless - /// immediate delivery is required. For messages with normal priority, the app - /// may receive the message with unspecified delay. - /// - /// When a message is sent with high priority, it is sent immediately, and the - /// app can wake a sleeping device and open a network connection to your - /// server. - /// - /// For more information, see [Setting the priority of a message][1]. - /// - /// This field is only used for downstream messages received through - /// Listener::OnMessage(). - /// - /// [1]: - /// https://firebase.google.com/docs/cloud-messaging/concept-options#setting-the-priority-of-a-message - std::string priority; - - /// This parameter specifies 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. For more - /// information, see [Setting the lifespan of a message][1]. - /// - /// This field is only used for downstream messages received through - /// Listener::OnMessage(). - /// - /// [1]: https://firebase.google.com/docs/cloud-messaging/concept-options#ttl - int32_t time_to_live; - - /// Error code. Used in "nack" messages for CCS, and in responses from the - /// server. - /// See the CCS specification for the externally-supported list. - /// - /// This field is only used for downstream messages received through - /// Listener::OnMessage(). - std::string error; - - /// Human readable details about the error. - /// - /// This field is only used for downstream messages received through - /// Listener::OnMessage(). - std::string error_description; - - /// Optional notification to show. This only set if a notification was - /// received with this message, otherwise it is null. - /// - /// The notification is only guaranteed to be valid during the call to - /// Listener::OnMessage(). If you need to keep it around longer you will need - /// to make a copy of either the Message or Notification. Copying the Message - /// object implicitly makes a deep copy of the notification (allocated with - /// new) which is owned by the Message. - /// - /// This field is only used for downstream messages received through - /// Listener::OnMessage(). - Notification* notification; - - /// A flag indicating whether this message was opened by tapping a - /// notification in the OS system tray. If the message was received this way - /// this flag is set to true. - bool notification_opened; - - /// The link into the app from the message. - /// - /// This field is only used for downstream messages received through - /// Listener::OnMessage(). - std::string link; - - /// @cond FIREBASE_APP_INTERNAL - /// Original priority of the message. - std::string original_priority; - - /// UTC timestamp in milliseconds when the message was sent. - /// See https://en.wikipedia.org/wiki/Unix_time for details of UTC. - int64_t sent_time; - /// @endcond -}; - -/// @brief Base class used to receive messages from Firebase Cloud Messaging. -/// -/// You need to override base class methods to handle any events required by the -/// application. Methods are invoked asynchronously and may be invoked on other -/// threads. -class Listener { - public: - virtual ~Listener(); - - /// Called on the client when a message arrives. - /// - /// @param[in] message The data describing this message. - virtual void OnMessage(const Message& message) = 0; - - /// Called on the client when a registration token arrives. This function - /// will eventually be called in response to a call to - /// firebase::messaging::Initialize(...). - /// - /// @param[in] token The registration token. - virtual void OnTokenReceived(const char* token) = 0; -}; - -/// @brief Initialize Firebase Cloud Messaging. -/// -/// After Initialize is called, the implementation may call functions on the -/// Listener provided at any time. -/// -/// @param[in] app The Firebase App object for this application. -/// @param[in] listener A Listener object that listens for events from the -/// Firebase Cloud Messaging servers. -/// -/// @return kInitResultSuccess if initialization succeeded, or -/// kInitResultFailedMissingDependency on Android if Google Play services is -/// not available on the current device. -InitResult Initialize(const App& app, Listener* listener); - -/// @brief Initialize Firebase Cloud Messaging. -/// -/// After Initialize is called, the implementation may call functions on the -/// Listener provided at any time. -/// -/// @param[in] app The Firebase App object for this application. -/// @param[in] listener A Listener object that listens for events from the -/// Firebase Cloud Messaging servers. -/// @param[in] options A set of options that configure the -/// initialzation behavior of Firebase Cloud Messaging. -/// -/// @return kInitResultSuccess if initialization succeeded, or -/// kInitResultFailedMissingDependency on Android if Google Play services is -/// not available on the current device. -InitResult Initialize(const App& app, Listener* listener, - const MessagingOptions& options); - -/// @brief Terminate Firebase Cloud Messaging. -/// -/// Frees resources associated with Firebase Cloud Messaging. -/// -/// @note On Android, the services will not be shut down by this method. -void Terminate(); - -/// Determines if automatic token registration during initalization is enabled. -/// -/// @return true if auto token registration is enabled and false if disabled. -bool IsTokenRegistrationOnInitEnabled(); - -/// Enable or disable token registration during initialization of Firebase Cloud -/// Messaging. -/// -/// This token is what identifies the user to Firebase, so disabling this avoids -/// creating any new identity and automatically sending it to Firebase, unless -/// consent has been granted. -/// -/// If this setting is enabled, it triggers the token registration refresh -/// immediately. This setting is persisted across app restarts and overrides the -/// setting "firebase_messaging_auto_init_enabled" specified in your Android -/// manifest (on Android) or Info.plist (on iOS and tvOS). -/// -///

By default, token registration during initialization is enabled. -/// -/// The registration happens before you can programmatically disable it, so -/// if you need to change the default, (for example, because you want to prompt -/// the user before FCM generates/refreshes a registration token on app -/// startup), add to your application’s manifest: -/// -/// -/// @if NOT_DOXYGEN -/// -/// @else -/// @code -/// <meta-data android:name="firebase_messaging_auto_init_enabled" -/// android:value="false" /> -/// @endcode -/// @endif -/// -/// or on iOS or tvOS to your Info.plist: -/// -/// @if NOT_DOXYGEN -/// FirebaseMessagingAutoInitEnabled -/// -/// @else -/// @code -/// <key>FirebaseMessagingAutoInitEnabled</key> -/// <false/> -/// @endcode -/// @endif -/// -/// @param enable sets if a registration token should be requested on -/// initialization. -void SetTokenRegistrationOnInitEnabled(bool enable); - -#ifndef SWIG -/// @brief Set the listener for events from the Firebase Cloud Messaging -/// servers. -/// -/// A listener must be set for the application to receive messages from -/// the Firebase Cloud Messaging servers. The implementation may call functions -/// on the Listener provided at any time. -/// -/// @param[in] listener A Listener object that listens for events from the -/// Firebase Cloud Messaging servers. -/// -/// @return Pointer to the previously set listener. -Listener* SetListener(Listener* listener); -#endif // !SWIG - -/// Error code returned by Firebase Cloud Messaging C++ functions. -enum Error { - /// The operation was a success, no error occurred. - kErrorNone = 0, - /// Permission to receive notifications was not granted. - kErrorFailedToRegisterForRemoteNotifications, - /// Topic name is invalid for subscription/unsubscription. - kErrorInvalidTopicName, - /// Could not subscribe/unsubscribe because there is no registration token. - kErrorNoRegistrationToken, - /// Unknown error. - kErrorUnknown, -}; - -/// @brief Displays a prompt to the user requesting permission to display -/// notifications. -/// -/// The permission prompt only appears on iOS and tvOS. If the user has -/// already agreed to allow notifications, no prompt is displayed and the -/// returned future is completed immediately. -/// -/// @return A future that completes when the notification prompt has been -/// dismissed. -Future RequestPermission(); - -/// @brief Gets the result of the most recent call to RequestPermission(); -/// -/// @return Result of the most recent call to RequestPermission(). -Future RequestPermissionLastResult(); - -/// @brief Subscribe to receive all messages to the specified topic. -/// -/// Subscribes an app instance to a topic, enabling it to receive messages -/// sent to that topic. -/// -/// Call this function from the main thread. FCM is not thread safe. -/// -/// @param[in] topic The name of the topic to subscribe. Must match the -/// following regular expression: `[a-zA-Z0-9-_.~%]{1,900}`. -Future Subscribe(const char* topic); - -/// @brief Gets the result of the most recent call to Unsubscribe(); -/// -/// @return Result of the most recent call to Unsubscribe(). -Future SubscribeLastResult(); - -/// @brief Unsubscribe from a topic. -/// -/// Unsubscribes an app instance from a topic, stopping it from receiving -/// any further messages sent to that topic. -/// -/// Call this function from the main thread. FCM is not thread safe. -/// -/// @param[in] topic The name of the topic to unsubscribe from. Must match the -/// following regular expression: `[a-zA-Z0-9-_.~%]{1,900}`. -Future Unsubscribe(const char* topic); - -/// @brief Gets the result of the most recent call to Unsubscribe(); -/// -/// @return Result of the most recent call to Unsubscribe(). -Future UnsubscribeLastResult(); - -/// Determines whether Firebase Cloud Messaging exports message delivery metrics -/// to BigQuery. -/// -/// This function is currently only implemented on Android, and returns false -/// with no other behavior on other platforms. -/// -/// @return true if Firebase Cloud Messaging exports message delivery metrics to -/// BigQuery. -bool DeliveryMetricsExportToBigQueryEnabled(); - -/// Enables or disables Firebase Cloud Messaging message delivery metrics export -/// to BigQuery. -/// -/// By default, message delivery metrics are not exported to BigQuery. Use this -/// method to enable or disable the export at runtime. In addition, you can -/// enable the export by adding to your manifest. Note that the run-time method -/// call will override the manifest value. -/// -/// -/// -/// This function is currently only implemented on Android, and has no behavior -/// on other platforms. -/// -/// @param[in] enable Whether Firebase Cloud Messaging should export message -/// delivery metrics to BigQuery. -void SetDeliveryMetricsExportToBigQuery(bool enable); - -/// @brief This creates a Firebase Installations ID, if one does not exist, and -/// sends information about the application and the device where it's running to -/// the Firebase backend. -/// -/// @return A future with the token. -Future GetToken(); - -/// @brief Gets the result of the most recent call to GetToken(); -/// -/// @return Result of the most recent call to GetToken(). -Future GetTokenLastResult(); - -/// @brief Deletes the default token for this Firebase project. -/// -/// Note that this does not delete the Firebase Installations ID that may have -/// been created when generating the token. See Installations.Delete() for -/// deleting that. -/// -/// @return A future that completes when the token is deleted. -Future DeleteToken(); - -/// @brief Gets the result of the most recent call to DeleteToken(); -/// -/// @return Result of the most recent call to DeleteToken(). -Future DeleteTokenLastResult(); - -class PollableListenerImpl; - -/// @brief A listener that can be polled to consume pending `Message`s. -/// -/// This class is intended to be used with applications that have a main loop -/// that frequently updates, such as in the case of a game that has a main -/// loop that updates 30 to 60 times a second. Rather than respond to incoming -/// messages and tokens via the `OnMessage` virtual function, this class will -/// queue up the message internally in a thread-safe manner so that it can be -/// consumed with `PollMessage`. For example: -/// -/// ::firebase::messaging::PollableListener listener; -/// ::firebase::messaging::Initialize(app, &listener); -/// -/// while (true) { -/// std::string token; -/// if (listener.PollRegistrationToken(&token)) { -/// LogMessage("Received a registration token"); -/// } -/// -/// ::firebase::messaging::Message message; -/// while (listener.PollMessage(&message)) { -/// LogMessage("Received a new message"); -/// } -/// -/// // Remainder of application logic... -/// } -class PollableListener : public Listener { - public: - /// @brief The default constructor. - PollableListener(); - - /// @brief The required virtual destructor. - virtual ~PollableListener(); - - /// @brief An implementation of `OnMessage` which adds the incoming messages - /// to a queue, which can be consumed by calling `PollMessage`. - virtual void OnMessage(const Message& message); - - /// @brief An implementation of `OnTokenReceived` which stores the incoming - /// token so that it can be consumed by calling `PollRegistrationToken`. - virtual void OnTokenReceived(const char* token); - - /// @brief Returns the first message queued up, if any. - /// - /// If one or more messages has been received, the first message in the - /// queue will be popped and used to populate the `message` argument and the - /// function will return `true`. If there are no pending messages, `false` is - /// returned. This function should be called in a loop until all messages have - /// been consumed, like so: - /// - /// ::firebase::messaging::Message message; - /// while (listener.PollMessage(&message)) { - /// LogMessage("Received a new message"); - /// } - /// - /// @param[out] message The `Message` struct to be populated. If there were no - /// pending messages, `message` is not modified. - /// - /// @return Returns `true` if there was a pending message, `false` otherwise. - bool PollMessage(Message* message); - - /// @brief Returns the registration key, if a new one has been received. - /// - /// When a new registration token is received, it is cached internally and can - /// be retrieved by calling `PollRegistrationToken`. The cached registration - /// token will be used to populate the `token` argument, then the cache will - /// be cleared and the function will return `true`. If there is no cached - /// registration token this function retuns `false`. - /// - /// std::string token; - /// if (listener.PollRegistrationToken(&token)) { - /// LogMessage("Received a registration token"); - /// } - /// - /// @param[out] token A string to be populated with the new token if one has - /// been received. If there were no new token, the string is left unmodified. - /// - /// @return Returns `true` if there was a new token, `false` otherwise. - bool PollRegistrationToken(std::string* token) { - bool got_token; - std::string token_received = PollRegistrationToken(&got_token); - if (got_token) { - *token = token_received; - } - return got_token; - } - - private: - std::string PollRegistrationToken(bool* got_token); - - // The implementation of the `PollableListener`. - PollableListenerImpl* impl_; -}; - -} // namespace messaging -} // namespace firebase - -#endif // FIREBASE_MESSAGING_SRC_INCLUDE_FIREBASE_MESSAGING_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/remote_config.h b/packages/firebase_core/firebase_core/firebase_core/firebase/remote_config.h deleted file mode 100644 index a2bd41775775..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/remote_config.h +++ /dev/null @@ -1,526 +0,0 @@ -// Copyright 2016 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef FIREBASE_REMOTE_CONFIG_SRC_INCLUDE_FIREBASE_REMOTE_CONFIG_H_ -#define FIREBASE_REMOTE_CONFIG_SRC_INCLUDE_FIREBASE_REMOTE_CONFIG_H_ - -#include -#include -#include - -#include "firebase/app.h" -#include "firebase/future.h" -#include "firebase/internal/common.h" -#include "firebase/internal/platform.h" -#ifndef SWIG -#include "firebase/variant.h" -#endif // SWIG - -#if !defined(DOXYGEN) && !defined(SWIG) -FIREBASE_APP_REGISTER_CALLBACKS_REFERENCE(remote_config) -#endif // !defined(DOXYGEN) && !defined(SWIG) - -/// @brief Namespace that encompasses all Firebase APIs. -namespace firebase { - -#ifndef SWIG -/// @brief Firebase Remote Config API. -/// -/// Firebase Remote Config is a cloud service that lets you change the -/// appearance and behavior of your app without requiring users to download an -/// app update. -#endif // SWIG -namespace remote_config { - -/// @brief Describes the most recent fetch request status. -enum LastFetchStatus { - /// The most recent fetch was a success, and its data is ready to be - /// applied, if you have not already done so. - kLastFetchStatusSuccess, - /// The most recent fetch request failed. - kLastFetchStatusFailure, - /// The most recent fetch is still in progress. - kLastFetchStatusPending, -}; - -/// @brief Describes the most recent fetch failure. -enum FetchFailureReason { - /// The fetch has not yet failed. - kFetchFailureReasonInvalid, - /// The most recent fetch failed because it was throttled by the server. - /// (You are sending too many fetch requests in too short a time.) - kFetchFailureReasonThrottled, - /// The most recent fetch failed for an unknown reason. - kFetchFailureReasonError, -}; - -/// @brief Describes the state of the most recent Fetch() call. -/// Normally returned as a result of the GetInfo() function. -struct ConfigInfo { - /// @brief The time (in milliseconds since the epoch) that the last fetch - /// operation completed. - uint64_t fetch_time; - - /// @brief The status of the last fetch request. - LastFetchStatus last_fetch_status; - - /// @brief The reason the most recent fetch failed. - FetchFailureReason last_fetch_failure_reason; - - /// @brief The time (in milliseconds since the epoch) when the refreshing of - /// Remote Config data is throttled. - uint64_t throttled_end_time; -}; - -/// @brief Describes the source a config value was retrieved from. -enum ValueSource { - /// The value was not specified and no default was specified, so a static - /// value (0 for numeric values, an empty string for strings) was returned. - kValueSourceStaticValue, - /// The value was found in the remote data store, and returned. - kValueSourceRemoteValue, - /// The value was not specified, so the specified default value was - /// returned instead. - kValueSourceDefaultValue, -}; - -/// @brief Describes a retrieved value. -struct ValueInfo { - /// Where the config value was retrieved from (Default Config or Active - /// Config). - ValueSource source; - /// If true this indicates conversion to the requested type - /// succeeded, otherwise conversion failed so the static value for the - /// requested type was retrieved instead. - bool conversion_successful; -}; - -/// @brief Keys of API settings. -/// -/// @see SetConfigSetting -/// @see GetConfigSetting -enum ConfigSetting { - /// Set the value associated with this key to "1" to enable developer mode - /// (i.e disable throttling) and "0" to disable. - kConfigSettingDeveloperMode, -}; - -/// @brief The default cache expiration used by Fetch(), equal to 12 hours, -/// in milliseconds. -static const uint64_t kDefaultCacheExpiration = 60 * 60 * 12 * 1000; - -/// @brief The default timeout used by Fetch(), equal to 30 seconds, -/// in milliseconds. -static const uint64_t kDefaultTimeoutInMilliseconds = 30 * 1000; - -/// @brief Describes a mapping of a key to a string value. Used to set default -/// values. -struct ConfigKeyValue { - /// The lookup key string. -#ifndef SWIG - /// - /// @note Ensure this string stays valid for the duration of the - /// call to SetDefaults. -#endif // SWIG - const char* key; - /// The value string to be stored. -#ifndef SWIG - /// - /// @note Ensure this string stays valid for the duration of the - /// call to SetDefaults. -#endif // SWIG - const char* value; -}; - -#ifndef SWIG -/// @brief Describes a mapping of a key to a value of any type. Used to set -/// default values. -struct ConfigKeyValueVariant { - /// The lookup key string. - /// - /// @note Ensure this string stays valid for the duration of the - /// call to SetDefaults. - const char* key; - /// The value to be stored. The type of the Variant determines the type of - /// default data for the given key. - /// - /// @note If you use a Variant of type StaticString, ensure it stays - /// valid for the duration of the call to SetDefaults. - Variant value; -}; -#endif // SWIG - -/// @brief Configurations for Remote Config behavior. -struct ConfigSettings { - /// The timeout specifies how long the client should wait for a connection to - /// the Firebase Remote Config servers. - /// - /// @note A fetch call will fail if it takes longer than the specified timeout - /// to connect to the Remote Config servers. Default is 60 seconds. - uint64_t fetch_timeout_in_milliseconds = kDefaultTimeoutInMilliseconds; - - /// The minimum interval between successive fetch calls. - /// - /// @note Fetches less than duration seconds after the last fetch from the - /// Firebase Remote Config server would use values returned during the last - /// fetch. Default is 12 hours. - uint64_t minimum_fetch_interval_in_milliseconds = kDefaultCacheExpiration; -}; - -namespace internal { -class RemoteConfigInternal; -} // namespace internal - -#ifndef SWIG -/// @brief Entry point for the Firebase C++ SDK for Remote Config. -/// -/// To use the SDK, call firebase::remote_config::RemoteConfig::GetInstance() to -/// obtain an instance of RemoteConfig, then call operations on that instance. -/// The instance contains the complete set of FRC parameter values available to -/// your app. The instance also stores values fetched from the FRC Server until -/// they are made available for use with a call to @ref Activate(). -#endif // SWIG -class RemoteConfig { - public: - ~RemoteConfig(); - - /// @brief Returns a Future that contains ConfigInfo representing the - /// initialization status of this Firebase Remote Config instance. - /// Use this method to ensure Set/Get call not being blocked. - Future EnsureInitialized(); - - /// @brief Get the (possibly still pending) results of the most recent - /// EnsureInitialized() call. - /// - /// @return The future result from the last call to EnsureInitialized(). - Future EnsureInitializedLastResult(); - - /// Asynchronously activates the most recently fetched configs, so that the - /// fetched key value pairs take effect. - /// - /// @return A Future that contains true if fetched configs were - /// activated. The future will contain false if the configs were already - /// activated. - Future Activate(); - - /// @brief Get the (possibly still pending) results of the most recent - /// Activate() call. - /// - /// @return The future result from the last call to Activate(). - Future ActivateLastResult(); - - /// Asynchronously fetches and then activates the fetched configs. - /// - /// If the time elapsed since the last fetch from the Firebase Remote Config - /// backend is more than the default minimum fetch interval, configs are - /// fetched from the backend. - /// - /// After the fetch is complete, the configs are activated so that the fetched - /// key value pairs take effect. - /// - /// @return A Future that contains true if the current call - /// activated the fetched configs; if no configs were fetched from the backend - /// and the local fetched configs have already been activated, the future will - /// contain false. - Future FetchAndActivate(); - - /// @brief Get the (possibly still pending) results of the most recent - /// FetchAndActivate() call. - /// - /// @return The future result from the last call to FetchAndActivate(). - Future FetchAndActivateLastResult(); - - /// @brief Fetches config data from the server. - /// - /// @note This does not actually apply the data or make it accessible, - /// it merely retrieves it and caches it. To accept and access the newly - /// retrieved values, you must call @ref Activate(). - /// - /// Note that this function is asynchronous, and will normally take an - /// unspecified amount of time before completion. - /// - /// @return A Future which can be used to determine when the fetch is - /// complete. - Future Fetch(); - - /// @brief Fetches config data from the server. - /// - /// @note This does not actually apply the data or make it accessible, - /// it merely retrieves it and caches it. To accept and access the newly - /// retrieved values, you must call @ref Activate(). - /// Note that this function is asynchronous, and will normally take an - /// unspecified amount of time before completion. - /// - /// @param[in] cache_expiration_in_seconds The number of seconds to keep - /// previously fetch data available. If cached data is available that is - /// newer than cache_expiration_in_seconds, then the function returns - /// immediately and does not fetch any data. A cache_expiration_in_seconds of - /// zero will always cause a fetch. - /// - /// @return A Future which can be used to determine when the fetch is - /// complete. - Future Fetch(uint64_t cache_expiration_in_seconds); - - /// @brief Get the (possibly still pending) results of the most recent Fetch() - /// call. - /// - /// @return The future result from the last call to Fetch(). - Future FetchLastResult(); - -#if defined(__ANDROID__) - /// @brief Sets the default values, using an XML resource. - /// - /// @note This method is specific to the Android implementation. - /// - /// This completely overwrites all previous default values. - /// - /// @param[in] defaults_resource_id Id for the XML resource, which should be - /// in your applications res/xml folder. - /// - /// @return a Future which can be used to determine when the operation is - /// complete. - Future SetDefaults(int defaults_resource_id); -#endif // __ANDROID__ - -#ifndef SWIG - /// @brief Sets the default values based on a mapping of string to Variant. - /// This allows you to specify defaults of type other than string. - /// - /// The type of each Variant in the map determines the type of data for which - /// you are providing a default. For example, boolean values can be retrieved - /// with GetBool(), integer values can be retrieved with GetLong(), double - /// values can be retrieved with GetDouble(), string values can be retrieved - /// with GetString(), and binary data can be retrieved with GetData(). - /// Aggregate Variant types are not allowed. - /// - /// @see firebase::Variant for more information on how to create a Variant of - /// each type. - /// - /// @note This completely overrides all previous values. - /// - /// @param defaults Array of ConfigKeyValueVariant, representing the new set - /// of defaults to apply. If the same key is specified multiple times, the - /// value associated with the last duplicate key is applied. - /// @param number_of_defaults Number of elements in the defaults array. - /// - /// @return a Future which can be used to determine when the operation is - /// complete. - Future SetDefaults(const ConfigKeyValueVariant* defaults, - size_t number_of_defaults); -#endif // SWIG - - /// @brief Sets the default values based on a string map. - /// - /// @note This completely overrides all previous values. - /// - /// @param defaults Array of ConfigKeyValue, representing the new set of - /// defaults to apply. If the same key is specified multiple times, the - /// value associated with the last duplicate key is applied. - /// @param number_of_defaults Number of elements in the defaults array. - /// - /// @return a Future which can be used to determine when the operation is - /// complete. - Future SetDefaults(const ConfigKeyValue* defaults, - size_t number_of_defaults); - - /// @brief Get the (possibly still pending) results of the most recent - /// SetDefaults() call. - /// - /// @return The future result from the last call to SetDefaults(). - Future SetDefaultsLastResult(); - - /// @brief Asynchronously changes the settings for this Remote Config - /// instance. - /// - /// @param settings The new settings to be applied. - /// - /// @return a Future which can be used to determine when the operation is - /// complete. - Future SetConfigSettings(ConfigSettings settings); - - /// @brief Gets the current settings of the RemoteConfig object. - /// - /// @return A ConfigSettings struct. - ConfigSettings GetConfigSettings(); - - /// @brief Get the (possibly still pending) results of the most recent - /// SetConfigSettings() call. - /// - /// @return The future result from the last call to SetConfigSettings(). - Future SetConfigSettingsLastResult(); - - /// @brief Returns the value associated with a key, converted to a bool. - /// - /// Values of "1", "true", "t", "yes", "y" and "on" are interpreted (case - /// insensitive) as true and "0", "false", "f", "no", "n", "off", - /// and empty strings are interpreted (case insensitive) as - /// false. - /// - /// @param[in] key Key of the value to be retrieved. - /// - /// @return Value associated with the specified key converted to a boolean - /// value. - bool GetBoolean(const char* key); - - /// @brief Returns the value associated with a key, converted to a bool. - /// - /// Values of "1", "true", "t", "yes", "y" and "on" are interpreted (case - /// insensitive) as true and "0", "false", "f", "no", "n", "off", - /// and empty strings are interpreted (case insensitive) as - /// false. - /// - /// @param[in] key Key of the value to be retrieved. - /// @param[out] info A return value, specifying the source of the returned - /// value. - /// - /// @return Value associated with the specified key converted to a boolean - /// value. - bool GetBoolean(const char* key, ValueInfo* info); - - /// @brief Returns the value associated with a key, converted to a 64-bit - /// integer. - /// - /// @param[in] key Key of the value to be retrieved. - /// - /// @return Value associated with the specified key converted to a 64-bit - /// integer. - int64_t GetLong(const char* key); - - /// @brief Returns the value associated with a key, converted to a 64-bit - /// integer. - /// - /// @param[in] key Key of the value to be retrieved. - /// @param[out] info A return value, specifying the source of the returned - /// value. - /// - /// @return Value associated with the specified key converted to a 64-bit - /// integer. - int64_t GetLong(const char* key, ValueInfo* info); - - /// @brief Returns the value associated with a key, converted to a double. - /// - /// @param[in] key Key of the value to be retrieved. - /// - /// @return Value associated with the specified key converted to a double. - double GetDouble(const char* key); - - /// @brief Returns the value associated with a key, converted to a double. - /// - /// @param[in] key Key of the value to be retrieved. - /// @param[out] info A return value, specifying the source of the returned - /// value. - /// - /// @return Value associated with the specified key converted to a double. - double GetDouble(const char* key, ValueInfo* info); - - /// @brief Returns the value associated with a key, converted to a string. - /// - /// @param[in] key Key of the value to be retrieved. - /// - /// @return Value as a string associated with the specified key. - std::string GetString(const char* key); - - /// @brief Returns the value associated with a key, converted to a string. - /// - /// @param[in] key Key of the value to be retrieved. - /// @param[out] info A return value, specifying the source of the returned - /// value. - /// - /// @return Value as a string associated with the specified key. - std::string GetString(const char* key, ValueInfo* info); - - /// @brief Returns the value associated with a key, as a vector of raw - /// byte-data. - /// - /// @param[in] key Key of the value to be retrieved. - /// - /// @return Vector of bytes. - std::vector GetData(const char* key); - - /// @brief Returns the value associated with a key, as a vector of raw - /// byte-data. - /// - /// @param[in] key Key of the value to be retrieved. - /// @param[out] info A return value, specifying the source of the returned - /// value. - /// - /// @return Vector of bytes. - std::vector GetData(const char* key, ValueInfo* info); - - /// @brief Gets the set of keys that start with the given prefix. - /// - /// @param[in] prefix The key prefix to look for. If empty or null, this - /// method will return all keys. - /// - /// @return Set of Remote Config parameter keys that start with the specified - /// prefix. Will return an empty set if there are no keys with the given - /// prefix. - std::vector GetKeysByPrefix(const char* prefix); - - /// @brief Gets the set of all keys. - /// - /// @return Set of all Remote Config parameter keys. - std::vector GetKeys(); - - /// @brief Returns a Map of Firebase Remote Config key value pairs. - /// - /// Evaluates the values of the parameters in the following order: - /// The activated value, if the last successful @ref Activate() contained the - /// key. The default value, if the key was set with @ref SetDefaults(). - std::map GetAll(); - - /// @brief Returns information about the last fetch request, in the form - /// of a ConfigInfo struct. - /// - /// @return A ConfigInfo struct, containing fields reflecting the state - /// of the most recent fetch request. - const ConfigInfo GetInfo(); - - /// Gets the App this remote config object is connected to. - App* app() { return app_; } - - /// Returns the RemoteConfig object for an App. Creates the RemoteConfig if - /// required. - /// - /// To get the RemoteConfig object for the default app, use, - /// GetInstance(GetDefaultFirebaseApp()); - /// - /// If the library RemoteConfig fails to initialize, init_result_out will be - /// written with the result status (if a pointer is given). - /// - /// @param[in] app The App to use for the RemoteConfig object. - static RemoteConfig* GetInstance(App* app); - - private: - explicit RemoteConfig(App* app); - - // Find RemoteConfig instance using App. Return null if the instance does not - // exist. - static RemoteConfig* FindRemoteConfig(App* app); - - // Clean up RemoteConfig instance. - void DeleteInternal(); - - /// The Firebase App this remote config is connected to. - App* app_; - - bool InitInternal(); - - internal::RemoteConfigInternal* internal_; -}; - -} // namespace remote_config -} // namespace firebase - -#endif // FIREBASE_REMOTE_CONFIG_SRC_INCLUDE_FIREBASE_REMOTE_CONFIG_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/storage.h b/packages/firebase_core/firebase_core/firebase_core/firebase/storage.h deleted file mode 100644 index 8d081e4c0ead..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/storage.h +++ /dev/null @@ -1,161 +0,0 @@ -// Copyright 2016 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_H_ -#define FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_H_ - -#include - -#include "firebase/app.h" -#include "firebase/internal/common.h" -#include "firebase/storage/common.h" -#include "firebase/storage/controller.h" -#include "firebase/storage/listener.h" -#include "firebase/storage/metadata.h" -#include "firebase/storage/storage_reference.h" - -#if !defined(DOXYGEN) -#ifndef SWIG -FIREBASE_APP_REGISTER_CALLBACKS_REFERENCE(storage) -#endif // SWIG -#endif // !defined(DOXYGEN) - -namespace firebase { - -/// Namespace for the Firebase C++ SDK for Cloud Storage. -namespace storage { - -namespace internal { -class StorageInternal; -class MetadataInternal; -} // namespace internal - -class StorageReference; - -#ifndef SWIG -/// @brief Entry point for the Firebase C++ SDK for Cloud Storage. -/// -/// To use the SDK, call firebase::storage::Storage::GetInstance() to -/// obtain an instance of Storage, then use GetReference() to obtain references -/// to child blobs. From there you can upload data with -/// StorageReference::PutStream(), get data via StorageReference::GetStream(). -#endif // SWIG -class Storage { - public: - /// @brief Destructor. You may delete an instance of Storage when - /// you are finished using it, to shut down the Storage library. - ~Storage(); - - /// @brief Get an instance of Storage corresponding to the given App. - /// - /// Cloud Storage uses firebase::App to communicate with Firebase - /// Authentication to authenticate users to the server backend. - /// - /// @param[in] app An instance of firebase::App. Cloud Storage will use - /// this to communicate with Firebase Authentication. - /// @param[out] init_result_out Optional: If provided, write the init result - /// here. Will be set to kInitResultSuccess if initialization succeeded, or - /// kInitResultFailedMissingDependency on Android if Google Play services is - /// not available on the current device. - /// - /// @returns An instance of Storage corresponding to the given App. - static Storage* GetInstance(::firebase::App* app, - InitResult* init_result_out = nullptr); - - /// @brief Get an instance of Storage corresponding to the given App, - /// with the given Cloud Storage URL. - /// - /// Cloud Storage uses firebase::App to communicate with Firebase - /// Authentication to authenticate users to the server backend. - /// - /// @param[in] app An instance of firebase::App. Cloud Storage will use - /// this to communicate with Firebase Authentication. - /// @param[in] url Cloud Storage URL. - /// @param[out] init_result_out Optional: If provided, write the init result - /// here. Will be set to kInitResultSuccess if initialization succeeded, or - /// kInitResultFailedMissingDependency on Android if Google Play services is - /// not available on the current device. - /// - /// @returns An instance of Storage corresponding to the given App. - static Storage* GetInstance(::firebase::App* app, const char* url, - InitResult* init_result_out = nullptr); - - /// @brief Get the firease::App that this Storage was created with. - /// - /// @returns The firebase::App this Storage was created with. - ::firebase::App* app(); - - /// @brief Get the URL that this Storage was created with. - /// - /// @returns The URL this Storage was created with, or an empty - /// string if this Storage was created with default parameters. - std::string url(); - - /// @brief Get a StorageReference to the root of the database. - StorageReference GetReference() const; - - /// @brief Get a StorageReference for the specified path. - StorageReference GetReference(const char* path) const; - /// @brief Get a StorageReference for the specified path. - StorageReference GetReference(const std::string& path) const { - return GetReference(path.c_str()); - } - - /// @brief Get a StorageReference for the provided URL. - StorageReference GetReferenceFromUrl(const char* url) const; - /// @brief Get a StorageReference for the provided URL. - StorageReference GetReferenceFromUrl(const std::string& url) const { - return GetReferenceFromUrl(url.c_str()); - } - - /// @brief Returns the maximum time in seconds to retry a download if a - /// failure occurs. - double max_download_retry_time(); - /// @brief Sets the maximum time to retry a download if a failure occurs. - /// Defaults to 600 seconds (10 minutes). - void set_max_download_retry_time(double max_transfer_retry_seconds); - - /// @brief Returns the maximum time to retry an upload if a failure occurs. - double max_upload_retry_time(); - /// @brief Sets the maximum time to retry an upload if a failure occurs. - /// Defaults to 600 seconds (10 minutes). - void set_max_upload_retry_time(double max_transfer_retry_seconds); - - /// @brief Returns the maximum time to retry operations other than upload - /// and download if a failure occurs. - double max_operation_retry_time(); - /// @brief Sets the maximum time to retry operations other than upload and - /// download if a failure occurs. Defaults to 120 seconds (2 minutes). - void set_max_operation_retry_time(double max_transfer_retry_seconds); - - private: - /// @cond FIREBASE_APP_INTERNAL - friend class Metadata; - friend class internal::MetadataInternal; - - Storage(::firebase::App* app, const char* url); - Storage(const Storage& src); - Storage& operator=(const Storage& src); - - // Destroy the internal_ object. - void DeleteInternal(); - - internal::StorageInternal* internal_; - /// @endcond -}; - -} // namespace storage -} // namespace firebase - -#endif // FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/storage/common.h b/packages/firebase_core/firebase_core/firebase_core/firebase/storage/common.h deleted file mode 100644 index 567ed714920c..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/storage/common.h +++ /dev/null @@ -1,62 +0,0 @@ -// Copyright 2016 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_COMMON_H_ -#define FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_COMMON_H_ - -namespace firebase { -namespace storage { - -/// Error code returned by Cloud Storage C++ functions. -enum Error { - /// The operation was a success, no error occurred. - kErrorNone = 0, - /// An unknown error occurred. - kErrorUnknown, - /// No object exists at the desired reference. - kErrorObjectNotFound, - /// No bucket is configured for Cloud Storage. - kErrorBucketNotFound, - /// No project is configured for Cloud Storage. - kErrorProjectNotFound, - /// Quota on your Cloud Storage bucket has been exceeded. - kErrorQuotaExceeded, - /// User is unauthenticated. - kErrorUnauthenticated, - /// User is not authorized to perform the desired action. - kErrorUnauthorized, - /// The maximum time limit on an operation (upload, download, delete, etc.) - /// has been exceeded. - kErrorRetryLimitExceeded, - /// File on the client does not match the checksum of the file received by the - /// server. - kErrorNonMatchingChecksum, - /// Size of the downloaded file exceeds the amount of memory allocated for the - /// download. - kErrorDownloadSizeExceeded, - /// User cancelled the operation. - kErrorCancelled, -}; - -/// @brief Get the human-readable error message corresponding to an error code. -/// -/// @param[in] error Error code to get the error message for. -/// -/// @returns Statically-allocated string describing the error. -const char* GetErrorMessage(Error error); - -} // namespace storage -} // namespace firebase - -#endif // FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_COMMON_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/storage/controller.h b/packages/firebase_core/firebase_core/firebase_core/firebase/storage/controller.h deleted file mode 100644 index 42f29aa0c73b..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/storage/controller.h +++ /dev/null @@ -1,146 +0,0 @@ -// Copyright 2016 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_CONTROLLER_H_ -#define FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_CONTROLLER_H_ - -#include "firebase/storage/storage_reference.h" - -namespace firebase { -namespace storage { - -/// @cond FIREBASE_APP_INTERNAL -namespace internal { -class ControllerInternal; -class ListenerInternal; -class RestOperation; -} // namespace internal -/// @endcond - -/// @brief Controls an ongoing operation, allowing the caller to Pause, Resume -/// or Cancel an ongoing download or upload. -/// -/// An instance of Controller can be constructed and passed to -/// StorageReference::GetBytes(), StorageReference::GetFile(), -/// StorageReference::PutBytes(), or StorageReference::PutFile() to become -/// associated with it. Each Controller can only be associated with one -/// operation at a time. -/// -/// A Controller is also passed as an argument to Listener's callbacks. The -/// Controller passed to a StorageReference operation is not the same object -/// passed to Listener callbacks (though it refers to the same operation), so -/// there are no restrictions on the lifetime of the Controller the user creates -/// (but the Controller passed into a Listener callbacks should only be used -/// from within that callback). -/// -/// This class is currently not thread safe and can only be called on the main -/// thread. -class Controller { - public: - /// @brief Default constructor. - /// - /// You may construct your own Controller to pass into various - /// StorageReference operations. - Controller(); - - /// @brief Destructor. - ~Controller(); - - /// @brief Copy constructor. - /// - /// @param[in] other Controller to copy from. - Controller(const Controller& other); - - /// @brief Copy assignment operator. - /// - /// @param[in] other Controller to copy from. - /// - /// @returns Reference to the destination Controller. - Controller& operator=(const Controller& other); - -#if defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) - /// @brief Move constructor. Moving is an efficient operation for - /// Controller instances. - /// - /// @param[in] other Controller to move from. - Controller(Controller&& other); - - /// @brief Move assignment operator. Moving is an efficient operation for - /// Controller instances. - /// - /// @param[in] other Controller to move from. - /// - /// @returns Reference to the destination Controller. - Controller& operator=(Controller&& other); -#endif // defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) - - /// @brief Pauses the operation currently in progress. - /// - /// @returns True if the operation was successfully paused, false otherwise. - bool Pause(); - - /// @brief Resumes the operation that is paused. - /// - /// @returns True if the operation was successfully resumed, false otherwise. - bool Resume(); - - /// @brief Cancels the operation currently in progress. - /// - /// @returns True if the operation was successfully canceled, false otherwise. - bool Cancel(); - - /// @brief Returns true if the operation is paused. - bool is_paused() const; - - /// @brief Returns the number of bytes transferred so far. - /// - /// @returns The number of bytes transferred so far. - int64_t bytes_transferred() const; - - /// @brief Returns the total bytes to be transferred. - /// - /// @returns The total bytes to be transferred. This will return -1 if - /// the size of the transfer is unknown. - int64_t total_byte_count() const; - - /// @brief Returns the StorageReference associated with this Controller. - /// - /// @returns The StorageReference associated with this Controller. - StorageReference GetReference() const; - - /// @brief Returns true if this Controller is valid, false if it is not - /// valid. An invalid Controller is one that is not associated with an - /// operation. - /// - /// @returns true if this Controller is valid, false if this Controller is - /// invalid. - bool is_valid() const; - - private: - /// @cond FIREBASE_APP_INTERNAL - friend class internal::StorageReferenceInternal; - friend class internal::ControllerInternal; - friend class internal::ListenerInternal; - friend class internal::RestOperation; - - Controller(internal::ControllerInternal* internal); - - internal::ControllerInternal* internal_; - /// @endcond -}; - -} // namespace storage -} // namespace firebase - -#endif // FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_CONTROLLER_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/storage/listener.h b/packages/firebase_core/firebase_core/firebase_core/firebase/storage/listener.h deleted file mode 100644 index 8bd624f61537..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/storage/listener.h +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright 2016 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_LISTENER_H_ -#define FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_LISTENER_H_ - -#include "firebase/storage/controller.h" - -namespace firebase { -namespace storage { - -/// @cond FIREBASE_APP_INTERNAL -namespace internal { -class ListenerInternal; -class StorageInternal; -class StorageReferenceInternal; -class RestOperation; -} // namespace internal -/// @endcond - -/// @brief Base class used to receive pause and progress events on a running -/// read or write operation. -/// -/// Subclasses of this listener class can be used to receive events about data -/// transfer progress a location. Attach the listener to a location using -/// StorageReference::GetBytes(), StorageReference::GetFile(), -/// StorageReference::PutBytes(), and StorageReference::PutFile(); then -/// OnPaused() will be called whenever the Read or Write operation is paused, -/// and OnProgress() will be called periodically as the transfer makes progress. -class Listener { - public: - /// @brief Constructor. - Listener(); - - /// @brief Virtual destructor. - virtual ~Listener(); - - /// @brief The operation was paused. - /// - /// @param[in] controller A controller that can be used to check the status - /// and make changes to the ongoing operation. - virtual void OnPaused(Controller* controller) = 0; - - /// @brief There has been progress event. - /// - /// @param[in] controller A controller that can be used to check the status - /// and make changes to the ongoing operation. - virtual void OnProgress(Controller* controller) = 0; - - private: - /// @cond FIREBASE_APP_INTERNAL - friend class internal::StorageReferenceInternal; - friend class internal::RestOperation; - - // Platform specific data. - internal::ListenerInternal* impl_; - /// @endcond -}; - -} // namespace storage -} // namespace firebase - -#endif // FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_LISTENER_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/storage/metadata.h b/packages/firebase_core/firebase_core/firebase_core/firebase/storage/metadata.h deleted file mode 100644 index 8d697c1072e7..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/storage/metadata.h +++ /dev/null @@ -1,276 +0,0 @@ -// Copyright 2016 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_METADATA_H_ -#define FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_METADATA_H_ - -#include -#include -#include -#include - -#include "firebase/internal/common.h" - -namespace firebase { -namespace storage { - -namespace internal { -class MetadataInternal; -class MetadataInternalCommon; -class StorageInternal; -class StorageReferenceInternal; -} // namespace internal - -class Storage; -class StorageReference; - -/// @brief Metadata stores default attributes such as size and content type. -/// -/// Metadata for a StorageReference. You may also store custom metadata key -/// value pairs. Metadata values may be used to authorize operations using -/// declarative validation rules. -class Metadata { - public: - /// @brief Create a default Metadata that you can modify and use. - Metadata(); - -#ifdef INTERNAL_EXPERIMENTAL - Metadata(internal::MetadataInternal* internal); -#endif - - /// @brief Copy constructor. - /// - /// @param[in] other Metadata to copy from. - Metadata(const Metadata& other); - - /// @brief Copy assignment operator. - /// - /// @param[in] other Metadata to copy from. - /// - /// @returns Reference to the destination Metadata. - Metadata& operator=(const Metadata& other); - -#if defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) - /// @brief Move constructor. Moving is an efficient operation for Metadata. - /// - /// @param[in] other Metadata to move from. - Metadata(Metadata&& other); - - /// @brief Move assignment operator. Moving is an efficient operation for - /// Metadata. - /// - /// @param[in] other Metadata to move from. - /// - /// @returns Reference to the destination Metadata. - Metadata& operator=(Metadata&& other); -#endif // defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) - - ~Metadata(); - - /// @brief Return the owning Google Cloud Storage bucket for the - /// StorageReference. - /// - /// @returns The owning Google Cloud Storage bucket for the StorageReference. - const char* bucket() const; - - /// @brief Set the Cache Control setting of the StorageReference. - /// - /// @see https://tools.ietf.org/html/rfc7234#section-5.2 - void set_cache_control(const char* cache_control); - - /// @brief Set the Cache Control setting of the StorageReference. - /// - /// @see https://tools.ietf.org/html/rfc7234#section-5.2 - void set_cache_control(const std::string& cache_control) { - set_cache_control(cache_control.c_str()); - } - - /// @brief Return the Cache Control setting of the StorageReference. - /// - /// @returns The Cache Control setting of the StorageReference. - /// - /// @see https://tools.ietf.org/html/rfc7234#section-5.2 - const char* cache_control() const; - - /// @brief Set the content disposition of the StorageReference. - /// - /// @see https://tools.ietf.org/html/rfc6266 - void set_content_disposition(const char* disposition); - - /// @brief Set the content disposition of the StorageReference. - /// - /// @see https://tools.ietf.org/html/rfc6266 - void set_content_disposition(const std::string& disposition) { - set_content_disposition(disposition.c_str()); - } - - /// @brief Return the content disposition of the StorageReference. - /// - /// @returns The content disposition of the StorageReference. - /// - /// @see https://tools.ietf.org/html/rfc6266 - const char* content_disposition() const; - - /// @brief Set the content encoding for the StorageReference. - /// - /// @see https://tools.ietf.org/html/rfc2616#section-14.11 - void set_content_encoding(const char* encoding); - - /// @brief Set the content encoding for the StorageReference. - /// - /// @see https://tools.ietf.org/html/rfc2616#section-14.11 - void set_content_encoding(const std::string& encoding) { - set_content_encoding(encoding.c_str()); - } - - /// @brief Return the content encoding for the StorageReference. - /// - /// @returns The content encoding for the StorageReference. - /// - /// @see https://tools.ietf.org/html/rfc2616#section-14.11 - const char* content_encoding() const; - - /// @brief Set the content language for the StorageReference. - /// - /// @see https://tools.ietf.org/html/rfc2616#section-14.12 - void set_content_language(const char* language); - - /// @brief Set the content language for the StorageReference. - /// - /// This must be an ISO 639-1 two-letter language code. - /// E.g. "zh", "es", "en". - /// - /// @see https://www.loc.gov/standards/iso639-2/php/code_list.php - void set_content_language(const std::string& language) { - set_content_language(language.c_str()); - } - - /// @brief Return the content language for the StorageReference. - /// - /// @returns The content language for the StorageReference. - /// - /// @see https://tools.ietf.org/html/rfc2616#section-14.12 - const char* content_language() const; - - /// @brief Set the content type of the StorageReference. - /// - /// @see https://tools.ietf.org/html/rfc2616#section-14.17 - void set_content_type(const char* type); - - /// @brief Set the content type of the StorageReference. - /// - /// @see https://tools.ietf.org/html/rfc2616#section-14.17 - void set_content_type(const std::string& type) { - set_content_type(type.c_str()); - } - - /// @brief Return the content type of the StorageReference. - /// - /// @returns The content type of the StorageReference. - /// - /// @see https://tools.ietf.org/html/rfc2616#section-14.17 - const char* content_type() const; - - /// @brief Return the time the StorageReference was created in milliseconds - /// since the epoch. - /// - /// @returns The time the StorageReference was created in milliseconds since - /// the epoch. - int64_t creation_time() const; - - /// @brief Return a map of custom metadata key value pairs. - /// - /// The pointer returned is only valid during the lifetime of the Metadata - /// object that owns it. - /// - /// @returns The keys for custom metadata. - std::map* custom_metadata() const; - - // download_url() and download_urls() are deprecated and removed. - // Please use StorageReference::GetDownloadUrl() instead. - - /// @brief Return a version String indicating what version of the - /// StorageReference. - /// - /// @returns A value indicating the version of the StorageReference. - int64_t generation() const; - - /// @brief Return a version String indicating the version of this - /// StorageMetadata. - /// - /// @returns A value indicating the version of this StorageMetadata. - int64_t metadata_generation() const; - - /// @brief Return a simple name of the StorageReference object. - /// - /// @returns A simple name of the StorageReference object. - const char* name() const; - - /// @brief Return the path of the StorageReference object. - /// - /// @returns The path of the StorageReference object. - const char* path() const; - - /// @brief Return the associated StorageReference to which this Metadata - /// belongs. - /// - /// @returns The associated StorageReference to which this Metadata belongs. - /// If this Metadata is invalid or is not associated with any file, an invalid - /// StorageReference is returned. - StorageReference GetReference() const; - - /// @brief Return the stored Size in bytes of the StorageReference object. - /// - /// @returns The stored Size in bytes of the StorageReference object. - int64_t size_bytes() const; - - /// @brief Return the time the StorageReference was last updated in - /// milliseconds since the epoch. - /// - /// @return The time the StorageReference was last updated in milliseconds - /// since the epoch. - int64_t updated_time() const; - - /// @brief Returns true if this Metadata is valid, false if it is not - /// valid. An invalid Metadata is returned when a method such as - /// StorageReference::GetMetadata() completes with an error. - /// - /// @returns true if this Metadata is valid, false if this Metadata is - /// invalid. - bool is_valid() const; - - /// @brief MD5 hash of the data; encoded using base64. - /// - /// @returns MD5 hash of the data; encoded using base64. - const char* md5_hash() const; - - private: - /// @cond FIREBASE_APP_INTERNAL - friend class StorageReference; - friend class internal::MetadataInternal; - friend class internal::MetadataInternalCommon; - friend class internal::StorageReferenceInternal; - -#ifndef INTERNAL_EXPERIMENTAL - Metadata(internal::MetadataInternal* internal); -#endif - - internal::MetadataInternal* internal_; - /// @endcond -}; - -} // namespace storage -} // namespace firebase - -#endif // FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_METADATA_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/storage/storage_reference.h b/packages/firebase_core/firebase_core/firebase_core/firebase/storage/storage_reference.h deleted file mode 100644 index e5c7c2f85ae6..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/storage/storage_reference.h +++ /dev/null @@ -1,361 +0,0 @@ -// Copyright 2016 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_STORAGE_REFERENCE_H_ -#define FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_STORAGE_REFERENCE_H_ - -#include -#include - -#include "firebase/future.h" -#include "firebase/internal/common.h" -#include "firebase/storage/metadata.h" - -namespace firebase { -namespace storage { - -class Controller; -class Listener; -class Storage; - -/// @cond FIREBASE_APP_INTERNAL -namespace internal { -class ControllerInternal; -class MetadataInternal; -class StorageInternal; -class StorageReferenceInternalCommon; -class StorageReferenceInternal; -} // namespace internal -/// @endcond FIREBASE_APP_INTERNAL - -#ifndef SWIG -/// Represents a reference to a Cloud Storage object. -/// Developers can upload and download objects, get/set object metadata, and -/// delete an object at a specified path. -#endif // SWIG -class StorageReference { - public: - /// @brief Default constructor. This creates an invalid StorageReference. - /// Attempting to perform any operations on this reference will fail unless a - /// valid StorageReference has been assigned to it. - StorageReference() : internal_(nullptr) {} - - ~StorageReference(); - - /// @brief Copy constructor. It's totally okay (and efficient) to copy - /// StorageReference instances, as they simply point to the same location. - /// - /// @param[in] reference StorageReference to copy from. - StorageReference(const StorageReference& reference); - - /// @brief Copy assignment operator. It's totally okay (and efficient) to copy - /// StorageReference instances, as they simply point to the same location. - /// - /// @param[in] reference StorageReference to copy from. - /// - /// @returns Reference to the destination StorageReference. - StorageReference& operator=(const StorageReference& reference); - -#if defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) - /// @brief Move constructor. Moving is an efficient operation for - /// StorageReference instances. - /// - /// @param[in] other StorageReference to move data from. - StorageReference(StorageReference&& other); - - /// @brief Move assignment operator. Moving is an efficient operation for - /// StorageReference instances. - /// - /// @param[in] other StorageReference to move data from. - /// - /// @returns Reference to the destination StorageReference. - StorageReference& operator=(StorageReference&& other); -#endif // defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) - - /// @brief Gets the firebase::storage::Storage instance to which we refer. - /// - /// The pointer will remain valid indefinitely. - /// - /// @returns The firebase::storage::Storage instance that this - /// StorageReference refers to. - Storage* storage(); - - /// @brief Gets a reference to a location relative to this one. - /// - /// @param[in] path Path relative to this reference's location. - /// The pointer only needs to be valid during this call. - /// - /// @returns Child relative to this location. - StorageReference Child(const char* path) const; - - /// @brief Gets a reference to a location relative to this one. - /// - /// @param[in] path Path relative to this reference's location. - /// - /// @returns Child relative to this location. - StorageReference Child(const std::string& path) const { - return Child(path.c_str()); - } - - /// @brief Deletes the object at the current path. - /// - /// @returns A Future result, which will complete when the operation either - /// succeeds or fails. When the Future is completed, if its Error is - /// kErrorNone, the operation succeeded. - Future Delete(); - - /// @brief Returns the result of the most recent call to RemoveValue(); - /// - /// @returns The result of the most recent call to RemoveValue(); - Future DeleteLastResult(); - - /// @brief Return the Google Cloud Storage bucket that holds this object. - /// - /// @returns The bucket. - std::string bucket(); - - /// @brief Return the full path of the storage reference, not including - /// the Google Cloud Storage bucket. - /// - /// @returns Full path to the storage reference, not including GCS bucket. - /// For example, for the reference "gs://bucket/path/to/object.txt", the full - /// path would be "path/to/object.txt". - std::string full_path(); - - /// @brief Asynchronously downloads the object from this StorageReference. - /// - /// A byte array will be allocated large enough to hold the entire file in - /// memory. Therefore, using this method will impact memory usage of your - /// process. - /// - /// @param[in] path Path to local file on device to download into. - /// @param[in] listener A listener that will respond to events on this read - /// operation. If not nullptr, a listener that will respond to events on this - /// read operation. The caller is responsible for allocating and deallocating - /// the listener. The same listener can be used for multiple operations. - /// @param[out] controller_out Controls the write operation, providing the - /// ability to pause, resume or cancel an ongoing write operation. If not - /// nullptr, this method will output a Controller here that you can use to - /// control the write operation. - /// - /// @returns A future that returns the number of bytes read. - Future GetFile(const char* path, Listener* listener = nullptr, - Controller* controller_out = nullptr); - - /// @brief Returns the result of the most recent call to GetFile(); - /// - /// @returns The result of the most recent call to GetFile(); - Future GetFileLastResult(); - - /// @brief Asynchronously downloads the object from this StorageReference. - /// - /// A byte array will be allocated large enough to hold the entire file in - /// memory. Therefore, using this method will impact memory usage of your - /// process. - /// - /// @param[in] buffer A byte buffer to read the data into. This buffer must - /// be valid for the duration of the transfer. - /// @param[in] buffer_size The size of the byte buffer. - /// @param[in] listener A listener that will respond to events on this read - /// operation. If not nullptr, a listener that will respond to events on this - /// read operation. The caller is responsible for allocating and deallocating - /// the listener. The same listener can be used for multiple operations. - /// @param[out] controller_out Controls the write operation, providing the - /// ability to pause, resume or cancel an ongoing write operation. If not - /// nullptr, this method will output a Controller here that you can use to - /// control the write operation. - /// - /// @returns A future that returns the number of bytes read. - Future GetBytes(void* buffer, size_t buffer_size, - Listener* listener = nullptr, - Controller* controller_out = nullptr); - - /// @brief Returns the result of the most recent call to GetBytes(); - /// - /// @returns The result of the most recent call to GetBytes(); - Future GetBytesLastResult(); - - /// @brief Asynchronously retrieves a long lived download URL with a revokable - /// token. - /// - /// This can be used to share the file with others, but can be revoked by a - /// developer in the Firebase Console if desired. - /// - /// @returns A Future result, which will complete when the operation either - /// succeeds or fails. When the Future is completed, if its Error is - /// kErrorNone, the operation succeeded and the URL is returned. - Future GetDownloadUrl(); - - /// @brief Returns the result of the most recent call to GetDownloadUrl(); - /// - /// @returns The result of the most recent call to GetDownloadUrl(); - Future GetDownloadUrlLastResult(); - - /// @brief Retrieves metadata associated with an object at this - /// StorageReference. - /// - /// @returns A Future result, which will complete when the operation either - /// succeeds or fails. When the Future is completed, if its Error is - /// kErrorNone, the operation succeeded and the Metadata is returned. - Future GetMetadata(); - - /// @brief Returns the result of the most recent call to GetMetadata(); - /// - /// @returns The result of the most recent call to GetMetadata(); - Future GetMetadataLastResult(); - - /// @brief Updates the metadata associated with this StorageReference. - /// - /// @returns A Future result, which will complete when the operation either - /// succeeds or fails. When the Future is completed, if its Error is - /// kErrorNone, the operation succeeded and the Metadata is returned. - Future UpdateMetadata(const Metadata& metadata); - - /// @brief Returns the result of the most recent call to UpdateMetadata(); - /// - /// @returns The result of the most recent call to UpdateMetadata(); - Future UpdateMetadataLastResult(); - - /// @brief Returns the short name of this object. - /// - /// @returns the short name of this object. - std::string name(); - - /// @brief Returns a new instance of StorageReference pointing to the parent - /// location or null if this instance references the root location. - /// - /// @returns The parent StorageReference. - StorageReference GetParent(); - - /// @brief Asynchronously uploads data to the currently specified - /// StorageReference, without additional metadata. - /// - /// @param[in] buffer A byte buffer to write data from. This buffer must be - /// valid for the duration of the transfer. - /// @param[in] buffer_size The size of the byte buffer. - /// @param[in] listener A listener that will respond to events on this read - /// operation. If not nullptr, a listener that will respond to events on this - /// write operation. The caller is responsible for allocating and deallocating - /// the listener. The same listener can be used for multiple operations. - /// @param[out] controller_out Controls the write operation, providing the - /// ability to pause, resume or cancel an ongoing write operation. If not - /// nullptr, this method will output a Controller here that you can use to - /// control the write operation. - /// - /// @returns A future that returns the Metadata. - Future PutBytes(const void* buffer, size_t buffer_size, - Listener* listener = nullptr, - Controller* controller_out = nullptr); - - /// @brief Asynchronously uploads data to the currently specified - /// StorageReference, without additional metadata. - /// - /// @param[in] buffer A byte buffer to write data from. This buffer must be - /// valid for the duration of the transfer. - /// @param[in] buffer_size The number of bytes to write. - /// @param[in] metadata Metadata containing additional information (MIME type, - /// etc.) about the object being uploaded. - /// @param[in] listener A listener that will respond to events on this read - /// operation. If not nullptr, a listener that will respond to events on this - /// write operation. The caller is responsible for allocating and deallocating - /// the listener. The same listener can be used for multiple operations. - /// @param[out] controller_out Controls the write operation, providing the - /// ability to pause, resume or cancel an ongoing write operation. If not - /// nullptr, this method will output a Controller here that you can use to - /// control the write operation. - /// - /// @returns A future that returns the Metadata. - Future PutBytes(const void* buffer, size_t buffer_size, - const Metadata& metadata, - Listener* listener = nullptr, - Controller* controller_out = nullptr); - - /// @brief Returns the result of the most recent call to PutBytes(); - /// - /// @returns The result of the most recent call to PutBytes(); - Future PutBytesLastResult(); - - /// @brief Asynchronously uploads data to the currently specified - /// StorageReference, without additional metadata. - /// - /// @param[in] path Path to local file on device to upload to Firebase - /// Storage. - /// @param[in] listener A listener that will respond to events on this read - /// operation. If not nullptr, a listener that will respond to events on this - /// write operation. The caller is responsible for allocating and deallocating - /// the listener. The same listener can be used for multiple operations. - /// @param[out] controller_out Controls the write operation, providing the - /// ability to pause, resume or cancel an ongoing write operation. If not - /// nullptr, this method will output a Controller here that you can use to - /// control the write operation. - /// - /// @returns A future that returns the Metadata. - Future PutFile(const char* path, Listener* listener = nullptr, - Controller* controller_out = nullptr); - - /// @brief Asynchronously uploads data to the currently specified - /// StorageReference, without additional metadata. - /// - /// @param[in] path Path to local file on device to upload to Firebase - /// Storage. - /// @param[in] metadata Metadata containing additional information (MIME type, - /// etc.) about the object being uploaded. - /// @param[in] listener A listener that will respond to events on this read - /// operation. If not nullptr, a listener that will respond to events on this - /// write operation. The caller is responsible for allocating and deallocating - /// the listener. The same listener can be used for multiple operations. - /// @param[out] controller_out Controls the write operation, providing the - /// ability to pause, resume or cancel an ongoing write operation. If not - /// nullptr, this method will output a Controller here that you can use to - /// control the write operation. - /// - /// @returns A future that returns the Metadata. - Future PutFile(const char* path, const Metadata& metadata, - Listener* listener = nullptr, - Controller* controller_out = nullptr); - - /// @brief Returns the result of the most recent call to PutFile(); - /// - /// @returns The result of the most recent call to PutFile(); - Future PutFileLastResult(); - - /// @brief Returns true if this StorageReference is valid, false if it is not - /// valid. An invalid StorageReference indicates that the reference is - /// uninitialized (created with the default constructor) or that there was an - /// error retrieving the reference. - /// - /// @returns true if this StorageReference is valid, false if this - /// StorageReference is invalid. - bool is_valid() const; - - private: - /// @cond FIREBASE_APP_INTERNAL - friend class Controller; - friend class internal::ControllerInternal; - friend class Metadata; - friend class internal::MetadataInternal; - friend class Storage; - friend class internal::StorageReferenceInternal; - friend class internal::StorageReferenceInternalCommon; - - StorageReference(internal::StorageReferenceInternal* internal); - - internal::StorageReferenceInternal* internal_; - /// @endcond -}; - -} // namespace storage -} // namespace firebase - -#endif // FIREBASE_STORAGE_SRC_INCLUDE_FIREBASE_STORAGE_STORAGE_REFERENCE_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/util.h b/packages/firebase_core/firebase_core/firebase_core/firebase/util.h deleted file mode 100644 index 4c78d45f3ac8..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/util.h +++ /dev/null @@ -1,101 +0,0 @@ -/* - * Copyright 2016 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_APP_SRC_INCLUDE_FIREBASE_UTIL_H_ -#define FIREBASE_APP_SRC_INCLUDE_FIREBASE_UTIL_H_ - -#include "firebase/app.h" -#include "firebase/future.h" - -namespace firebase { - -struct ModuleInitializerData; - -/// @brief Utility class to help with initializing Firebase modules. -/// -/// This optional class handles a basic Firebase C++ SDK code pattern: attempt -/// to initialize a Firebase module, and if the initialization fails on Android -/// due to Google Play services being unavailable, prompt the user to -/// update/enable Google Play services on their device. -/// -/// If the developer wants more advanced behavior (for example, wait to prompt -/// the user to update or enable Google Play services until later, or opt not to -/// use Firebase modules), they can still initialize each Firebase module -/// individually, and use google_play_services::MakeAvailable() directly if any -/// initializations fail. -class ModuleInitializer { - public: - /// @brief Initialization function, which should initialize a single Firebase - /// module and return the InitResult. - typedef InitResult (*InitializerFn)(App* app, void* context); - - ModuleInitializer(); - virtual ~ModuleInitializer(); - - /// @brief Initialize Firebase modules by calling one or more user-supplied - /// functions, each of which must initialize at most one library, and should - /// return the InitResult of the initialization. - /// - /// This function will run the initializers in order, checking the return - /// value of each. On Android, if the InitResult returned is - /// kInitResultFailedMissingDependency, this indicates that Google Play - /// services is not available and a Firebase module requires it. This function - /// will attempt to fix Google Play services, and will retry initializations - /// where it left off, beginning with the one that failed. - /// - /// @returns A future result. When all of the initializers are completed, the - /// Future will be completed with Error() = 0. If an initializer fails and the - /// situation cannot be fixed, the Future will be completed with Error() equal - /// to the number of initializers that did not succeed (since they are run in - /// order, this tells you which ones failed). - /// - /// @param[in] app The firebase::App that will be passed to the initializers, - /// as well as used to fix Google Play services on Android if needed. - /// - /// @param[in] context User-defined context, which will be passed to the - /// initializer functions. If you don't need this, you can use nullptr. - /// - /// @param[in] init_fns Your initialization functions to call, in an array. At - /// their simplest, these will each simply call a single Firebase module's - /// Initialize(app) and return the result, but you can perform more complex - /// logic if you prefer. - /// - /// @param[in] init_fns_count Number of initialization functions in the - /// supplied array. - /// - /// @note If a pending Initialize() is already running, this function will - /// return the existing Future rather than adding any new functions to the - /// initializer list. - Future Initialize(App* app, void* context, - const InitializerFn* init_fns, size_t init_fns_count); - - /// @brief Initialize one Firebase module by calling a single user-supplied - /// function that should initialize a Firebase module and return the - /// InitResult. @see Initialize(::firebase::App*, void*, const InitializerFn*) - /// for more information. - Future Initialize(App* app, void* context, InitializerFn init_fn); - - /// @brief Get the result of the most recent call to @see Initialize(). - Future InitializeLastResult(); - - private: - ModuleInitializerData* data_; -}; - -// NOLINTNEXTLINE - allow namespace overridden -} // namespace firebase - -#endif // FIREBASE_APP_SRC_INCLUDE_FIREBASE_UTIL_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/variant.h b/packages/firebase_core/firebase_core/firebase_core/firebase/variant.h deleted file mode 100644 index ef1d552dffa4..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/variant.h +++ /dev/null @@ -1,1197 +0,0 @@ -/* - * Copyright 2016 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIREBASE_APP_SRC_INCLUDE_FIREBASE_VARIANT_H_ -#define FIREBASE_APP_SRC_INCLUDE_FIREBASE_VARIANT_H_ - -#include - -#include -#include -#include -#include -#include - -#include "firebase/internal/common.h" - -/// @brief Namespace that encompasses all Firebase APIs. - -namespace firebase { -namespace internal { -class VariantInternal; -} -} // namespace firebase - -namespace firebase { - -// -// SWIG uses the Variant class as a readonly object, and so ignores most of the -// functions. In order to keep things clean, functions that should be exposed -// are explicitly listed in app.SWIG, and everything else is ignored. -// - -/// Variant data type used by Firebase libraries. -class Variant { - public: - /// Type of data that this variant object contains. - enum Type { - /// Null, or no data. - kTypeNull, - /// A 64-bit integer. - kTypeInt64, - /// A double-precision floating point number. - kTypeDouble, - /// A boolean value. - kTypeBool, - /// A statically-allocated string we point to. - kTypeStaticString, - /// A std::string. - kTypeMutableString, - /// A std::vector of Variant. - kTypeVector, - /// A std::map, mapping Variant to Variant. - kTypeMap, - /// An statically-allocated blob of data that we point to. Never constructed - /// by default. Use Variant::FromStaticBlob() to create a Variant of this - /// type. - kTypeStaticBlob, - /// A blob of data that the Variant holds. Never constructed by default. Use - /// Variant::FromMutableBlob() to create a Variant of this type, and copy - /// binary data from an existing source. - kTypeMutableBlob, - - // Note: If you add new types update enum InternalType; - }; - -// -// Because of the VariantVariantMap C# class, we need to hide the constructors -// explicitly, as the SWIG ignore does not seem to work with that macro. -// -#ifndef SWIG - /// @brief Construct a null Variant. - /// - /// The Variant constructed will be of type Null. - Variant() : type_(kInternalTypeNull), value_({}) {} - - /// @brief Construct a Variant with the given templated type. - /// - /// @param[in] value The value to construct the variant. - /// - /// Valid types for this constructor are `int`, `int64_t`, `float`, `double`, - /// `bool`, `const char*`, and `char*` (but see below for additional Variant - /// types). - /// - /// - /// Type `int` or `int64_t`: - /// * The Variant constructed will be of type Int64. - /// - /// Type `double` or `float`: - /// * The Variant constructed will be of type Double. - /// - /// Type `bool`: - /// * The Variant constructed will be of type Bool. - /// - /// Type `const char*`: - /// * The Variant constructed will be of type StaticString, and is_string() - /// will return true. **Note:** If you use this constructor, you must - /// ensure that the memory pointed to stays valid for the life of the - /// Variant, otherwise call mutable_string() or set_mutable_string(), - /// which will copy the string to an internal buffer. - /// - /// Type `char*`: - /// * The Variant constructed will be of type MutableString, and is_string() - /// will return true. - /// - /// Other types will result in compiler error unless using the following - /// constructor overloads: - /// * `std::string` - /// * `std::vector` - /// * `std::vector` where T is convertible to variant type - /// * `T*`, `size_t` where T is convertible to variant type - /// * `std::map` - /// * `std::map` where K and V is convertible to variant type - template - Variant(T value) // NOLINT - : type_(kInternalTypeNull) { - set_value_t(value); - } - - /// @brief Construct a Variant containing the given string value (makes a - /// copy). - /// - /// The Variant constructed will be of type MutableString, and is_string() - /// will return true. - /// - /// @param[in] value The string to use for the Variant. - Variant(const std::string& value) // NOLINT - : type_(kInternalTypeNull) { - set_mutable_string(value); - } - - /// @brief Construct a Variant containing the given std::vector of Variant. - /// - /// The Variant constructed will be of type Vector. - /// - /// @param[in] value The STL vector to copy into the Variant. - Variant(const std::vector& value) // NOLINT - : type_(kInternalTypeNull) { - set_vector(value); - } - - /// @brief Construct a Variant containing the given std::vector of something - /// that can be constructed into a Variant. - /// - /// The Variant constructed will be of type Vector. - /// - /// @param[in] value An STL vector containing elements that can be converted - /// to Variant (such as ints, strings, vectors). A Variant will be created for - /// each element, and copied into the Vector Variant constructed here. - template - Variant(const std::vector& value) // NOLINT - : type_(kInternalTypeNull) { - Clear(kTypeVector); - vector().reserve(value.size()); - for (size_t i = 0; i < value.size(); i++) { - vector().push_back(Variant(static_cast(value[i]))); - } - } - - /// @brief Construct a Variant from an array of supported types into a Vector. - /// - /// The Variant constructed will be of type Vector. - /// - /// @param[in] array_of_values A C array containing elements that can be - /// converted to Variant (such as ints, strings, vectors). A Variant will be - /// created for each element, and copied into the Vector Variant constructed - /// here. - /// @param[in] array_size Number of elements of the array. - template - Variant(const T array_of_values[], size_t array_size) - : type_(kInternalTypeNull) { - Clear(kTypeVector); - vector().reserve(array_size); - for (size_t i = 0; i < array_size; i++) { - vector()[i] = Variant(array_of_values[i]); - } - } - - /// @brief Construct a Variatn containing the given std::map of Variant to - /// Variant. - /// - /// The Variant constructed will be of type Map. - /// - /// @param[in] value The STL map to copy into the Variant. - Variant(const std::map& value) // NOLINT - : type_(kInternalTypeNull) { - set_map(value); - } - - /// @brief Construct a Variant containing the given std::map of something that - /// can be constructed into a Variant, to something that can be constructed - /// into a Variant. - /// - /// The Variant constructed will be of type Map. - /// - /// @param[in] value An STL map containing keys and values that can be - /// converted to Variant (such as ints, strings, vectors). A Variant will be - /// created for each key and for each value, and copied by pairs into the Map - /// Variant constructed here. - template - Variant(const std::map& value) // NOLINT - : type_(kInternalTypeNull) { - Clear(kTypeMap); - for (typename std::map::const_iterator i = value.begin(); - i != value.end(); ++i) { - map().insert(std::make_pair(Variant(i->first), Variant(i->second))); - } - } - - /// @brief Copy constructor. Performs a deep copy. - /// - /// @param[in] other Source Variant to copy from. - Variant(const Variant& other) : type_(kInternalTypeNull) { *this = other; } - - /// @brief Copy assignment operator. Performs a deep copy. - /// - /// @param[in] other Source Variant to copy from. - Variant& operator=(const Variant& other); - -#if defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) - - /// @brief Move constructor. Efficiently moves the more complex data types by - /// simply reassigning pointer ownership. - /// - /// @param[in] other Source Variant to move from. - Variant(Variant&& other) noexcept : type_(kInternalTypeNull) { - *this = std::move(other); - } - - /// @brief Move assignment operator. Efficiently moves the more complex data - /// types by simply reassigning pointer ownership. - /// - /// @param[in] other Source Variant to move from. - Variant& operator=(Variant&& other) noexcept; - -#endif // defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) -#endif // SWIG - - /// Destructor. Frees the memory that this Variant owns. - ~Variant() { Clear(); } - - /// @brief Equality operator. Both the type and the value must be equal - /// (except that static strings CAN be == to mutable strings). For container - /// types, element-by-element comparison is performed. For strings, string - /// comparison is performed. - /// - /// @param[in] other Variant to compare to. - /// - /// @return True if the Variants are of identical types and values, false - /// otherwise. - bool operator==(const Variant& other) const; - - /// @brief Inequality operator, only meant for internal use. - /// - /// Explanation: In order to use Variant as a key for std::map, we must - /// provide a comparison function. This comparison function is ONLY for - /// std::map to be able to use a Variant as a map key. - /// - /// We define v1 < v2 IFF: - /// * If different types, compare type as int: v1.type() < v2.type() - /// (note: this means that Variant(1) < Variant(0.0) - be careful!) - /// * If both are int64: v1.int64_value() < v2.int64_value(); - /// * If both are double: v1.double_value() < v2.double_value() - /// * If both are bool: v1.bool_value() < v2.bool_value(); - /// * If both are either static or mutable strings: strcmp(v1, v2) < 0 - /// * If both are vectors: - /// * If v1[0] < v2[0], that means v1 < v2 == true. Otherwise: - /// * If v1[0] > v2[0], that means v1 < v2 == false. Otherwise: - /// * Continue to the next element of both vectors and compare again. - /// * If you reach the end of one vector first, that vector is considered - /// to be lesser. - /// * If both are maps, iterate similar to vectors (since maps are ordered), - /// but for each element, first compare the key, then the value. - /// * If both are blobs, the smaller-sized blob is considered lesser. If both - /// blobs are the same size, use memcmp to compare the bytes. - /// - /// We have defined this operation such that if !(v1 < v2) && !(v2 < v1), it - /// must follow that v1 == v2. - /// - /// @param[in] other Variant to compare to. - /// - /// @return Results of the comparison, as described in this documentation. - /// - /// @note This will not give you the results you expect if you compare - /// Variants of different types! For example, Variant(0.0) < Variant(1). - bool operator<(const Variant& other) const; - - /// @brief Inequality operator: x != y is evaluated as !(x == y). - /// - /// @param[in] other Variant to compare to. - /// - /// @return Results of the comparison. - bool operator!=(const Variant& other) const { return !(*this == other); } - - /// @brief Inequality operator: x > y is evaluated as y < x - /// - /// @param[in] other Variant to compare to. - /// - /// @return Results of the comparison. - bool operator>(const Variant& other) const { return other < *this; } - - /// @brief Inequality operator: x >= y is evaluated as !(x < y) - /// - /// @param[in] other Variant to compare to. - /// - /// @return Results of the comparison. - bool operator>=(const Variant& other) const { return !(*this < other); } - - /// @brief Inequality operator: x <= y is evaluated as !(x > y) - /// - /// @param[in] other Variant to compare to. - /// - /// @return Results of the comparison. - bool operator<=(const Variant& other) const { return !(*this > other); } - - /// @brief Clear the given Variant data, optionally into a new type. Frees up - /// any memory that might have been allocated. After calling this, you can - /// access the Variant as the new type. - /// - /// @param[in] new_type Optional new type to clear the Variant to. You may - /// immediately begin using the Variant as that new type. - void Clear(Type new_type = kTypeNull); - - // Convenience functions (used similarly to constants). - - /// @brief Get a Variant of type Null. - /// - /// @return A Variant of type Null. - static Variant Null() { return Variant(); } - - /// @brief Get a Variant of integer value 0. - /// - /// @return A Variant of type Int64, with value 0. - static Variant Zero() { return Variant::FromInt64(0L); } - - /// @brief Get a Variant of integer value 1. - /// - /// @return A Variant of type Int64, with value 1. - static Variant One() { return Variant::FromInt64(1L); } - - /// @brief Get a Variant of double value 0.0. - /// - /// @return A Variant of type Double, with value 0.0. - static Variant ZeroPointZero() { return Variant::FromDouble(0.0); } - - /// @brief Get a Variant of double value 1.0. - /// - /// @return A Variant of type Double, with value 1.0. - static Variant OnePointZero() { return Variant::FromDouble(1.0); } - - /// @brief Get a Variant of bool value false. - /// - /// @return A Variant of type Bool, with value false. - static Variant False() { return Variant::FromBool(false); } - - /// @brief Get a Variant of bool value true. - /// - /// @return A Variant of type Bool, with value true. - static Variant True() { return Variant::FromBool(true); } - - /// @brief Get an empty string variant. - /// - /// @return A Variant of type StaticString, referring to an empty string. - static Variant EmptyString() { return Variant::FromStaticString(""); } - - /// @brief Get a Variant containing an empty mutable string. - /// - /// @return A Variant of type MutableString, containing an empty string. - static Variant EmptyMutableString() { - Variant v; - v.Clear(kTypeMutableString); - return v; - } - - /// @brief Get a Variant containing an empty vector. You can immediately call - /// vector() on it to work with the vector it contains. - /// - /// @return A Variant of type Vector, containing no elements. - static Variant EmptyVector() { - Variant v; - v.Clear(kTypeVector); - return v; - } - - /// @brief Get a Variant containing an empty map. You can immediately call - /// map() on - /// it to work with the map it contains. - /// - /// @return A Variant of type Map, containing no elements. - static Variant EmptyMap() { - Variant v; - v.Clear(kTypeMap); - return v; - } - - /// @brief Return a Variant containing an empty mutable blob of the requested - /// size, filled with 0-bytes. - /// - /// @param[in] size_bytes Size of the buffer you want, in bytes. - /// - /// @returns A Variant containing a mutable blob of the requested size, filled - /// with 0-bytes. - static Variant EmptyMutableBlob(size_t size_bytes) { - Variant v; - uint8_t* blank_data = new uint8_t[size_bytes]; - memset(blank_data, 0, size_bytes); - v.Clear(kTypeMutableBlob); - v.set_blob_pointer(blank_data, size_bytes); - return v; - } - - /// @brief Get the current type contained in this Variant. - /// - /// @return The Variant's type. - Type type() const { - // To avoid breaking user code, alias the small string type to mutable - // string. - if (type_ == kInternalTypeSmallString) { - return kTypeMutableString; - } - - return static_cast(type_); - } - - /// @brief Get whether this Variant is currently null. - /// - /// @return True if the Variant is Null, false otherwise. - bool is_null() const { return type() == kTypeNull; } - - /// @brief Get whether this Variant contains an integer. - /// - /// @return True if the Variant's type is Int64, false otherwise. - bool is_int64() const { return type() == kTypeInt64; } - - /// @brief Get whether this Variant contains a double. - /// - /// @return True if the Variant's type is Double, false otherwise. - bool is_double() const { return type() == kTypeDouble; } - - /// @brief Get whether this Variant contains a bool. - /// - /// @return True if the Variant's type is Bool, false otherwise. - bool is_bool() const { return type() == kTypeBool; } - - /// @brief Get whether this Variant contains a vector. - /// - /// @return True if the Variant's type is Vector, false otherwise. - bool is_vector() const { return type() == kTypeVector; } - - /// @brief Get whether this Variant contains a map. - /// - /// @return True if the Variant's type is Map, false otherwise. - bool is_map() const { return type() == kTypeMap; } - - /// @brief Get whether this Variant contains a static string. - /// - /// @return True if the Variant's type is StaticString, false otherwise. - bool is_static_string() const { return type() == kTypeStaticString; } - - /// @brief Get whether this Variant contains a mutable string. - /// - /// @return True if the Variant's type is MutableString, false otherwise. - bool is_mutable_string() const { return type() == kTypeMutableString; } - - /// @brief Get whether this Variant contains a string. - /// - /// @return True if the Variant's type is either StaticString or - /// MutableString or SmallString; false otherwise. - /// - /// @note No matter which type of string the Variant contains, you can read - /// its value via string_value(). - bool is_string() const { - return is_static_string() || is_mutable_string() || is_small_string(); - } - - /// @brief Get whether this Variant contains a static blob. - /// - /// @return True if the Variant's type is StaticBlob, false otherwise. - bool is_static_blob() const { return type() == kTypeStaticBlob; } - - /// @brief Get whether this Variant contains a mutable blob. - /// - /// @return True if the Variant's type is MutableBlob, false otherwise. - bool is_mutable_blob() const { return type() == kTypeMutableBlob; } - - /// @brief Get whether this Variant contains a blob. - /// - /// @return True if the Variant's type is either StaticBlob or - /// MutableBlob; false otherwise. - /// - /// @note No matter which type of blob the Variant contains, you can read - /// its data via blob_data() and get its size via blob_size(). - bool is_blob() const { return is_static_blob() || is_mutable_blob(); } - - /// @brief Get whether this Variant contains a numeric type, Int64 or Double. - /// - /// @return True if the Variant's type is either Int64 or Double; false - /// otherwise. - bool is_numeric() const { return is_int64() || is_double(); } - - /// @brief Get whether this Variant contains a fundamental type: Null, Int64, - /// Double, Bool, or one of the two String types. Essentially - /// !is_containerType(). - /// - /// @return True if the Variant's type is Int64, Double, Bool, or Null; false - /// otherwise. - bool is_fundamental_type() const { - return is_int64() || is_double() || is_string() || is_bool() || is_null(); - } - - /// @brief Get whether this Variant contains a container type: Vector or Map. - /// - /// @return True if the Variant's type is Vector or Map; false otherwise. - bool is_container_type() const { return is_vector() || is_map(); } - - /// @brief Get the current Variant converted into a string. Only valid for - /// fundamental types. - /// - /// Special cases: Booleans will be returned as "true" or "false". Null will - /// be returned as an empty string. The returned string may be either mutable - /// or static, depending on the source type. All other cases will return an - /// empty string. - /// - /// @return A Variant containing a String that represents the value of this - /// original Variant. - Variant AsString() const; - - /// @brief Get the current Variant converted into an integer. Only valid for - /// fundamental types. - /// - /// Special cases: If a String can be parsed as a number - /// via strtol(), it will be. If a Bool is true, this will return 1. All other - /// cases (including non-fundamental types) will return 0. - /// - /// @return A Variant containing an Int64 that represents the value of this - /// original Variant. - Variant AsInt64() const; - - /// @brief Get the current Variant converted into a floating-point - /// number. Only valid for fundamental types. - /// - /// Special cases: If a Bool is true, this will return 1. All other cases will - /// return 0. - /// - /// @return A Variant containing a Double that represents the value of this - /// original Variant. - Variant AsDouble() const; - - /// @brief Get the current Variant converted into a boolean. Null, 0, 0.0, - /// empty strings, empty vectors, empty maps, blobs of size 0, and "false" - /// (case-sensitive) are all considered false. All other values are true. - /// - /// @return A Variant of type Bool containing the original Variant interpreted - /// as a Bool. - Variant AsBool() const; - - /// @brief Mutable accessor for a Variant containing a string. - /// - /// If the Variant contains a static string, it will be converted into a - /// mutable string, which copies the const char*'s data into a std::string. - /// - /// @return Reference to the string contained in this Variant. - /// - /// @note If the Variant is not one of the two String types, this will assert. - std::string& mutable_string() { - if (type_ == kInternalTypeStaticString || - type_ == kInternalTypeSmallString) { - // Automatically promote a static or small string to a mutable string. - set_mutable_string(string_value(), false); - } - assert_is_type(kTypeMutableString); - return *value_.mutable_string_value; - } - - /// @brief Get the size of a blob. This method works with both static - /// and mutable blobs. - /// - /// @return Number of bytes of binary data contained in the blob. - size_t blob_size() const { - assert_is_blob(); - return value_.blob_value.size; - } - - /// @brief Get the pointer to the binary data contained in a blob. - /// This method works with both static and mutable blob. - /// - /// @return Pointer to the binary data. Use blob_size() to get the - /// number of bytes. - const uint8_t* blob_data() const { - assert_is_blob(); - return value_.blob_value.ptr; - } - - /// @brief Get a mutable pointer to the binary data contained in - /// a blob. - /// - /// If the Variant contains a static blob, it will be converted into a mutable - /// blob, which copies the binary data into the Variant's buffer. - /// - /// @returns Pointer to a mutable buffer of binary data. The size of the - /// buffer cannot be changed, but the contents are mutable. - uint8_t* mutable_blob_data() { - if (type_ == kInternalTypeStaticBlob) { - // Automatically promote a static blob to a mutable blob. - set_mutable_blob(blob_data(), blob_size()); - } - assert_is_type(kTypeMutableBlob); - return const_cast(value_.blob_value.ptr); - } - - /// @brief Const accessor for a Variant contianing mutable blob data. - /// - /// @note Unlike the non-const accessor, this accessor cannot "promote" a - /// static blob to mutable, and thus will assert if the Variant you pass in - /// is not of MutableBlob type. - /// - /// @returns Pointer to a mutable buffer of binary data. The size of the - /// buffer cannot be changed, but the contents are mutable. - uint8_t* mutable_blob_data() const { - assert_is_type(kTypeMutableBlob); - return const_cast(value_.blob_value.ptr); - } - - /// @brief Mutable accessor for a Variant containing a vector of Variant - /// data. - /// - /// @return Reference to the vector contained in this Variant. - /// - /// @note If the Variant is not of Vector type, this will assert. - std::vector& vector() { - assert_is_type(kTypeVector); - return *value_.vector_value; - } - /// @brief Mutable accessor for a Variant containing a map of Variant data. - /// - /// @return Reference to the map contained in this Variant. - /// - /// @note If the Variant is not of Map type, this will assert. - std::map& map() { - assert_is_type(kTypeMap); - return *value_.map_value; - } - - /// @brief Const accessor for a Variant containing an integer. - /// - /// @return The integer contained in this Variant. - /// - /// @note If the Variant is not of Int64 type, this will assert. - int64_t int64_value() const { - assert_is_type(kTypeInt64); - return value_.int64_value; - } - - /// @brief Const accessor for a Variant containing a double. - /// - /// @return The double contained in this Variant. - /// - /// @note If the Variant is not of Double type, this will assert. - double double_value() const { - assert_is_type(kTypeDouble); - return value_.double_value; - } - - /// @brief Const accessor for a Variant containing a bool. - /// - /// @return The bool contained in this Variant. - /// - /// @note If the Variant is not of Bool type, this will assert. - const bool& bool_value() const { - assert_is_type(kTypeBool); - return value_.bool_value; - } - - /// @brief Const accessor for a Variant containing a string. - /// - /// This can return both static and mutable strings. The pointer is only - /// guaranteed to persist if this Variant's type is StaticString. - /// - /// @return The string contained in this Variant. - /// - /// @note If the Variant is not of StaticString or MutableString type, this - /// will assert. - const char* string_value() const { - assert_is_string(); - if (type_ == kInternalTypeMutableString) - return value_.mutable_string_value->c_str(); - else if (type_ == kInternalTypeStaticString) - return value_.static_string_value; - else // if (type_ == kInternalTypeSmallString) - return value_.small_string; - } - - /// @brief Const accessor for a Variant containing a string. - /// - /// @note Unlike the non-const accessor, this accessor cannot "promote" a - /// static string to mutable, and thus returns a std::string copy instead of a - /// const reference to a std::string - /// - /// @return std::string with the string contents contained in this Variant. - std::string mutable_string() const { - assert_is_string(); - return string_value(); - } - - /// @brief Const accessor for a Variant containing a vector of Variant data. - /// - /// @return Reference to the vector contained in this Variant. - /// - /// @note If the Variant is not of Vector type, this will assert. - const std::vector& vector() const { - assert_is_type(kTypeVector); - return *value_.vector_value; - } - - /// @brief Const accessor for a Variant containing a map of strings to - /// Variant - /// data. - /// - /// @return Reference to the map contained in this Variant. - /// - /// @note If the Variant is not of Map type, this will assert. - const std::map& map() const { - assert_is_type(kTypeMap); - return *value_.map_value; - } - - /// @brief Sets the Variant value to null. - /// - /// The Variant's type will be Null. - void set_null() { Clear(kTypeNull); } - - /// @brief Sets the Variant to an 64-bit integer value. - /// - /// The Variant's type will be set to Int64. - /// - /// @param[in] value The 64-bit integer value for the Variant. - void set_int64_value(int64_t value) { - Clear(kTypeInt64); - value_.int64_value = value; - } - - /// @brief Sets the Variant to an double-precision floating point value. - /// - /// The Variant's type will be set to Double. - /// - /// @param[in] value The double-precision floating point value for the - /// Variant. - void set_double_value(double value) { - Clear(kTypeDouble); - value_.double_value = value; - } - - /// @brief Sets the Variant to the given boolean value. - /// - /// The Variant's type will be set to Bool. - /// - /// @param[in] value The boolean value for the Variant. - void set_bool_value(bool value) { - Clear(kTypeBool); - value_.bool_value = value; - } - - /// @brief Sets the Variant to point to a static string buffer. - /// - /// The Variant's type will be set to StaticString. - /// - /// @note If you use this method, you must ensure that the memory pointed to - /// stays valid for the life of the Variant, or otherwise call - /// mutable_string() or set_mutable_string(), which will copy the string to an - /// internal buffer. - /// - /// @param[in] value A pointer to the static null-terminated string for the - /// Variant. - void set_string_value(const char* value) { - Clear(kTypeStaticString); - value_.static_string_value = value; - } - - /// @brief Sets the Variant to a mutable string. - /// - /// The Variant's type will be set to MutableString. - /// - /// @param[in] value A pointer to a null-terminated string, which will be - /// copied into to the Variant. - void set_string_value(char* value) { - size_t len = strlen(value); - if (len < kMaxSmallStringSize) { - Clear(static_cast(kInternalTypeSmallString)); - strncpy(value_.small_string, value, len + 1); - } else { - set_mutable_string(std::string(value, len)); - } - } - - /// @brief Sets the Variant to a mutable string. - /// - /// The Variant's type will be set to MutableString. - /// - /// @param[in] value The string to use for the Variant. - void set_string_value(const std::string& value) { set_mutable_string(value); } - - /// @brief Sets the Variant to a copy of the given string. - /// - /// The Variant's type will be set to SmallString if the size of the string is - /// less than kMaxSmallStringSize (8 bytes on x86, 16 bytes on x64) or - /// otherwise set to MutableString. - /// - /// @param[in] value The string to use for the Variant. - /// @param[in] use_small_string Check to see if the input string should be - /// treated as a small string or left as a mutable string - void set_mutable_string(const std::string& value, - bool use_small_string = true) { - if (value.size() < kMaxSmallStringSize && use_small_string) { - Clear(static_cast(kInternalTypeSmallString)); - strncpy(value_.small_string, value.data(), value.size() + 1); - } else { - Clear(kTypeMutableString); - *value_.mutable_string_value = value; - } - } - - /// @brief Sets the Variant to a copy of the given binary data. - /// - /// The Variant's type will be set to MutableBlob. - /// - /// @param[in] src_data The data to use for the Variant. If you - /// pass in nullptr, no data will be copied, but a buffer of the - /// requested size will be allocated. - /// @param[in] size_bytes The size of the data, in bytes. - void set_mutable_blob(const void* src_data, size_t size_bytes) { - uint8_t* dest_data = new uint8_t[size_bytes]; // Will be deleted when - // `this` is deleted. - if (src_data != nullptr) { - memcpy(dest_data, src_data, size_bytes); - } - Clear(kTypeMutableBlob); - set_blob_pointer(dest_data, size_bytes); - } - - /// @brief Sets the Variant to point to static binary data. - /// - /// The Variant's type will be set to kTypeStaticBlob. - /// - /// @param[in] static_data Pointer to statically-allocated binary data. The - /// Variant will point to the data, not copy it. - /// @param[in] size_bytes Size of the data, in bytes. - /// - /// @note If you use this method, you must ensure that the memory pointer to - /// stays valid for the life of the Variant, or otherwise call - /// mutable_blob_data() or set_mutable_blob(), which will copy the data into - /// an internal buffer. - void set_static_blob(const void* static_data, size_t size_bytes) { - Clear(kTypeStaticBlob); - set_blob_pointer(static_data, size_bytes); - } - - /// @brief Sets the Variant to a copy of the given vector. - /// - /// The Variant's type will be set to Vector. - /// - /// @param[in] value The STL vector to copy into the Variant. - - void set_vector(const std::vector& value) { - Clear(kTypeVector); - *value_.vector_value = value; - } - - /// @brief Sets the Variant to a copy of the given map. - /// - /// The Variant's type will be set to Map. - /// - /// @param[in] value The STL map to copy into the Variant. - void set_map(const std::map& value) { - Clear(kTypeMap); - *value_.map_value = value; - } - - /// @brief Assigns an existing string which was allocated on the heap into the - /// Variant without performing a copy. This object will take over ownership of - /// the pointer, and will set the std::string* you pass in to NULL. - /// - /// The Variant's type will be set to MutableString. - /// - /// @param[in, out] str Pointer to a pointer to an STL string. The Variant - /// will take over ownership of the pointer to the string, and set the - /// pointer - /// you passed in to NULL. - void AssignMutableString(std::string** str) { - Clear(kTypeNull); - type_ = kInternalTypeMutableString; - value_.mutable_string_value = *str; - *str = NULL; // NOLINT - } - - /// @brief Assigns an existing vector which was allocated on the heap into the - /// Variant without performing a copy. This object will take over ownership of - /// the pointer, and will set the std::vector* you pass in to NULL. - /// - /// The Variant's type will be set to Vector. - /// - /// @param[in, out] vect Pointer to a pointer to an STL vector. The Variant - /// will take over ownership of the pointer to the vector, and set the - /// pointer - /// you passed in to NULL. - void AssignVector(std::vector** vect) { - Clear(kTypeNull); - type_ = kInternalTypeVector; - value_.vector_value = *vect; - *vect = NULL; // NOLINT - } - - /// @brief Assigns an existing map which was allocated on the heap into the - /// Variant without performing a copy. This object will take over ownership - /// of - /// the map, and will set the std::map** you pass in to NULL. - /// - /// The Variant's type will be set to Map. - /// - /// @param[in, out] map Pointer to a pointer to an STL map. The Variant will - /// take over ownership of the pointer to the map, and set the pointer you - /// passed in to NULL. - void AssignMap(std::map** map) { - Clear(kTypeNull); - type_ = kInternalTypeMap; - value_.map_value = *map; - *map = NULL; // NOLINT - } - - // Convenience methods for the times when constructors are too ambiguious. - - /// @brief Return a Variant from a 64-bit integer. - /// - /// @param[in] value 64-bit integer value to put into the Variant. - /// - /// @returns A Variant containing the 64-bit integer. - static Variant FromInt64(int64_t value) { return Variant(value); } - - /// @brief Return a Variant from a double-precision floating point number. - /// - /// @param[in] value Double-precision floating point value to put into the - /// Variant; - /// - /// @returns A Variant containing the double-precision floating point number. - static Variant FromDouble(double value) { return Variant(value); } - - /// @brief Return a Variant from a boolean. - /// - /// @param[in] value Boolean value to put into the Variant. - /// - /// @returns A Variant containing the Boolean. - static Variant FromBool(bool value) { return Variant(value); } - - /// @brief Return a Variant from a static string. - /// - /// @param[in] value Pointer to statically-allocated null-terminated string. - /// - /// @returns A Variant referring to the string pointer you passed in. - /// - /// @note If you use this function, you must ensure that the memory pointed - /// to stays valid for the life of the Variant, otherwise call - /// mutable_string() or set_mutable_string(), which will copy the string to an - /// internal buffer. - static Variant FromStaticString(const char* value) { return Variant(value); } - - /// @brief Return a Variant from a string. - /// - /// This method makes a copy of the string. - /// - /// @param[in] value String value to copy into the Variant. - /// - /// @returns A Variant containing a copy of the string. - static Variant FromMutableString(const std::string& value) { - return Variant(value); - } - - /// @brief Return a Variant that points to static binary data. - /// - /// @param[in] static_data Pointer to statically-allocated binary data. The - /// Variant will point to the data, not copy it. - /// @param[in] size_bytes Size of the data, in bytes. - /// - /// @returns A Variant pointing to the binary data. - /// - /// @note If you use this function, you must ensure that the memory pointed - /// to stays valid for the life of the Variant, otherwise call - /// mutable_blob() or set_mutable_blob(), which will copy the data to an - /// internal buffer. - static Variant FromStaticBlob(const void* static_data, size_t size_bytes) { - Variant v; - v.set_static_blob(static_data, size_bytes); - return v; - } - - /// @brief Return a Variant containing a copy of binary data. - /// - /// @param[in] src_data Pointer to binary data to be copied into the Variant. - /// @param[in] size_bytes Size of the data, in bytes. - /// - /// @returns A Variant containing a copy of the binary data. - static Variant FromMutableBlob(const void* src_data, size_t size_bytes) { - Variant v; - v.set_mutable_blob(src_data, size_bytes); - return v; - } - - /// @brief Return a Variant from a string, but make it mutable. - /// - /// Only copies the string once, unlike Variant(std::string(value)), which - /// copies the string twice. - /// - /// @param[in] value String value to copy into the Variant and make mutable. - /// - /// @returns A Variant containing a mutable copy of the string. - static Variant MutableStringFromStaticString(const char* value) { - std::string* str = new std::string(value); - Variant v; - v.AssignMutableString(&str); - return v; - } - - /// @brief Get the human-readable type name of a Variant type. - /// - /// @param[in] type Variant type to describe. - /// - /// @returns A string describing the type, suitable for error messages or - /// debugging. For example "Int64" or "MutableString". - static const char* TypeName(Type type); - - private: - // Internal Type of data that this variant object contains to avoid breaking - // API - enum InternalType { - /// Null, or no data. - kInternalTypeNull = kTypeNull, - /// A 64-bit integer. - kInternalTypeInt64 = kTypeInt64, - /// A double-precision floating point number. - kInternalTypeDouble = kTypeDouble, - /// A boolean value. - kInternalTypeBool = kTypeBool, - /// A statically-allocated string we point to. - kInternalTypeStaticString = kTypeStaticString, - /// A std::string. - kInternalTypeMutableString = kTypeMutableString, - /// A std::vector of Variant. - kInternalTypeVector = kTypeVector, - /// A std::map, mapping Variant to Variant. - kInternalTypeMap = kTypeMap, - /// An statically-allocated blob of data that we point to. Never constructed - /// by default. Use Variant::FromStaticBlob() to create a Variant of this - /// type. - kInternalTypeStaticBlob = kTypeStaticBlob, - /// A blob of data that the Variant holds. Never constructed by default. Use - /// Variant::FromMutableBlob() to create a Variant of this type, and copy - /// binary data from an existing source. - kInternalTypeMutableBlob = kTypeMutableBlob, - // A c string stored in the Variant internal data blob as opposed to be - // newed as a std::string. Max size is 16 bytes on x64 and 8 bytes on x86. - kInternalTypeSmallString = kTypeMutableBlob + 1, - // Not a valid type. Used to get the total number of Variant types. - kMaxTypeValue, - }; - - /// Human-readable type names, for error logging. - static const char* const kTypeNames[]; - - /// Assert that this Variant is of the given type, failing if it is not. - void assert_is_type(Type type) const; - - /// Assert that this Variant is NOT of the given type, failing if it is. - void assert_is_not_type(Type type) const; - - /// Assert that this Variant is a static string or mutable string, failing if - /// it is not. - void assert_is_string() const; - - /// Assert that this Variant is a static blob or mutable blob, failing if - /// it is not. - void assert_is_blob() const; - - /// Sets the blob's data pointer, for kTypeStaticBlob and kTypeMutableBlob. - /// Asserts if the Variant isn't a blob. Caller is responsible for managing - /// the pointer's memory and deleting any existing data at the location. - void set_blob_pointer(const void* blob_ptr, size_t size) { - assert_is_blob(); - value_.blob_value.ptr = static_cast(blob_ptr); - value_.blob_value.size = size; - } - - // If you hit a compiler error here it means you are trying to construct a - // variant with unsupported type. Ether cast to correct type or add support - // below. - template - void set_value_t(T value) = delete; - - // Get whether this Variant contains a small string. - bool is_small_string() const { return type_ == kInternalTypeSmallString; } - - // Current type contained in this Variant. - InternalType type_; - - // Older versions of visual studio cant have this inline in the union and do - // sizeof for small string - typedef struct { - const uint8_t* ptr; - size_t size; - } BlobValue; - - // Union of plain old data (scalars or pointers). - union Value { - int64_t int64_value; - double double_value; - bool bool_value; - const char* static_string_value; - std::string* mutable_string_value; - std::vector* vector_value; - std::map* map_value; - BlobValue blob_value; - char small_string[sizeof(BlobValue)]; - } value_; - - static constexpr size_t kMaxSmallStringSize = sizeof(Value::small_string); - - friend class firebase::internal::VariantInternal; -}; - -template <> -inline void Variant::set_value_t(int64_t value) { - set_int64_value(value); -} - -template <> -inline void Variant::set_value_t(int value) { - set_int64_value(static_cast(value)); -} - -template <> -inline void Variant::set_value_t(int16_t value) { - set_int64_value(static_cast(value)); -} - -template <> -inline void Variant::set_value_t(uint8_t value) { - set_int64_value(static_cast(value)); -} - -template <> -inline void Variant::set_value_t(int8_t value) { - set_int64_value(static_cast(value)); -} - -template <> -inline void Variant::set_value_t(char value) { - set_int64_value(static_cast(value)); -} - -template <> -inline void Variant::set_value_t(double value) { - set_double_value(value); -} - -template <> -inline void Variant::set_value_t(float value) { - set_double_value(static_cast(value)); -} - -template <> -inline void Variant::set_value_t(bool value) { - set_bool_value(value); -} - -template <> -inline void Variant::set_value_t(const char* value) { - set_string_value(value); -} - -template <> -inline void Variant::set_value_t(char* value) { - set_mutable_string(value); -} - -// NOLINTNEXTLINE - allow namespace overridden -} // namespace firebase - -#endif // FIREBASE_APP_SRC_INCLUDE_FIREBASE_VARIANT_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/firebase/version.h b/packages/firebase_core/firebase_core/firebase_core/firebase/version.h deleted file mode 100644 index 79d77fc8af4a..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/firebase/version.h +++ /dev/null @@ -1,68 +0,0 @@ -// Copyright 2016 Google Inc. All Rights Reserved. - -#ifndef FIREBASE_APP_CLIENT_CPP_SRC_VERSION_H_ -#define FIREBASE_APP_CLIENT_CPP_SRC_VERSION_H_ - -/// @def FIREBASE_VERSION_MAJOR -/// @brief Major version number of the Firebase C++ SDK. -/// @see kFirebaseVersionString -#define FIREBASE_VERSION_MAJOR 10 -/// @def FIREBASE_VERSION_MINOR -/// @brief Minor version number of the Firebase C++ SDK. -/// @see kFirebaseVersionString -#define FIREBASE_VERSION_MINOR 5 -/// @def FIREBASE_VERSION_REVISION -/// @brief Revision number of the Firebase C++ SDK. -/// @see kFirebaseVersionString -#define FIREBASE_VERSION_REVISION 0 - -/// @cond FIREBASE_APP_INTERNAL -#define FIREBASE_STRING_EXPAND(X) #X -#define FIREBASE_STRING(X) FIREBASE_STRING_EXPAND(X) -/// @endcond - -// Version number. -// clang-format off -#define FIREBASE_VERSION_NUMBER_STRING \ - FIREBASE_STRING(FIREBASE_VERSION_MAJOR) "." \ - FIREBASE_STRING(FIREBASE_VERSION_MINOR) "." \ - FIREBASE_STRING(FIREBASE_VERSION_REVISION) -// clang-format on - -// Identifier for version string, e.g. kFirebaseVersionString. -#define FIREBASE_VERSION_IDENTIFIER(library) k##library##VersionString - -// Concatenated version string, e.g. "Firebase C++ x.y.z". -#define FIREBASE_VERSION_STRING(library) \ - #library " C++ " FIREBASE_VERSION_NUMBER_STRING - -#if !defined(DOXYGEN) -#if !defined(_WIN32) && !defined(__CYGWIN__) -#define DEFINE_FIREBASE_VERSION_STRING(library) \ - extern volatile __attribute__((weak)) \ - const char* FIREBASE_VERSION_IDENTIFIER(library); \ - volatile __attribute__((weak)) \ - const char* FIREBASE_VERSION_IDENTIFIER(library) = \ - FIREBASE_VERSION_STRING(library) -#else -#define DEFINE_FIREBASE_VERSION_STRING(library) \ - static const char* FIREBASE_VERSION_IDENTIFIER(library) = \ - FIREBASE_VERSION_STRING(library) -#endif // !defined(_WIN32) && !defined(__CYGWIN__) -#else // if defined(DOXYGEN) - -/// @brief Namespace that encompasses all Firebase APIs. -namespace firebase { - -/// @brief String which identifies the current version of the Firebase C++ -/// SDK. -/// -/// @see FIREBASE_VERSION_MAJOR -/// @see FIREBASE_VERSION_MINOR -/// @see FIREBASE_VERSION_REVISION -static const char* kFirebaseVersionString = FIREBASE_VERSION_STRING; - -} // namespace firebase -#endif // !defined(DOXYGEN) - -#endif // FIREBASE_APP_CLIENT_CPP_SRC_VERSION_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/generate_xml_from_google_services_json.py b/packages/firebase_core/firebase_core/firebase_core/generate_xml_from_google_services_json.py deleted file mode 100644 index 8996cd8490f3..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/generate_xml_from_google_services_json.py +++ /dev/null @@ -1,496 +0,0 @@ -#!/usr/bin/python - -# Copyright 2016 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Stand-alone implementation of the Gradle Firebase plugin. - -Converts the services json file to xml: -https://googleplex-android.googlesource.com/platform/tools/base/+/studio-master-dev/build-system/google-services/src/main/groovy/com/google/gms/googleservices -""" - -__author__ = 'Wouter van Oortmerssen' - -import argparse -import ctypes -import json -import os -import platform -import sys -from xml.etree import ElementTree - -if platform.system().lower() == 'windows': - import ctypes.wintypes # pylint: disable=g-import-not-at-top - -# Map Python 2's unicode method to encode a string as bytes in python 3. -try: - unicode('') # See whether unicode class is available (Python < 3) -except NameError: - unicode = str # pylint: disable=redefined-builtin,invalid-name - -# Input filename if it isn't set. -DEFAULT_INPUT_FILENAME = 'app/google-services.json' -# Output filename if it isn't set. -DEFAULT_OUTPUT_FILENAME = 'res/values/googleservices.xml' -# Input filename for .plist files, if it isn't set. -DEFAULT_PLIST_INPUT_FILENAME = 'GoogleService-Info.plist' -# Output filename for .json files, if it isn't set. -DEFAULT_JSON_OUTPUT_FILENAME = 'google-services-desktop.json' - -OAUTH_CLIENT_TYPE_ANDROID_APP = 1 -OAUTH_CLIENT_TYPE_WEB = 3 - - -def read_xml_value(xml_node): - """Utility method for reading values from the plist XML. - - Args: - xml_node: An ElementTree node, that contains a value. - - Returns: - The value of the node, or None, if it could not be read. - """ - if xml_node.tag == 'string': - return xml_node.text - elif xml_node.tag == 'integer': - return int(xml_node.text) - elif xml_node.tag == 'real': - return float(xml_node.text) - elif xml_node.tag == 'false': - return 0 - elif xml_node.tag == 'true': - return 1 - else: - # other types of input are ignored. (data, dates, arrays, etc.) - return None - - -def construct_plist_dictionary(xml_root): - """Constructs a dictionary of values based on the contents of a plist file. - - Args: - xml_root: An ElementTree node, that represents the root of the xml file - that is to be parsed. (Which should be a dictionary containing - key-value pairs of the properties that need to be extracted.) - - Returns: - A dictionary, containing key-value pairs for all (supported) entries in the - node. - """ - xml_dict = xml_root.find('dict') - - if xml_dict is None: - return None - - plist_dict = {} - i = 0 - while i < len(xml_dict): - if xml_dict[i].tag == 'key': - key = xml_dict[i].text - i += 1 - if i < len(xml_dict): - value = read_xml_value(xml_dict[i]) - if value is not None: - plist_dict[key] = value - i += 1 - - return plist_dict - - -def update_dict_keys(key_map, input_dict): - """Creates a dict from input_dict with the same values but new keys. - - Two dictionaries are passed to this function: the key_map that represents a - mapping of source keys to destination keys, and the input_dict that is the - dictionary that is to be duplicated, replacing any key that matches a source - key with a destination key. Source keys that are not present in the - input_dict will not have their destination key represented in the result. - - In other words, if key_map is `{'old': 'new', 'foo': 'bar'}`, and input_dict - is `{'old': 10}`, the result will be `{'new': 10}`. - - Args: - key_map (dict): A dictionary of strings to strings that maps source keys to - destination keys. - input_dict (dict): The dictionary of string keys to any value type, which - is to be duplicated, replacing source keys with the corresponding - destination keys from key_map. - - Returns: - dict: A new dictionary with updated keys. - """ - return { - new_key: input_dict[old_key] - for (old_key, new_key) in key_map.items() - if old_key in input_dict - } - - -def construct_google_services_json(xml_dict): - """Constructs a google services json file from a dictionary. - - Args: - xml_dict: A dictionary of all the key/value pairs that are needed for the - output json file. - Returns: - A string representing the output json file. - """ - - try: - json_struct = { - 'project_info': - update_dict_keys( - { - 'GCM_SENDER_ID': 'project_number', - 'DATABASE_URL': 'firebase_url', - 'PROJECT_ID': 'project_id', - 'STORAGE_BUCKET': 'storage_bucket' - }, xml_dict), - 'client': [{ - 'client_info': { - 'mobilesdk_app_id': xml_dict['GOOGLE_APP_ID'], - 'android_client_info': { - 'package_name': xml_dict['BUNDLE_ID'] - } - }, - 'oauth_client': [{ - 'client_id': xml_dict['CLIENT_ID'], - }], - 'api_key': [{ - 'current_key': xml_dict['API_KEY'] - }], - 'services': { - 'analytics_service': { - 'status': xml_dict['IS_ANALYTICS_ENABLED'] - }, - 'appinvite_service': { - 'status': xml_dict['IS_APPINVITE_ENABLED'] - } - } - },], - 'configuration_version': - '1' - } - return json.dumps(json_struct, indent=2) - except KeyError as e: - sys.stderr.write('Could not find key in plist file: [%s]\n' % (e.args[0])) - return None - - -def convert_plist_to_json(plist_string, input_filename): - """Converts an input plist string into a .json file and saves it. - - Args: - plist_string: The contents of the loaded plist file. - - input_filename: The file name that the plist data was read from. - Returns: - the converted string, or None if there were errors. - """ - - try: - root = ElementTree.fromstring(plist_string) - except ElementTree.ParseError: - sys.stderr.write('Error parsing file %s.\n' - 'It does not appear to be valid XML.\n' % (input_filename)) - return None - - plist_dict = construct_plist_dictionary(root) - if plist_dict is None: - sys.stderr.write('In file %s, could not locate a top-level \'dict\' ' - 'element.\n' - 'File format should be plist XML, with a top-level ' - 'dictionary containing project settings as key-value ' - 'pairs.\n' % (input_filename)) - return None - - json_string = construct_google_services_json(plist_dict) - return json_string - - -def gen_string(parent, name, text): - """Generate one element and put into the list of keeps. - - Args: - parent: The object that will hold the string. - name: The name to store the string under. - text: The text of the string. - """ - if text: - prev = parent.get('tools:keep', '') - if prev: - prev += ',' - parent.set('tools:keep', prev + '@string/' + name) - child = ElementTree.SubElement(parent, 'string', { - 'name': name, - 'translatable': 'false' - }) - child.text = text - - -def indent(elem, level=0): - """Recurse through XML tree and add indentation. - - Args: - elem: The element to recurse over - level: The current indentation level. - """ - i = '\n' + level*' ' - if elem is not None: - if not elem.text or not elem.text.strip(): - elem.text = i + ' ' - if not elem.tail or not elem.tail.strip(): - elem.tail = i - for elem in elem: - indent(elem, level+1) - if not elem.tail or not elem.tail.strip(): - elem.tail = i - else: - if level and (not elem.tail or not elem.tail.strip()): - elem.tail = i - - -def argv_as_unicode_win32(): - """Returns unicode command line arguments on windows. - """ - - get_command_line_w = ctypes.cdll.kernel32.GetCommandLineW - get_command_line_w.restype = ctypes.wintypes.LPCWSTR - - # CommandLineToArgvW parses the Unicode command line - command_line_to_argv_w = ctypes.windll.shell32.CommandLineToArgvW - command_line_to_argv_w.argtypes = [ - ctypes.wintypes.LPCWSTR, - ctypes.POINTER(ctypes.c_int) - ] - command_line_to_argv_w.restype = ctypes.POINTER( - ctypes.wintypes.LPWSTR) - - argc = ctypes.c_int(0) - argv = command_line_to_argv_w(get_command_line_w(), argc) - - # Strip the python executable from the arguments if it exists - # (It would be listed as the first argument on the windows command line, but - # not in the arguments to the python script) - sys_argv_len = len(sys.argv) - return [unicode(argv[i]) for i in - range(argc.value - sys_argv_len, argc.value)] - - -def main(): - parser = argparse.ArgumentParser( - description=(( - 'Converts a Firebase %s into %s similar to the Gradle plugin, or ' - 'converts a Firebase %s into a %s suitible for use on desktop apps.' % - (DEFAULT_INPUT_FILENAME, DEFAULT_OUTPUT_FILENAME, - DEFAULT_PLIST_INPUT_FILENAME, DEFAULT_JSON_OUTPUT_FILENAME)))) - parser.add_argument('-i', help='Override input file name', - metavar='FILE', required=False) - parser.add_argument('-o', help='Override destination file name', - metavar='FILE', required=False) - parser.add_argument('-p', help=('Package ID to select within the set of ' - 'packages in the input file. If this is ' - 'not specified, the first package in the ' - 'input file is selected.')) - parser.add_argument('-l', help=('List all package IDs referenced by the ' - 'input file. If this is specified, ' - 'the output file is not created.'), - action='store_true', default=False, required=False) - parser.add_argument('-f', help=('Print project fields from the input file ' - 'in the form \'name=value\\n\' for each ' - 'field. If this is specified, the output ' - 'is not created.'), - action='store_true', default=False, required=False) - parser.add_argument( - '--plist', - help=( - 'Specifies a plist file to convert to a JSON configuration file. ' - 'If this is enabled, the script will expect a .plist file as input, ' - 'which it will convert into %s file. The output file is ' - '*not* suitable for use with Firebase on Android.' % - (DEFAULT_JSON_OUTPUT_FILENAME)), - action='store_true', - default=False, - required=False) - - # python 2 on Windows doesn't handle unicode arguments well, so we need to - # pre-process the command line arguments before trying to parse them. - if platform.system() == 'Windows': - sys.argv = argv_as_unicode_win32() - - args = parser.parse_args() - - if args.plist: - input_filename = DEFAULT_PLIST_INPUT_FILENAME - output_filename = DEFAULT_JSON_OUTPUT_FILENAME - else: - input_filename = DEFAULT_INPUT_FILENAME - output_filename = DEFAULT_OUTPUT_FILENAME - - if args.i: - # Encode the input string (type unicode) as a normal string (type str) - # using the 'utf-8' encoding so that it can be worked with the same as - # input names from other sources (like the defaults). - input_filename_raw = args.i.encode('utf-8') - # Decode the filename to a unicode string using the 'utf-8' encoding to - # properly handle filepaths with unicode characters in them. - input_filename = input_filename_raw.decode('utf-8') - - if args.o: - output_filename = args.o - - with open(input_filename, 'r') as ifile: - file_string = ifile.read() - - json_string = None - if args.plist: - json_string = convert_plist_to_json(file_string, input_filename) - if json_string is None: - return 1 - jsobj = json.loads(json_string) - else: - jsobj = json.loads(file_string) - - root = ElementTree.Element('resources') - root.set('xmlns:tools', 'http://schemas.android.com/tools') - - project_info = jsobj.get('project_info') - if project_info: - gen_string(root, 'firebase_database_url', project_info.get('firebase_url')) - gen_string(root, 'gcm_defaultSenderId', project_info.get('project_number')) - gen_string(root, 'google_storage_bucket', - project_info.get('storage_bucket')) - gen_string(root, 'project_id', project_info.get('project_id')) - - if args.f: - if not project_info: - sys.stderr.write('No project info found in %s.' % input_filename) - return 1 - for field, value in sorted(project_info.items()): - sys.stdout.write('%s=%s\n' % (field, value)) - return 0 - - packages = set() - client_list = jsobj.get('client') - if client_list: - # Search for the user specified package in the file. - selected_package_name = '' - selected_client = client_list[0] - find_package_name = args.p - for client in client_list: - package_name = client.get('client_info', {}).get( - 'android_client_info', {}).get('package_name', '') - if not package_name: - package_name = client.get('oauth_client', {}).get( - 'android_info', {}).get('package_name', '') - if package_name: - if not selected_package_name: - selected_package_name = package_name - selected_client = client - if package_name == find_package_name: - selected_package_name = package_name - selected_client = client - packages.add(package_name) - - if args.p and selected_package_name != find_package_name: - sys.stderr.write('No packages found in %s which match the package ' - 'name %s\n' - '\n' - 'Found the following:\n' - '%s\n' % (input_filename, find_package_name, - '\n'.join(packages))) - return 1 - - client_api_key = selected_client.get('api_key') - if client_api_key: - client_api_key0 = client_api_key[0] - gen_string(root, 'google_api_key', client_api_key0.get('current_key')) - gen_string(root, 'google_crash_reporting_api_key', - client_api_key0.get('current_key')) - - client_info = selected_client.get('client_info') - if client_info: - gen_string(root, 'google_app_id', client_info.get('mobilesdk_app_id')) - - # Only include the first matching OAuth client ID per type. - client_id_web_parsed = False - client_id_android_parsed = False - - oauth_client_list = selected_client.get('oauth_client') - if oauth_client_list: - for oauth_client in oauth_client_list: - client_type = oauth_client.get('client_type') - client_id = oauth_client.get('client_id') - if not (client_type and client_id): continue - if (client_type == OAUTH_CLIENT_TYPE_WEB and - not client_id_web_parsed): - gen_string(root, 'default_web_client_id', client_id) - client_id_web_parsed = True - if (client_type == OAUTH_CLIENT_TYPE_ANDROID_APP and - not client_id_android_parsed): - gen_string(root, 'default_android_client_id', client_id) - client_id_android_parsed = True - - services = selected_client.get('services') - if services: - ads_service = services.get('ads_service') - if ads_service: - gen_string(root, 'test_banner_ad_unit_id', - ads_service.get('test_banner_ad_unit_id')) - gen_string(root, 'test_interstitial_ad_unit_id', - ads_service.get('test_interstitial_ad_unit_id')) - analytics_service = services.get('analytics_service') - if analytics_service: - analytics_property = analytics_service.get('analytics_property') - if analytics_property: - gen_string(root, 'ga_trackingId', - analytics_property.get('tracking_id')) - # enable this once we have an example if this service being present - # in the json data: - maps_service_enabled = False - if maps_service_enabled: - maps_service = services.get('maps_service') - if maps_service: - maps_api_key = maps_service.get('api_key') - if maps_api_key: - for k in range(0, len(maps_api_key)): - # generates potentially multiple of these keys, which is - # the same behavior as the java plugin. - gen_string(root, 'google_maps_key', - maps_api_key[k].get('maps_api_key')) - - tree = ElementTree.ElementTree(root) - - indent(root) - - if args.l: - for package in sorted(packages): - if package: - sys.stdout.write(package + '\n') - else: - path = os.path.dirname(output_filename) - - if path and not os.path.exists(path): - os.makedirs(path) - - if not args.plist: - tree.write(output_filename, 'utf-8', True) - else: - with open(output_filename, 'w') as ofile: - ofile.write(json_string) - - return 0 - -if __name__ == '__main__': - sys.exit(main()) \ No newline at end of file diff --git a/packages/firebase_core/firebase_core/firebase_core/generated_bindings.dart b/packages/firebase_core/firebase_core/firebase_core/generated_bindings.dart deleted file mode 100644 index f58d1524bee8..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/generated_bindings.dart +++ /dev/null @@ -1,26 +0,0 @@ -// AUTO GENERATED FILE, DO NOT EDIT. -// -// Generated by `package:ffigen`. -import 'dart:ffi' as ffi; - -class NativeLibrary { - /// Holds the symbol lookup function. - final ffi.Pointer Function(String symbolName) - _lookup; - - /// The symbols are looked up in [dynamicLibrary]. - NativeLibrary(ffi.DynamicLibrary dynamicLibrary) - : _lookup = dynamicLibrary.lookup; - - /// The symbols are looked up with [lookup]. - NativeLibrary.fromLookup( - ffi.Pointer Function(String symbolName) - lookup) - : _lookup = lookup; - - late final ffi.Pointer _firebase = _lookup('firebase'); - - int get firebase => _firebase.value; - - set firebase(int value) => _firebase.value = value; -} diff --git a/packages/firebase_core/firebase_core/firebase_core/google-services-desktop.json b/packages/firebase_core/firebase_core/firebase_core/google-services-desktop.json deleted file mode 100644 index a3bf216f4de0..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/google-services-desktop.json +++ /dev/null @@ -1,37 +0,0 @@ -{ - "project_info": { - "project_number": "406099696497", - "firebase_url": "https://flutterfire-e2e-tests-default-rtdb.europe-west1.firebasedatabase.app", - "project_id": "flutterfire-e2e-tests", - "storage_bucket": "flutterfire-e2e-tests.appspot.com" - }, - "client": [ - { - "client_info": { - "mobilesdk_app_id": "1:406099696497:ios:58cbc26aca8e5cf83574d0", - "android_client_info": { - "package_name": "io.flutter.plugins.firebase.auth.example" - } - }, - "oauth_client": [ - { - "client_id": "406099696497-134k3722m01rtrsklhf3b7k8sqa5r7in.apps.googleusercontent.com" - } - ], - "api_key": [ - { - "current_key": "AIzaSyDooSUGSf63Ghq02_iIhtnmwMDs4HlWS6c" - } - ], - "services": { - "analytics_service": { - "status": 0 - }, - "appinvite_service": { - "status": 1 - } - } - } - ], - "configuration_version": "1" -} \ No newline at end of file diff --git a/packages/firebase_core/firebase_core/firebase_core/lib/firebase_core.dart b/packages/firebase_core/firebase_core/firebase_core/lib/firebase_core.dart deleted file mode 100644 index d1295e26ad15..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/lib/firebase_core.dart +++ /dev/null @@ -1,8 +0,0 @@ - -import 'firebase_core_platform_interface.dart'; - -class FirebaseCore { - Future getPlatformVersion() { - return FirebaseCorePlatform.instance.getPlatformVersion(); - } -} diff --git a/packages/firebase_core/firebase_core/firebase_core/lib/firebase_core_method_channel.dart b/packages/firebase_core/firebase_core/firebase_core/lib/firebase_core_method_channel.dart deleted file mode 100644 index 5da300fa9013..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/lib/firebase_core_method_channel.dart +++ /dev/null @@ -1,17 +0,0 @@ -import 'package:flutter/foundation.dart'; -import 'package:flutter/services.dart'; - -import 'firebase_core_platform_interface.dart'; - -/// An implementation of [FirebaseCorePlatform] that uses method channels. -class MethodChannelFirebaseCore extends FirebaseCorePlatform { - /// The method channel used to interact with the native platform. - @visibleForTesting - final methodChannel = const MethodChannel('firebase_core'); - - @override - Future getPlatformVersion() async { - final version = await methodChannel.invokeMethod('getPlatformVersion'); - return version; - } -} diff --git a/packages/firebase_core/firebase_core/firebase_core/lib/firebase_core_platform_interface.dart b/packages/firebase_core/firebase_core/firebase_core/lib/firebase_core_platform_interface.dart deleted file mode 100644 index 6f6e165b7957..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/lib/firebase_core_platform_interface.dart +++ /dev/null @@ -1,29 +0,0 @@ -import 'package:plugin_platform_interface/plugin_platform_interface.dart'; - -import 'firebase_core_method_channel.dart'; - -abstract class FirebaseCorePlatform extends PlatformInterface { - /// Constructs a FirebaseCorePlatform. - FirebaseCorePlatform() : super(token: _token); - - static final Object _token = Object(); - - static FirebaseCorePlatform _instance = MethodChannelFirebaseCore(); - - /// The default instance of [FirebaseCorePlatform] to use. - /// - /// Defaults to [MethodChannelFirebaseCore]. - static FirebaseCorePlatform get instance => _instance; - - /// Platform-specific implementations should set this with their own - /// platform-specific class that extends [FirebaseCorePlatform] when - /// they register themselves. - static set instance(FirebaseCorePlatform instance) { - PlatformInterface.verifyToken(instance, _token); - _instance = instance; - } - - Future getPlatformVersion() { - throw UnimplementedError('platformVersion() has not been implemented.'); - } -} diff --git a/packages/firebase_core/firebase_core/firebase_core/linux/CMakeLists.txt b/packages/firebase_core/firebase_core/firebase_core/linux/CMakeLists.txt deleted file mode 100644 index 5cec31c86b71..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/linux/CMakeLists.txt +++ /dev/null @@ -1,47 +0,0 @@ -# The Flutter tooling requires that developers have CMake 3.10 or later -# installed. You should not increase this version, as doing so will cause -# the plugin to fail to compile for some customers of the plugin. -cmake_minimum_required(VERSION 3.10) - -# Project-level configuration. -set(PROJECT_NAME "firebase_core") -project(${PROJECT_NAME} LANGUAGES CXX) - -# This value is used when generating builds using this plugin, so it must -# not be changed. -set(PLUGIN_NAME "firebase_core_plugin") - -# Define the plugin library target. Its name must not be changed (see comment -# on PLUGIN_NAME above). -# -# Any new source files that you add to the plugin should be added here. -add_library(${PLUGIN_NAME} SHARED - "firebase_core_plugin.cc" -) - -# Apply a standard set of build settings that are configured in the -# application-level CMakeLists.txt. This can be removed for plugins that want -# full control over build settings. -apply_standard_settings(${PLUGIN_NAME}) - -# Symbols are hidden by default to reduce the chance of accidental conflicts -# between plugins. This should not be removed; any symbols that should be -# exported should be explicitly exported with the FLUTTER_PLUGIN_EXPORT macro. -set_target_properties(${PLUGIN_NAME} PROPERTIES - CXX_VISIBILITY_PRESET hidden) -target_compile_definitions(${PLUGIN_NAME} PRIVATE FLUTTER_PLUGIN_IMPL) - -# Source include directories and library dependencies. Add any plugin-specific -# dependencies here. -target_include_directories(${PLUGIN_NAME} INTERFACE - "${CMAKE_CURRENT_SOURCE_DIR}/include") -target_link_libraries(${PLUGIN_NAME} PRIVATE flutter) -target_link_libraries(${PLUGIN_NAME} PRIVATE PkgConfig::GTK) - -# List of absolute paths to libraries that should be bundled with the plugin. -# This list could contain prebuilt libraries, or libraries created by an -# external build triggered from this build file. -set(firebase_core_bundled_libraries - "" - PARENT_SCOPE -) diff --git a/packages/firebase_core/firebase_core/firebase_core/linux/firebase_core_plugin.cc b/packages/firebase_core/firebase_core/firebase_core/linux/firebase_core_plugin.cc deleted file mode 100644 index 4fd897624ca4..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/linux/firebase_core_plugin.cc +++ /dev/null @@ -1,70 +0,0 @@ -#include "include/firebase_core/firebase_core_plugin.h" - -#include -#include -#include - -#include - -#define FIREBASE_CORE_PLUGIN(obj) \ - (G_TYPE_CHECK_INSTANCE_CAST((obj), firebase_core_plugin_get_type(), \ - FirebaseCorePlugin)) - -struct _FirebaseCorePlugin { - GObject parent_instance; -}; - -G_DEFINE_TYPE(FirebaseCorePlugin, firebase_core_plugin, g_object_get_type()) - -// Called when a method call is received from Flutter. -static void firebase_core_plugin_handle_method_call( - FirebaseCorePlugin* self, - FlMethodCall* method_call) { - g_autoptr(FlMethodResponse) response = nullptr; - - const gchar* method = fl_method_call_get_name(method_call); - - if (strcmp(method, "getPlatformVersion") == 0) { - struct utsname uname_data = {}; - uname(&uname_data); - g_autofree gchar *version = g_strdup_printf("Linux %s", uname_data.version); - g_autoptr(FlValue) result = fl_value_new_string(version); - response = FL_METHOD_RESPONSE(fl_method_success_response_new(result)); - } else { - response = FL_METHOD_RESPONSE(fl_method_not_implemented_response_new()); - } - - fl_method_call_respond(method_call, response, nullptr); -} - -static void firebase_core_plugin_dispose(GObject* object) { - G_OBJECT_CLASS(firebase_core_plugin_parent_class)->dispose(object); -} - -static void firebase_core_plugin_class_init(FirebaseCorePluginClass* klass) { - G_OBJECT_CLASS(klass)->dispose = firebase_core_plugin_dispose; -} - -static void firebase_core_plugin_init(FirebaseCorePlugin* self) {} - -static void method_call_cb(FlMethodChannel* channel, FlMethodCall* method_call, - gpointer user_data) { - FirebaseCorePlugin* plugin = FIREBASE_CORE_PLUGIN(user_data); - firebase_core_plugin_handle_method_call(plugin, method_call); -} - -void firebase_core_plugin_register_with_registrar(FlPluginRegistrar* registrar) { - FirebaseCorePlugin* plugin = FIREBASE_CORE_PLUGIN( - g_object_new(firebase_core_plugin_get_type(), nullptr)); - - g_autoptr(FlStandardMethodCodec) codec = fl_standard_method_codec_new(); - g_autoptr(FlMethodChannel) channel = - fl_method_channel_new(fl_plugin_registrar_get_messenger(registrar), - "firebase_core", - FL_METHOD_CODEC(codec)); - fl_method_channel_set_method_call_handler(channel, method_call_cb, - g_object_ref(plugin), - g_object_unref); - - g_object_unref(plugin); -} diff --git a/packages/firebase_core/firebase_core/firebase_core/linux/include/firebase_core/firebase_core_plugin.h b/packages/firebase_core/firebase_core/firebase_core/linux/include/firebase_core/firebase_core_plugin.h deleted file mode 100644 index 3f15a61a3e72..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/linux/include/firebase_core/firebase_core_plugin.h +++ /dev/null @@ -1,26 +0,0 @@ -#ifndef FLUTTER_PLUGIN_FIREBASE_CORE_PLUGIN_H_ -#define FLUTTER_PLUGIN_FIREBASE_CORE_PLUGIN_H_ - -#include - -G_BEGIN_DECLS - -#ifdef FLUTTER_PLUGIN_IMPL -#define FLUTTER_PLUGIN_EXPORT __attribute__((visibility("default"))) -#else -#define FLUTTER_PLUGIN_EXPORT -#endif - -typedef struct _FirebaseCorePlugin FirebaseCorePlugin; -typedef struct { - GObjectClass parent_class; -} FirebaseCorePluginClass; - -FLUTTER_PLUGIN_EXPORT GType firebase_core_plugin_get_type(); - -FLUTTER_PLUGIN_EXPORT void firebase_core_plugin_register_with_registrar( - FlPluginRegistrar* registrar); - -G_END_DECLS - -#endif // FLUTTER_PLUGIN_FIREBASE_CORE_PLUGIN_H_ diff --git a/packages/firebase_core/firebase_core/firebase_core/pubspec.yaml b/packages/firebase_core/firebase_core/firebase_core/pubspec.yaml deleted file mode 100644 index c942173c517b..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/pubspec.yaml +++ /dev/null @@ -1,36 +0,0 @@ -name: firebase_core -description: A new Flutter plugin project. -version: 0.0.1 -homepage: - -environment: - sdk: '>=2.19.2 <3.0.0' - flutter: '>=2.5.0' - -dependencies: - ffi: ^2.0.1 - flutter: - sdk: flutter - plugin_platform_interface: ^2.0.2 - -dev_dependencies: - flutter_test: - sdk: flutter - flutter_lints: ^2.0.0 - ffigen: ^7.2.6 - -flutter: - plugin: - platforms: - linux: - pluginClass: FirebaseCorePlugin - windows: - pluginClass: FirebaseCorePluginCApi - -ffigen: - output: 'generated_bindings.dart' - headers: - entry-points: - - 'firebase/app.h' - include-directives: - - 'firebase/**.h' diff --git a/packages/firebase_core/firebase_core/firebase_core/test/firebase_core_method_channel_test.dart b/packages/firebase_core/firebase_core/firebase_core/test/firebase_core_method_channel_test.dart deleted file mode 100644 index 70c7fc5e7362..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/test/firebase_core_method_channel_test.dart +++ /dev/null @@ -1,24 +0,0 @@ -import 'package:flutter/services.dart'; -import 'package:flutter_test/flutter_test.dart'; -import 'package:firebase_core/firebase_core_method_channel.dart'; - -void main() { - MethodChannelFirebaseCore platform = MethodChannelFirebaseCore(); - const MethodChannel channel = MethodChannel('firebase_core'); - - TestWidgetsFlutterBinding.ensureInitialized(); - - setUp(() { - channel.setMockMethodCallHandler((MethodCall methodCall) async { - return '42'; - }); - }); - - tearDown(() { - channel.setMockMethodCallHandler(null); - }); - - test('getPlatformVersion', () async { - expect(await platform.getPlatformVersion(), '42'); - }); -} diff --git a/packages/firebase_core/firebase_core/firebase_core/test/firebase_core_test.dart b/packages/firebase_core/firebase_core/firebase_core/test/firebase_core_test.dart deleted file mode 100644 index bb8e54416b4e..000000000000 --- a/packages/firebase_core/firebase_core/firebase_core/test/firebase_core_test.dart +++ /dev/null @@ -1,29 +0,0 @@ -import 'package:flutter_test/flutter_test.dart'; -import 'package:firebase_core/firebase_core.dart'; -import 'package:firebase_core/firebase_core_platform_interface.dart'; -import 'package:firebase_core/firebase_core_method_channel.dart'; -import 'package:plugin_platform_interface/plugin_platform_interface.dart'; - -class MockFirebaseCorePlatform - with MockPlatformInterfaceMixin - implements FirebaseCorePlatform { - - @override - Future getPlatformVersion() => Future.value('42'); -} - -void main() { - final FirebaseCorePlatform initialPlatform = FirebaseCorePlatform.instance; - - test('$MethodChannelFirebaseCore is the default instance', () { - expect(initialPlatform, isInstanceOf()); - }); - - test('getPlatformVersion', () async { - FirebaseCore firebaseCorePlugin = FirebaseCore(); - MockFirebaseCorePlatform fakePlatform = MockFirebaseCorePlatform(); - FirebaseCorePlatform.instance = fakePlatform; - - expect(await firebaseCorePlugin.getPlatformVersion(), '42'); - }); -} diff --git a/packages/firebase_core/firebase_core/pubspec.yaml b/packages/firebase_core/firebase_core/pubspec.yaml index 61d7e5155ead..f0f3a628f60d 100644 --- a/packages/firebase_core/firebase_core/pubspec.yaml +++ b/packages/firebase_core/firebase_core/pubspec.yaml @@ -37,6 +37,9 @@ flutter: pluginClass: FLTFirebaseCorePlugin web: default_package: firebase_core_web + windows: + pluginClass: FirebaseCorePluginCApi + firebase: google_services_gradle_plugin_version: "4.3.10" diff --git a/packages/firebase_core/firebase_core/firebase_core/windows/.gitignore b/packages/firebase_core/firebase_core/windows/.gitignore similarity index 100% rename from packages/firebase_core/firebase_core/firebase_core/windows/.gitignore rename to packages/firebase_core/firebase_core/windows/.gitignore diff --git a/packages/firebase_core/firebase_core/firebase_core/windows/CMakeLists.txt b/packages/firebase_core/firebase_core/windows/CMakeLists.txt similarity index 100% rename from packages/firebase_core/firebase_core/firebase_core/windows/CMakeLists.txt rename to packages/firebase_core/firebase_core/windows/CMakeLists.txt diff --git a/packages/firebase_core/firebase_core/firebase_core/windows/firebase_core_plugin.cpp b/packages/firebase_core/firebase_core/windows/firebase_core_plugin.cpp similarity index 100% rename from packages/firebase_core/firebase_core/firebase_core/windows/firebase_core_plugin.cpp rename to packages/firebase_core/firebase_core/windows/firebase_core_plugin.cpp diff --git a/packages/firebase_core/firebase_core/firebase_core/windows/firebase_core_plugin.h b/packages/firebase_core/firebase_core/windows/firebase_core_plugin.h similarity index 100% rename from packages/firebase_core/firebase_core/firebase_core/windows/firebase_core_plugin.h rename to packages/firebase_core/firebase_core/windows/firebase_core_plugin.h diff --git a/packages/firebase_core/firebase_core/firebase_core/windows/firebase_core_plugin_c_api.cpp b/packages/firebase_core/firebase_core/windows/firebase_core_plugin_c_api.cpp similarity index 100% rename from packages/firebase_core/firebase_core/firebase_core/windows/firebase_core_plugin_c_api.cpp rename to packages/firebase_core/firebase_core/windows/firebase_core_plugin_c_api.cpp diff --git a/packages/firebase_core/firebase_core/firebase_core/windows/include/firebase_core/firebase_core_plugin_c_api.h b/packages/firebase_core/firebase_core/windows/include/firebase_core/firebase_core_plugin_c_api.h similarity index 100% rename from packages/firebase_core/firebase_core/firebase_core/windows/include/firebase_core/firebase_core_plugin_c_api.h rename to packages/firebase_core/firebase_core/windows/include/firebase_core/firebase_core_plugin_c_api.h From 9dd978113247084dce34052d01338468a617ada8 Mon Sep 17 00:00:00 2001 From: Guillaume Bernos Date: Tue, 14 Mar 2023 11:05:49 +0100 Subject: [PATCH 35/65] feat(core, windows): update pigeon --- .../firebase_core/firebase_core_platform_interface/pubspec.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/firebase_core/firebase_core_platform_interface/pubspec.yaml b/packages/firebase_core/firebase_core_platform_interface/pubspec.yaml index 1babada2b072..c35e4f208b9f 100644 --- a/packages/firebase_core/firebase_core_platform_interface/pubspec.yaml +++ b/packages/firebase_core/firebase_core_platform_interface/pubspec.yaml @@ -22,4 +22,4 @@ dependencies: dev_dependencies: mockito: ^5.0.0 - pigeon: ^3.1.5 + pigeon: ^9.0.6 From 276b7cba6adb9f45eb120752e9d08f532a3d769f Mon Sep 17 00:00:00 2001 From: Guillaume Bernos Date: Tue, 14 Mar 2023 14:29:50 +0100 Subject: [PATCH 36/65] feat(core, windows): update pigeon --- .../core/GeneratedAndroidFirebaseCore.java | 276 +++++++------- .../firebase_core/ios/Classes/messages.g.h | 95 +++-- .../firebase_core/ios/Classes/messages.g.m | 339 +++++++----------- .../lib/src/pigeon/messages.pigeon.dart | 260 +++++++------- .../lib/src/pigeon/test_api.dart | 84 ++--- 5 files changed, 455 insertions(+), 599 deletions(-) diff --git a/packages/firebase_core/firebase_core/android/src/main/java/io/flutter/plugins/firebase/core/GeneratedAndroidFirebaseCore.java b/packages/firebase_core/firebase_core/android/src/main/java/io/flutter/plugins/firebase/core/GeneratedAndroidFirebaseCore.java index d3f4b5ed3b83..c19c5b8b4ca3 100644 --- a/packages/firebase_core/firebase_core/android/src/main/java/io/flutter/plugins/firebase/core/GeneratedAndroidFirebaseCore.java +++ b/packages/firebase_core/firebase_core/android/src/main/java/io/flutter/plugins/firebase/core/GeneratedAndroidFirebaseCore.java @@ -1,10 +1,4 @@ -/* - * Copyright 2022, the Chromium project authors. Please see the AUTHORS file - * for details. All rights reserved. Use of this source code is governed by a - * BSD-style license that can be found in the LICENSE file. - */ - -// Autogenerated from Pigeon (v3.2.0), do not edit directly. +// Autogenerated from Pigeon (v9.0.6), do not edit directly. // See also: https://pub.dev/packages/pigeon package io.flutter.plugins.firebase.core; @@ -19,6 +13,8 @@ import java.io.ByteArrayOutputStream; import java.nio.ByteBuffer; import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -26,9 +22,18 @@ /** Generated class from Pigeon. */ @SuppressWarnings({"unused", "unchecked", "CodeBlock2Expr", "RedundantSuppression"}) public class GeneratedAndroidFirebaseCore { + @NonNull + private static ArrayList wrapError(@NonNull Throwable exception) { + ArrayList errorList = new ArrayList(3); + errorList.add(exception.toString()); + errorList.add(exception.getClass().getSimpleName()); + errorList.add( + "Cause: " + exception.getCause() + ", Stacktrace: " + Log.getStackTraceString(exception)); + return errorList; + } /** Generated class from Pigeon that represents data sent in messages. */ - public static class PigeonFirebaseOptions { + public static final class PigeonFirebaseOptions { private @NonNull String apiKey; public @NonNull String getApiKey() { @@ -185,6 +190,7 @@ public void setAppGroupId(@Nullable String setterArg) { private PigeonFirebaseOptions() {} public static final class Builder { + private @Nullable String apiKey; public @NonNull Builder setApiKey(@NonNull String setterArg) { @@ -304,61 +310,61 @@ public static final class Builder { } @NonNull - Map toMap() { - Map toMapResult = new HashMap<>(); - toMapResult.put("apiKey", apiKey); - toMapResult.put("appId", appId); - toMapResult.put("messagingSenderId", messagingSenderId); - toMapResult.put("projectId", projectId); - toMapResult.put("authDomain", authDomain); - toMapResult.put("databaseURL", databaseURL); - toMapResult.put("storageBucket", storageBucket); - toMapResult.put("measurementId", measurementId); - toMapResult.put("trackingId", trackingId); - toMapResult.put("deepLinkURLScheme", deepLinkURLScheme); - toMapResult.put("androidClientId", androidClientId); - toMapResult.put("iosClientId", iosClientId); - toMapResult.put("iosBundleId", iosBundleId); - toMapResult.put("appGroupId", appGroupId); - return toMapResult; - } - - static @NonNull PigeonFirebaseOptions fromMap(@NonNull Map map) { + ArrayList toList() { + ArrayList toListResult = new ArrayList(14); + toListResult.add(apiKey); + toListResult.add(appId); + toListResult.add(messagingSenderId); + toListResult.add(projectId); + toListResult.add(authDomain); + toListResult.add(databaseURL); + toListResult.add(storageBucket); + toListResult.add(measurementId); + toListResult.add(trackingId); + toListResult.add(deepLinkURLScheme); + toListResult.add(androidClientId); + toListResult.add(iosClientId); + toListResult.add(iosBundleId); + toListResult.add(appGroupId); + return toListResult; + } + + static @NonNull PigeonFirebaseOptions fromList(@NonNull ArrayList list) { PigeonFirebaseOptions pigeonResult = new PigeonFirebaseOptions(); - Object apiKey = map.get("apiKey"); + Object apiKey = list.get(0); pigeonResult.setApiKey((String) apiKey); - Object appId = map.get("appId"); + Object appId = list.get(1); pigeonResult.setAppId((String) appId); - Object messagingSenderId = map.get("messagingSenderId"); + Object messagingSenderId = list.get(2); pigeonResult.setMessagingSenderId((String) messagingSenderId); - Object projectId = map.get("projectId"); + Object projectId = list.get(3); pigeonResult.setProjectId((String) projectId); - Object authDomain = map.get("authDomain"); + Object authDomain = list.get(4); pigeonResult.setAuthDomain((String) authDomain); - Object databaseURL = map.get("databaseURL"); + Object databaseURL = list.get(5); pigeonResult.setDatabaseURL((String) databaseURL); - Object storageBucket = map.get("storageBucket"); + Object storageBucket = list.get(6); pigeonResult.setStorageBucket((String) storageBucket); - Object measurementId = map.get("measurementId"); + Object measurementId = list.get(7); pigeonResult.setMeasurementId((String) measurementId); - Object trackingId = map.get("trackingId"); + Object trackingId = list.get(8); pigeonResult.setTrackingId((String) trackingId); - Object deepLinkURLScheme = map.get("deepLinkURLScheme"); + Object deepLinkURLScheme = list.get(9); pigeonResult.setDeepLinkURLScheme((String) deepLinkURLScheme); - Object androidClientId = map.get("androidClientId"); + Object androidClientId = list.get(10); pigeonResult.setAndroidClientId((String) androidClientId); - Object iosClientId = map.get("iosClientId"); + Object iosClientId = list.get(11); pigeonResult.setIosClientId((String) iosClientId); - Object iosBundleId = map.get("iosBundleId"); + Object iosBundleId = list.get(12); pigeonResult.setIosBundleId((String) iosBundleId); - Object appGroupId = map.get("appGroupId"); + Object appGroupId = list.get(13); pigeonResult.setAppGroupId((String) appGroupId); return pigeonResult; } } /** Generated class from Pigeon that represents data sent in messages. */ - public static class PigeonInitializeResponse { + public static final class PigeonInitializeResponse { private @NonNull String name; public @NonNull String getName() { @@ -412,6 +418,7 @@ public void setPluginConstants(@NonNull Map setterArg) { private PigeonInitializeResponse() {} public static final class Builder { + private @Nullable String name; public @NonNull Builder setName(@NonNull String setterArg) { @@ -451,25 +458,24 @@ public static final class Builder { } @NonNull - Map toMap() { - Map toMapResult = new HashMap<>(); - toMapResult.put("name", name); - toMapResult.put("options", (options == null) ? null : options.toMap()); - toMapResult.put("isAutomaticDataCollectionEnabled", isAutomaticDataCollectionEnabled); - toMapResult.put("pluginConstants", pluginConstants); - return toMapResult; + ArrayList toList() { + ArrayList toListResult = new ArrayList(4); + toListResult.add(name); + toListResult.add((options == null) ? null : options.toList()); + toListResult.add(isAutomaticDataCollectionEnabled); + toListResult.add(pluginConstants); + return toListResult; } - static @NonNull PigeonInitializeResponse fromMap(@NonNull Map map) { + static @NonNull PigeonInitializeResponse fromList(@NonNull ArrayList list) { PigeonInitializeResponse pigeonResult = new PigeonInitializeResponse(); - Object name = map.get("name"); + Object name = list.get(0); pigeonResult.setName((String) name); - Object options = map.get("options"); - pigeonResult.setOptions( - (options == null) ? null : PigeonFirebaseOptions.fromMap((Map) options)); - Object isAutomaticDataCollectionEnabled = map.get("isAutomaticDataCollectionEnabled"); + Object options = list.get(1); + pigeonResult.setOptions((options == null) ? null : PigeonFirebaseOptions.fromList((ArrayList) options)); + Object isAutomaticDataCollectionEnabled = list.get(2); pigeonResult.setIsAutomaticDataCollectionEnabled((Boolean) isAutomaticDataCollectionEnabled); - Object pluginConstants = map.get("pluginConstants"); + Object pluginConstants = list.get(3); pigeonResult.setPluginConstants((Map) pluginConstants); return pigeonResult; } @@ -487,27 +493,25 @@ private static class FirebaseCoreHostApiCodec extends StandardMessageCodec { private FirebaseCoreHostApiCodec() {} @Override - protected Object readValueOfType(byte type, ByteBuffer buffer) { + protected Object readValueOfType(byte type, @NonNull ByteBuffer buffer) { switch (type) { case (byte) 128: - return PigeonFirebaseOptions.fromMap((Map) readValue(buffer)); - + return PigeonFirebaseOptions.fromList((ArrayList) readValue(buffer)); case (byte) 129: - return PigeonInitializeResponse.fromMap((Map) readValue(buffer)); - + return PigeonInitializeResponse.fromList((ArrayList) readValue(buffer)); default: return super.readValueOfType(type, buffer); } } @Override - protected void writeValue(ByteArrayOutputStream stream, Object value) { + protected void writeValue(@NonNull ByteArrayOutputStream stream, Object value) { if (value instanceof PigeonFirebaseOptions) { stream.write(128); - writeValue(stream, ((PigeonFirebaseOptions) value).toMap()); + writeValue(stream, ((PigeonFirebaseOptions) value).toList()); } else if (value instanceof PigeonInitializeResponse) { stream.write(129); - writeValue(stream, ((PigeonInitializeResponse) value).toMap()); + writeValue(stream, ((PigeonInitializeResponse) value).toList()); } else { super.writeValue(stream, value); } @@ -516,10 +520,8 @@ protected void writeValue(ByteArrayOutputStream stream, Object value) { /** Generated interface from Pigeon that represents a handler of messages from Flutter. */ public interface FirebaseCoreHostApi { - void initializeApp( - @NonNull String appName, - @NonNull PigeonFirebaseOptions initializeAppRequest, - Result result); + + void initializeApp(@NonNull String appName, @NonNull PigeonFirebaseOptions initializeAppRequest, Result result); void initializeCore(Result> result); @@ -529,50 +531,44 @@ void initializeApp( static MessageCodec getCodec() { return FirebaseCoreHostApiCodec.INSTANCE; } - - /** - * Sets up an instance of `FirebaseCoreHostApi` to handle messages through the - * `binaryMessenger`. - */ + /**Sets up an instance of `FirebaseCoreHostApi` to handle messages through the `binaryMessenger`. */ static void setup(BinaryMessenger binaryMessenger, FirebaseCoreHostApi api) { { BasicMessageChannel channel = new BasicMessageChannel<>( - binaryMessenger, - "dev.flutter.pigeon.FirebaseCoreHostApi.initializeApp", - getCodec()); + binaryMessenger, "dev.flutter.pigeon.FirebaseCoreHostApi.initializeApp", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { - Map wrapped = new HashMap<>(); + ArrayList wrapped = new ArrayList(); try { ArrayList args = (ArrayList) message; + assert args != null; String appNameArg = (String) args.get(0); if (appNameArg == null) { throw new NullPointerException("appNameArg unexpectedly null."); } - PigeonFirebaseOptions initializeAppRequestArg = - (PigeonFirebaseOptions) args.get(1); + PigeonFirebaseOptions initializeAppRequestArg = (PigeonFirebaseOptions) args.get(1); if (initializeAppRequestArg == null) { throw new NullPointerException("initializeAppRequestArg unexpectedly null."); } Result resultCallback = new Result() { public void success(PigeonInitializeResponse result) { - wrapped.put("result", result); + wrapped.add(0, result); reply.reply(wrapped); } public void error(Throwable error) { - wrapped.put("error", wrapError(error)); - reply.reply(wrapped); + ArrayList wrappedError = wrapError(error); + reply.reply(wrappedError); } }; api.initializeApp(appNameArg, initializeAppRequestArg, resultCallback); } catch (Error | RuntimeException exception) { - wrapped.put("error", wrapError(exception)); - reply.reply(wrapped); + ArrayList wrappedError = wrapError(exception); + reply.reply(wrappedError); } }); } else { @@ -582,31 +578,29 @@ public void error(Throwable error) { { BasicMessageChannel channel = new BasicMessageChannel<>( - binaryMessenger, - "dev.flutter.pigeon.FirebaseCoreHostApi.initializeCore", - getCodec()); + binaryMessenger, "dev.flutter.pigeon.FirebaseCoreHostApi.initializeCore", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { - Map wrapped = new HashMap<>(); + ArrayList wrapped = new ArrayList(); try { Result> resultCallback = new Result>() { public void success(List result) { - wrapped.put("result", result); + wrapped.add(0, result); reply.reply(wrapped); } public void error(Throwable error) { - wrapped.put("error", wrapError(error)); - reply.reply(wrapped); + ArrayList wrappedError = wrapError(error); + reply.reply(wrappedError); } }; api.initializeCore(resultCallback); } catch (Error | RuntimeException exception) { - wrapped.put("error", wrapError(exception)); - reply.reply(wrapped); + ArrayList wrappedError = wrapError(exception); + reply.reply(wrappedError); } }); } else { @@ -616,31 +610,29 @@ public void error(Throwable error) { { BasicMessageChannel channel = new BasicMessageChannel<>( - binaryMessenger, - "dev.flutter.pigeon.FirebaseCoreHostApi.optionsFromResource", - getCodec()); + binaryMessenger, "dev.flutter.pigeon.FirebaseCoreHostApi.optionsFromResource", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { - Map wrapped = new HashMap<>(); + ArrayList wrapped = new ArrayList(); try { Result resultCallback = new Result() { public void success(PigeonFirebaseOptions result) { - wrapped.put("result", result); + wrapped.add(0, result); reply.reply(wrapped); } public void error(Throwable error) { - wrapped.put("error", wrapError(error)); - reply.reply(wrapped); + ArrayList wrappedError = wrapError(error); + reply.reply(wrappedError); } }; api.optionsFromResource(resultCallback); } catch (Error | RuntimeException exception) { - wrapped.put("error", wrapError(exception)); - reply.reply(wrapped); + ArrayList wrappedError = wrapError(exception); + reply.reply(wrappedError); } }); } else { @@ -649,44 +641,32 @@ public void error(Throwable error) { } } } - - private static class FirebaseAppHostApiCodec extends StandardMessageCodec { - public static final FirebaseAppHostApiCodec INSTANCE = new FirebaseAppHostApiCodec(); - - private FirebaseAppHostApiCodec() {} - } - /** Generated interface from Pigeon that represents a handler of messages from Flutter. */ public interface FirebaseAppHostApi { - void setAutomaticDataCollectionEnabled( - @NonNull String appName, @NonNull Boolean enabled, Result result); - void setAutomaticResourceManagementEnabled( - @NonNull String appName, @NonNull Boolean enabled, Result result); + void setAutomaticDataCollectionEnabled(@NonNull String appName, @NonNull Boolean enabled, Result result); + + void setAutomaticResourceManagementEnabled(@NonNull String appName, @NonNull Boolean enabled, Result result); void delete(@NonNull String appName, Result result); /** The codec used by FirebaseAppHostApi. */ static MessageCodec getCodec() { - return FirebaseAppHostApiCodec.INSTANCE; + return new StandardMessageCodec(); } - - /** - * Sets up an instance of `FirebaseAppHostApi` to handle messages through the `binaryMessenger`. - */ + /**Sets up an instance of `FirebaseAppHostApi` to handle messages through the `binaryMessenger`. */ static void setup(BinaryMessenger binaryMessenger, FirebaseAppHostApi api) { { BasicMessageChannel channel = new BasicMessageChannel<>( - binaryMessenger, - "dev.flutter.pigeon.FirebaseAppHostApi.setAutomaticDataCollectionEnabled", - getCodec()); + binaryMessenger, "dev.flutter.pigeon.FirebaseAppHostApi.setAutomaticDataCollectionEnabled", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { - Map wrapped = new HashMap<>(); + ArrayList wrapped = new ArrayList(); try { ArrayList args = (ArrayList) message; + assert args != null; String appNameArg = (String) args.get(0); if (appNameArg == null) { throw new NullPointerException("appNameArg unexpectedly null."); @@ -698,20 +678,20 @@ static void setup(BinaryMessenger binaryMessenger, FirebaseAppHostApi api) { Result resultCallback = new Result() { public void success(Void result) { - wrapped.put("result", null); + wrapped.add(0, null); reply.reply(wrapped); } public void error(Throwable error) { - wrapped.put("error", wrapError(error)); - reply.reply(wrapped); + ArrayList wrappedError = wrapError(error); + reply.reply(wrappedError); } }; api.setAutomaticDataCollectionEnabled(appNameArg, enabledArg, resultCallback); } catch (Error | RuntimeException exception) { - wrapped.put("error", wrapError(exception)); - reply.reply(wrapped); + ArrayList wrappedError = wrapError(exception); + reply.reply(wrappedError); } }); } else { @@ -721,15 +701,14 @@ public void error(Throwable error) { { BasicMessageChannel channel = new BasicMessageChannel<>( - binaryMessenger, - "dev.flutter.pigeon.FirebaseAppHostApi.setAutomaticResourceManagementEnabled", - getCodec()); + binaryMessenger, "dev.flutter.pigeon.FirebaseAppHostApi.setAutomaticResourceManagementEnabled", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { - Map wrapped = new HashMap<>(); + ArrayList wrapped = new ArrayList(); try { ArrayList args = (ArrayList) message; + assert args != null; String appNameArg = (String) args.get(0); if (appNameArg == null) { throw new NullPointerException("appNameArg unexpectedly null."); @@ -741,20 +720,20 @@ public void error(Throwable error) { Result resultCallback = new Result() { public void success(Void result) { - wrapped.put("result", null); + wrapped.add(0, null); reply.reply(wrapped); } public void error(Throwable error) { - wrapped.put("error", wrapError(error)); - reply.reply(wrapped); + ArrayList wrappedError = wrapError(error); + reply.reply(wrappedError); } }; api.setAutomaticResourceManagementEnabled(appNameArg, enabledArg, resultCallback); } catch (Error | RuntimeException exception) { - wrapped.put("error", wrapError(exception)); - reply.reply(wrapped); + ArrayList wrappedError = wrapError(exception); + reply.reply(wrappedError); } }); } else { @@ -768,9 +747,10 @@ public void error(Throwable error) { if (api != null) { channel.setMessageHandler( (message, reply) -> { - Map wrapped = new HashMap<>(); + ArrayList wrapped = new ArrayList(); try { ArrayList args = (ArrayList) message; + assert args != null; String appNameArg = (String) args.get(0); if (appNameArg == null) { throw new NullPointerException("appNameArg unexpectedly null."); @@ -778,20 +758,20 @@ public void error(Throwable error) { Result resultCallback = new Result() { public void success(Void result) { - wrapped.put("result", null); + wrapped.add(0, null); reply.reply(wrapped); } public void error(Throwable error) { - wrapped.put("error", wrapError(error)); - reply.reply(wrapped); + ArrayList wrappedError = wrapError(error); + reply.reply(wrappedError); } }; api.delete(appNameArg, resultCallback); } catch (Error | RuntimeException exception) { - wrapped.put("error", wrapError(exception)); - reply.reply(wrapped); + ArrayList wrappedError = wrapError(exception); + reply.reply(wrappedError); } }); } else { @@ -800,14 +780,4 @@ public void error(Throwable error) { } } } - - private static Map wrapError(Throwable exception) { - Map errorMap = new HashMap<>(); - errorMap.put("message", exception.toString()); - errorMap.put("code", exception.getClass().getSimpleName()); - errorMap.put( - "details", - "Cause: " + exception.getCause() + ", Stacktrace: " + Log.getStackTraceString(exception)); - return errorMap; - } } diff --git a/packages/firebase_core/firebase_core/ios/Classes/messages.g.h b/packages/firebase_core/firebase_core/ios/Classes/messages.g.h index 70cdb4f374a9..621dc1a79ccf 100644 --- a/packages/firebase_core/firebase_core/ios/Classes/messages.g.h +++ b/packages/firebase_core/firebase_core/ios/Classes/messages.g.h @@ -1,6 +1,8 @@ -// Autogenerated from Pigeon (v3.2.0), do not edit directly. +// Autogenerated from Pigeon (v9.0.6), do not edit directly. // See also: https://pub.dev/packages/pigeon + #import + @protocol FlutterBinaryMessenger; @protocol FlutterMessageCodec; @class FlutterError; @@ -15,79 +17,68 @@ NS_ASSUME_NONNULL_BEGIN /// `init` unavailable to enforce nonnull fields, see the `make` class method. - (instancetype)init NS_UNAVAILABLE; + (instancetype)makeWithApiKey:(NSString *)apiKey - appId:(NSString *)appId - messagingSenderId:(NSString *)messagingSenderId - projectId:(NSString *)projectId - authDomain:(nullable NSString *)authDomain - databaseURL:(nullable NSString *)databaseURL - storageBucket:(nullable NSString *)storageBucket - measurementId:(nullable NSString *)measurementId - trackingId:(nullable NSString *)trackingId - deepLinkURLScheme:(nullable NSString *)deepLinkURLScheme - androidClientId:(nullable NSString *)androidClientId - iosClientId:(nullable NSString *)iosClientId - iosBundleId:(nullable NSString *)iosBundleId - appGroupId:(nullable NSString *)appGroupId; -@property(nonatomic, copy) NSString *apiKey; -@property(nonatomic, copy) NSString *appId; -@property(nonatomic, copy) NSString *messagingSenderId; -@property(nonatomic, copy) NSString *projectId; -@property(nonatomic, copy, nullable) NSString *authDomain; -@property(nonatomic, copy, nullable) NSString *databaseURL; -@property(nonatomic, copy, nullable) NSString *storageBucket; -@property(nonatomic, copy, nullable) NSString *measurementId; -@property(nonatomic, copy, nullable) NSString *trackingId; -@property(nonatomic, copy, nullable) NSString *deepLinkURLScheme; -@property(nonatomic, copy, nullable) NSString *androidClientId; -@property(nonatomic, copy, nullable) NSString *iosClientId; -@property(nonatomic, copy, nullable) NSString *iosBundleId; -@property(nonatomic, copy, nullable) NSString *appGroupId; + appId:(NSString *)appId + messagingSenderId:(NSString *)messagingSenderId + projectId:(NSString *)projectId + authDomain:(nullable NSString *)authDomain + databaseURL:(nullable NSString *)databaseURL + storageBucket:(nullable NSString *)storageBucket + measurementId:(nullable NSString *)measurementId + trackingId:(nullable NSString *)trackingId + deepLinkURLScheme:(nullable NSString *)deepLinkURLScheme + androidClientId:(nullable NSString *)androidClientId + iosClientId:(nullable NSString *)iosClientId + iosBundleId:(nullable NSString *)iosBundleId + appGroupId:(nullable NSString *)appGroupId; +@property(nonatomic, copy) NSString * apiKey; +@property(nonatomic, copy) NSString * appId; +@property(nonatomic, copy) NSString * messagingSenderId; +@property(nonatomic, copy) NSString * projectId; +@property(nonatomic, copy, nullable) NSString * authDomain; +@property(nonatomic, copy, nullable) NSString * databaseURL; +@property(nonatomic, copy, nullable) NSString * storageBucket; +@property(nonatomic, copy, nullable) NSString * measurementId; +@property(nonatomic, copy, nullable) NSString * trackingId; +@property(nonatomic, copy, nullable) NSString * deepLinkURLScheme; +@property(nonatomic, copy, nullable) NSString * androidClientId; +@property(nonatomic, copy, nullable) NSString * iosClientId; +@property(nonatomic, copy, nullable) NSString * iosBundleId; +@property(nonatomic, copy, nullable) NSString * appGroupId; @end @interface PigeonInitializeResponse : NSObject /// `init` unavailable to enforce nonnull fields, see the `make` class method. - (instancetype)init NS_UNAVAILABLE; + (instancetype)makeWithName:(NSString *)name - options:(PigeonFirebaseOptions *)options + options:(PigeonFirebaseOptions *)options isAutomaticDataCollectionEnabled:(nullable NSNumber *)isAutomaticDataCollectionEnabled - pluginConstants:(NSDictionary *)pluginConstants; -@property(nonatomic, copy) NSString *name; -@property(nonatomic, strong) PigeonFirebaseOptions *options; -@property(nonatomic, strong, nullable) NSNumber *isAutomaticDataCollectionEnabled; -@property(nonatomic, strong) NSDictionary *pluginConstants; + pluginConstants:(NSDictionary *)pluginConstants; +@property(nonatomic, copy) NSString * name; +@property(nonatomic, strong) PigeonFirebaseOptions * options; +@property(nonatomic, strong, nullable) NSNumber * isAutomaticDataCollectionEnabled; +@property(nonatomic, strong) NSDictionary * pluginConstants; @end /// The codec used by FirebaseCoreHostApi. NSObject *FirebaseCoreHostApiGetCodec(void); @protocol FirebaseCoreHostApi -- (void)initializeAppAppName:(NSString *)appName - initializeAppRequest:(PigeonFirebaseOptions *)initializeAppRequest - completion:(void (^)(PigeonInitializeResponse *_Nullable, - FlutterError *_Nullable))completion; -- (void)initializeCoreWithCompletion:(void (^)(NSArray *_Nullable, - FlutterError *_Nullable))completion; -- (void)optionsFromResourceWithCompletion:(void (^)(PigeonFirebaseOptions *_Nullable, - FlutterError *_Nullable))completion; +- (void)initializeAppAppName:(NSString *)appName initializeAppRequest:(PigeonFirebaseOptions *)initializeAppRequest completion:(void (^)(PigeonInitializeResponse *_Nullable, FlutterError *_Nullable))completion; +- (void)initializeCoreWithCompletion:(void (^)(NSArray *_Nullable, FlutterError *_Nullable))completion; +- (void)optionsFromResourceWithCompletion:(void (^)(PigeonFirebaseOptions *_Nullable, FlutterError *_Nullable))completion; @end -extern void FirebaseCoreHostApiSetup(id binaryMessenger, - NSObject *_Nullable api); +extern void FirebaseCoreHostApiSetup(id binaryMessenger, NSObject *_Nullable api); /// The codec used by FirebaseAppHostApi. NSObject *FirebaseAppHostApiGetCodec(void); @protocol FirebaseAppHostApi -- (void)setAutomaticDataCollectionEnabledAppName:(NSString *)appName - enabled:(NSNumber *)enabled - completion:(void (^)(FlutterError *_Nullable))completion; -- (void)setAutomaticResourceManagementEnabledAppName:(NSString *)appName - enabled:(NSNumber *)enabled - completion:(void (^)(FlutterError *_Nullable))completion; +- (void)setAutomaticDataCollectionEnabledAppName:(NSString *)appName enabled:(NSNumber *)enabled completion:(void (^)(FlutterError *_Nullable))completion; +- (void)setAutomaticResourceManagementEnabledAppName:(NSString *)appName enabled:(NSNumber *)enabled completion:(void (^)(FlutterError *_Nullable))completion; - (void)deleteAppName:(NSString *)appName completion:(void (^)(FlutterError *_Nullable))completion; @end -extern void FirebaseAppHostApiSetup(id binaryMessenger, - NSObject *_Nullable api); +extern void FirebaseAppHostApiSetup(id binaryMessenger, NSObject *_Nullable api); NS_ASSUME_NONNULL_END diff --git a/packages/firebase_core/firebase_core/ios/Classes/messages.g.m b/packages/firebase_core/firebase_core/ios/Classes/messages.g.m index 1c22807964d1..8d6cda3d45af 100644 --- a/packages/firebase_core/firebase_core/ios/Classes/messages.g.m +++ b/packages/firebase_core/firebase_core/ios/Classes/messages.g.m @@ -1,33 +1,20 @@ -// Autogenerated from Pigeon (v3.2.0), do not edit directly. +// Autogenerated from Pigeon (v9.0.6), do not edit directly. // See also: https://pub.dev/packages/pigeon + #import "messages.g.h" -#if TARGET_OS_OSX -#import -#else #import -#endif #if !__has_feature(objc_arc) #error File requires ARC to be enabled. #endif -static NSDictionary *wrapResult(id result, FlutterError *error) { - NSDictionary *errorDict = (NSDictionary *)[NSNull null]; +static NSArray *wrapResult(id result, FlutterError *error) { if (error) { - errorDict = @{ - @"code" : (error.code ?: [NSNull null]), - @"message" : (error.message ?: [NSNull null]), - @"details" : (error.details ?: [NSNull null]), - }; + return @[ + error.code ?: [NSNull null], error.message ?: [NSNull null], error.details ?: [NSNull null] + ]; } - return @{ - @"result" : (result ?: [NSNull null]), - @"error" : errorDict, - }; -} -static id GetNullableObject(NSDictionary *dict, id key) { - id result = dict[key]; - return (result == [NSNull null]) ? nil : result; + return @[ result ?: [NSNull null] ]; } static id GetNullableObjectAtIndex(NSArray *array, NSInteger key) { id result = array[key]; @@ -35,32 +22,33 @@ static id GetNullableObjectAtIndex(NSArray *array, NSInteger key) { } @interface PigeonFirebaseOptions () -+ (PigeonFirebaseOptions *)fromMap:(NSDictionary *)dict; -+ (nullable PigeonFirebaseOptions *)nullableFromMap:(NSDictionary *)dict; -- (NSDictionary *)toMap; ++ (PigeonFirebaseOptions *)fromList:(NSArray *)list; ++ (nullable PigeonFirebaseOptions *)nullableFromList:(NSArray *)list; +- (NSArray *)toList; @end + @interface PigeonInitializeResponse () -+ (PigeonInitializeResponse *)fromMap:(NSDictionary *)dict; -+ (nullable PigeonInitializeResponse *)nullableFromMap:(NSDictionary *)dict; -- (NSDictionary *)toMap; ++ (PigeonInitializeResponse *)fromList:(NSArray *)list; ++ (nullable PigeonInitializeResponse *)nullableFromList:(NSArray *)list; +- (NSArray *)toList; @end @implementation PigeonFirebaseOptions + (instancetype)makeWithApiKey:(NSString *)apiKey - appId:(NSString *)appId - messagingSenderId:(NSString *)messagingSenderId - projectId:(NSString *)projectId - authDomain:(nullable NSString *)authDomain - databaseURL:(nullable NSString *)databaseURL - storageBucket:(nullable NSString *)storageBucket - measurementId:(nullable NSString *)measurementId - trackingId:(nullable NSString *)trackingId - deepLinkURLScheme:(nullable NSString *)deepLinkURLScheme - androidClientId:(nullable NSString *)androidClientId - iosClientId:(nullable NSString *)iosClientId - iosBundleId:(nullable NSString *)iosBundleId - appGroupId:(nullable NSString *)appGroupId { - PigeonFirebaseOptions *pigeonResult = [[PigeonFirebaseOptions alloc] init]; + appId:(NSString *)appId + messagingSenderId:(NSString *)messagingSenderId + projectId:(NSString *)projectId + authDomain:(nullable NSString *)authDomain + databaseURL:(nullable NSString *)databaseURL + storageBucket:(nullable NSString *)storageBucket + measurementId:(nullable NSString *)measurementId + trackingId:(nullable NSString *)trackingId + deepLinkURLScheme:(nullable NSString *)deepLinkURLScheme + androidClientId:(nullable NSString *)androidClientId + iosClientId:(nullable NSString *)iosClientId + iosBundleId:(nullable NSString *)iosBundleId + appGroupId:(nullable NSString *)appGroupId { + PigeonFirebaseOptions* pigeonResult = [[PigeonFirebaseOptions alloc] init]; pigeonResult.apiKey = apiKey; pigeonResult.appId = appId; pigeonResult.messagingSenderId = messagingSenderId; @@ -77,86 +65,84 @@ + (instancetype)makeWithApiKey:(NSString *)apiKey pigeonResult.appGroupId = appGroupId; return pigeonResult; } -+ (PigeonFirebaseOptions *)fromMap:(NSDictionary *)dict { ++ (PigeonFirebaseOptions *)fromList:(NSArray *)list { PigeonFirebaseOptions *pigeonResult = [[PigeonFirebaseOptions alloc] init]; - pigeonResult.apiKey = GetNullableObject(dict, @"apiKey"); + pigeonResult.apiKey = GetNullableObjectAtIndex(list, 0); NSAssert(pigeonResult.apiKey != nil, @""); - pigeonResult.appId = GetNullableObject(dict, @"appId"); + pigeonResult.appId = GetNullableObjectAtIndex(list, 1); NSAssert(pigeonResult.appId != nil, @""); - pigeonResult.messagingSenderId = GetNullableObject(dict, @"messagingSenderId"); + pigeonResult.messagingSenderId = GetNullableObjectAtIndex(list, 2); NSAssert(pigeonResult.messagingSenderId != nil, @""); - pigeonResult.projectId = GetNullableObject(dict, @"projectId"); + pigeonResult.projectId = GetNullableObjectAtIndex(list, 3); NSAssert(pigeonResult.projectId != nil, @""); - pigeonResult.authDomain = GetNullableObject(dict, @"authDomain"); - pigeonResult.databaseURL = GetNullableObject(dict, @"databaseURL"); - pigeonResult.storageBucket = GetNullableObject(dict, @"storageBucket"); - pigeonResult.measurementId = GetNullableObject(dict, @"measurementId"); - pigeonResult.trackingId = GetNullableObject(dict, @"trackingId"); - pigeonResult.deepLinkURLScheme = GetNullableObject(dict, @"deepLinkURLScheme"); - pigeonResult.androidClientId = GetNullableObject(dict, @"androidClientId"); - pigeonResult.iosClientId = GetNullableObject(dict, @"iosClientId"); - pigeonResult.iosBundleId = GetNullableObject(dict, @"iosBundleId"); - pigeonResult.appGroupId = GetNullableObject(dict, @"appGroupId"); + pigeonResult.authDomain = GetNullableObjectAtIndex(list, 4); + pigeonResult.databaseURL = GetNullableObjectAtIndex(list, 5); + pigeonResult.storageBucket = GetNullableObjectAtIndex(list, 6); + pigeonResult.measurementId = GetNullableObjectAtIndex(list, 7); + pigeonResult.trackingId = GetNullableObjectAtIndex(list, 8); + pigeonResult.deepLinkURLScheme = GetNullableObjectAtIndex(list, 9); + pigeonResult.androidClientId = GetNullableObjectAtIndex(list, 10); + pigeonResult.iosClientId = GetNullableObjectAtIndex(list, 11); + pigeonResult.iosBundleId = GetNullableObjectAtIndex(list, 12); + pigeonResult.appGroupId = GetNullableObjectAtIndex(list, 13); return pigeonResult; } -+ (nullable PigeonFirebaseOptions *)nullableFromMap:(NSDictionary *)dict { - return (dict) ? [PigeonFirebaseOptions fromMap:dict] : nil; ++ (nullable PigeonFirebaseOptions *)nullableFromList:(NSArray *)list { + return (list) ? [PigeonFirebaseOptions fromList:list] : nil; } -- (NSDictionary *)toMap { - return @{ - @"apiKey" : (self.apiKey ?: [NSNull null]), - @"appId" : (self.appId ?: [NSNull null]), - @"messagingSenderId" : (self.messagingSenderId ?: [NSNull null]), - @"projectId" : (self.projectId ?: [NSNull null]), - @"authDomain" : (self.authDomain ?: [NSNull null]), - @"databaseURL" : (self.databaseURL ?: [NSNull null]), - @"storageBucket" : (self.storageBucket ?: [NSNull null]), - @"measurementId" : (self.measurementId ?: [NSNull null]), - @"trackingId" : (self.trackingId ?: [NSNull null]), - @"deepLinkURLScheme" : (self.deepLinkURLScheme ?: [NSNull null]), - @"androidClientId" : (self.androidClientId ?: [NSNull null]), - @"iosClientId" : (self.iosClientId ?: [NSNull null]), - @"iosBundleId" : (self.iosBundleId ?: [NSNull null]), - @"appGroupId" : (self.appGroupId ?: [NSNull null]), - }; +- (NSArray *)toList { + return @[ + (self.apiKey ?: [NSNull null]), + (self.appId ?: [NSNull null]), + (self.messagingSenderId ?: [NSNull null]), + (self.projectId ?: [NSNull null]), + (self.authDomain ?: [NSNull null]), + (self.databaseURL ?: [NSNull null]), + (self.storageBucket ?: [NSNull null]), + (self.measurementId ?: [NSNull null]), + (self.trackingId ?: [NSNull null]), + (self.deepLinkURLScheme ?: [NSNull null]), + (self.androidClientId ?: [NSNull null]), + (self.iosClientId ?: [NSNull null]), + (self.iosBundleId ?: [NSNull null]), + (self.appGroupId ?: [NSNull null]), + ]; } @end @implementation PigeonInitializeResponse + (instancetype)makeWithName:(NSString *)name - options:(PigeonFirebaseOptions *)options + options:(PigeonFirebaseOptions *)options isAutomaticDataCollectionEnabled:(nullable NSNumber *)isAutomaticDataCollectionEnabled - pluginConstants:(NSDictionary *)pluginConstants { - PigeonInitializeResponse *pigeonResult = [[PigeonInitializeResponse alloc] init]; + pluginConstants:(NSDictionary *)pluginConstants { + PigeonInitializeResponse* pigeonResult = [[PigeonInitializeResponse alloc] init]; pigeonResult.name = name; pigeonResult.options = options; pigeonResult.isAutomaticDataCollectionEnabled = isAutomaticDataCollectionEnabled; pigeonResult.pluginConstants = pluginConstants; return pigeonResult; } -+ (PigeonInitializeResponse *)fromMap:(NSDictionary *)dict { ++ (PigeonInitializeResponse *)fromList:(NSArray *)list { PigeonInitializeResponse *pigeonResult = [[PigeonInitializeResponse alloc] init]; - pigeonResult.name = GetNullableObject(dict, @"name"); + pigeonResult.name = GetNullableObjectAtIndex(list, 0); NSAssert(pigeonResult.name != nil, @""); - pigeonResult.options = - [PigeonFirebaseOptions nullableFromMap:GetNullableObject(dict, @"options")]; + pigeonResult.options = [PigeonFirebaseOptions nullableFromList:(GetNullableObjectAtIndex(list, 1))]; NSAssert(pigeonResult.options != nil, @""); - pigeonResult.isAutomaticDataCollectionEnabled = - GetNullableObject(dict, @"isAutomaticDataCollectionEnabled"); - pigeonResult.pluginConstants = GetNullableObject(dict, @"pluginConstants"); + pigeonResult.isAutomaticDataCollectionEnabled = GetNullableObjectAtIndex(list, 2); + pigeonResult.pluginConstants = GetNullableObjectAtIndex(list, 3); NSAssert(pigeonResult.pluginConstants != nil, @""); return pigeonResult; } -+ (nullable PigeonInitializeResponse *)nullableFromMap:(NSDictionary *)dict { - return (dict) ? [PigeonInitializeResponse fromMap:dict] : nil; ++ (nullable PigeonInitializeResponse *)nullableFromList:(NSArray *)list { + return (list) ? [PigeonInitializeResponse fromList:list] : nil; } -- (NSDictionary *)toMap { - return @{ - @"name" : (self.name ?: [NSNull null]), - @"options" : (self.options ? [self.options toMap] : [NSNull null]), - @"isAutomaticDataCollectionEnabled" : (self.isAutomaticDataCollectionEnabled ?: [NSNull null]), - @"pluginConstants" : (self.pluginConstants ?: [NSNull null]), - }; +- (NSArray *)toList { + return @[ + (self.name ?: [NSNull null]), + (self.options ? [self.options toList] : [NSNull null]), + (self.isAutomaticDataCollectionEnabled ?: [NSNull null]), + (self.pluginConstants ?: [NSNull null]), + ]; } @end @@ -165,12 +151,10 @@ @interface FirebaseCoreHostApiCodecReader : FlutterStandardReader @implementation FirebaseCoreHostApiCodecReader - (nullable id)readValueOfType:(UInt8)type { switch (type) { - case 128: - return [PigeonFirebaseOptions fromMap:[self readValue]]; - - case 129: - return [PigeonInitializeResponse fromMap:[self readValue]]; - + case 128: + return [PigeonFirebaseOptions fromList:[self readValue]]; + case 129: + return [PigeonInitializeResponse fromList:[self readValue]]; default: return [super readValueOfType:type]; } @@ -183,10 +167,10 @@ @implementation FirebaseCoreHostApiCodecWriter - (void)writeValue:(id)value { if ([value isKindOfClass:[PigeonFirebaseOptions class]]) { [self writeByte:128]; - [self writeValue:[value toMap]]; + [self writeValue:[value toList]]; } else if ([value isKindOfClass:[PigeonInitializeResponse class]]) { [self writeByte:129]; - [self writeValue:[value toMap]]; + [self writeValue:[value toList]]; } else { [super writeValue:value]; } @@ -205,57 +189,46 @@ - (FlutterStandardReader *)readerWithData:(NSData *)data { @end NSObject *FirebaseCoreHostApiGetCodec() { - static dispatch_once_t sPred = 0; static FlutterStandardMessageCodec *sSharedObject = nil; + static dispatch_once_t sPred = 0; dispatch_once(&sPred, ^{ - FirebaseCoreHostApiCodecReaderWriter *readerWriter = - [[FirebaseCoreHostApiCodecReaderWriter alloc] init]; + FirebaseCoreHostApiCodecReaderWriter *readerWriter = [[FirebaseCoreHostApiCodecReaderWriter alloc] init]; sSharedObject = [FlutterStandardMessageCodec codecWithReaderWriter:readerWriter]; }); return sSharedObject; } -void FirebaseCoreHostApiSetup(id binaryMessenger, - NSObject *api) { +void FirebaseCoreHostApiSetup(id binaryMessenger, NSObject *api) { { - FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] - initWithName:@"dev.flutter.pigeon.FirebaseCoreHostApi.initializeApp" + FlutterBasicMessageChannel *channel = + [[FlutterBasicMessageChannel alloc] + initWithName:@"dev.flutter.pigeon.FirebaseCoreHostApi.initializeApp" binaryMessenger:binaryMessenger - codec:FirebaseCoreHostApiGetCodec()]; + codec:FirebaseCoreHostApiGetCodec()]; if (api) { - NSCAssert([api respondsToSelector:@selector(initializeAppAppName: - initializeAppRequest:completion:)], - @"FirebaseCoreHostApi api (%@) doesn't respond to " - @"@selector(initializeAppAppName:initializeAppRequest:completion:)", - api); + NSCAssert([api respondsToSelector:@selector(initializeAppAppName:initializeAppRequest:completion:)], @"FirebaseCoreHostApi api (%@) doesn't respond to @selector(initializeAppAppName:initializeAppRequest:completion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; NSString *arg_appName = GetNullableObjectAtIndex(args, 0); PigeonFirebaseOptions *arg_initializeAppRequest = GetNullableObjectAtIndex(args, 1); - [api initializeAppAppName:arg_appName - initializeAppRequest:arg_initializeAppRequest - completion:^(PigeonInitializeResponse *_Nullable output, - FlutterError *_Nullable error) { - callback(wrapResult(output, error)); - }]; + [api initializeAppAppName:arg_appName initializeAppRequest:arg_initializeAppRequest completion:^(PigeonInitializeResponse *_Nullable output, FlutterError *_Nullable error) { + callback(wrapResult(output, error)); + }]; }]; } else { [channel setMessageHandler:nil]; } } { - FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] - initWithName:@"dev.flutter.pigeon.FirebaseCoreHostApi.initializeCore" + FlutterBasicMessageChannel *channel = + [[FlutterBasicMessageChannel alloc] + initWithName:@"dev.flutter.pigeon.FirebaseCoreHostApi.initializeCore" binaryMessenger:binaryMessenger - codec:FirebaseCoreHostApiGetCodec()]; + codec:FirebaseCoreHostApiGetCodec()]; if (api) { - NSCAssert([api respondsToSelector:@selector(initializeCoreWithCompletion:)], - @"FirebaseCoreHostApi api (%@) doesn't respond to " - @"@selector(initializeCoreWithCompletion:)", - api); + NSCAssert([api respondsToSelector:@selector(initializeCoreWithCompletion:)], @"FirebaseCoreHostApi api (%@) doesn't respond to @selector(initializeCoreWithCompletion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { - [api initializeCoreWithCompletion:^(NSArray *_Nullable output, - FlutterError *_Nullable error) { + [api initializeCoreWithCompletion:^(NSArray *_Nullable output, FlutterError *_Nullable error) { callback(wrapResult(output, error)); }]; }]; @@ -264,18 +237,15 @@ void FirebaseCoreHostApiSetup(id binaryMessenger, } } { - FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] - initWithName:@"dev.flutter.pigeon.FirebaseCoreHostApi.optionsFromResource" + FlutterBasicMessageChannel *channel = + [[FlutterBasicMessageChannel alloc] + initWithName:@"dev.flutter.pigeon.FirebaseCoreHostApi.optionsFromResource" binaryMessenger:binaryMessenger - codec:FirebaseCoreHostApiGetCodec()]; + codec:FirebaseCoreHostApiGetCodec()]; if (api) { - NSCAssert([api respondsToSelector:@selector(optionsFromResourceWithCompletion:)], - @"FirebaseCoreHostApi api (%@) doesn't respond to " - @"@selector(optionsFromResourceWithCompletion:)", - api); + NSCAssert([api respondsToSelector:@selector(optionsFromResourceWithCompletion:)], @"FirebaseCoreHostApi api (%@) doesn't respond to @selector(optionsFromResourceWithCompletion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { - [api optionsFromResourceWithCompletion:^(PigeonFirebaseOptions *_Nullable output, - FlutterError *_Nullable error) { + [api optionsFromResourceWithCompletion:^(PigeonFirebaseOptions *_Nullable output, FlutterError *_Nullable error) { callback(wrapResult(output, error)); }]; }]; @@ -284,108 +254,67 @@ void FirebaseCoreHostApiSetup(id binaryMessenger, } } } -@interface FirebaseAppHostApiCodecReader : FlutterStandardReader -@end -@implementation FirebaseAppHostApiCodecReader -@end - -@interface FirebaseAppHostApiCodecWriter : FlutterStandardWriter -@end -@implementation FirebaseAppHostApiCodecWriter -@end - -@interface FirebaseAppHostApiCodecReaderWriter : FlutterStandardReaderWriter -@end -@implementation FirebaseAppHostApiCodecReaderWriter -- (FlutterStandardWriter *)writerWithData:(NSMutableData *)data { - return [[FirebaseAppHostApiCodecWriter alloc] initWithData:data]; -} -- (FlutterStandardReader *)readerWithData:(NSData *)data { - return [[FirebaseAppHostApiCodecReader alloc] initWithData:data]; -} -@end - NSObject *FirebaseAppHostApiGetCodec() { - static dispatch_once_t sPred = 0; static FlutterStandardMessageCodec *sSharedObject = nil; - dispatch_once(&sPred, ^{ - FirebaseAppHostApiCodecReaderWriter *readerWriter = - [[FirebaseAppHostApiCodecReaderWriter alloc] init]; - sSharedObject = [FlutterStandardMessageCodec codecWithReaderWriter:readerWriter]; - }); + sSharedObject = [FlutterStandardMessageCodec sharedInstance]; return sSharedObject; } -void FirebaseAppHostApiSetup(id binaryMessenger, - NSObject *api) { +void FirebaseAppHostApiSetup(id binaryMessenger, NSObject *api) { { - FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] - initWithName:@"dev.flutter.pigeon.FirebaseAppHostApi.setAutomaticDataCollectionEnabled" + FlutterBasicMessageChannel *channel = + [[FlutterBasicMessageChannel alloc] + initWithName:@"dev.flutter.pigeon.FirebaseAppHostApi.setAutomaticDataCollectionEnabled" binaryMessenger:binaryMessenger - codec:FirebaseAppHostApiGetCodec()]; + codec:FirebaseAppHostApiGetCodec()]; if (api) { - NSCAssert([api respondsToSelector:@selector - (setAutomaticDataCollectionEnabledAppName:enabled:completion:)], - @"FirebaseAppHostApi api (%@) doesn't respond to " - @"@selector(setAutomaticDataCollectionEnabledAppName:enabled:completion:)", - api); + NSCAssert([api respondsToSelector:@selector(setAutomaticDataCollectionEnabledAppName:enabled:completion:)], @"FirebaseAppHostApi api (%@) doesn't respond to @selector(setAutomaticDataCollectionEnabledAppName:enabled:completion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; NSString *arg_appName = GetNullableObjectAtIndex(args, 0); NSNumber *arg_enabled = GetNullableObjectAtIndex(args, 1); - [api setAutomaticDataCollectionEnabledAppName:arg_appName - enabled:arg_enabled - completion:^(FlutterError *_Nullable error) { - callback(wrapResult(nil, error)); - }]; + [api setAutomaticDataCollectionEnabledAppName:arg_appName enabled:arg_enabled completion:^(FlutterError *_Nullable error) { + callback(wrapResult(nil, error)); + }]; }]; } else { [channel setMessageHandler:nil]; } } { - FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] - initWithName: - @"dev.flutter.pigeon.FirebaseAppHostApi.setAutomaticResourceManagementEnabled" + FlutterBasicMessageChannel *channel = + [[FlutterBasicMessageChannel alloc] + initWithName:@"dev.flutter.pigeon.FirebaseAppHostApi.setAutomaticResourceManagementEnabled" binaryMessenger:binaryMessenger - codec:FirebaseAppHostApiGetCodec()]; + codec:FirebaseAppHostApiGetCodec()]; if (api) { - NSCAssert([api respondsToSelector:@selector - (setAutomaticResourceManagementEnabledAppName:enabled:completion:)], - @"FirebaseAppHostApi api (%@) doesn't respond to " - @"@selector(setAutomaticResourceManagementEnabledAppName:enabled:completion:)", - api); + NSCAssert([api respondsToSelector:@selector(setAutomaticResourceManagementEnabledAppName:enabled:completion:)], @"FirebaseAppHostApi api (%@) doesn't respond to @selector(setAutomaticResourceManagementEnabledAppName:enabled:completion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; NSString *arg_appName = GetNullableObjectAtIndex(args, 0); NSNumber *arg_enabled = GetNullableObjectAtIndex(args, 1); - [api setAutomaticResourceManagementEnabledAppName:arg_appName - enabled:arg_enabled - completion:^(FlutterError *_Nullable error) { - callback(wrapResult(nil, error)); - }]; + [api setAutomaticResourceManagementEnabledAppName:arg_appName enabled:arg_enabled completion:^(FlutterError *_Nullable error) { + callback(wrapResult(nil, error)); + }]; }]; } else { [channel setMessageHandler:nil]; } } { - FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] - initWithName:@"dev.flutter.pigeon.FirebaseAppHostApi.delete" + FlutterBasicMessageChannel *channel = + [[FlutterBasicMessageChannel alloc] + initWithName:@"dev.flutter.pigeon.FirebaseAppHostApi.delete" binaryMessenger:binaryMessenger - codec:FirebaseAppHostApiGetCodec()]; + codec:FirebaseAppHostApiGetCodec()]; if (api) { - NSCAssert( - [api respondsToSelector:@selector(deleteAppName:completion:)], - @"FirebaseAppHostApi api (%@) doesn't respond to @selector(deleteAppName:completion:)", - api); + NSCAssert([api respondsToSelector:@selector(deleteAppName:completion:)], @"FirebaseAppHostApi api (%@) doesn't respond to @selector(deleteAppName:completion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; NSString *arg_appName = GetNullableObjectAtIndex(args, 0); - [api deleteAppName:arg_appName - completion:^(FlutterError *_Nullable error) { - callback(wrapResult(nil, error)); - }]; + [api deleteAppName:arg_appName completion:^(FlutterError *_Nullable error) { + callback(wrapResult(nil, error)); + }]; }]; } else { [channel setMessageHandler:nil]; diff --git a/packages/firebase_core/firebase_core_platform_interface/lib/src/pigeon/messages.pigeon.dart b/packages/firebase_core/firebase_core_platform_interface/lib/src/pigeon/messages.pigeon.dart index 9420915342de..034242fe27b6 100644 --- a/packages/firebase_core/firebase_core_platform_interface/lib/src/pigeon/messages.pigeon.dart +++ b/packages/firebase_core/firebase_core_platform_interface/lib/src/pigeon/messages.pigeon.dart @@ -1,15 +1,11 @@ -// Copyright 2022, the Chromium project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -// Autogenerated from Pigeon (v3.2.0), do not edit directly. +// Autogenerated from Pigeon (v9.0.6), do not edit directly. // See also: https://pub.dev/packages/pigeon -// ignore_for_file: public_member_api_docs, non_constant_identifier_names, avoid_as, unused_import, unnecessary_parenthesis, prefer_null_aware_operators, omit_local_variable_types, unused_shown_name -// @dart = 2.12 +// ignore_for_file: public_member_api_docs, non_constant_identifier_names, avoid_as, unused_import, unnecessary_parenthesis, prefer_null_aware_operators, omit_local_variable_types, unused_shown_name, unnecessary_import + import 'dart:async'; -import 'dart:typed_data' show Uint8List, Int32List, Int64List, Float64List; +import 'dart:typed_data' show Float64List, Int32List, Int64List, Uint8List; -import 'package:flutter/foundation.dart' show WriteBuffer, ReadBuffer; +import 'package:flutter/foundation.dart' show ReadBuffer, WriteBuffer; import 'package:flutter/services.dart'; class PigeonFirebaseOptions { @@ -31,56 +27,69 @@ class PigeonFirebaseOptions { }); String apiKey; + String appId; + String messagingSenderId; + String projectId; + String? authDomain; + String? databaseURL; + String? storageBucket; + String? measurementId; + String? trackingId; + String? deepLinkURLScheme; + String? androidClientId; + String? iosClientId; + String? iosBundleId; + String? appGroupId; Object encode() { - final Map pigeonMap = {}; - pigeonMap['apiKey'] = apiKey; - pigeonMap['appId'] = appId; - pigeonMap['messagingSenderId'] = messagingSenderId; - pigeonMap['projectId'] = projectId; - pigeonMap['authDomain'] = authDomain; - pigeonMap['databaseURL'] = databaseURL; - pigeonMap['storageBucket'] = storageBucket; - pigeonMap['measurementId'] = measurementId; - pigeonMap['trackingId'] = trackingId; - pigeonMap['deepLinkURLScheme'] = deepLinkURLScheme; - pigeonMap['androidClientId'] = androidClientId; - pigeonMap['iosClientId'] = iosClientId; - pigeonMap['iosBundleId'] = iosBundleId; - pigeonMap['appGroupId'] = appGroupId; - return pigeonMap; + return [ + apiKey, + appId, + messagingSenderId, + projectId, + authDomain, + databaseURL, + storageBucket, + measurementId, + trackingId, + deepLinkURLScheme, + androidClientId, + iosClientId, + iosBundleId, + appGroupId, + ]; } - static PigeonFirebaseOptions decode(Object message) { - final Map pigeonMap = message as Map; + static PigeonFirebaseOptions decode(Object result) { + result as List; return PigeonFirebaseOptions( - apiKey: pigeonMap['apiKey']! as String, - appId: pigeonMap['appId']! as String, - messagingSenderId: pigeonMap['messagingSenderId']! as String, - projectId: pigeonMap['projectId']! as String, - authDomain: pigeonMap['authDomain'] as String?, - databaseURL: pigeonMap['databaseURL'] as String?, - storageBucket: pigeonMap['storageBucket'] as String?, - measurementId: pigeonMap['measurementId'] as String?, - trackingId: pigeonMap['trackingId'] as String?, - deepLinkURLScheme: pigeonMap['deepLinkURLScheme'] as String?, - androidClientId: pigeonMap['androidClientId'] as String?, - iosClientId: pigeonMap['iosClientId'] as String?, - iosBundleId: pigeonMap['iosBundleId'] as String?, - appGroupId: pigeonMap['appGroupId'] as String?, + apiKey: result[0]! as String, + appId: result[1]! as String, + messagingSenderId: result[2]! as String, + projectId: result[3]! as String, + authDomain: result[4] as String?, + databaseURL: result[5] as String?, + storageBucket: result[6] as String?, + measurementId: result[7] as String?, + trackingId: result[8] as String?, + deepLinkURLScheme: result[9] as String?, + androidClientId: result[10] as String?, + iosClientId: result[11] as String?, + iosBundleId: result[12] as String?, + appGroupId: result[13] as String?, ); } } @@ -94,29 +103,29 @@ class PigeonInitializeResponse { }); String name; + PigeonFirebaseOptions options; + bool? isAutomaticDataCollectionEnabled; + Map pluginConstants; Object encode() { - final Map pigeonMap = {}; - pigeonMap['name'] = name; - pigeonMap['options'] = options.encode(); - pigeonMap['isAutomaticDataCollectionEnabled'] = - isAutomaticDataCollectionEnabled; - pigeonMap['pluginConstants'] = pluginConstants; - return pigeonMap; + return [ + name, + options.encode(), + isAutomaticDataCollectionEnabled, + pluginConstants, + ]; } - static PigeonInitializeResponse decode(Object message) { - final Map pigeonMap = message as Map; + static PigeonInitializeResponse decode(Object result) { + result as List; return PigeonInitializeResponse( - name: pigeonMap['name']! as String, - options: PigeonFirebaseOptions.decode(pigeonMap['options']!), - isAutomaticDataCollectionEnabled: - pigeonMap['isAutomaticDataCollectionEnabled'] as bool?, - pluginConstants: (pigeonMap['pluginConstants'] as Map?)! - .cast(), + name: result[0]! as String, + options: PigeonFirebaseOptions.decode(result[1]! as List), + isAutomaticDataCollectionEnabled: result[2] as bool?, + pluginConstants: (result[3] as Map?)!.cast(), ); } } @@ -139,12 +148,10 @@ class _FirebaseCoreHostApiCodec extends StandardMessageCodec { @override Object? readValueOfType(int type, ReadBuffer buffer) { switch (type) { - case 128: + case 128: return PigeonFirebaseOptions.decode(readValue(buffer)!); - - case 129: + case 129: return PigeonInitializeResponse.decode(readValue(buffer)!); - default: return super.readValueOfType(type, buffer); } @@ -157,39 +164,34 @@ class FirebaseCoreHostApi { /// BinaryMessenger will be used which routes to the host platform. FirebaseCoreHostApi({BinaryMessenger? binaryMessenger}) : _binaryMessenger = binaryMessenger; - final BinaryMessenger? _binaryMessenger; static const MessageCodec codec = _FirebaseCoreHostApiCodec(); - Future initializeApp(String arg_appName, - PigeonFirebaseOptions arg_initializeAppRequest) async { + Future initializeApp(String arg_appName, PigeonFirebaseOptions arg_initializeAppRequest) async { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.FirebaseCoreHostApi.initializeApp', codec, binaryMessenger: _binaryMessenger); - final Map? replyMap = - await channel.send([arg_appName, arg_initializeAppRequest]) - as Map?; - if (replyMap == null) { + final List? replyList = + await channel.send([arg_appName, arg_initializeAppRequest]) as List?; + if (replyList == null) { throw PlatformException( code: 'channel-error', message: 'Unable to establish connection on channel.', ); - } else if (replyMap['error'] != null) { - final Map error = - (replyMap['error'] as Map?)!; + } else if (replyList.length > 1) { throw PlatformException( - code: (error['code'] as String?)!, - message: error['message'] as String?, - details: error['details'], + code: replyList[0]! as String, + message: replyList[1] as String?, + details: replyList[2], ); - } else if (replyMap['result'] == null) { + } else if (replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { - return (replyMap['result'] as PigeonInitializeResponse?)!; + return (replyList[0] as PigeonInitializeResponse?)!; } } @@ -197,29 +199,26 @@ class FirebaseCoreHostApi { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.FirebaseCoreHostApi.initializeCore', codec, binaryMessenger: _binaryMessenger); - final Map? replyMap = - await channel.send(null) as Map?; - if (replyMap == null) { + final List? replyList = + await channel.send(null) as List?; + if (replyList == null) { throw PlatformException( code: 'channel-error', message: 'Unable to establish connection on channel.', ); - } else if (replyMap['error'] != null) { - final Map error = - (replyMap['error'] as Map?)!; + } else if (replyList.length > 1) { throw PlatformException( - code: (error['code'] as String?)!, - message: error['message'] as String?, - details: error['details'], + code: replyList[0]! as String, + message: replyList[1] as String?, + details: replyList[2], ); - } else if (replyMap['result'] == null) { + } else if (replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { - return (replyMap['result'] as List?)! - .cast(); + return (replyList[0] as List?)!.cast(); } } @@ -227,93 +226,78 @@ class FirebaseCoreHostApi { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.FirebaseCoreHostApi.optionsFromResource', codec, binaryMessenger: _binaryMessenger); - final Map? replyMap = - await channel.send(null) as Map?; - if (replyMap == null) { + final List? replyList = + await channel.send(null) as List?; + if (replyList == null) { throw PlatformException( code: 'channel-error', message: 'Unable to establish connection on channel.', ); - } else if (replyMap['error'] != null) { - final Map error = - (replyMap['error'] as Map?)!; + } else if (replyList.length > 1) { throw PlatformException( - code: (error['code'] as String?)!, - message: error['message'] as String?, - details: error['details'], + code: replyList[0]! as String, + message: replyList[1] as String?, + details: replyList[2], ); - } else if (replyMap['result'] == null) { + } else if (replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { - return (replyMap['result'] as PigeonFirebaseOptions?)!; + return (replyList[0] as PigeonFirebaseOptions?)!; } } } -class _FirebaseAppHostApiCodec extends StandardMessageCodec { - const _FirebaseAppHostApiCodec(); -} - class FirebaseAppHostApi { /// Constructor for [FirebaseAppHostApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. FirebaseAppHostApi({BinaryMessenger? binaryMessenger}) : _binaryMessenger = binaryMessenger; - final BinaryMessenger? _binaryMessenger; - static const MessageCodec codec = _FirebaseAppHostApiCodec(); + static const MessageCodec codec = StandardMessageCodec(); - Future setAutomaticDataCollectionEnabled( - String arg_appName, bool arg_enabled) async { + Future setAutomaticDataCollectionEnabled(String arg_appName, bool arg_enabled) async { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.FirebaseAppHostApi.setAutomaticDataCollectionEnabled', - codec, + 'dev.flutter.pigeon.FirebaseAppHostApi.setAutomaticDataCollectionEnabled', codec, binaryMessenger: _binaryMessenger); - final Map? replyMap = await channel - .send([arg_appName, arg_enabled]) as Map?; - if (replyMap == null) { + final List? replyList = + await channel.send([arg_appName, arg_enabled]) as List?; + if (replyList == null) { throw PlatformException( code: 'channel-error', message: 'Unable to establish connection on channel.', ); - } else if (replyMap['error'] != null) { - final Map error = - (replyMap['error'] as Map?)!; + } else if (replyList.length > 1) { throw PlatformException( - code: (error['code'] as String?)!, - message: error['message'] as String?, - details: error['details'], + code: replyList[0]! as String, + message: replyList[1] as String?, + details: replyList[2], ); } else { return; } } - Future setAutomaticResourceManagementEnabled( - String arg_appName, bool arg_enabled) async { + Future setAutomaticResourceManagementEnabled(String arg_appName, bool arg_enabled) async { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.FirebaseAppHostApi.setAutomaticResourceManagementEnabled', - codec, + 'dev.flutter.pigeon.FirebaseAppHostApi.setAutomaticResourceManagementEnabled', codec, binaryMessenger: _binaryMessenger); - final Map? replyMap = await channel - .send([arg_appName, arg_enabled]) as Map?; - if (replyMap == null) { + final List? replyList = + await channel.send([arg_appName, arg_enabled]) as List?; + if (replyList == null) { throw PlatformException( code: 'channel-error', message: 'Unable to establish connection on channel.', ); - } else if (replyMap['error'] != null) { - final Map error = - (replyMap['error'] as Map?)!; + } else if (replyList.length > 1) { throw PlatformException( - code: (error['code'] as String?)!, - message: error['message'] as String?, - details: error['details'], + code: replyList[0]! as String, + message: replyList[1] as String?, + details: replyList[2], ); } else { return; @@ -324,20 +308,18 @@ class FirebaseAppHostApi { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.FirebaseAppHostApi.delete', codec, binaryMessenger: _binaryMessenger); - final Map? replyMap = - await channel.send([arg_appName]) as Map?; - if (replyMap == null) { + final List? replyList = + await channel.send([arg_appName]) as List?; + if (replyList == null) { throw PlatformException( code: 'channel-error', message: 'Unable to establish connection on channel.', ); - } else if (replyMap['error'] != null) { - final Map error = - (replyMap['error'] as Map?)!; + } else if (replyList.length > 1) { throw PlatformException( - code: (error['code'] as String?)!, - message: error['message'] as String?, - details: error['details'], + code: replyList[0]! as String, + message: replyList[1] as String?, + details: replyList[2], ); } else { return; diff --git a/packages/firebase_core/firebase_core_platform_interface/lib/src/pigeon/test_api.dart b/packages/firebase_core/firebase_core_platform_interface/lib/src/pigeon/test_api.dart index 95751f138e27..617ae9eb93ee 100644 --- a/packages/firebase_core/firebase_core_platform_interface/lib/src/pigeon/test_api.dart +++ b/packages/firebase_core/firebase_core_platform_interface/lib/src/pigeon/test_api.dart @@ -1,15 +1,10 @@ -// Copyright 2022, the Chromium project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -// Autogenerated from Pigeon (v3.2.0), do not edit directly. +// Autogenerated from Pigeon (v9.0.6), do not edit directly. // See also: https://pub.dev/packages/pigeon -// ignore_for_file: public_member_api_docs, non_constant_identifier_names, avoid_as, unused_import, unnecessary_parenthesis +// ignore_for_file: public_member_api_docs, non_constant_identifier_names, avoid_as, unused_import, unnecessary_parenthesis, unnecessary_import // ignore_for_file: avoid_relative_lib_imports -// @dart = 2.12 import 'dart:async'; -import 'dart:typed_data' show Uint8List, Int32List, Int64List, Float64List; -import 'package:flutter/foundation.dart' show WriteBuffer, ReadBuffer; +import 'dart:typed_data' show Float64List, Int32List, Int64List, Uint8List; +import 'package:flutter/foundation.dart' show ReadBuffer, WriteBuffer; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; @@ -33,12 +28,10 @@ class _TestFirebaseCoreHostApiCodec extends StandardMessageCodec { @override Object? readValueOfType(int type, ReadBuffer buffer) { switch (type) { - case 128: + case 128: return PigeonFirebaseOptions.decode(readValue(buffer)!); - - case 129: + case 129: return PigeonInitializeResponse.decode(readValue(buffer)!); - default: return super.readValueOfType(type, buffer); } @@ -48,12 +41,13 @@ class _TestFirebaseCoreHostApiCodec extends StandardMessageCodec { abstract class TestFirebaseCoreHostApi { static const MessageCodec codec = _TestFirebaseCoreHostApiCodec(); - Future initializeApp( - String appName, PigeonFirebaseOptions initializeAppRequest); + Future initializeApp(String appName, PigeonFirebaseOptions initializeAppRequest); + Future> initializeCore(); + Future optionsFromResource(); - static void setup(TestFirebaseCoreHostApi? api, - {BinaryMessenger? binaryMessenger}) { + + static void setup(TestFirebaseCoreHostApi? api, {BinaryMessenger? binaryMessenger}) { { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.FirebaseCoreHostApi.initializeApp', codec, @@ -63,18 +57,16 @@ abstract class TestFirebaseCoreHostApi { } else { channel.setMockMessageHandler((Object? message) async { assert(message != null, - 'Argument for dev.flutter.pigeon.FirebaseCoreHostApi.initializeApp was null.'); + 'Argument for dev.flutter.pigeon.FirebaseCoreHostApi.initializeApp was null.'); final List args = (message as List?)!; final String? arg_appName = (args[0] as String?); assert(arg_appName != null, 'Argument for dev.flutter.pigeon.FirebaseCoreHostApi.initializeApp was null, expected non-null String.'); - final PigeonFirebaseOptions? arg_initializeAppRequest = - (args[1] as PigeonFirebaseOptions?); + final PigeonFirebaseOptions? arg_initializeAppRequest = (args[1] as PigeonFirebaseOptions?); assert(arg_initializeAppRequest != null, 'Argument for dev.flutter.pigeon.FirebaseCoreHostApi.initializeApp was null, expected non-null PigeonFirebaseOptions.'); - final PigeonInitializeResponse output = - await api.initializeApp(arg_appName!, arg_initializeAppRequest!); - return {'result': output}; + final PigeonInitializeResponse output = await api.initializeApp(arg_appName!, arg_initializeAppRequest!); + return [output]; }); } } @@ -87,9 +79,8 @@ abstract class TestFirebaseCoreHostApi { } else { channel.setMockMessageHandler((Object? message) async { // ignore message - final List output = - await api.initializeCore(); - return {'result': output}; + final List output = await api.initializeCore(); + return [output]; }); } } @@ -103,37 +94,33 @@ abstract class TestFirebaseCoreHostApi { channel.setMockMessageHandler((Object? message) async { // ignore message final PigeonFirebaseOptions output = await api.optionsFromResource(); - return {'result': output}; + return [output]; }); } } } } -class _TestFirebaseAppHostApiCodec extends StandardMessageCodec { - const _TestFirebaseAppHostApiCodec(); -} - abstract class TestFirebaseAppHostApi { - static const MessageCodec codec = _TestFirebaseAppHostApiCodec(); + static const MessageCodec codec = StandardMessageCodec(); Future setAutomaticDataCollectionEnabled(String appName, bool enabled); - Future setAutomaticResourceManagementEnabled( - String appName, bool enabled); + + Future setAutomaticResourceManagementEnabled(String appName, bool enabled); + Future delete(String appName); - static void setup(TestFirebaseAppHostApi? api, - {BinaryMessenger? binaryMessenger}) { + + static void setup(TestFirebaseAppHostApi? api, {BinaryMessenger? binaryMessenger}) { { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.FirebaseAppHostApi.setAutomaticDataCollectionEnabled', - codec, + 'dev.flutter.pigeon.FirebaseAppHostApi.setAutomaticDataCollectionEnabled', codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMockMessageHandler(null); } else { channel.setMockMessageHandler((Object? message) async { assert(message != null, - 'Argument for dev.flutter.pigeon.FirebaseAppHostApi.setAutomaticDataCollectionEnabled was null.'); + 'Argument for dev.flutter.pigeon.FirebaseAppHostApi.setAutomaticDataCollectionEnabled was null.'); final List args = (message as List?)!; final String? arg_appName = (args[0] as String?); assert(arg_appName != null, @@ -141,23 +128,21 @@ abstract class TestFirebaseAppHostApi { final bool? arg_enabled = (args[1] as bool?); assert(arg_enabled != null, 'Argument for dev.flutter.pigeon.FirebaseAppHostApi.setAutomaticDataCollectionEnabled was null, expected non-null bool.'); - await api.setAutomaticDataCollectionEnabled( - arg_appName!, arg_enabled!); - return {}; + await api.setAutomaticDataCollectionEnabled(arg_appName!, arg_enabled!); + return []; }); } } { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.FirebaseAppHostApi.setAutomaticResourceManagementEnabled', - codec, + 'dev.flutter.pigeon.FirebaseAppHostApi.setAutomaticResourceManagementEnabled', codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMockMessageHandler(null); } else { channel.setMockMessageHandler((Object? message) async { assert(message != null, - 'Argument for dev.flutter.pigeon.FirebaseAppHostApi.setAutomaticResourceManagementEnabled was null.'); + 'Argument for dev.flutter.pigeon.FirebaseAppHostApi.setAutomaticResourceManagementEnabled was null.'); final List args = (message as List?)!; final String? arg_appName = (args[0] as String?); assert(arg_appName != null, @@ -165,9 +150,8 @@ abstract class TestFirebaseAppHostApi { final bool? arg_enabled = (args[1] as bool?); assert(arg_enabled != null, 'Argument for dev.flutter.pigeon.FirebaseAppHostApi.setAutomaticResourceManagementEnabled was null, expected non-null bool.'); - await api.setAutomaticResourceManagementEnabled( - arg_appName!, arg_enabled!); - return {}; + await api.setAutomaticResourceManagementEnabled(arg_appName!, arg_enabled!); + return []; }); } } @@ -180,13 +164,13 @@ abstract class TestFirebaseAppHostApi { } else { channel.setMockMessageHandler((Object? message) async { assert(message != null, - 'Argument for dev.flutter.pigeon.FirebaseAppHostApi.delete was null.'); + 'Argument for dev.flutter.pigeon.FirebaseAppHostApi.delete was null.'); final List args = (message as List?)!; final String? arg_appName = (args[0] as String?); assert(arg_appName != null, 'Argument for dev.flutter.pigeon.FirebaseAppHostApi.delete was null, expected non-null String.'); await api.delete(arg_appName!); - return {}; + return []; }); } } From 9c6cbccacb1770fd0bcc3d4213281eea51fea0b3 Mon Sep 17 00:00:00 2001 From: Guillaume Bernos Date: Tue, 14 Mar 2023 14:32:55 +0100 Subject: [PATCH 37/65] feat(core, windows): update pigeon --- .../core/GeneratedAndroidFirebaseCore.java | 51 ++++-- .../firebase_core/ios/Classes/messages.g.h | 91 +++++----- .../firebase_core/ios/Classes/messages.g.m | 164 +++++++++++------- .../windows/firebase_core_plugin.h | 4 +- .../lib/src/pigeon/messages.pigeon.dart | 42 +++-- .../lib/src/pigeon/test_api.dart | 45 +++-- 6 files changed, 237 insertions(+), 160 deletions(-) diff --git a/packages/firebase_core/firebase_core/android/src/main/java/io/flutter/plugins/firebase/core/GeneratedAndroidFirebaseCore.java b/packages/firebase_core/firebase_core/android/src/main/java/io/flutter/plugins/firebase/core/GeneratedAndroidFirebaseCore.java index c19c5b8b4ca3..5710a21f0950 100644 --- a/packages/firebase_core/firebase_core/android/src/main/java/io/flutter/plugins/firebase/core/GeneratedAndroidFirebaseCore.java +++ b/packages/firebase_core/firebase_core/android/src/main/java/io/flutter/plugins/firebase/core/GeneratedAndroidFirebaseCore.java @@ -13,9 +13,6 @@ import java.io.ByteArrayOutputStream; import java.nio.ByteBuffer; import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; import java.util.List; import java.util.Map; @@ -28,7 +25,7 @@ private static ArrayList wrapError(@NonNull Throwable exception) { errorList.add(exception.toString()); errorList.add(exception.getClass().getSimpleName()); errorList.add( - "Cause: " + exception.getCause() + ", Stacktrace: " + Log.getStackTraceString(exception)); + "Cause: " + exception.getCause() + ", Stacktrace: " + Log.getStackTraceString(exception)); return errorList; } @@ -472,7 +469,8 @@ ArrayList toList() { Object name = list.get(0); pigeonResult.setName((String) name); Object options = list.get(1); - pigeonResult.setOptions((options == null) ? null : PigeonFirebaseOptions.fromList((ArrayList) options)); + pigeonResult.setOptions( + (options == null) ? null : PigeonFirebaseOptions.fromList((ArrayList) options)); Object isAutomaticDataCollectionEnabled = list.get(2); pigeonResult.setIsAutomaticDataCollectionEnabled((Boolean) isAutomaticDataCollectionEnabled); Object pluginConstants = list.get(3); @@ -521,7 +519,10 @@ protected void writeValue(@NonNull ByteArrayOutputStream stream, Object value) { /** Generated interface from Pigeon that represents a handler of messages from Flutter. */ public interface FirebaseCoreHostApi { - void initializeApp(@NonNull String appName, @NonNull PigeonFirebaseOptions initializeAppRequest, Result result); + void initializeApp( + @NonNull String appName, + @NonNull PigeonFirebaseOptions initializeAppRequest, + Result result); void initializeCore(Result> result); @@ -531,12 +532,17 @@ public interface FirebaseCoreHostApi { static MessageCodec getCodec() { return FirebaseCoreHostApiCodec.INSTANCE; } - /**Sets up an instance of `FirebaseCoreHostApi` to handle messages through the `binaryMessenger`. */ + /** + * Sets up an instance of `FirebaseCoreHostApi` to handle messages through the + * `binaryMessenger`. + */ static void setup(BinaryMessenger binaryMessenger, FirebaseCoreHostApi api) { { BasicMessageChannel channel = new BasicMessageChannel<>( - binaryMessenger, "dev.flutter.pigeon.FirebaseCoreHostApi.initializeApp", getCodec()); + binaryMessenger, + "dev.flutter.pigeon.FirebaseCoreHostApi.initializeApp", + getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { @@ -548,7 +554,8 @@ static void setup(BinaryMessenger binaryMessenger, FirebaseCoreHostApi api) { if (appNameArg == null) { throw new NullPointerException("appNameArg unexpectedly null."); } - PigeonFirebaseOptions initializeAppRequestArg = (PigeonFirebaseOptions) args.get(1); + PigeonFirebaseOptions initializeAppRequestArg = + (PigeonFirebaseOptions) args.get(1); if (initializeAppRequestArg == null) { throw new NullPointerException("initializeAppRequestArg unexpectedly null."); } @@ -578,7 +585,9 @@ public void error(Throwable error) { { BasicMessageChannel channel = new BasicMessageChannel<>( - binaryMessenger, "dev.flutter.pigeon.FirebaseCoreHostApi.initializeCore", getCodec()); + binaryMessenger, + "dev.flutter.pigeon.FirebaseCoreHostApi.initializeCore", + getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { @@ -610,7 +619,9 @@ public void error(Throwable error) { { BasicMessageChannel channel = new BasicMessageChannel<>( - binaryMessenger, "dev.flutter.pigeon.FirebaseCoreHostApi.optionsFromResource", getCodec()); + binaryMessenger, + "dev.flutter.pigeon.FirebaseCoreHostApi.optionsFromResource", + getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { @@ -644,9 +655,11 @@ public void error(Throwable error) { /** Generated interface from Pigeon that represents a handler of messages from Flutter. */ public interface FirebaseAppHostApi { - void setAutomaticDataCollectionEnabled(@NonNull String appName, @NonNull Boolean enabled, Result result); + void setAutomaticDataCollectionEnabled( + @NonNull String appName, @NonNull Boolean enabled, Result result); - void setAutomaticResourceManagementEnabled(@NonNull String appName, @NonNull Boolean enabled, Result result); + void setAutomaticResourceManagementEnabled( + @NonNull String appName, @NonNull Boolean enabled, Result result); void delete(@NonNull String appName, Result result); @@ -654,12 +667,16 @@ public interface FirebaseAppHostApi { static MessageCodec getCodec() { return new StandardMessageCodec(); } - /**Sets up an instance of `FirebaseAppHostApi` to handle messages through the `binaryMessenger`. */ + /** + * Sets up an instance of `FirebaseAppHostApi` to handle messages through the `binaryMessenger`. + */ static void setup(BinaryMessenger binaryMessenger, FirebaseAppHostApi api) { { BasicMessageChannel channel = new BasicMessageChannel<>( - binaryMessenger, "dev.flutter.pigeon.FirebaseAppHostApi.setAutomaticDataCollectionEnabled", getCodec()); + binaryMessenger, + "dev.flutter.pigeon.FirebaseAppHostApi.setAutomaticDataCollectionEnabled", + getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { @@ -701,7 +718,9 @@ public void error(Throwable error) { { BasicMessageChannel channel = new BasicMessageChannel<>( - binaryMessenger, "dev.flutter.pigeon.FirebaseAppHostApi.setAutomaticResourceManagementEnabled", getCodec()); + binaryMessenger, + "dev.flutter.pigeon.FirebaseAppHostApi.setAutomaticResourceManagementEnabled", + getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { diff --git a/packages/firebase_core/firebase_core/ios/Classes/messages.g.h b/packages/firebase_core/firebase_core/ios/Classes/messages.g.h index 621dc1a79ccf..9a98f1fe9b10 100644 --- a/packages/firebase_core/firebase_core/ios/Classes/messages.g.h +++ b/packages/firebase_core/firebase_core/ios/Classes/messages.g.h @@ -17,68 +17,79 @@ NS_ASSUME_NONNULL_BEGIN /// `init` unavailable to enforce nonnull fields, see the `make` class method. - (instancetype)init NS_UNAVAILABLE; + (instancetype)makeWithApiKey:(NSString *)apiKey - appId:(NSString *)appId - messagingSenderId:(NSString *)messagingSenderId - projectId:(NSString *)projectId - authDomain:(nullable NSString *)authDomain - databaseURL:(nullable NSString *)databaseURL - storageBucket:(nullable NSString *)storageBucket - measurementId:(nullable NSString *)measurementId - trackingId:(nullable NSString *)trackingId - deepLinkURLScheme:(nullable NSString *)deepLinkURLScheme - androidClientId:(nullable NSString *)androidClientId - iosClientId:(nullable NSString *)iosClientId - iosBundleId:(nullable NSString *)iosBundleId - appGroupId:(nullable NSString *)appGroupId; -@property(nonatomic, copy) NSString * apiKey; -@property(nonatomic, copy) NSString * appId; -@property(nonatomic, copy) NSString * messagingSenderId; -@property(nonatomic, copy) NSString * projectId; -@property(nonatomic, copy, nullable) NSString * authDomain; -@property(nonatomic, copy, nullable) NSString * databaseURL; -@property(nonatomic, copy, nullable) NSString * storageBucket; -@property(nonatomic, copy, nullable) NSString * measurementId; -@property(nonatomic, copy, nullable) NSString * trackingId; -@property(nonatomic, copy, nullable) NSString * deepLinkURLScheme; -@property(nonatomic, copy, nullable) NSString * androidClientId; -@property(nonatomic, copy, nullable) NSString * iosClientId; -@property(nonatomic, copy, nullable) NSString * iosBundleId; -@property(nonatomic, copy, nullable) NSString * appGroupId; + appId:(NSString *)appId + messagingSenderId:(NSString *)messagingSenderId + projectId:(NSString *)projectId + authDomain:(nullable NSString *)authDomain + databaseURL:(nullable NSString *)databaseURL + storageBucket:(nullable NSString *)storageBucket + measurementId:(nullable NSString *)measurementId + trackingId:(nullable NSString *)trackingId + deepLinkURLScheme:(nullable NSString *)deepLinkURLScheme + androidClientId:(nullable NSString *)androidClientId + iosClientId:(nullable NSString *)iosClientId + iosBundleId:(nullable NSString *)iosBundleId + appGroupId:(nullable NSString *)appGroupId; +@property(nonatomic, copy) NSString *apiKey; +@property(nonatomic, copy) NSString *appId; +@property(nonatomic, copy) NSString *messagingSenderId; +@property(nonatomic, copy) NSString *projectId; +@property(nonatomic, copy, nullable) NSString *authDomain; +@property(nonatomic, copy, nullable) NSString *databaseURL; +@property(nonatomic, copy, nullable) NSString *storageBucket; +@property(nonatomic, copy, nullable) NSString *measurementId; +@property(nonatomic, copy, nullable) NSString *trackingId; +@property(nonatomic, copy, nullable) NSString *deepLinkURLScheme; +@property(nonatomic, copy, nullable) NSString *androidClientId; +@property(nonatomic, copy, nullable) NSString *iosClientId; +@property(nonatomic, copy, nullable) NSString *iosBundleId; +@property(nonatomic, copy, nullable) NSString *appGroupId; @end @interface PigeonInitializeResponse : NSObject /// `init` unavailable to enforce nonnull fields, see the `make` class method. - (instancetype)init NS_UNAVAILABLE; + (instancetype)makeWithName:(NSString *)name - options:(PigeonFirebaseOptions *)options + options:(PigeonFirebaseOptions *)options isAutomaticDataCollectionEnabled:(nullable NSNumber *)isAutomaticDataCollectionEnabled - pluginConstants:(NSDictionary *)pluginConstants; -@property(nonatomic, copy) NSString * name; -@property(nonatomic, strong) PigeonFirebaseOptions * options; -@property(nonatomic, strong, nullable) NSNumber * isAutomaticDataCollectionEnabled; -@property(nonatomic, strong) NSDictionary * pluginConstants; + pluginConstants:(NSDictionary *)pluginConstants; +@property(nonatomic, copy) NSString *name; +@property(nonatomic, strong) PigeonFirebaseOptions *options; +@property(nonatomic, strong, nullable) NSNumber *isAutomaticDataCollectionEnabled; +@property(nonatomic, strong) NSDictionary *pluginConstants; @end /// The codec used by FirebaseCoreHostApi. NSObject *FirebaseCoreHostApiGetCodec(void); @protocol FirebaseCoreHostApi -- (void)initializeAppAppName:(NSString *)appName initializeAppRequest:(PigeonFirebaseOptions *)initializeAppRequest completion:(void (^)(PigeonInitializeResponse *_Nullable, FlutterError *_Nullable))completion; -- (void)initializeCoreWithCompletion:(void (^)(NSArray *_Nullable, FlutterError *_Nullable))completion; -- (void)optionsFromResourceWithCompletion:(void (^)(PigeonFirebaseOptions *_Nullable, FlutterError *_Nullable))completion; +- (void)initializeAppAppName:(NSString *)appName + initializeAppRequest:(PigeonFirebaseOptions *)initializeAppRequest + completion:(void (^)(PigeonInitializeResponse *_Nullable, + FlutterError *_Nullable))completion; +- (void)initializeCoreWithCompletion:(void (^)(NSArray *_Nullable, + FlutterError *_Nullable))completion; +- (void)optionsFromResourceWithCompletion:(void (^)(PigeonFirebaseOptions *_Nullable, + FlutterError *_Nullable))completion; @end -extern void FirebaseCoreHostApiSetup(id binaryMessenger, NSObject *_Nullable api); +extern void FirebaseCoreHostApiSetup(id binaryMessenger, + NSObject *_Nullable api); /// The codec used by FirebaseAppHostApi. NSObject *FirebaseAppHostApiGetCodec(void); @protocol FirebaseAppHostApi -- (void)setAutomaticDataCollectionEnabledAppName:(NSString *)appName enabled:(NSNumber *)enabled completion:(void (^)(FlutterError *_Nullable))completion; -- (void)setAutomaticResourceManagementEnabledAppName:(NSString *)appName enabled:(NSNumber *)enabled completion:(void (^)(FlutterError *_Nullable))completion; +- (void)setAutomaticDataCollectionEnabledAppName:(NSString *)appName + enabled:(NSNumber *)enabled + completion:(void (^)(FlutterError *_Nullable))completion; +- (void)setAutomaticResourceManagementEnabledAppName:(NSString *)appName + enabled:(NSNumber *)enabled + completion:(void (^)(FlutterError *_Nullable))completion; - (void)deleteAppName:(NSString *)appName completion:(void (^)(FlutterError *_Nullable))completion; @end -extern void FirebaseAppHostApiSetup(id binaryMessenger, NSObject *_Nullable api); +extern void FirebaseAppHostApiSetup(id binaryMessenger, + NSObject *_Nullable api); NS_ASSUME_NONNULL_END diff --git a/packages/firebase_core/firebase_core/ios/Classes/messages.g.m b/packages/firebase_core/firebase_core/ios/Classes/messages.g.m index 8d6cda3d45af..f1bc91f423b8 100644 --- a/packages/firebase_core/firebase_core/ios/Classes/messages.g.m +++ b/packages/firebase_core/firebase_core/ios/Classes/messages.g.m @@ -35,20 +35,20 @@ - (NSArray *)toList; @implementation PigeonFirebaseOptions + (instancetype)makeWithApiKey:(NSString *)apiKey - appId:(NSString *)appId - messagingSenderId:(NSString *)messagingSenderId - projectId:(NSString *)projectId - authDomain:(nullable NSString *)authDomain - databaseURL:(nullable NSString *)databaseURL - storageBucket:(nullable NSString *)storageBucket - measurementId:(nullable NSString *)measurementId - trackingId:(nullable NSString *)trackingId - deepLinkURLScheme:(nullable NSString *)deepLinkURLScheme - androidClientId:(nullable NSString *)androidClientId - iosClientId:(nullable NSString *)iosClientId - iosBundleId:(nullable NSString *)iosBundleId - appGroupId:(nullable NSString *)appGroupId { - PigeonFirebaseOptions* pigeonResult = [[PigeonFirebaseOptions alloc] init]; + appId:(NSString *)appId + messagingSenderId:(NSString *)messagingSenderId + projectId:(NSString *)projectId + authDomain:(nullable NSString *)authDomain + databaseURL:(nullable NSString *)databaseURL + storageBucket:(nullable NSString *)storageBucket + measurementId:(nullable NSString *)measurementId + trackingId:(nullable NSString *)trackingId + deepLinkURLScheme:(nullable NSString *)deepLinkURLScheme + androidClientId:(nullable NSString *)androidClientId + iosClientId:(nullable NSString *)iosClientId + iosBundleId:(nullable NSString *)iosBundleId + appGroupId:(nullable NSString *)appGroupId { + PigeonFirebaseOptions *pigeonResult = [[PigeonFirebaseOptions alloc] init]; pigeonResult.apiKey = apiKey; pigeonResult.appId = appId; pigeonResult.messagingSenderId = messagingSenderId; @@ -112,10 +112,10 @@ - (NSArray *)toList { @implementation PigeonInitializeResponse + (instancetype)makeWithName:(NSString *)name - options:(PigeonFirebaseOptions *)options + options:(PigeonFirebaseOptions *)options isAutomaticDataCollectionEnabled:(nullable NSNumber *)isAutomaticDataCollectionEnabled - pluginConstants:(NSDictionary *)pluginConstants { - PigeonInitializeResponse* pigeonResult = [[PigeonInitializeResponse alloc] init]; + pluginConstants:(NSDictionary *)pluginConstants { + PigeonInitializeResponse *pigeonResult = [[PigeonInitializeResponse alloc] init]; pigeonResult.name = name; pigeonResult.options = options; pigeonResult.isAutomaticDataCollectionEnabled = isAutomaticDataCollectionEnabled; @@ -126,7 +126,8 @@ + (PigeonInitializeResponse *)fromList:(NSArray *)list { PigeonInitializeResponse *pigeonResult = [[PigeonInitializeResponse alloc] init]; pigeonResult.name = GetNullableObjectAtIndex(list, 0); NSAssert(pigeonResult.name != nil, @""); - pigeonResult.options = [PigeonFirebaseOptions nullableFromList:(GetNullableObjectAtIndex(list, 1))]; + pigeonResult.options = + [PigeonFirebaseOptions nullableFromList:(GetNullableObjectAtIndex(list, 1))]; NSAssert(pigeonResult.options != nil, @""); pigeonResult.isAutomaticDataCollectionEnabled = GetNullableObjectAtIndex(list, 2); pigeonResult.pluginConstants = GetNullableObjectAtIndex(list, 3); @@ -151,9 +152,9 @@ @interface FirebaseCoreHostApiCodecReader : FlutterStandardReader @implementation FirebaseCoreHostApiCodecReader - (nullable id)readValueOfType:(UInt8)type { switch (type) { - case 128: + case 128: return [PigeonFirebaseOptions fromList:[self readValue]]; - case 129: + case 129: return [PigeonInitializeResponse fromList:[self readValue]]; default: return [super readValueOfType:type]; @@ -192,43 +193,54 @@ - (FlutterStandardReader *)readerWithData:(NSData *)data { static FlutterStandardMessageCodec *sSharedObject = nil; static dispatch_once_t sPred = 0; dispatch_once(&sPred, ^{ - FirebaseCoreHostApiCodecReaderWriter *readerWriter = [[FirebaseCoreHostApiCodecReaderWriter alloc] init]; + FirebaseCoreHostApiCodecReaderWriter *readerWriter = + [[FirebaseCoreHostApiCodecReaderWriter alloc] init]; sSharedObject = [FlutterStandardMessageCodec codecWithReaderWriter:readerWriter]; }); return sSharedObject; } -void FirebaseCoreHostApiSetup(id binaryMessenger, NSObject *api) { +void FirebaseCoreHostApiSetup(id binaryMessenger, + NSObject *api) { { - FlutterBasicMessageChannel *channel = - [[FlutterBasicMessageChannel alloc] - initWithName:@"dev.flutter.pigeon.FirebaseCoreHostApi.initializeApp" + FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] + initWithName:@"dev.flutter.pigeon.FirebaseCoreHostApi.initializeApp" binaryMessenger:binaryMessenger - codec:FirebaseCoreHostApiGetCodec()]; + codec:FirebaseCoreHostApiGetCodec()]; if (api) { - NSCAssert([api respondsToSelector:@selector(initializeAppAppName:initializeAppRequest:completion:)], @"FirebaseCoreHostApi api (%@) doesn't respond to @selector(initializeAppAppName:initializeAppRequest:completion:)", api); + NSCAssert([api respondsToSelector:@selector(initializeAppAppName: + initializeAppRequest:completion:)], + @"FirebaseCoreHostApi api (%@) doesn't respond to " + @"@selector(initializeAppAppName:initializeAppRequest:completion:)", + api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; NSString *arg_appName = GetNullableObjectAtIndex(args, 0); PigeonFirebaseOptions *arg_initializeAppRequest = GetNullableObjectAtIndex(args, 1); - [api initializeAppAppName:arg_appName initializeAppRequest:arg_initializeAppRequest completion:^(PigeonInitializeResponse *_Nullable output, FlutterError *_Nullable error) { - callback(wrapResult(output, error)); - }]; + [api initializeAppAppName:arg_appName + initializeAppRequest:arg_initializeAppRequest + completion:^(PigeonInitializeResponse *_Nullable output, + FlutterError *_Nullable error) { + callback(wrapResult(output, error)); + }]; }]; } else { [channel setMessageHandler:nil]; } } { - FlutterBasicMessageChannel *channel = - [[FlutterBasicMessageChannel alloc] - initWithName:@"dev.flutter.pigeon.FirebaseCoreHostApi.initializeCore" + FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] + initWithName:@"dev.flutter.pigeon.FirebaseCoreHostApi.initializeCore" binaryMessenger:binaryMessenger - codec:FirebaseCoreHostApiGetCodec()]; + codec:FirebaseCoreHostApiGetCodec()]; if (api) { - NSCAssert([api respondsToSelector:@selector(initializeCoreWithCompletion:)], @"FirebaseCoreHostApi api (%@) doesn't respond to @selector(initializeCoreWithCompletion:)", api); + NSCAssert([api respondsToSelector:@selector(initializeCoreWithCompletion:)], + @"FirebaseCoreHostApi api (%@) doesn't respond to " + @"@selector(initializeCoreWithCompletion:)", + api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { - [api initializeCoreWithCompletion:^(NSArray *_Nullable output, FlutterError *_Nullable error) { + [api initializeCoreWithCompletion:^(NSArray *_Nullable output, + FlutterError *_Nullable error) { callback(wrapResult(output, error)); }]; }]; @@ -237,15 +249,18 @@ void FirebaseCoreHostApiSetup(id binaryMessenger, NSObje } } { - FlutterBasicMessageChannel *channel = - [[FlutterBasicMessageChannel alloc] - initWithName:@"dev.flutter.pigeon.FirebaseCoreHostApi.optionsFromResource" + FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] + initWithName:@"dev.flutter.pigeon.FirebaseCoreHostApi.optionsFromResource" binaryMessenger:binaryMessenger - codec:FirebaseCoreHostApiGetCodec()]; + codec:FirebaseCoreHostApiGetCodec()]; if (api) { - NSCAssert([api respondsToSelector:@selector(optionsFromResourceWithCompletion:)], @"FirebaseCoreHostApi api (%@) doesn't respond to @selector(optionsFromResourceWithCompletion:)", api); + NSCAssert([api respondsToSelector:@selector(optionsFromResourceWithCompletion:)], + @"FirebaseCoreHostApi api (%@) doesn't respond to " + @"@selector(optionsFromResourceWithCompletion:)", + api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { - [api optionsFromResourceWithCompletion:^(PigeonFirebaseOptions *_Nullable output, FlutterError *_Nullable error) { + [api optionsFromResourceWithCompletion:^(PigeonFirebaseOptions *_Nullable output, + FlutterError *_Nullable error) { callback(wrapResult(output, error)); }]; }]; @@ -260,61 +275,76 @@ void FirebaseCoreHostApiSetup(id binaryMessenger, NSObje return sSharedObject; } -void FirebaseAppHostApiSetup(id binaryMessenger, NSObject *api) { +void FirebaseAppHostApiSetup(id binaryMessenger, + NSObject *api) { { - FlutterBasicMessageChannel *channel = - [[FlutterBasicMessageChannel alloc] - initWithName:@"dev.flutter.pigeon.FirebaseAppHostApi.setAutomaticDataCollectionEnabled" + FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] + initWithName:@"dev.flutter.pigeon.FirebaseAppHostApi.setAutomaticDataCollectionEnabled" binaryMessenger:binaryMessenger - codec:FirebaseAppHostApiGetCodec()]; + codec:FirebaseAppHostApiGetCodec()]; if (api) { - NSCAssert([api respondsToSelector:@selector(setAutomaticDataCollectionEnabledAppName:enabled:completion:)], @"FirebaseAppHostApi api (%@) doesn't respond to @selector(setAutomaticDataCollectionEnabledAppName:enabled:completion:)", api); + NSCAssert([api respondsToSelector:@selector + (setAutomaticDataCollectionEnabledAppName:enabled:completion:)], + @"FirebaseAppHostApi api (%@) doesn't respond to " + @"@selector(setAutomaticDataCollectionEnabledAppName:enabled:completion:)", + api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; NSString *arg_appName = GetNullableObjectAtIndex(args, 0); NSNumber *arg_enabled = GetNullableObjectAtIndex(args, 1); - [api setAutomaticDataCollectionEnabledAppName:arg_appName enabled:arg_enabled completion:^(FlutterError *_Nullable error) { - callback(wrapResult(nil, error)); - }]; + [api setAutomaticDataCollectionEnabledAppName:arg_appName + enabled:arg_enabled + completion:^(FlutterError *_Nullable error) { + callback(wrapResult(nil, error)); + }]; }]; } else { [channel setMessageHandler:nil]; } } { - FlutterBasicMessageChannel *channel = - [[FlutterBasicMessageChannel alloc] - initWithName:@"dev.flutter.pigeon.FirebaseAppHostApi.setAutomaticResourceManagementEnabled" + FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] + initWithName: + @"dev.flutter.pigeon.FirebaseAppHostApi.setAutomaticResourceManagementEnabled" binaryMessenger:binaryMessenger - codec:FirebaseAppHostApiGetCodec()]; + codec:FirebaseAppHostApiGetCodec()]; if (api) { - NSCAssert([api respondsToSelector:@selector(setAutomaticResourceManagementEnabledAppName:enabled:completion:)], @"FirebaseAppHostApi api (%@) doesn't respond to @selector(setAutomaticResourceManagementEnabledAppName:enabled:completion:)", api); + NSCAssert([api respondsToSelector:@selector + (setAutomaticResourceManagementEnabledAppName:enabled:completion:)], + @"FirebaseAppHostApi api (%@) doesn't respond to " + @"@selector(setAutomaticResourceManagementEnabledAppName:enabled:completion:)", + api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; NSString *arg_appName = GetNullableObjectAtIndex(args, 0); NSNumber *arg_enabled = GetNullableObjectAtIndex(args, 1); - [api setAutomaticResourceManagementEnabledAppName:arg_appName enabled:arg_enabled completion:^(FlutterError *_Nullable error) { - callback(wrapResult(nil, error)); - }]; + [api setAutomaticResourceManagementEnabledAppName:arg_appName + enabled:arg_enabled + completion:^(FlutterError *_Nullable error) { + callback(wrapResult(nil, error)); + }]; }]; } else { [channel setMessageHandler:nil]; } } { - FlutterBasicMessageChannel *channel = - [[FlutterBasicMessageChannel alloc] - initWithName:@"dev.flutter.pigeon.FirebaseAppHostApi.delete" + FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] + initWithName:@"dev.flutter.pigeon.FirebaseAppHostApi.delete" binaryMessenger:binaryMessenger - codec:FirebaseAppHostApiGetCodec()]; + codec:FirebaseAppHostApiGetCodec()]; if (api) { - NSCAssert([api respondsToSelector:@selector(deleteAppName:completion:)], @"FirebaseAppHostApi api (%@) doesn't respond to @selector(deleteAppName:completion:)", api); + NSCAssert( + [api respondsToSelector:@selector(deleteAppName:completion:)], + @"FirebaseAppHostApi api (%@) doesn't respond to @selector(deleteAppName:completion:)", + api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; NSString *arg_appName = GetNullableObjectAtIndex(args, 0); - [api deleteAppName:arg_appName completion:^(FlutterError *_Nullable error) { - callback(wrapResult(nil, error)); - }]; + [api deleteAppName:arg_appName + completion:^(FlutterError *_Nullable error) { + callback(wrapResult(nil, error)); + }]; }]; } else { [channel setMessageHandler:nil]; diff --git a/packages/firebase_core/firebase_core/windows/firebase_core_plugin.h b/packages/firebase_core/firebase_core/windows/firebase_core_plugin.h index fe99490af2c2..52794b6a0e51 100644 --- a/packages/firebase_core/firebase_core/windows/firebase_core_plugin.h +++ b/packages/firebase_core/firebase_core/windows/firebase_core_plugin.h @@ -17,8 +17,8 @@ class FirebaseCorePlugin : public flutter::Plugin { virtual ~FirebaseCorePlugin(); // Disallow copy and assign. - FirebaseCorePlugin(const FirebaseCorePlugin&) = delete; - FirebaseCorePlugin& operator=(const FirebaseCorePlugin&) = delete; + FirebaseCorePlugin(const FirebaseCorePlugin &) = delete; + FirebaseCorePlugin &operator=(const FirebaseCorePlugin &) = delete; private: // Called when a method is called on this plugin's channel from Dart. diff --git a/packages/firebase_core/firebase_core_platform_interface/lib/src/pigeon/messages.pigeon.dart b/packages/firebase_core/firebase_core_platform_interface/lib/src/pigeon/messages.pigeon.dart index 034242fe27b6..9e0bd88c15d7 100644 --- a/packages/firebase_core/firebase_core_platform_interface/lib/src/pigeon/messages.pigeon.dart +++ b/packages/firebase_core/firebase_core_platform_interface/lib/src/pigeon/messages.pigeon.dart @@ -125,7 +125,8 @@ class PigeonInitializeResponse { name: result[0]! as String, options: PigeonFirebaseOptions.decode(result[1]! as List), isAutomaticDataCollectionEnabled: result[2] as bool?, - pluginConstants: (result[3] as Map?)!.cast(), + pluginConstants: + (result[3] as Map?)!.cast(), ); } } @@ -148,9 +149,9 @@ class _FirebaseCoreHostApiCodec extends StandardMessageCodec { @override Object? readValueOfType(int type, ReadBuffer buffer) { switch (type) { - case 128: + case 128: return PigeonFirebaseOptions.decode(readValue(buffer)!); - case 129: + case 129: return PigeonInitializeResponse.decode(readValue(buffer)!); default: return super.readValueOfType(type, buffer); @@ -168,12 +169,14 @@ class FirebaseCoreHostApi { static const MessageCodec codec = _FirebaseCoreHostApiCodec(); - Future initializeApp(String arg_appName, PigeonFirebaseOptions arg_initializeAppRequest) async { + Future initializeApp(String arg_appName, + PigeonFirebaseOptions arg_initializeAppRequest) async { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.FirebaseCoreHostApi.initializeApp', codec, binaryMessenger: _binaryMessenger); final List? replyList = - await channel.send([arg_appName, arg_initializeAppRequest]) as List?; + await channel.send([arg_appName, arg_initializeAppRequest]) + as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -199,8 +202,7 @@ class FirebaseCoreHostApi { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.FirebaseCoreHostApi.initializeCore', codec, binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send(null) as List?; + final List? replyList = await channel.send(null) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -218,7 +220,8 @@ class FirebaseCoreHostApi { message: 'Host platform returned null value for non-null return value.', ); } else { - return (replyList[0] as List?)!.cast(); + return (replyList[0] as List?)! + .cast(); } } @@ -226,8 +229,7 @@ class FirebaseCoreHostApi { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.FirebaseCoreHostApi.optionsFromResource', codec, binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send(null) as List?; + final List? replyList = await channel.send(null) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -260,12 +262,14 @@ class FirebaseAppHostApi { static const MessageCodec codec = StandardMessageCodec(); - Future setAutomaticDataCollectionEnabled(String arg_appName, bool arg_enabled) async { + Future setAutomaticDataCollectionEnabled( + String arg_appName, bool arg_enabled) async { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.FirebaseAppHostApi.setAutomaticDataCollectionEnabled', codec, + 'dev.flutter.pigeon.FirebaseAppHostApi.setAutomaticDataCollectionEnabled', + codec, binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send([arg_appName, arg_enabled]) as List?; + final List? replyList = await channel + .send([arg_appName, arg_enabled]) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', @@ -282,12 +286,14 @@ class FirebaseAppHostApi { } } - Future setAutomaticResourceManagementEnabled(String arg_appName, bool arg_enabled) async { + Future setAutomaticResourceManagementEnabled( + String arg_appName, bool arg_enabled) async { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.FirebaseAppHostApi.setAutomaticResourceManagementEnabled', codec, + 'dev.flutter.pigeon.FirebaseAppHostApi.setAutomaticResourceManagementEnabled', + codec, binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send([arg_appName, arg_enabled]) as List?; + final List? replyList = await channel + .send([arg_appName, arg_enabled]) as List?; if (replyList == null) { throw PlatformException( code: 'channel-error', diff --git a/packages/firebase_core/firebase_core_platform_interface/lib/src/pigeon/test_api.dart b/packages/firebase_core/firebase_core_platform_interface/lib/src/pigeon/test_api.dart index 617ae9eb93ee..0b9065036612 100644 --- a/packages/firebase_core/firebase_core_platform_interface/lib/src/pigeon/test_api.dart +++ b/packages/firebase_core/firebase_core_platform_interface/lib/src/pigeon/test_api.dart @@ -28,9 +28,9 @@ class _TestFirebaseCoreHostApiCodec extends StandardMessageCodec { @override Object? readValueOfType(int type, ReadBuffer buffer) { switch (type) { - case 128: + case 128: return PigeonFirebaseOptions.decode(readValue(buffer)!); - case 129: + case 129: return PigeonInitializeResponse.decode(readValue(buffer)!); default: return super.readValueOfType(type, buffer); @@ -41,13 +41,15 @@ class _TestFirebaseCoreHostApiCodec extends StandardMessageCodec { abstract class TestFirebaseCoreHostApi { static const MessageCodec codec = _TestFirebaseCoreHostApiCodec(); - Future initializeApp(String appName, PigeonFirebaseOptions initializeAppRequest); + Future initializeApp( + String appName, PigeonFirebaseOptions initializeAppRequest); Future> initializeCore(); Future optionsFromResource(); - static void setup(TestFirebaseCoreHostApi? api, {BinaryMessenger? binaryMessenger}) { + static void setup(TestFirebaseCoreHostApi? api, + {BinaryMessenger? binaryMessenger}) { { final BasicMessageChannel channel = BasicMessageChannel( 'dev.flutter.pigeon.FirebaseCoreHostApi.initializeApp', codec, @@ -57,15 +59,17 @@ abstract class TestFirebaseCoreHostApi { } else { channel.setMockMessageHandler((Object? message) async { assert(message != null, - 'Argument for dev.flutter.pigeon.FirebaseCoreHostApi.initializeApp was null.'); + 'Argument for dev.flutter.pigeon.FirebaseCoreHostApi.initializeApp was null.'); final List args = (message as List?)!; final String? arg_appName = (args[0] as String?); assert(arg_appName != null, 'Argument for dev.flutter.pigeon.FirebaseCoreHostApi.initializeApp was null, expected non-null String.'); - final PigeonFirebaseOptions? arg_initializeAppRequest = (args[1] as PigeonFirebaseOptions?); + final PigeonFirebaseOptions? arg_initializeAppRequest = + (args[1] as PigeonFirebaseOptions?); assert(arg_initializeAppRequest != null, 'Argument for dev.flutter.pigeon.FirebaseCoreHostApi.initializeApp was null, expected non-null PigeonFirebaseOptions.'); - final PigeonInitializeResponse output = await api.initializeApp(arg_appName!, arg_initializeAppRequest!); + final PigeonInitializeResponse output = + await api.initializeApp(arg_appName!, arg_initializeAppRequest!); return [output]; }); } @@ -79,7 +83,8 @@ abstract class TestFirebaseCoreHostApi { } else { channel.setMockMessageHandler((Object? message) async { // ignore message - final List output = await api.initializeCore(); + final List output = + await api.initializeCore(); return [output]; }); } @@ -106,21 +111,24 @@ abstract class TestFirebaseAppHostApi { Future setAutomaticDataCollectionEnabled(String appName, bool enabled); - Future setAutomaticResourceManagementEnabled(String appName, bool enabled); + Future setAutomaticResourceManagementEnabled( + String appName, bool enabled); Future delete(String appName); - static void setup(TestFirebaseAppHostApi? api, {BinaryMessenger? binaryMessenger}) { + static void setup(TestFirebaseAppHostApi? api, + {BinaryMessenger? binaryMessenger}) { { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.FirebaseAppHostApi.setAutomaticDataCollectionEnabled', codec, + 'dev.flutter.pigeon.FirebaseAppHostApi.setAutomaticDataCollectionEnabled', + codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMockMessageHandler(null); } else { channel.setMockMessageHandler((Object? message) async { assert(message != null, - 'Argument for dev.flutter.pigeon.FirebaseAppHostApi.setAutomaticDataCollectionEnabled was null.'); + 'Argument for dev.flutter.pigeon.FirebaseAppHostApi.setAutomaticDataCollectionEnabled was null.'); final List args = (message as List?)!; final String? arg_appName = (args[0] as String?); assert(arg_appName != null, @@ -128,21 +136,23 @@ abstract class TestFirebaseAppHostApi { final bool? arg_enabled = (args[1] as bool?); assert(arg_enabled != null, 'Argument for dev.flutter.pigeon.FirebaseAppHostApi.setAutomaticDataCollectionEnabled was null, expected non-null bool.'); - await api.setAutomaticDataCollectionEnabled(arg_appName!, arg_enabled!); + await api.setAutomaticDataCollectionEnabled( + arg_appName!, arg_enabled!); return []; }); } } { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.FirebaseAppHostApi.setAutomaticResourceManagementEnabled', codec, + 'dev.flutter.pigeon.FirebaseAppHostApi.setAutomaticResourceManagementEnabled', + codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMockMessageHandler(null); } else { channel.setMockMessageHandler((Object? message) async { assert(message != null, - 'Argument for dev.flutter.pigeon.FirebaseAppHostApi.setAutomaticResourceManagementEnabled was null.'); + 'Argument for dev.flutter.pigeon.FirebaseAppHostApi.setAutomaticResourceManagementEnabled was null.'); final List args = (message as List?)!; final String? arg_appName = (args[0] as String?); assert(arg_appName != null, @@ -150,7 +160,8 @@ abstract class TestFirebaseAppHostApi { final bool? arg_enabled = (args[1] as bool?); assert(arg_enabled != null, 'Argument for dev.flutter.pigeon.FirebaseAppHostApi.setAutomaticResourceManagementEnabled was null, expected non-null bool.'); - await api.setAutomaticResourceManagementEnabled(arg_appName!, arg_enabled!); + await api.setAutomaticResourceManagementEnabled( + arg_appName!, arg_enabled!); return []; }); } @@ -164,7 +175,7 @@ abstract class TestFirebaseAppHostApi { } else { channel.setMockMessageHandler((Object? message) async { assert(message != null, - 'Argument for dev.flutter.pigeon.FirebaseAppHostApi.delete was null.'); + 'Argument for dev.flutter.pigeon.FirebaseAppHostApi.delete was null.'); final List args = (message as List?)!; final String? arg_appName = (args[0] as String?); assert(arg_appName != null, From 6feecbf5d7c560f72c4f7b8c66c7e80b0bdbffb7 Mon Sep 17 00:00:00 2001 From: Guillaume Bernos Date: Tue, 14 Mar 2023 14:36:43 +0100 Subject: [PATCH 38/65] feat(core, windows): update pigeon --- .../core/GeneratedAndroidFirebaseCore.java | 3 + .../firebase_core/ios/Classes/messages.g.h | 3 + .../firebase_core/ios/Classes/messages.g.m | 3 + .../firebase_core/windows/messages.g.cpp | 667 ++++++++++++++++++ .../firebase_core/windows/messages.g.h | 249 +++++++ .../lib/src/pigeon/messages.pigeon.dart | 3 + .../lib/src/pigeon/test_api.dart | 3 + .../pigeons/copyright.txt | 3 + .../pigeons/messages.dart | 4 + 9 files changed, 938 insertions(+) create mode 100644 packages/firebase_core/firebase_core/windows/messages.g.cpp create mode 100644 packages/firebase_core/firebase_core/windows/messages.g.h create mode 100644 packages/firebase_core/firebase_core_platform_interface/pigeons/copyright.txt diff --git a/packages/firebase_core/firebase_core/android/src/main/java/io/flutter/plugins/firebase/core/GeneratedAndroidFirebaseCore.java b/packages/firebase_core/firebase_core/android/src/main/java/io/flutter/plugins/firebase/core/GeneratedAndroidFirebaseCore.java index 5710a21f0950..cfd9421325b8 100644 --- a/packages/firebase_core/firebase_core/android/src/main/java/io/flutter/plugins/firebase/core/GeneratedAndroidFirebaseCore.java +++ b/packages/firebase_core/firebase_core/android/src/main/java/io/flutter/plugins/firebase/core/GeneratedAndroidFirebaseCore.java @@ -1,3 +1,6 @@ +// Copyright 2023, the Chromium project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. // Autogenerated from Pigeon (v9.0.6), do not edit directly. // See also: https://pub.dev/packages/pigeon diff --git a/packages/firebase_core/firebase_core/ios/Classes/messages.g.h b/packages/firebase_core/firebase_core/ios/Classes/messages.g.h index 9a98f1fe9b10..d9dc465d55b9 100644 --- a/packages/firebase_core/firebase_core/ios/Classes/messages.g.h +++ b/packages/firebase_core/firebase_core/ios/Classes/messages.g.h @@ -1,3 +1,6 @@ +// Copyright 2023, the Chromium project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. // Autogenerated from Pigeon (v9.0.6), do not edit directly. // See also: https://pub.dev/packages/pigeon diff --git a/packages/firebase_core/firebase_core/ios/Classes/messages.g.m b/packages/firebase_core/firebase_core/ios/Classes/messages.g.m index f1bc91f423b8..7d9fe2a2cee5 100644 --- a/packages/firebase_core/firebase_core/ios/Classes/messages.g.m +++ b/packages/firebase_core/firebase_core/ios/Classes/messages.g.m @@ -1,3 +1,6 @@ +// Copyright 2023, the Chromium project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. // Autogenerated from Pigeon (v9.0.6), do not edit directly. // See also: https://pub.dev/packages/pigeon diff --git a/packages/firebase_core/firebase_core/windows/messages.g.cpp b/packages/firebase_core/firebase_core/windows/messages.g.cpp new file mode 100644 index 000000000000..921801b19b47 --- /dev/null +++ b/packages/firebase_core/firebase_core/windows/messages.g.cpp @@ -0,0 +1,667 @@ +// Copyright 2023, the Chromium project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Autogenerated from Pigeon (v9.0.6), do not edit directly. +// See also: https://pub.dev/packages/pigeon + +#undef _HAS_EXCEPTIONS + +#include "messages.g.h" + +#include +#include +#include +#include + +#include +#include +#include + +namespace firebase_core_windows { +using flutter::BasicMessageChannel; +using flutter::CustomEncodableValue; +using flutter::EncodableList; +using flutter::EncodableMap; +using flutter::EncodableValue; + +// PigeonFirebaseOptions + +const std::string& PigeonFirebaseOptions::api_key() const { return api_key_; } +void PigeonFirebaseOptions::set_api_key(std::string_view value_arg) { + api_key_ = value_arg; +} + +const std::string& PigeonFirebaseOptions::app_id() const { return app_id_; } +void PigeonFirebaseOptions::set_app_id(std::string_view value_arg) { + app_id_ = value_arg; +} + +const std::string& PigeonFirebaseOptions::messaging_sender_id() const { + return messaging_sender_id_; +} +void PigeonFirebaseOptions::set_messaging_sender_id( + std::string_view value_arg) { + messaging_sender_id_ = value_arg; +} + +const std::string& PigeonFirebaseOptions::project_id() const { + return project_id_; +} +void PigeonFirebaseOptions::set_project_id(std::string_view value_arg) { + project_id_ = value_arg; +} + +const std::string* PigeonFirebaseOptions::auth_domain() const { + return auth_domain_ ? &(*auth_domain_) : nullptr; +} +void PigeonFirebaseOptions::set_auth_domain(const std::string_view* value_arg) { + auth_domain_ = + value_arg ? std::optional(*value_arg) : std::nullopt; +} +void PigeonFirebaseOptions::set_auth_domain(std::string_view value_arg) { + auth_domain_ = value_arg; +} + +const std::string* PigeonFirebaseOptions::database_u_r_l() const { + return database_u_r_l_ ? &(*database_u_r_l_) : nullptr; +} +void PigeonFirebaseOptions::set_database_u_r_l( + const std::string_view* value_arg) { + database_u_r_l_ = + value_arg ? std::optional(*value_arg) : std::nullopt; +} +void PigeonFirebaseOptions::set_database_u_r_l(std::string_view value_arg) { + database_u_r_l_ = value_arg; +} + +const std::string* PigeonFirebaseOptions::storage_bucket() const { + return storage_bucket_ ? &(*storage_bucket_) : nullptr; +} +void PigeonFirebaseOptions::set_storage_bucket( + const std::string_view* value_arg) { + storage_bucket_ = + value_arg ? std::optional(*value_arg) : std::nullopt; +} +void PigeonFirebaseOptions::set_storage_bucket(std::string_view value_arg) { + storage_bucket_ = value_arg; +} + +const std::string* PigeonFirebaseOptions::measurement_id() const { + return measurement_id_ ? &(*measurement_id_) : nullptr; +} +void PigeonFirebaseOptions::set_measurement_id( + const std::string_view* value_arg) { + measurement_id_ = + value_arg ? std::optional(*value_arg) : std::nullopt; +} +void PigeonFirebaseOptions::set_measurement_id(std::string_view value_arg) { + measurement_id_ = value_arg; +} + +const std::string* PigeonFirebaseOptions::tracking_id() const { + return tracking_id_ ? &(*tracking_id_) : nullptr; +} +void PigeonFirebaseOptions::set_tracking_id(const std::string_view* value_arg) { + tracking_id_ = + value_arg ? std::optional(*value_arg) : std::nullopt; +} +void PigeonFirebaseOptions::set_tracking_id(std::string_view value_arg) { + tracking_id_ = value_arg; +} + +const std::string* PigeonFirebaseOptions::deep_link_u_r_l_scheme() const { + return deep_link_u_r_l_scheme_ ? &(*deep_link_u_r_l_scheme_) : nullptr; +} +void PigeonFirebaseOptions::set_deep_link_u_r_l_scheme( + const std::string_view* value_arg) { + deep_link_u_r_l_scheme_ = + value_arg ? std::optional(*value_arg) : std::nullopt; +} +void PigeonFirebaseOptions::set_deep_link_u_r_l_scheme( + std::string_view value_arg) { + deep_link_u_r_l_scheme_ = value_arg; +} + +const std::string* PigeonFirebaseOptions::android_client_id() const { + return android_client_id_ ? &(*android_client_id_) : nullptr; +} +void PigeonFirebaseOptions::set_android_client_id( + const std::string_view* value_arg) { + android_client_id_ = + value_arg ? std::optional(*value_arg) : std::nullopt; +} +void PigeonFirebaseOptions::set_android_client_id(std::string_view value_arg) { + android_client_id_ = value_arg; +} + +const std::string* PigeonFirebaseOptions::ios_client_id() const { + return ios_client_id_ ? &(*ios_client_id_) : nullptr; +} +void PigeonFirebaseOptions::set_ios_client_id( + const std::string_view* value_arg) { + ios_client_id_ = + value_arg ? std::optional(*value_arg) : std::nullopt; +} +void PigeonFirebaseOptions::set_ios_client_id(std::string_view value_arg) { + ios_client_id_ = value_arg; +} + +const std::string* PigeonFirebaseOptions::ios_bundle_id() const { + return ios_bundle_id_ ? &(*ios_bundle_id_) : nullptr; +} +void PigeonFirebaseOptions::set_ios_bundle_id( + const std::string_view* value_arg) { + ios_bundle_id_ = + value_arg ? std::optional(*value_arg) : std::nullopt; +} +void PigeonFirebaseOptions::set_ios_bundle_id(std::string_view value_arg) { + ios_bundle_id_ = value_arg; +} + +const std::string* PigeonFirebaseOptions::app_group_id() const { + return app_group_id_ ? &(*app_group_id_) : nullptr; +} +void PigeonFirebaseOptions::set_app_group_id( + const std::string_view* value_arg) { + app_group_id_ = + value_arg ? std::optional(*value_arg) : std::nullopt; +} +void PigeonFirebaseOptions::set_app_group_id(std::string_view value_arg) { + app_group_id_ = value_arg; +} + +EncodableList PigeonFirebaseOptions::ToEncodableList() const { + EncodableList list; + list.reserve(14); + list.push_back(EncodableValue(api_key_)); + list.push_back(EncodableValue(app_id_)); + list.push_back(EncodableValue(messaging_sender_id_)); + list.push_back(EncodableValue(project_id_)); + list.push_back(auth_domain_ ? EncodableValue(*auth_domain_) + : EncodableValue()); + list.push_back(database_u_r_l_ ? EncodableValue(*database_u_r_l_) + : EncodableValue()); + list.push_back(storage_bucket_ ? EncodableValue(*storage_bucket_) + : EncodableValue()); + list.push_back(measurement_id_ ? EncodableValue(*measurement_id_) + : EncodableValue()); + list.push_back(tracking_id_ ? EncodableValue(*tracking_id_) + : EncodableValue()); + list.push_back(deep_link_u_r_l_scheme_ + ? EncodableValue(*deep_link_u_r_l_scheme_) + : EncodableValue()); + list.push_back(android_client_id_ ? EncodableValue(*android_client_id_) + : EncodableValue()); + list.push_back(ios_client_id_ ? EncodableValue(*ios_client_id_) + : EncodableValue()); + list.push_back(ios_bundle_id_ ? EncodableValue(*ios_bundle_id_) + : EncodableValue()); + list.push_back(app_group_id_ ? EncodableValue(*app_group_id_) + : EncodableValue()); + return list; +} + +PigeonFirebaseOptions::PigeonFirebaseOptions() {} + +PigeonFirebaseOptions::PigeonFirebaseOptions(const EncodableList& list) { + auto& encodable_api_key = list[0]; + if (const std::string* pointer_api_key = + std::get_if(&encodable_api_key)) { + api_key_ = *pointer_api_key; + } + auto& encodable_app_id = list[1]; + if (const std::string* pointer_app_id = + std::get_if(&encodable_app_id)) { + app_id_ = *pointer_app_id; + } + auto& encodable_messaging_sender_id = list[2]; + if (const std::string* pointer_messaging_sender_id = + std::get_if(&encodable_messaging_sender_id)) { + messaging_sender_id_ = *pointer_messaging_sender_id; + } + auto& encodable_project_id = list[3]; + if (const std::string* pointer_project_id = + std::get_if(&encodable_project_id)) { + project_id_ = *pointer_project_id; + } + auto& encodable_auth_domain = list[4]; + if (const std::string* pointer_auth_domain = + std::get_if(&encodable_auth_domain)) { + auth_domain_ = *pointer_auth_domain; + } + auto& encodable_database_u_r_l = list[5]; + if (const std::string* pointer_database_u_r_l = + std::get_if(&encodable_database_u_r_l)) { + database_u_r_l_ = *pointer_database_u_r_l; + } + auto& encodable_storage_bucket = list[6]; + if (const std::string* pointer_storage_bucket = + std::get_if(&encodable_storage_bucket)) { + storage_bucket_ = *pointer_storage_bucket; + } + auto& encodable_measurement_id = list[7]; + if (const std::string* pointer_measurement_id = + std::get_if(&encodable_measurement_id)) { + measurement_id_ = *pointer_measurement_id; + } + auto& encodable_tracking_id = list[8]; + if (const std::string* pointer_tracking_id = + std::get_if(&encodable_tracking_id)) { + tracking_id_ = *pointer_tracking_id; + } + auto& encodable_deep_link_u_r_l_scheme = list[9]; + if (const std::string* pointer_deep_link_u_r_l_scheme = + std::get_if(&encodable_deep_link_u_r_l_scheme)) { + deep_link_u_r_l_scheme_ = *pointer_deep_link_u_r_l_scheme; + } + auto& encodable_android_client_id = list[10]; + if (const std::string* pointer_android_client_id = + std::get_if(&encodable_android_client_id)) { + android_client_id_ = *pointer_android_client_id; + } + auto& encodable_ios_client_id = list[11]; + if (const std::string* pointer_ios_client_id = + std::get_if(&encodable_ios_client_id)) { + ios_client_id_ = *pointer_ios_client_id; + } + auto& encodable_ios_bundle_id = list[12]; + if (const std::string* pointer_ios_bundle_id = + std::get_if(&encodable_ios_bundle_id)) { + ios_bundle_id_ = *pointer_ios_bundle_id; + } + auto& encodable_app_group_id = list[13]; + if (const std::string* pointer_app_group_id = + std::get_if(&encodable_app_group_id)) { + app_group_id_ = *pointer_app_group_id; + } +} + +// PigeonInitializeResponse + +const std::string& PigeonInitializeResponse::name() const { return name_; } +void PigeonInitializeResponse::set_name(std::string_view value_arg) { + name_ = value_arg; +} + +const PigeonFirebaseOptions& PigeonInitializeResponse::options() const { + return options_; +} +void PigeonInitializeResponse::set_options( + const PigeonFirebaseOptions& value_arg) { + options_ = value_arg; +} + +const bool* PigeonInitializeResponse::is_automatic_data_collection_enabled() + const { + return is_automatic_data_collection_enabled_ + ? &(*is_automatic_data_collection_enabled_) + : nullptr; +} +void PigeonInitializeResponse::set_is_automatic_data_collection_enabled( + const bool* value_arg) { + is_automatic_data_collection_enabled_ = + value_arg ? std::optional(*value_arg) : std::nullopt; +} +void PigeonInitializeResponse::set_is_automatic_data_collection_enabled( + bool value_arg) { + is_automatic_data_collection_enabled_ = value_arg; +} + +const EncodableMap& PigeonInitializeResponse::plugin_constants() const { + return plugin_constants_; +} +void PigeonInitializeResponse::set_plugin_constants( + const EncodableMap& value_arg) { + plugin_constants_ = value_arg; +} + +EncodableList PigeonInitializeResponse::ToEncodableList() const { + EncodableList list; + list.reserve(4); + list.push_back(EncodableValue(name_)); + list.push_back(EncodableValue(options_.ToEncodableList())); + list.push_back(is_automatic_data_collection_enabled_ + ? EncodableValue(*is_automatic_data_collection_enabled_) + : EncodableValue()); + list.push_back(EncodableValue(plugin_constants_)); + return list; +} + +PigeonInitializeResponse::PigeonInitializeResponse() {} + +PigeonInitializeResponse::PigeonInitializeResponse(const EncodableList& list) { + auto& encodable_name = list[0]; + if (const std::string* pointer_name = + std::get_if(&encodable_name)) { + name_ = *pointer_name; + } + auto& encodable_options = list[1]; + if (const EncodableList* pointer_options = + std::get_if(&encodable_options)) { + options_ = PigeonFirebaseOptions(*pointer_options); + } + auto& encodable_is_automatic_data_collection_enabled = list[2]; + if (const bool* pointer_is_automatic_data_collection_enabled = + std::get_if(&encodable_is_automatic_data_collection_enabled)) { + is_automatic_data_collection_enabled_ = + *pointer_is_automatic_data_collection_enabled; + } + auto& encodable_plugin_constants = list[3]; + if (const EncodableMap* pointer_plugin_constants = + std::get_if(&encodable_plugin_constants)) { + plugin_constants_ = *pointer_plugin_constants; + } +} + +FirebaseCoreHostApiCodecSerializer::FirebaseCoreHostApiCodecSerializer() {} +EncodableValue FirebaseCoreHostApiCodecSerializer::ReadValueOfType( + uint8_t type, flutter::ByteStreamReader* stream) const { + switch (type) { + case 128: + return CustomEncodableValue( + PigeonFirebaseOptions(std::get(ReadValue(stream)))); + case 129: + return CustomEncodableValue( + PigeonInitializeResponse(std::get(ReadValue(stream)))); + default: + return flutter::StandardCodecSerializer::ReadValueOfType(type, stream); + } +} + +void FirebaseCoreHostApiCodecSerializer::WriteValue( + const EncodableValue& value, flutter::ByteStreamWriter* stream) const { + if (const CustomEncodableValue* custom_value = + std::get_if(&value)) { + if (custom_value->type() == typeid(PigeonFirebaseOptions)) { + stream->WriteByte(128); + WriteValue( + EncodableValue(std::any_cast(*custom_value) + .ToEncodableList()), + stream); + return; + } + if (custom_value->type() == typeid(PigeonInitializeResponse)) { + stream->WriteByte(129); + WriteValue( + EncodableValue(std::any_cast(*custom_value) + .ToEncodableList()), + stream); + return; + } + } + flutter::StandardCodecSerializer::WriteValue(value, stream); +} + +/// The codec used by FirebaseCoreHostApi. +const flutter::StandardMessageCodec& FirebaseCoreHostApi::GetCodec() { + return flutter::StandardMessageCodec::GetInstance( + &FirebaseCoreHostApiCodecSerializer::GetInstance()); +} + +// Sets up an instance of `FirebaseCoreHostApi` to handle messages through the +// `binary_messenger`. +void FirebaseCoreHostApi::SetUp(flutter::BinaryMessenger* binary_messenger, + FirebaseCoreHostApi* api) { + { + auto channel = std::make_unique>( + binary_messenger, + "dev.flutter.pigeon.FirebaseCoreHostApi.initializeApp", &GetCodec()); + if (api != nullptr) { + channel->SetMessageHandler( + [api](const EncodableValue& message, + const flutter::MessageReply& reply) { + try { + const auto& args = std::get(message); + const auto& encodable_app_name_arg = args.at(0); + if (encodable_app_name_arg.IsNull()) { + reply(WrapError("app_name_arg unexpectedly null.")); + return; + } + const auto& app_name_arg = + std::get(encodable_app_name_arg); + const auto& encodable_initialize_app_request_arg = args.at(1); + if (encodable_initialize_app_request_arg.IsNull()) { + reply( + WrapError("initialize_app_request_arg unexpectedly null.")); + return; + } + const auto& initialize_app_request_arg = + std::any_cast( + std::get( + encodable_initialize_app_request_arg)); + api->InitializeApp( + app_name_arg, initialize_app_request_arg, + [reply](ErrorOr&& output) { + if (output.has_error()) { + reply(WrapError(output.error())); + return; + } + EncodableList wrapped; + wrapped.push_back( + CustomEncodableValue(std::move(output).TakeValue())); + reply(EncodableValue(std::move(wrapped))); + }); + } catch (const std::exception& exception) { + reply(WrapError(exception.what())); + } + }); + } else { + channel->SetMessageHandler(nullptr); + } + } + { + auto channel = std::make_unique>( + binary_messenger, + "dev.flutter.pigeon.FirebaseCoreHostApi.initializeCore", &GetCodec()); + if (api != nullptr) { + channel->SetMessageHandler( + [api](const EncodableValue& message, + const flutter::MessageReply& reply) { + try { + api->InitializeCore([reply](ErrorOr&& output) { + if (output.has_error()) { + reply(WrapError(output.error())); + return; + } + EncodableList wrapped; + wrapped.push_back( + EncodableValue(std::move(output).TakeValue())); + reply(EncodableValue(std::move(wrapped))); + }); + } catch (const std::exception& exception) { + reply(WrapError(exception.what())); + } + }); + } else { + channel->SetMessageHandler(nullptr); + } + } + { + auto channel = std::make_unique>( + binary_messenger, + "dev.flutter.pigeon.FirebaseCoreHostApi.optionsFromResource", + &GetCodec()); + if (api != nullptr) { + channel->SetMessageHandler( + [api](const EncodableValue& message, + const flutter::MessageReply& reply) { + try { + api->OptionsFromResource( + [reply](ErrorOr&& output) { + if (output.has_error()) { + reply(WrapError(output.error())); + return; + } + EncodableList wrapped; + wrapped.push_back( + CustomEncodableValue(std::move(output).TakeValue())); + reply(EncodableValue(std::move(wrapped))); + }); + } catch (const std::exception& exception) { + reply(WrapError(exception.what())); + } + }); + } else { + channel->SetMessageHandler(nullptr); + } + } +} + +EncodableValue FirebaseCoreHostApi::WrapError(std::string_view error_message) { + return EncodableValue( + EncodableList{EncodableValue(std::string(error_message)), + EncodableValue("Error"), EncodableValue()}); +} +EncodableValue FirebaseCoreHostApi::WrapError(const FlutterError& error) { + return EncodableValue(EncodableList{EncodableValue(error.message()), + EncodableValue(error.code()), + error.details()}); +} + +/// The codec used by FirebaseAppHostApi. +const flutter::StandardMessageCodec& FirebaseAppHostApi::GetCodec() { + return flutter::StandardMessageCodec::GetInstance( + &flutter::StandardCodecSerializer::GetInstance()); +} + +// Sets up an instance of `FirebaseAppHostApi` to handle messages through the +// `binary_messenger`. +void FirebaseAppHostApi::SetUp(flutter::BinaryMessenger* binary_messenger, + FirebaseAppHostApi* api) { + { + auto channel = std::make_unique>( + binary_messenger, + "dev.flutter.pigeon.FirebaseAppHostApi." + "setAutomaticDataCollectionEnabled", + &GetCodec()); + if (api != nullptr) { + channel->SetMessageHandler( + [api](const EncodableValue& message, + const flutter::MessageReply& reply) { + try { + const auto& args = std::get(message); + const auto& encodable_app_name_arg = args.at(0); + if (encodable_app_name_arg.IsNull()) { + reply(WrapError("app_name_arg unexpectedly null.")); + return; + } + const auto& app_name_arg = + std::get(encodable_app_name_arg); + const auto& encodable_enabled_arg = args.at(1); + if (encodable_enabled_arg.IsNull()) { + reply(WrapError("enabled_arg unexpectedly null.")); + return; + } + const auto& enabled_arg = std::get(encodable_enabled_arg); + api->SetAutomaticDataCollectionEnabled( + app_name_arg, enabled_arg, + [reply](std::optional&& output) { + if (output.has_value()) { + reply(WrapError(output.value())); + return; + } + EncodableList wrapped; + wrapped.push_back(EncodableValue()); + reply(EncodableValue(std::move(wrapped))); + }); + } catch (const std::exception& exception) { + reply(WrapError(exception.what())); + } + }); + } else { + channel->SetMessageHandler(nullptr); + } + } + { + auto channel = std::make_unique>( + binary_messenger, + "dev.flutter.pigeon.FirebaseAppHostApi." + "setAutomaticResourceManagementEnabled", + &GetCodec()); + if (api != nullptr) { + channel->SetMessageHandler( + [api](const EncodableValue& message, + const flutter::MessageReply& reply) { + try { + const auto& args = std::get(message); + const auto& encodable_app_name_arg = args.at(0); + if (encodable_app_name_arg.IsNull()) { + reply(WrapError("app_name_arg unexpectedly null.")); + return; + } + const auto& app_name_arg = + std::get(encodable_app_name_arg); + const auto& encodable_enabled_arg = args.at(1); + if (encodable_enabled_arg.IsNull()) { + reply(WrapError("enabled_arg unexpectedly null.")); + return; + } + const auto& enabled_arg = std::get(encodable_enabled_arg); + api->SetAutomaticResourceManagementEnabled( + app_name_arg, enabled_arg, + [reply](std::optional&& output) { + if (output.has_value()) { + reply(WrapError(output.value())); + return; + } + EncodableList wrapped; + wrapped.push_back(EncodableValue()); + reply(EncodableValue(std::move(wrapped))); + }); + } catch (const std::exception& exception) { + reply(WrapError(exception.what())); + } + }); + } else { + channel->SetMessageHandler(nullptr); + } + } + { + auto channel = std::make_unique>( + binary_messenger, "dev.flutter.pigeon.FirebaseAppHostApi.delete", + &GetCodec()); + if (api != nullptr) { + channel->SetMessageHandler( + [api](const EncodableValue& message, + const flutter::MessageReply& reply) { + try { + const auto& args = std::get(message); + const auto& encodable_app_name_arg = args.at(0); + if (encodable_app_name_arg.IsNull()) { + reply(WrapError("app_name_arg unexpectedly null.")); + return; + } + const auto& app_name_arg = + std::get(encodable_app_name_arg); + api->Delete(app_name_arg, + [reply](std::optional&& output) { + if (output.has_value()) { + reply(WrapError(output.value())); + return; + } + EncodableList wrapped; + wrapped.push_back(EncodableValue()); + reply(EncodableValue(std::move(wrapped))); + }); + } catch (const std::exception& exception) { + reply(WrapError(exception.what())); + } + }); + } else { + channel->SetMessageHandler(nullptr); + } + } +} + +EncodableValue FirebaseAppHostApi::WrapError(std::string_view error_message) { + return EncodableValue( + EncodableList{EncodableValue(std::string(error_message)), + EncodableValue("Error"), EncodableValue()}); +} +EncodableValue FirebaseAppHostApi::WrapError(const FlutterError& error) { + return EncodableValue(EncodableList{EncodableValue(error.message()), + EncodableValue(error.code()), + error.details()}); +} + +} // namespace firebase_core_windows diff --git a/packages/firebase_core/firebase_core/windows/messages.g.h b/packages/firebase_core/firebase_core/windows/messages.g.h new file mode 100644 index 000000000000..e38a5a5081e8 --- /dev/null +++ b/packages/firebase_core/firebase_core/windows/messages.g.h @@ -0,0 +1,249 @@ +// Copyright 2023, the Chromium project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Autogenerated from Pigeon (v9.0.6), do not edit directly. +// See also: https://pub.dev/packages/pigeon + +#ifndef PIGEON_MESSAGES_G_H_ +#define PIGEON_MESSAGES_G_H_ +#include +#include +#include +#include + +#include +#include +#include + +namespace firebase_core_windows { + +// Generated class from Pigeon. + +class FlutterError { + public: + explicit FlutterError(const std::string& code) : code_(code) {} + explicit FlutterError(const std::string& code, const std::string& message) + : code_(code), message_(message) {} + explicit FlutterError(const std::string& code, const std::string& message, + const flutter::EncodableValue& details) + : code_(code), message_(message), details_(details) {} + + const std::string& code() const { return code_; } + const std::string& message() const { return message_; } + const flutter::EncodableValue& details() const { return details_; } + + private: + std::string code_; + std::string message_; + flutter::EncodableValue details_; +}; + +template +class ErrorOr { + public: + ErrorOr(const T& rhs) { new (&v_) T(rhs); } + ErrorOr(const T&& rhs) { v_ = std::move(rhs); } + ErrorOr(const FlutterError& rhs) { new (&v_) FlutterError(rhs); } + ErrorOr(const FlutterError&& rhs) { v_ = std::move(rhs); } + + bool has_error() const { return std::holds_alternative(v_); } + const T& value() const { return std::get(v_); }; + const FlutterError& error() const { return std::get(v_); }; + + private: + friend class FirebaseCoreHostApi; + friend class FirebaseAppHostApi; + ErrorOr() = default; + T TakeValue() && { return std::get(std::move(v_)); } + + std::variant v_; +}; + +// Generated class from Pigeon that represents data sent in messages. +class PigeonFirebaseOptions { + public: + PigeonFirebaseOptions(); + const std::string& api_key() const; + void set_api_key(std::string_view value_arg); + + const std::string& app_id() const; + void set_app_id(std::string_view value_arg); + + const std::string& messaging_sender_id() const; + void set_messaging_sender_id(std::string_view value_arg); + + const std::string& project_id() const; + void set_project_id(std::string_view value_arg); + + const std::string* auth_domain() const; + void set_auth_domain(const std::string_view* value_arg); + void set_auth_domain(std::string_view value_arg); + + const std::string* database_u_r_l() const; + void set_database_u_r_l(const std::string_view* value_arg); + void set_database_u_r_l(std::string_view value_arg); + + const std::string* storage_bucket() const; + void set_storage_bucket(const std::string_view* value_arg); + void set_storage_bucket(std::string_view value_arg); + + const std::string* measurement_id() const; + void set_measurement_id(const std::string_view* value_arg); + void set_measurement_id(std::string_view value_arg); + + const std::string* tracking_id() const; + void set_tracking_id(const std::string_view* value_arg); + void set_tracking_id(std::string_view value_arg); + + const std::string* deep_link_u_r_l_scheme() const; + void set_deep_link_u_r_l_scheme(const std::string_view* value_arg); + void set_deep_link_u_r_l_scheme(std::string_view value_arg); + + const std::string* android_client_id() const; + void set_android_client_id(const std::string_view* value_arg); + void set_android_client_id(std::string_view value_arg); + + const std::string* ios_client_id() const; + void set_ios_client_id(const std::string_view* value_arg); + void set_ios_client_id(std::string_view value_arg); + + const std::string* ios_bundle_id() const; + void set_ios_bundle_id(const std::string_view* value_arg); + void set_ios_bundle_id(std::string_view value_arg); + + const std::string* app_group_id() const; + void set_app_group_id(const std::string_view* value_arg); + void set_app_group_id(std::string_view value_arg); + + private: + PigeonFirebaseOptions(const flutter::EncodableList& list); + flutter::EncodableList ToEncodableList() const; + friend class PigeonInitializeResponse; + friend class FirebaseCoreHostApi; + friend class FirebaseCoreHostApiCodecSerializer; + friend class FirebaseAppHostApi; + friend class FirebaseAppHostApiCodecSerializer; + std::string api_key_; + std::string app_id_; + std::string messaging_sender_id_; + std::string project_id_; + std::optional auth_domain_; + std::optional database_u_r_l_; + std::optional storage_bucket_; + std::optional measurement_id_; + std::optional tracking_id_; + std::optional deep_link_u_r_l_scheme_; + std::optional android_client_id_; + std::optional ios_client_id_; + std::optional ios_bundle_id_; + std::optional app_group_id_; +}; + +// Generated class from Pigeon that represents data sent in messages. +class PigeonInitializeResponse { + public: + PigeonInitializeResponse(); + const std::string& name() const; + void set_name(std::string_view value_arg); + + const PigeonFirebaseOptions& options() const; + void set_options(const PigeonFirebaseOptions& value_arg); + + const bool* is_automatic_data_collection_enabled() const; + void set_is_automatic_data_collection_enabled(const bool* value_arg); + void set_is_automatic_data_collection_enabled(bool value_arg); + + const flutter::EncodableMap& plugin_constants() const; + void set_plugin_constants(const flutter::EncodableMap& value_arg); + + private: + PigeonInitializeResponse(const flutter::EncodableList& list); + flutter::EncodableList ToEncodableList() const; + friend class FirebaseCoreHostApi; + friend class FirebaseCoreHostApiCodecSerializer; + friend class FirebaseAppHostApi; + friend class FirebaseAppHostApiCodecSerializer; + std::string name_; + PigeonFirebaseOptions options_; + std::optional is_automatic_data_collection_enabled_; + flutter::EncodableMap plugin_constants_; +}; + +class FirebaseCoreHostApiCodecSerializer + : public flutter::StandardCodecSerializer { + public: + inline static FirebaseCoreHostApiCodecSerializer& GetInstance() { + static FirebaseCoreHostApiCodecSerializer sInstance; + return sInstance; + } + + FirebaseCoreHostApiCodecSerializer(); + + public: + void WriteValue(const flutter::EncodableValue& value, + flutter::ByteStreamWriter* stream) const override; + + protected: + flutter::EncodableValue ReadValueOfType( + uint8_t type, flutter::ByteStreamReader* stream) const override; +}; + +// Generated interface from Pigeon that represents a handler of messages from +// Flutter. +class FirebaseCoreHostApi { + public: + FirebaseCoreHostApi(const FirebaseCoreHostApi&) = delete; + FirebaseCoreHostApi& operator=(const FirebaseCoreHostApi&) = delete; + virtual ~FirebaseCoreHostApi() {} + virtual void InitializeApp( + const std::string& app_name, + const PigeonFirebaseOptions& initialize_app_request, + std::function reply)> result) = 0; + virtual void InitializeCore( + std::function reply)> result) = 0; + virtual void OptionsFromResource( + std::function reply)> result) = 0; + + // The codec used by FirebaseCoreHostApi. + static const flutter::StandardMessageCodec& GetCodec(); + // Sets up an instance of `FirebaseCoreHostApi` to handle messages through the + // `binary_messenger`. + static void SetUp(flutter::BinaryMessenger* binary_messenger, + FirebaseCoreHostApi* api); + static flutter::EncodableValue WrapError(std::string_view error_message); + static flutter::EncodableValue WrapError(const FlutterError& error); + + protected: + FirebaseCoreHostApi() = default; +}; +// Generated interface from Pigeon that represents a handler of messages from +// Flutter. +class FirebaseAppHostApi { + public: + FirebaseAppHostApi(const FirebaseAppHostApi&) = delete; + FirebaseAppHostApi& operator=(const FirebaseAppHostApi&) = delete; + virtual ~FirebaseAppHostApi() {} + virtual void SetAutomaticDataCollectionEnabled( + const std::string& app_name, bool enabled, + std::function reply)> result) = 0; + virtual void SetAutomaticResourceManagementEnabled( + const std::string& app_name, bool enabled, + std::function reply)> result) = 0; + virtual void Delete( + const std::string& app_name, + std::function reply)> result) = 0; + + // The codec used by FirebaseAppHostApi. + static const flutter::StandardMessageCodec& GetCodec(); + // Sets up an instance of `FirebaseAppHostApi` to handle messages through the + // `binary_messenger`. + static void SetUp(flutter::BinaryMessenger* binary_messenger, + FirebaseAppHostApi* api); + static flutter::EncodableValue WrapError(std::string_view error_message); + static flutter::EncodableValue WrapError(const FlutterError& error); + + protected: + FirebaseAppHostApi() = default; +}; +} // namespace firebase_core_windows +#endif // PIGEON_MESSAGES_G_H_ diff --git a/packages/firebase_core/firebase_core_platform_interface/lib/src/pigeon/messages.pigeon.dart b/packages/firebase_core/firebase_core_platform_interface/lib/src/pigeon/messages.pigeon.dart index 9e0bd88c15d7..a7ad812dab6e 100644 --- a/packages/firebase_core/firebase_core_platform_interface/lib/src/pigeon/messages.pigeon.dart +++ b/packages/firebase_core/firebase_core_platform_interface/lib/src/pigeon/messages.pigeon.dart @@ -1,3 +1,6 @@ +// Copyright 2023, the Chromium project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. // Autogenerated from Pigeon (v9.0.6), do not edit directly. // See also: https://pub.dev/packages/pigeon // ignore_for_file: public_member_api_docs, non_constant_identifier_names, avoid_as, unused_import, unnecessary_parenthesis, prefer_null_aware_operators, omit_local_variable_types, unused_shown_name, unnecessary_import diff --git a/packages/firebase_core/firebase_core_platform_interface/lib/src/pigeon/test_api.dart b/packages/firebase_core/firebase_core_platform_interface/lib/src/pigeon/test_api.dart index 0b9065036612..cde69f942086 100644 --- a/packages/firebase_core/firebase_core_platform_interface/lib/src/pigeon/test_api.dart +++ b/packages/firebase_core/firebase_core_platform_interface/lib/src/pigeon/test_api.dart @@ -1,3 +1,6 @@ +// Copyright 2023, the Chromium project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. // Autogenerated from Pigeon (v9.0.6), do not edit directly. // See also: https://pub.dev/packages/pigeon // ignore_for_file: public_member_api_docs, non_constant_identifier_names, avoid_as, unused_import, unnecessary_parenthesis, unnecessary_import diff --git a/packages/firebase_core/firebase_core_platform_interface/pigeons/copyright.txt b/packages/firebase_core/firebase_core_platform_interface/pigeons/copyright.txt new file mode 100644 index 000000000000..42fc84b1210b --- /dev/null +++ b/packages/firebase_core/firebase_core_platform_interface/pigeons/copyright.txt @@ -0,0 +1,3 @@ +Copyright 2023, the Chromium project authors. Please see the AUTHORS file +for details. All rights reserved. Use of this source code is governed by a +BSD-style license that can be found in the LICENSE file. \ No newline at end of file diff --git a/packages/firebase_core/firebase_core_platform_interface/pigeons/messages.dart b/packages/firebase_core/firebase_core_platform_interface/pigeons/messages.dart index cc877df589de..00fa0d744802 100644 --- a/packages/firebase_core/firebase_core_platform_interface/pigeons/messages.dart +++ b/packages/firebase_core/firebase_core_platform_interface/pigeons/messages.dart @@ -17,6 +17,10 @@ import 'package:pigeon/pigeon.dart'; ), objcHeaderOut: '../firebase_core/ios/Classes/messages.g.h', objcSourceOut: '../firebase_core/ios/Classes/messages.g.m', + cppHeaderOut: '../firebase_core/windows/messages.g.h', + cppSourceOut: '../firebase_core/windows/messages.g.cpp', + cppOptions: CppOptions(namespace: 'firebase_core_windows'), + copyrightHeader: 'pigeons/copyright.txt', ), ) class PigeonFirebaseOptions { From 67621a9f0ac4e15dbf6f749a9a294ac949db377e Mon Sep 17 00:00:00 2001 From: Guillaume Bernos Date: Mon, 20 Mar 2023 10:26:47 +0100 Subject: [PATCH 39/65] feat: merge with main package --- .../firebase_core/example/.metadata | 24 +- .../example/lib/firebase_options.dart | 3 + .../example/test/widget_test.dart | 30 ++ .../firebase_core/example/windows/.gitignore | 17 ++ .../example/windows/CMakeLists.txt | 102 +++++++ .../example/windows/flutter/CMakeLists.txt | 104 +++++++ .../flutter/generated_plugin_registrant.cc | 14 + .../flutter/generated_plugin_registrant.h | 15 + .../windows/flutter/generated_plugins.cmake | 24 ++ .../example/windows/runner/CMakeLists.txt | 40 +++ .../example/windows/runner/Runner.rc | 121 ++++++++ .../example/windows/runner/flutter_window.cpp | 66 ++++ .../example/windows/runner/flutter_window.h | 33 ++ .../runner/google-services-desktop.json | 37 +++ .../example/windows/runner/main.cpp | 43 +++ .../example/windows/runner/resource.h | 16 + .../windows/runner/resources/app_icon.ico | Bin 0 -> 33772 bytes .../windows/runner/runner.exe.manifest | 20 ++ .../example/windows/runner/utils.cpp | 64 ++++ .../example/windows/runner/utils.h | 19 ++ .../example/windows/runner/win32_window.cpp | 288 ++++++++++++++++++ .../example/windows/runner/win32_window.h | 102 +++++++ 22 files changed, 1180 insertions(+), 2 deletions(-) create mode 100644 packages/firebase_core/firebase_core/example/test/widget_test.dart create mode 100644 packages/firebase_core/firebase_core/example/windows/.gitignore create mode 100644 packages/firebase_core/firebase_core/example/windows/CMakeLists.txt create mode 100644 packages/firebase_core/firebase_core/example/windows/flutter/CMakeLists.txt create mode 100644 packages/firebase_core/firebase_core/example/windows/flutter/generated_plugin_registrant.cc create mode 100644 packages/firebase_core/firebase_core/example/windows/flutter/generated_plugin_registrant.h create mode 100644 packages/firebase_core/firebase_core/example/windows/flutter/generated_plugins.cmake create mode 100644 packages/firebase_core/firebase_core/example/windows/runner/CMakeLists.txt create mode 100644 packages/firebase_core/firebase_core/example/windows/runner/Runner.rc create mode 100644 packages/firebase_core/firebase_core/example/windows/runner/flutter_window.cpp create mode 100644 packages/firebase_core/firebase_core/example/windows/runner/flutter_window.h create mode 100644 packages/firebase_core/firebase_core/example/windows/runner/google-services-desktop.json create mode 100644 packages/firebase_core/firebase_core/example/windows/runner/main.cpp create mode 100644 packages/firebase_core/firebase_core/example/windows/runner/resource.h create mode 100644 packages/firebase_core/firebase_core/example/windows/runner/resources/app_icon.ico create mode 100644 packages/firebase_core/firebase_core/example/windows/runner/runner.exe.manifest create mode 100644 packages/firebase_core/firebase_core/example/windows/runner/utils.cpp create mode 100644 packages/firebase_core/firebase_core/example/windows/runner/utils.h create mode 100644 packages/firebase_core/firebase_core/example/windows/runner/win32_window.cpp create mode 100644 packages/firebase_core/firebase_core/example/windows/runner/win32_window.h diff --git a/packages/firebase_core/firebase_core/example/.metadata b/packages/firebase_core/firebase_core/example/.metadata index 4adf4bf025f8..3993ce7b7531 100644 --- a/packages/firebase_core/firebase_core/example/.metadata +++ b/packages/firebase_core/firebase_core/example/.metadata @@ -1,10 +1,30 @@ # This file tracks properties of this Flutter project. # Used by Flutter tool to assess capabilities and perform upgrades etc. # -# This file should be version controlled and should not be manually edited. +# This file should be version controlled. version: - revision: f139b11009aeb8ed2a3a3aa8b0066e482709dde3 + revision: 12cb4eb7a009f52b347b62ade7cb4854b926af72 channel: stable project_type: app + +# Tracks metadata for the flutter migrate command +migration: + platforms: + - platform: root + create_revision: 12cb4eb7a009f52b347b62ade7cb4854b926af72 + base_revision: 12cb4eb7a009f52b347b62ade7cb4854b926af72 + - platform: windows + create_revision: 12cb4eb7a009f52b347b62ade7cb4854b926af72 + base_revision: 12cb4eb7a009f52b347b62ade7cb4854b926af72 + + # User provided section + + # List of Local paths (relative to this file) that should be + # ignored by the migrate tool. + # + # Files that are not part of the templates will be ignored by default. + unmanaged_files: + - 'lib/main.dart' + - 'ios/Runner.xcodeproj/project.pbxproj' diff --git a/packages/firebase_core/firebase_core/example/lib/firebase_options.dart b/packages/firebase_core/firebase_core/example/lib/firebase_options.dart index da380a3ec8bb..63c4c8857ca7 100644 --- a/packages/firebase_core/firebase_core/example/lib/firebase_options.dart +++ b/packages/firebase_core/firebase_core/example/lib/firebase_options.dart @@ -30,6 +30,9 @@ class DefaultFirebaseOptions { return ios; case TargetPlatform.macOS: return macos; + // TODO(Lyokone): FIX + case TargetPlatform.windows: + return android; default: throw UnsupportedError( 'DefaultFirebaseOptions are not supported for this platform.', diff --git a/packages/firebase_core/firebase_core/example/test/widget_test.dart b/packages/firebase_core/firebase_core/example/test/widget_test.dart new file mode 100644 index 000000000000..092d222f7e16 --- /dev/null +++ b/packages/firebase_core/firebase_core/example/test/widget_test.dart @@ -0,0 +1,30 @@ +// This is a basic Flutter widget test. +// +// To perform an interaction with a widget in your test, use the WidgetTester +// utility in the flutter_test package. For example, you can send tap and scroll +// gestures. You can also use WidgetTester to find child widgets in the widget +// tree, read text, and verify that the values of widget properties are correct. + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'package:example/main.dart'; + +void main() { + testWidgets('Counter increments smoke test', (WidgetTester tester) async { + // Build our app and trigger a frame. + await tester.pumpWidget(const MyApp()); + + // Verify that our counter starts at 0. + expect(find.text('0'), findsOneWidget); + expect(find.text('1'), findsNothing); + + // Tap the '+' icon and trigger a frame. + await tester.tap(find.byIcon(Icons.add)); + await tester.pump(); + + // Verify that our counter has incremented. + expect(find.text('0'), findsNothing); + expect(find.text('1'), findsOneWidget); + }); +} diff --git a/packages/firebase_core/firebase_core/example/windows/.gitignore b/packages/firebase_core/firebase_core/example/windows/.gitignore new file mode 100644 index 000000000000..d492d0d98c8f --- /dev/null +++ b/packages/firebase_core/firebase_core/example/windows/.gitignore @@ -0,0 +1,17 @@ +flutter/ephemeral/ + +# Visual Studio user-specific files. +*.suo +*.user +*.userosscache +*.sln.docstates + +# Visual Studio build-related files. +x64/ +x86/ + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!*.[Cc]ache/ diff --git a/packages/firebase_core/firebase_core/example/windows/CMakeLists.txt b/packages/firebase_core/firebase_core/example/windows/CMakeLists.txt new file mode 100644 index 000000000000..55f6cda64bf2 --- /dev/null +++ b/packages/firebase_core/firebase_core/example/windows/CMakeLists.txt @@ -0,0 +1,102 @@ +# Project-level configuration. +cmake_minimum_required(VERSION 3.14) +project(firebase_core_example LANGUAGES CXX) + +# The name of the executable created for the application. Change this to change +# the on-disk name of your application. +set(BINARY_NAME "firebase_core_example") + +# Explicitly opt in to modern CMake behaviors to avoid warnings with recent +# versions of CMake. +cmake_policy(SET CMP0063 NEW) + +# Define build configuration option. +get_property(IS_MULTICONFIG GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG) +if(IS_MULTICONFIG) + set(CMAKE_CONFIGURATION_TYPES "Debug;Profile;Release" + CACHE STRING "" FORCE) +else() + if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) + set(CMAKE_BUILD_TYPE "Debug" CACHE + STRING "Flutter build mode" FORCE) + set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS + "Debug" "Profile" "Release") + endif() +endif() +# Define settings for the Profile build mode. +set(CMAKE_EXE_LINKER_FLAGS_PROFILE "${CMAKE_EXE_LINKER_FLAGS_RELEASE}") +set(CMAKE_SHARED_LINKER_FLAGS_PROFILE "${CMAKE_SHARED_LINKER_FLAGS_RELEASE}") +set(CMAKE_C_FLAGS_PROFILE "${CMAKE_C_FLAGS_RELEASE}") +set(CMAKE_CXX_FLAGS_PROFILE "${CMAKE_CXX_FLAGS_RELEASE}") +set(FIREBASE_CPP_SDK_DIR "c:/Users/guill/Downloads/firebase_cpp_sdk_10.5.0/firebase_cpp_sdk") + +# Use Unicode for all projects. +add_definitions(-DUNICODE -D_UNICODE) + +# Compilation settings that should be applied to most targets. +# +# Be cautious about adding new options here, as plugins use this function by +# default. In most cases, you should add new options to specific targets instead +# of modifying this function. +function(APPLY_STANDARD_SETTINGS TARGET) + target_compile_features(${TARGET} PUBLIC cxx_std_17) + target_compile_options(${TARGET} PRIVATE /W4 /WX /wd"4100") + target_compile_options(${TARGET} PRIVATE /EHsc) + target_compile_definitions(${TARGET} PRIVATE "_HAS_EXCEPTIONS=0") + target_compile_definitions(${TARGET} PRIVATE "$<$:_DEBUG>") +endfunction() + +# Flutter library and tool build rules. +set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") +add_subdirectory(${FLUTTER_MANAGED_DIR}) + +# Application build; see runner/CMakeLists.txt. +add_subdirectory("runner") + +# Generated plugin build rules, which manage building the plugins and adding +# them to the application. +include(flutter/generated_plugins.cmake) + + +# === Installation === +# Support files are copied into place next to the executable, so that it can +# run in place. This is done instead of making a separate bundle (as on Linux) +# so that building and running from within Visual Studio will work. +set(BUILD_BUNDLE_DIR "$") +# Make the "install" step default, as it's required to run. +set(CMAKE_VS_INCLUDE_INSTALL_TO_DEFAULT_BUILD 1) +if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) + set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) +endif() + +set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") +set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}") + +install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +if(PLUGIN_BUNDLED_LIBRARIES) + install(FILES "${PLUGIN_BUNDLED_LIBRARIES}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endif() + +# Fully re-copy the assets directory on each build to avoid having stale files +# from a previous install. +set(FLUTTER_ASSET_DIR_NAME "flutter_assets") +install(CODE " + file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") + " COMPONENT Runtime) +install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" + DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) + +# Install the AOT library on non-Debug builds only. +install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + CONFIGURATIONS Profile;Release + COMPONENT Runtime) diff --git a/packages/firebase_core/firebase_core/example/windows/flutter/CMakeLists.txt b/packages/firebase_core/firebase_core/example/windows/flutter/CMakeLists.txt new file mode 100644 index 000000000000..930d2071a324 --- /dev/null +++ b/packages/firebase_core/firebase_core/example/windows/flutter/CMakeLists.txt @@ -0,0 +1,104 @@ +# This file controls Flutter-level build steps. It should not be edited. +cmake_minimum_required(VERSION 3.14) + +set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") + +# Configuration provided via flutter tool. +include(${EPHEMERAL_DIR}/generated_config.cmake) + +# TODO: Move the rest of this into files in ephemeral. See +# https://github.com/flutter/flutter/issues/57146. +set(WRAPPER_ROOT "${EPHEMERAL_DIR}/cpp_client_wrapper") + +# === Flutter Library === +set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/flutter_windows.dll") + +# Published to parent scope for install step. +set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) +set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) +set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) +set(AOT_LIBRARY "${PROJECT_DIR}/build/windows/app.so" PARENT_SCOPE) + +list(APPEND FLUTTER_LIBRARY_HEADERS + "flutter_export.h" + "flutter_windows.h" + "flutter_messenger.h" + "flutter_plugin_registrar.h" + "flutter_texture_registrar.h" +) +list(TRANSFORM FLUTTER_LIBRARY_HEADERS PREPEND "${EPHEMERAL_DIR}/") +add_library(flutter INTERFACE) +target_include_directories(flutter INTERFACE + "${EPHEMERAL_DIR}" +) +target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}.lib") +add_dependencies(flutter flutter_assemble) + +# === Wrapper === +list(APPEND CPP_WRAPPER_SOURCES_CORE + "core_implementations.cc" + "standard_codec.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_CORE PREPEND "${WRAPPER_ROOT}/") +list(APPEND CPP_WRAPPER_SOURCES_PLUGIN + "plugin_registrar.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_PLUGIN PREPEND "${WRAPPER_ROOT}/") +list(APPEND CPP_WRAPPER_SOURCES_APP + "flutter_engine.cc" + "flutter_view_controller.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_APP PREPEND "${WRAPPER_ROOT}/") + +# Wrapper sources needed for a plugin. +add_library(flutter_wrapper_plugin STATIC + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_PLUGIN} +) +apply_standard_settings(flutter_wrapper_plugin) +set_target_properties(flutter_wrapper_plugin PROPERTIES + POSITION_INDEPENDENT_CODE ON) +set_target_properties(flutter_wrapper_plugin PROPERTIES + CXX_VISIBILITY_PRESET hidden) +target_link_libraries(flutter_wrapper_plugin PUBLIC flutter) +target_include_directories(flutter_wrapper_plugin PUBLIC + "${WRAPPER_ROOT}/include" +) +add_dependencies(flutter_wrapper_plugin flutter_assemble) + +# Wrapper sources needed for the runner. +add_library(flutter_wrapper_app STATIC + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_APP} +) +apply_standard_settings(flutter_wrapper_app) +target_link_libraries(flutter_wrapper_app PUBLIC flutter) +target_include_directories(flutter_wrapper_app PUBLIC + "${WRAPPER_ROOT}/include" +) +add_dependencies(flutter_wrapper_app flutter_assemble) + +# === Flutter tool backend === +# _phony_ is a non-existent file to force this command to run every time, +# since currently there's no way to get a full input/output list from the +# flutter tool. +set(PHONY_OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/_phony_") +set_source_files_properties("${PHONY_OUTPUT}" PROPERTIES SYMBOLIC TRUE) +add_custom_command( + OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} + ${CPP_WRAPPER_SOURCES_CORE} ${CPP_WRAPPER_SOURCES_PLUGIN} + ${CPP_WRAPPER_SOURCES_APP} + ${PHONY_OUTPUT} + COMMAND ${CMAKE_COMMAND} -E env + ${FLUTTER_TOOL_ENVIRONMENT} + "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.bat" + windows-x64 $ + VERBATIM +) +add_custom_target(flutter_assemble DEPENDS + "${FLUTTER_LIBRARY}" + ${FLUTTER_LIBRARY_HEADERS} + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_PLUGIN} + ${CPP_WRAPPER_SOURCES_APP} +) diff --git a/packages/firebase_core/firebase_core/example/windows/flutter/generated_plugin_registrant.cc b/packages/firebase_core/firebase_core/example/windows/flutter/generated_plugin_registrant.cc new file mode 100644 index 000000000000..1a82e7d01dce --- /dev/null +++ b/packages/firebase_core/firebase_core/example/windows/flutter/generated_plugin_registrant.cc @@ -0,0 +1,14 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#include "generated_plugin_registrant.h" + +#include + +void RegisterPlugins(flutter::PluginRegistry* registry) { + FirebaseCorePluginCApiRegisterWithRegistrar( + registry->GetRegistrarForPlugin("FirebaseCorePluginCApi")); +} diff --git a/packages/firebase_core/firebase_core/example/windows/flutter/generated_plugin_registrant.h b/packages/firebase_core/firebase_core/example/windows/flutter/generated_plugin_registrant.h new file mode 100644 index 000000000000..dc139d85a931 --- /dev/null +++ b/packages/firebase_core/firebase_core/example/windows/flutter/generated_plugin_registrant.h @@ -0,0 +1,15 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#ifndef GENERATED_PLUGIN_REGISTRANT_ +#define GENERATED_PLUGIN_REGISTRANT_ + +#include + +// Registers Flutter plugins. +void RegisterPlugins(flutter::PluginRegistry* registry); + +#endif // GENERATED_PLUGIN_REGISTRANT_ diff --git a/packages/firebase_core/firebase_core/example/windows/flutter/generated_plugins.cmake b/packages/firebase_core/firebase_core/example/windows/flutter/generated_plugins.cmake new file mode 100644 index 000000000000..fa8a39bab15e --- /dev/null +++ b/packages/firebase_core/firebase_core/example/windows/flutter/generated_plugins.cmake @@ -0,0 +1,24 @@ +# +# Generated file, do not edit. +# + +list(APPEND FLUTTER_PLUGIN_LIST + firebase_core +) + +list(APPEND FLUTTER_FFI_PLUGIN_LIST +) + +set(PLUGIN_BUNDLED_LIBRARIES) + +foreach(plugin ${FLUTTER_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/windows plugins/${plugin}) + target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) + list(APPEND PLUGIN_BUNDLED_LIBRARIES $) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) +endforeach(plugin) + +foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/windows plugins/${ffi_plugin}) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries}) +endforeach(ffi_plugin) diff --git a/packages/firebase_core/firebase_core/example/windows/runner/CMakeLists.txt b/packages/firebase_core/firebase_core/example/windows/runner/CMakeLists.txt new file mode 100644 index 000000000000..394917c053a0 --- /dev/null +++ b/packages/firebase_core/firebase_core/example/windows/runner/CMakeLists.txt @@ -0,0 +1,40 @@ +cmake_minimum_required(VERSION 3.14) +project(runner LANGUAGES CXX) + +# Define the application target. To change its name, change BINARY_NAME in the +# top-level CMakeLists.txt, not the value here, or `flutter run` will no longer +# work. +# +# Any new source files that you add to the application should be added here. +add_executable(${BINARY_NAME} WIN32 + "flutter_window.cpp" + "main.cpp" + "utils.cpp" + "win32_window.cpp" + "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" + "Runner.rc" + "runner.exe.manifest" +) + +# Apply the standard set of build settings. This can be removed for applications +# that need different build settings. +apply_standard_settings(${BINARY_NAME}) + +# Add preprocessor definitions for the build version. +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION=\"${FLUTTER_VERSION}\"") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MAJOR=${FLUTTER_VERSION_MAJOR}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MINOR=${FLUTTER_VERSION_MINOR}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_PATCH=${FLUTTER_VERSION_PATCH}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_BUILD=${FLUTTER_VERSION_BUILD}") + +# Disable Windows macros that collide with C++ standard library functions. +target_compile_definitions(${BINARY_NAME} PRIVATE "NOMINMAX") + +# Add dependency libraries and include directories. Add any application-specific +# dependencies here. +target_link_libraries(${BINARY_NAME} PRIVATE flutter flutter_wrapper_app) +target_link_libraries(${BINARY_NAME} PRIVATE "dwmapi.lib") +target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") + +# Run the Flutter tool portions of the build. This must not be removed. +add_dependencies(${BINARY_NAME} flutter_assemble) diff --git a/packages/firebase_core/firebase_core/example/windows/runner/Runner.rc b/packages/firebase_core/firebase_core/example/windows/runner/Runner.rc new file mode 100644 index 000000000000..c0d7fe21c712 --- /dev/null +++ b/packages/firebase_core/firebase_core/example/windows/runner/Runner.rc @@ -0,0 +1,121 @@ +// Microsoft Visual C++ generated resource script. +// +#pragma code_page(65001) +#include "resource.h" + +#define APSTUDIO_READONLY_SYMBOLS +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 2 resource. +// +#include "winres.h" + +///////////////////////////////////////////////////////////////////////////// +#undef APSTUDIO_READONLY_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +// English (United States) resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) +LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US + +#ifdef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// TEXTINCLUDE +// + +1 TEXTINCLUDE +BEGIN + "resource.h\0" +END + +2 TEXTINCLUDE +BEGIN + "#include ""winres.h""\r\n" + "\0" +END + +3 TEXTINCLUDE +BEGIN + "\r\n" + "\0" +END + +#endif // APSTUDIO_INVOKED + + +///////////////////////////////////////////////////////////////////////////// +// +// Icon +// + +// Icon with lowest ID value placed first to ensure application icon +// remains consistent on all systems. +IDI_APP_ICON ICON "resources\\app_icon.ico" + + +///////////////////////////////////////////////////////////////////////////// +// +// Version +// + +#if defined(FLUTTER_VERSION_MAJOR) && defined(FLUTTER_VERSION_MINOR) && defined(FLUTTER_VERSION_PATCH) && defined(FLUTTER_VERSION_BUILD) +#define VERSION_AS_NUMBER FLUTTER_VERSION_MAJOR,FLUTTER_VERSION_MINOR,FLUTTER_VERSION_PATCH,FLUTTER_VERSION_BUILD +#else +#define VERSION_AS_NUMBER 1,0,0,0 +#endif + +#if defined(FLUTTER_VERSION) +#define VERSION_AS_STRING FLUTTER_VERSION +#else +#define VERSION_AS_STRING "1.0.0" +#endif + +VS_VERSION_INFO VERSIONINFO + FILEVERSION VERSION_AS_NUMBER + PRODUCTVERSION VERSION_AS_NUMBER + FILEFLAGSMASK VS_FFI_FILEFLAGSMASK +#ifdef _DEBUG + FILEFLAGS VS_FF_DEBUG +#else + FILEFLAGS 0x0L +#endif + FILEOS VOS__WINDOWS32 + FILETYPE VFT_APP + FILESUBTYPE 0x0L +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "040904e4" + BEGIN + VALUE "CompanyName", "com.example" "\0" + VALUE "FileDescription", "firebase_core_example" "\0" + VALUE "FileVersion", VERSION_AS_STRING "\0" + VALUE "InternalName", "firebase_core_example" "\0" + VALUE "LegalCopyright", "Copyright (C) 2023 com.example. All rights reserved." "\0" + VALUE "OriginalFilename", "firebase_core_example.exe" "\0" + VALUE "ProductName", "firebase_core_example" "\0" + VALUE "ProductVersion", VERSION_AS_STRING "\0" + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x409, 1252 + END +END + +#endif // English (United States) resources +///////////////////////////////////////////////////////////////////////////// + + + +#ifndef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 3 resource. +// + + +///////////////////////////////////////////////////////////////////////////// +#endif // not APSTUDIO_INVOKED diff --git a/packages/firebase_core/firebase_core/example/windows/runner/flutter_window.cpp b/packages/firebase_core/firebase_core/example/windows/runner/flutter_window.cpp new file mode 100644 index 000000000000..b25e363efa42 --- /dev/null +++ b/packages/firebase_core/firebase_core/example/windows/runner/flutter_window.cpp @@ -0,0 +1,66 @@ +#include "flutter_window.h" + +#include + +#include "flutter/generated_plugin_registrant.h" + +FlutterWindow::FlutterWindow(const flutter::DartProject& project) + : project_(project) {} + +FlutterWindow::~FlutterWindow() {} + +bool FlutterWindow::OnCreate() { + if (!Win32Window::OnCreate()) { + return false; + } + + RECT frame = GetClientArea(); + + // The size here must match the window dimensions to avoid unnecessary surface + // creation / destruction in the startup path. + flutter_controller_ = std::make_unique( + frame.right - frame.left, frame.bottom - frame.top, project_); + // Ensure that basic setup of the controller was successful. + if (!flutter_controller_->engine() || !flutter_controller_->view()) { + return false; + } + RegisterPlugins(flutter_controller_->engine()); + SetChildContent(flutter_controller_->view()->GetNativeWindow()); + + flutter_controller_->engine()->SetNextFrameCallback([&]() { + this->Show(); + }); + + return true; +} + +void FlutterWindow::OnDestroy() { + if (flutter_controller_) { + flutter_controller_ = nullptr; + } + + Win32Window::OnDestroy(); +} + +LRESULT +FlutterWindow::MessageHandler(HWND hwnd, UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + // Give Flutter, including plugins, an opportunity to handle window messages. + if (flutter_controller_) { + std::optional result = + flutter_controller_->HandleTopLevelWindowProc(hwnd, message, wparam, + lparam); + if (result) { + return *result; + } + } + + switch (message) { + case WM_FONTCHANGE: + flutter_controller_->engine()->ReloadSystemFonts(); + break; + } + + return Win32Window::MessageHandler(hwnd, message, wparam, lparam); +} diff --git a/packages/firebase_core/firebase_core/example/windows/runner/flutter_window.h b/packages/firebase_core/firebase_core/example/windows/runner/flutter_window.h new file mode 100644 index 000000000000..6da0652f05f2 --- /dev/null +++ b/packages/firebase_core/firebase_core/example/windows/runner/flutter_window.h @@ -0,0 +1,33 @@ +#ifndef RUNNER_FLUTTER_WINDOW_H_ +#define RUNNER_FLUTTER_WINDOW_H_ + +#include +#include + +#include + +#include "win32_window.h" + +// A window that does nothing but host a Flutter view. +class FlutterWindow : public Win32Window { + public: + // Creates a new FlutterWindow hosting a Flutter view running |project|. + explicit FlutterWindow(const flutter::DartProject& project); + virtual ~FlutterWindow(); + + protected: + // Win32Window: + bool OnCreate() override; + void OnDestroy() override; + LRESULT MessageHandler(HWND window, UINT const message, WPARAM const wparam, + LPARAM const lparam) noexcept override; + + private: + // The project to run. + flutter::DartProject project_; + + // The Flutter instance hosted by this window. + std::unique_ptr flutter_controller_; +}; + +#endif // RUNNER_FLUTTER_WINDOW_H_ diff --git a/packages/firebase_core/firebase_core/example/windows/runner/google-services-desktop.json b/packages/firebase_core/firebase_core/example/windows/runner/google-services-desktop.json new file mode 100644 index 000000000000..a3bf216f4de0 --- /dev/null +++ b/packages/firebase_core/firebase_core/example/windows/runner/google-services-desktop.json @@ -0,0 +1,37 @@ +{ + "project_info": { + "project_number": "406099696497", + "firebase_url": "https://flutterfire-e2e-tests-default-rtdb.europe-west1.firebasedatabase.app", + "project_id": "flutterfire-e2e-tests", + "storage_bucket": "flutterfire-e2e-tests.appspot.com" + }, + "client": [ + { + "client_info": { + "mobilesdk_app_id": "1:406099696497:ios:58cbc26aca8e5cf83574d0", + "android_client_info": { + "package_name": "io.flutter.plugins.firebase.auth.example" + } + }, + "oauth_client": [ + { + "client_id": "406099696497-134k3722m01rtrsklhf3b7k8sqa5r7in.apps.googleusercontent.com" + } + ], + "api_key": [ + { + "current_key": "AIzaSyDooSUGSf63Ghq02_iIhtnmwMDs4HlWS6c" + } + ], + "services": { + "analytics_service": { + "status": 0 + }, + "appinvite_service": { + "status": 1 + } + } + } + ], + "configuration_version": "1" +} \ No newline at end of file diff --git a/packages/firebase_core/firebase_core/example/windows/runner/main.cpp b/packages/firebase_core/firebase_core/example/windows/runner/main.cpp new file mode 100644 index 000000000000..2b640e48b2b0 --- /dev/null +++ b/packages/firebase_core/firebase_core/example/windows/runner/main.cpp @@ -0,0 +1,43 @@ +#include +#include +#include + +#include "flutter_window.h" +#include "utils.h" + +int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev, + _In_ wchar_t *command_line, _In_ int show_command) { + // Attach to console when present (e.g., 'flutter run') or create a + // new console when running with a debugger. + if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent()) { + CreateAndAttachConsole(); + } + + // Initialize COM, so that it is available for use in the library and/or + // plugins. + ::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED); + + flutter::DartProject project(L"data"); + + std::vector command_line_arguments = + GetCommandLineArguments(); + + project.set_dart_entrypoint_arguments(std::move(command_line_arguments)); + + FlutterWindow window(project); + Win32Window::Point origin(10, 10); + Win32Window::Size size(1280, 720); + if (!window.Create(L"firebase_core_example", origin, size)) { + return EXIT_FAILURE; + } + window.SetQuitOnClose(true); + + ::MSG msg; + while (::GetMessage(&msg, nullptr, 0, 0)) { + ::TranslateMessage(&msg); + ::DispatchMessage(&msg); + } + + ::CoUninitialize(); + return EXIT_SUCCESS; +} diff --git a/packages/firebase_core/firebase_core/example/windows/runner/resource.h b/packages/firebase_core/firebase_core/example/windows/runner/resource.h new file mode 100644 index 000000000000..66a65d1e4a79 --- /dev/null +++ b/packages/firebase_core/firebase_core/example/windows/runner/resource.h @@ -0,0 +1,16 @@ +//{{NO_DEPENDENCIES}} +// Microsoft Visual C++ generated include file. +// Used by Runner.rc +// +#define IDI_APP_ICON 101 + +// Next default values for new objects +// +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_NEXT_RESOURCE_VALUE 102 +#define _APS_NEXT_COMMAND_VALUE 40001 +#define _APS_NEXT_CONTROL_VALUE 1001 +#define _APS_NEXT_SYMED_VALUE 101 +#endif +#endif diff --git a/packages/firebase_core/firebase_core/example/windows/runner/resources/app_icon.ico b/packages/firebase_core/firebase_core/example/windows/runner/resources/app_icon.ico new file mode 100644 index 0000000000000000000000000000000000000000..c04e20caf6370ebb9253ad831cc31de4a9c965f6 GIT binary patch literal 33772 zcmeHQc|26z|35SKE&G-*mXah&B~fFkXr)DEO&hIfqby^T&>|8^_Ub8Vp#`BLl3lbZ zvPO!8k!2X>cg~Elr=IVxo~J*a`+9wR=A83c-k-DFd(XM&UI1VKCqM@V;DDtJ09WB} zRaHKiW(GT00brH|0EeTeKVbpbGZg?nK6-j827q-+NFM34gXjqWxJ*a#{b_apGN<-L_m3#8Z26atkEn& ze87Bvv^6vVmM+p+cQ~{u%=NJF>#(d;8{7Q{^rWKWNtf14H}>#&y7$lqmY6xmZryI& z($uy?c5-+cPnt2%)R&(KIWEXww>Cnz{OUpT>W$CbO$h1= z#4BPMkFG1Y)x}Ui+WXr?Z!w!t_hjRq8qTaWpu}FH{MsHlU{>;08goVLm{V<&`itk~ zE_Ys=D(hjiy+5=?=$HGii=Y5)jMe9|wWoD_K07(}edAxh`~LBorOJ!Cf@f{_gNCC| z%{*04ViE!#>@hc1t5bb+NO>ncf@@Dv01K!NxH$3Eg1%)|wLyMDF8^d44lV!_Sr}iEWefOaL z8f?ud3Q%Sen39u|%00W<#!E=-RpGa+H8}{ulxVl4mwpjaU+%2pzmi{3HM)%8vb*~-M9rPUAfGCSos8GUXp02|o~0BTV2l#`>>aFV&_P$ejS;nGwSVP8 zMbOaG7<7eKD>c12VdGH;?2@q7535sa7MN*L@&!m?L`ASG%boY7(&L5imY#EQ$KrBB z4@_tfP5m50(T--qv1BJcD&aiH#b-QC>8#7Fx@3yXlonJI#aEIi=8&ChiVpc#N=5le zM*?rDIdcpawoc5kizv$GEjnveyrp3sY>+5_R5;>`>erS%JolimF=A^EIsAK zsPoVyyUHCgf0aYr&alx`<)eb6Be$m&`JYSuBu=p8j%QlNNp$-5C{b4#RubPb|CAIS zGE=9OFLP7?Hgc{?k45)84biT0k&-C6C%Q}aI~q<(7BL`C#<6HyxaR%!dFx7*o^laG z=!GBF^cwK$IA(sn9y6>60Rw{mYRYkp%$jH z*xQM~+bp)G$_RhtFPYx2HTsWk80+p(uqv9@I9)y{b$7NK53rYL$ezbmRjdXS?V}fj zWxX_feWoLFNm3MG7pMUuFPs$qrQWO9!l2B(SIuy2}S|lHNbHzoE+M2|Zxhjq9+Ws8c{*}x^VAib7SbxJ*Q3EnY5lgI9 z=U^f3IW6T=TWaVj+2N%K3<%Un;CF(wUp`TC&Y|ZjyFu6co^uqDDB#EP?DV5v_dw~E zIRK*BoY9y-G_ToU2V_XCX4nJ32~`czdjT!zwme zGgJ0nOk3U4@IE5JwtM}pwimLjk{ln^*4HMU%Fl4~n(cnsLB}Ja-jUM>xIB%aY;Nq8 z)Fp8dv1tkqKanv<68o@cN|%thj$+f;zGSO7H#b+eMAV8xH$hLggtt?O?;oYEgbq@= zV(u9bbd12^%;?nyk6&$GPI%|+<_mEpJGNfl*`!KV;VfmZWw{n{rnZ51?}FDh8we_L z8OI9nE31skDqJ5Oa_ybn7|5@ui>aC`s34p4ZEu6-s!%{uU45$Zd1=p$^^dZBh zu<*pDDPLW+c>iWO$&Z_*{VSQKg7=YEpS3PssPn1U!lSm6eZIho*{@&20e4Y_lRklKDTUCKI%o4Pc<|G^Xgu$J^Q|B87U;`c1zGwf^-zH*VQ^x+i^OUWE0yd z;{FJq)2w!%`x7yg@>uGFFf-XJl4H`YtUG%0slGKOlXV`q?RP>AEWg#x!b{0RicxGhS!3$p7 zij;{gm!_u@D4$Ox%>>bPtLJ> zwKtYz?T_DR1jN>DkkfGU^<#6sGz|~p*I{y`aZ>^Di#TC|Z!7j_O1=Wo8thuit?WxR zh9_S>kw^{V^|g}HRUF=dcq>?q(pHxw!8rx4dC6vbQVmIhmICF#zU!HkHpQ>9S%Uo( zMw{eC+`&pb=GZRou|3;Po1}m46H6NGd$t<2mQh}kaK-WFfmj_66_17BX0|j-E2fe3Jat}ijpc53 zJV$$;PC<5aW`{*^Z6e5##^`Ed#a0nwJDT#Qq~^e8^JTA=z^Kl>La|(UQ!bI@#ge{Dzz@61p-I)kc2?ZxFt^QQ}f%ldLjO*GPj(5)V9IyuUakJX=~GnTgZ4$5!3E=V#t`yOG4U z(gphZB6u2zsj=qNFLYShhg$}lNpO`P9xOSnO*$@@UdMYES*{jJVj|9z-}F^riksLK zbsU+4-{281P9e2UjY6tse^&a)WM1MFw;p#_dHhWI7p&U*9TR0zKdVuQed%6{otTsq z$f~S!;wg#Bd9kez=Br{m|66Wv z#g1xMup<0)H;c2ZO6su_ii&m8j&+jJz4iKnGZ&wxoQX|5a>v&_e#6WA!MB_4asTxLRGQCC5cI(em z%$ZfeqP>!*q5kU>a+BO&ln=4Jm>Ef(QE8o&RgLkk%2}4Tf}U%IFP&uS7}&|Q-)`5< z+e>;s#4cJ-z%&-^&!xsYx777Wt(wZY9(3(avmr|gRe4cD+a8&!LY`1^T?7x{E<=kdY9NYw>A;FtTvQ=Y&1M%lyZPl$ss1oY^Sl8we}n}Aob#6 zl4jERwnt9BlSoWb@3HxYgga(752Vu6Y)k4yk9u~Kw>cA5&LHcrvn1Y-HoIuFWg~}4 zEw4bR`mXZQIyOAzo)FYqg?$5W<;^+XX%Uz61{-L6@eP|lLH%|w?g=rFc;OvEW;^qh z&iYXGhVt(G-q<+_j}CTbPS_=K>RKN0&;dubh0NxJyDOHFF;<1k!{k#7b{|Qok9hac z;gHz}6>H6C6RnB`Tt#oaSrX0p-j-oRJ;_WvS-qS--P*8}V943RT6kou-G=A+7QPGQ z!ze^UGxtW3FC0$|(lY9^L!Lx^?Q8cny(rR`es5U;-xBhphF%_WNu|aO<+e9%6LuZq zt(0PoagJG<%hyuf;te}n+qIl_Ej;czWdc{LX^pS>77s9t*2b4s5dvP_!L^3cwlc)E!(!kGrg~FescVT zZCLeua3f4;d;Tk4iXzt}g}O@nlK3?_o91_~@UMIl?@77Qc$IAlLE95#Z=TES>2E%z zxUKpK{_HvGF;5%Q7n&vA?`{%8ohlYT_?(3A$cZSi)MvIJygXD}TS-3UwyUxGLGiJP znblO~G|*uA^|ac8E-w#}uBtg|s_~s&t>-g0X%zIZ@;o_wNMr_;{KDg^O=rg`fhDZu zFp(VKd1Edj%F zWHPl+)FGj%J1BO3bOHVfH^3d1F{)*PL&sRX`~(-Zy3&9UQX)Z;c51tvaI2E*E7!)q zcz|{vpK7bjxix(k&6=OEIBJC!9lTkUbgg?4-yE{9+pFS)$Ar@vrIf`D0Bnsed(Cf? zObt2CJ>BKOl>q8PyFO6w)+6Iz`LW%T5^R`U_NIW0r1dWv6OY=TVF?N=EfA(k(~7VBW(S;Tu5m4Lg8emDG-(mOSSs=M9Q&N8jc^Y4&9RqIsk(yO_P(mcCr}rCs%1MW1VBrn=0-oQN(Xj!k%iKV zb%ricBF3G4S1;+8lzg5PbZ|$Se$)I=PwiK=cDpHYdov2QO1_a-*dL4KUi|g&oh>(* zq$<`dQ^fat`+VW?m)?_KLn&mp^-@d=&7yGDt<=XwZZC=1scwxO2^RRI7n@g-1o8ps z)&+et_~)vr8aIF1VY1Qrq~Xe``KJrQSnAZ{CSq3yP;V*JC;mmCT6oRLSs7=GA?@6g zUooM}@tKtx(^|aKK8vbaHlUQqwE0}>j&~YlN3H#vKGm@u)xxS?n9XrOWUfCRa< z`20Fld2f&;gg7zpo{Adh+mqNntMc-D$N^yWZAZRI+u1T1zWHPxk{+?vcS1D>08>@6 zLhE@`gt1Y9mAK6Z4p|u(5I%EkfU7rKFSM=E4?VG9tI;a*@?6!ey{lzN5=Y-!$WFSe z&2dtO>^0@V4WRc#L&P%R(?@KfSblMS+N+?xUN$u3K4Ys%OmEh+tq}fnU}i>6YHM?< zlnL2gl~sF!j!Y4E;j3eIU-lfa`RsOL*Tt<%EFC0gPzoHfNWAfKFIKZN8}w~(Yi~=q z>=VNLO2|CjkxP}RkutxjV#4fWYR1KNrPYq5ha9Wl+u>ipsk*I(HS@iLnmGH9MFlTU zaFZ*KSR0px>o+pL7BbhB2EC1%PJ{67_ z#kY&#O4@P=OV#-79y_W>Gv2dxL*@G7%LksNSqgId9v;2xJ zrh8uR!F-eU$NMx@S*+sk=C~Dxr9Qn7TfWnTupuHKuQ$;gGiBcU>GF5sWx(~4IP3`f zWE;YFO*?jGwYh%C3X<>RKHC-DZ!*r;cIr}GLOno^3U4tFSSoJp%oHPiSa%nh=Zgn% z14+8v@ygy0>UgEN1bczD6wK45%M>psM)y^)IfG*>3ItX|TzV*0i%@>L(VN!zdKb8S?Qf7BhjNpziA zR}?={-eu>9JDcl*R=OP9B8N$IcCETXah9SUDhr{yrld{G;PnCWRsPD7!eOOFBTWUQ=LrA_~)mFf&!zJX!Oc-_=kT<}m|K52 z)M=G#;p;Rdb@~h5D{q^K;^fX-m5V}L%!wVC2iZ1uu401Ll}#rocTeK|7FAeBRhNdQ zCc2d^aQnQp=MpOmak60N$OgS}a;p(l9CL`o4r(e-nN}mQ?M&isv-P&d$!8|1D1I(3-z!wi zTgoo)*Mv`gC?~bm?S|@}I|m-E2yqPEvYybiD5azInexpK8?9q*$9Yy9-t%5jU8~ym zgZDx>!@ujQ=|HJnwp^wv-FdD{RtzO9SnyfB{mH_(c!jHL*$>0o-(h(eqe*ZwF6Lvu z{7rkk%PEqaA>o+f{H02tzZ@TWy&su?VNw43! z-X+rN`6llvpUms3ZiSt)JMeztB~>9{J8SPmYs&qohxdYFi!ra8KR$35Zp9oR)eFC4 zE;P31#3V)n`w$fZ|4X-|%MX`xZDM~gJyl2W;O$H25*=+1S#%|53>|LyH za@yh+;325%Gq3;J&a)?%7X%t@WXcWL*BaaR*7UEZad4I8iDt7^R_Fd`XeUo256;sAo2F!HcIQKk;h})QxEsPE5BcKc7WyerTchgKmrfRX z!x#H_%cL#B9TWAqkA4I$R^8{%do3Y*&(;WFmJ zU7Dih{t1<{($VtJRl9|&EB?|cJ)xse!;}>6mSO$o5XIx@V|AA8ZcoD88ZM?C*;{|f zZVmf94_l1OmaICt`2sTyG!$^UeTHx9YuUP!omj(r|7zpm5475|yXI=rR>>fteLI+| z)MoiGho0oEt=*J(;?VY0QzwCqw@cVm?d7Y!z0A@u#H?sCJ*ecvyhj& z-F77lO;SH^dmf?L>3i>?Z*U}Em4ZYV_CjgfvzYsRZ+1B!Uo6H6mbS<-FFL`ytqvb& zE7+)2ahv-~dz(Hs+f})z{*4|{)b=2!RZK;PWwOnO=hG7xG`JU5>bAvUbdYd_CjvtHBHgtGdlO+s^9ca^Bv3`t@VRX2_AD$Ckg36OcQRF zXD6QtGfHdw*hx~V(MV-;;ZZF#dJ-piEF+s27z4X1qi5$!o~xBnvf=uopcn7ftfsZc zy@(PuOk`4GL_n(H9(E2)VUjqRCk9kR?w)v@xO6Jm_Mx})&WGEl=GS0#)0FAq^J*o! zAClhvoTsNP*-b~rN{8Yym3g{01}Ep^^Omf=SKqvN?{Q*C4HNNAcrowIa^mf+3PRy! z*_G-|3i8a;+q;iP@~Of_$(vtFkB8yOyWt2*K)vAn9El>=D;A$CEx6b*XF@4y_6M+2 zpeW`RHoI_p(B{%(&jTHI->hmNmZjHUj<@;7w0mx3&koy!2$@cfX{sN19Y}euYJFn& z1?)+?HCkD0MRI$~uB2UWri})0bru_B;klFdwsLc!ne4YUE;t41JqfG# zZJq6%vbsdx!wYeE<~?>o4V`A3?lN%MnKQ`z=uUivQN^vzJ|C;sdQ37Qn?;lpzg})y z)_2~rUdH}zNwX;Tp0tJ78+&I=IwOQ-fl30R79O8@?Ub8IIA(6I`yHn%lARVL`%b8+ z4$8D-|MZZWxc_)vu6@VZN!HsI$*2NOV&uMxBNzIbRgy%ob_ zhwEH{J9r$!dEix9XM7n&c{S(h>nGm?el;gaX0@|QnzFD@bne`el^CO$yXC?BDJ|Qg z+y$GRoR`?ST1z^e*>;!IS@5Ovb7*RlN>BV_UC!7E_F;N#ky%1J{+iixp(dUJj93aK zzHNN>R-oN7>kykHClPnoPTIj7zc6KM(Pnlb(|s??)SMb)4!sMHU^-ntJwY5Big7xv zb1Ew`Xj;|D2kzGja*C$eS44(d&RMU~c_Y14V9_TLTz0J#uHlsx`S6{nhsA0dWZ#cG zJ?`fO50E>*X4TQLv#nl%3GOk*UkAgt=IY+u0LNXqeln3Z zv$~&Li`ZJOKkFuS)dJRA>)b_Da%Q~axwA_8zNK{BH{#}#m}zGcuckz}riDE-z_Ms> zR8-EqAMcfyGJCtvTpaUVQtajhUS%c@Yj}&6Zz;-M7MZzqv3kA7{SuW$oW#=0az2wQ zg-WG@Vb4|D`pl~Il54N7Hmsauc_ne-a!o5#j3WaBBh@Wuefb!QJIOn5;d)%A#s+5% zuD$H=VNux9bE-}1&bcYGZ+>1Fo;3Z@e&zX^n!?JK*adSbONm$XW9z;Q^L>9U!}Toj2WdafJ%oL#h|yWWwyAGxzfrAWdDTtaKl zK4`5tDpPg5>z$MNv=X0LZ0d6l%D{(D8oT@+w0?ce$DZ6pv>{1&Ok67Ix1 zH}3=IEhPJEhItCC8E=`T`N5(k?G=B4+xzZ?<4!~ ze~z6Wk9!CHTI(0rLJ4{JU?E-puc;xusR?>G?;4vt;q~iI9=kDL=z0Rr%O$vU`30X$ zDZRFyZ`(omOy@u|i6h;wtJlP;+}$|Ak|k2dea7n?U1*$T!sXqqOjq^NxLPMmk~&qI zYg0W?yK8T(6+Ea+$YyspKK?kP$+B`~t3^Pib_`!6xCs32!i@pqXfFV6PmBIR<-QW= zN8L{pt0Vap0x`Gzn#E@zh@H)0FfVfA_Iu4fjYZ+umO1LXIbVc$pY+E234u)ttcrl$ z>s92z4vT%n6cMb>=XT6;l0+9e(|CZG)$@C7t7Z7Ez@a)h)!hyuV&B5K%%)P5?Lk|C zZZSVzdXp{@OXSP0hoU-gF8s8Um(#xzjP2Vem zec#-^JqTa&Y#QJ>-FBxd7tf`XB6e^JPUgagB8iBSEps;92KG`!#mvVcPQ5yNC-GEG zTiHEDYfH+0O15}r^+ z#jxj=@x8iNHWALe!P3R67TwmhItn**0JwnzSV2O&KE8KcT+0hWH^OPD1pwiuyx=b@ zNf5Jh0{9X)8;~Es)$t@%(3!OnbY+`@?i{mGX7Yy}8T_*0a6g;kaFPq;*=px5EhO{Cp%1kI<0?*|h8v!6WnO3cCJRF2-CRrU3JiLJnj@6;L)!0kWYAc_}F{2P))3HmCrz zQ&N&gE70;`!6*eJ4^1IR{f6j4(-l&X!tjHxkbHA^Zhrnhr9g{exN|xrS`5Pq=#Xf& zG%P=#ra-TyVFfgW%cZo5OSIwFL9WtXAlFOa+ubmI5t*3=g#Y zF%;70p5;{ZeFL}&}yOY1N1*Q;*<(kTB!7vM$QokF)yr2FlIU@$Ph58$Bz z0J?xQG=MlS4L6jA22eS42g|9*9pX@$#*sUeM(z+t?hr@r5J&D1rx}2pW&m*_`VDCW zUYY@v-;bAO0HqoAgbbiGGC<=ryf96}3pouhy3XJrX+!!u*O_>Si38V{uJmQ&USptX zKp#l(?>%^7;2%h(q@YWS#9;a!JhKlkR#Vd)ERILlgu!Hr@jA@V;sk4BJ-H#p*4EqC zDGjC*tl=@3Oi6)Bn^QwFpul18fpkbpg0+peH$xyPBqb%`$OUhPKyWb32o7clB*9Z< zN=i~NLjavrLtwgJ01bufP+>p-jR2I95|TpmKpQL2!oV>g(4RvS2pK4*ou%m(h6r3A zX#s&`9LU1ZG&;{CkOK!4fLDTnBys`M!vuz>Q&9OZ0hGQl!~!jSDg|~s*w52opC{sB ze|Cf2luD(*G13LcOAGA!s2FjSK8&IE5#W%J25w!vM0^VyQM!t)inj&RTiJ!wXzFgz z3^IqzB7I0L$llljsGq})thBy9UOyjtFO_*hYM_sgcMk>44jeH0V1FDyELc{S1F-;A zS;T^k^~4biG&V*Irq}O;e}j$$+E_#G?HKIn05iP3j|87TkGK~SqG!-KBg5+mN(aLm z8ybhIM`%C19UX$H$KY6JgXbY$0AT%rEpHC;u`rQ$Y=rxUdsc5*Kvc8jaYaO$^)cI6){P6K0r)I6DY4Wr4&B zLQUBraey#0HV|&c4v7PVo3n$zHj99(TZO^3?Ly%C4nYvJTL9eLBLHsM3WKKD>5!B` zQ=BsR3aR6PD(Fa>327E2HAu5TM~Wusc!)>~(gM)+3~m;92Jd;FnSib=M5d6;;5{%R zb4V7DEJ0V!CP-F*oU?gkc>ksUtAYP&V4ND5J>J2^jt*vcFflQWCrB&fLdT%O59PVJ zhid#toR=FNgD!q3&r8#wEBr`!wzvQu5zX?Q>nlSJ4i@WC*CN*-xU66F^V5crWevQ9gsq$I@z1o(a=k7LL~ z7m_~`o;_Ozha1$8Q}{WBehvAlO4EL60y5}8GDrZ< zXh&F}71JbW2A~8KfEWj&UWV#4+Z4p`b{uAj4&WC zha`}X@3~+Iz^WRlOHU&KngK>#j}+_o@LdBC1H-`gT+krWX3-;!)6?{FBp~%20a}FL zFP9%Emqcwa#(`=G>BBZ0qZDQhmZKJg_g8<=bBFKWr!dyg(YkpE+|R*SGpDVU!+VlU zFC54^DLv}`qa%49T>nNiA9Q7Ips#!Xx90tCU2gvK`(F+GPcL=J^>No{)~we#o@&mUb6c$ zCc*<|NJBk-#+{j9xkQ&ujB zI~`#kN~7W!f*-}wkG~Ld!JqZ@tK}eeSnsS5J1fMFXm|`LJx&}5`@dK3W^7#Wnm+_P zBZkp&j1fa2Y=eIjJ0}gh85jt43kaIXXv?xmo@eHrka!Z|vQv12HN#+!I5E z`(fbuW>gFiJL|uXJ!vKt#z3e3HlVdboH7;e#i3(2<)Fg-I@BR!qY#eof3MFZ&*Y@l zI|KJf&ge@p2Dq09Vu$$Qxb7!}{m-iRk@!)%KL)txi3;~Z4Pb}u@GsW;ELiWeG9V51 znX#}B&4Y2E7-H=OpNE@q{%hFLxwIpBF2t{vPREa8_{linXT;#1vMRWjOzLOP$-hf( z>=?$0;~~PnkqY;~K{EM6Vo-T(0K{A0}VUGmu*hR z{tw3hvBN%N3G3Yw`X5Te+F{J`(3w1s3-+1EbnFQKcrgrX1Jqvs@ADGe%M0s$EbK$$ zK)=y=upBc6SjGYAACCcI=Y*6Fi8_jgwZlLxD26fnQfJmb8^gHRN5(TemhX@0e=vr> zg`W}6U>x6VhoA3DqsGGD9uL1DhB3!OXO=k}59TqD@(0Nb{)Ut_luTioK_>7wjc!5C zIr@w}b`Fez3)0wQfKl&bae7;PcTA7%?f2xucM0G)wt_KO!Ewx>F~;=BI0j=Fb4>pp zv}0R^xM4eti~+^+gE$6b81p(kwzuDti(-K9bc|?+pJEl@H+jSYuxZQV8rl8 zjp@M{#%qItIUFN~KcO9Hed*`$5A-2~pAo~K&<-Q+`9`$CK>rzqAI4w~$F%vs9s{~x zg4BP%Gy*@m?;D6=SRX?888Q6peF@_4Z->8wAH~Cn!R$|Hhq2cIzFYqT_+cDourHbY z0qroxJnrZ4Gh+Ay+F`_c%+KRT>y3qw{)89?=hJ@=KO=@ep)aBJ$c!JHfBMJpsP*3G za7|)VJJ8B;4?n{~ldJF7%jmb`-ftIvNd~ekoufG(`K(3=LNc;HBY& z(lp#q8XAD#cIf}k49zX_i`*fO+#!zKA&%T3j@%)R+#yag067CU%yUEe47>wzGU8^` z1EXFT^@I!{J!F8!X?S6ph8J=gUi5tl93*W>7}_uR<2N2~e}FaG?}KPyugQ=-OGEZs z!GBoyYY+H*ANn4?Z)X4l+7H%`17i5~zRlRIX?t)6_eu=g2Q`3WBhxSUeea+M-S?RL zX9oBGKn%a!H+*hx4d2(I!gsi+@SQK%<{X22M~2tMulJoa)0*+z9=-YO+;DFEm5eE1U9b^B(Z}2^9!Qk`!A$wUE z7$Ar5?NRg2&G!AZqnmE64eh^Anss3i!{}%6@Et+4rr!=}!SBF8eZ2*J3ujCWbl;3; z48H~goPSv(8X61fKKdpP!Z7$88NL^Z?j`!^*I?-P4X^pMxyWz~@$(UeAcTSDd(`vO z{~rc;9|GfMJcApU3k}22a!&)k4{CU!e_ny^Y3cO;tOvOMKEyWz!vG(Kp*;hB?d|R3`2X~=5a6#^o5@qn?J-bI8Ppip{-yG z!k|VcGsq!jF~}7DMr49Wap-s&>o=U^T0!Lcy}!(bhtYsPQy z4|EJe{12QL#=c(suQ89Mhw9<`bui%nx7Nep`C&*M3~vMEACmcRYYRGtANq$F%zh&V zc)cEVeHz*Z1N)L7k-(k3np#{GcDh2Q@ya0YHl*n7fl*ZPAsbU-a94MYYtA#&!c`xGIaV;yzsmrjfieTEtqB_WgZp2*NplHx=$O{M~2#i_vJ{ps-NgK zQsxKK_CBM2PP_je+Xft`(vYfXXgIUr{=PA=7a8`2EHk)Ym2QKIforz# tySWtj{oF3N9@_;i*Fv5S)9x^z=nlWP>jpp-9)52ZmLVA=i*%6g{{fxOO~wEK literal 0 HcmV?d00001 diff --git a/packages/firebase_core/firebase_core/example/windows/runner/runner.exe.manifest b/packages/firebase_core/firebase_core/example/windows/runner/runner.exe.manifest new file mode 100644 index 000000000000..a42ea7687cb6 --- /dev/null +++ b/packages/firebase_core/firebase_core/example/windows/runner/runner.exe.manifest @@ -0,0 +1,20 @@ + + + + + PerMonitorV2 + + + + + + + + + + + + + + + diff --git a/packages/firebase_core/firebase_core/example/windows/runner/utils.cpp b/packages/firebase_core/firebase_core/example/windows/runner/utils.cpp new file mode 100644 index 000000000000..f5bf9fa0f536 --- /dev/null +++ b/packages/firebase_core/firebase_core/example/windows/runner/utils.cpp @@ -0,0 +1,64 @@ +#include "utils.h" + +#include +#include +#include +#include + +#include + +void CreateAndAttachConsole() { + if (::AllocConsole()) { + FILE *unused; + if (freopen_s(&unused, "CONOUT$", "w", stdout)) { + _dup2(_fileno(stdout), 1); + } + if (freopen_s(&unused, "CONOUT$", "w", stderr)) { + _dup2(_fileno(stdout), 2); + } + std::ios::sync_with_stdio(); + FlutterDesktopResyncOutputStreams(); + } +} + +std::vector GetCommandLineArguments() { + // Convert the UTF-16 command line arguments to UTF-8 for the Engine to use. + int argc; + wchar_t** argv = ::CommandLineToArgvW(::GetCommandLineW(), &argc); + if (argv == nullptr) { + return std::vector(); + } + + std::vector command_line_arguments; + + // Skip the first argument as it's the binary name. + for (int i = 1; i < argc; i++) { + command_line_arguments.push_back(Utf8FromUtf16(argv[i])); + } + + ::LocalFree(argv); + + return command_line_arguments; +} + +std::string Utf8FromUtf16(const wchar_t* utf16_string) { + if (utf16_string == nullptr) { + return std::string(); + } + int target_length = ::WideCharToMultiByte( + CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, + -1, nullptr, 0, nullptr, nullptr); + std::string utf8_string; + if (target_length == 0 || target_length > utf8_string.max_size()) { + return utf8_string; + } + utf8_string.resize(target_length); + int converted_length = ::WideCharToMultiByte( + CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, + -1, utf8_string.data(), + target_length, nullptr, nullptr); + if (converted_length == 0) { + return std::string(); + } + return utf8_string; +} diff --git a/packages/firebase_core/firebase_core/example/windows/runner/utils.h b/packages/firebase_core/firebase_core/example/windows/runner/utils.h new file mode 100644 index 000000000000..3879d5475579 --- /dev/null +++ b/packages/firebase_core/firebase_core/example/windows/runner/utils.h @@ -0,0 +1,19 @@ +#ifndef RUNNER_UTILS_H_ +#define RUNNER_UTILS_H_ + +#include +#include + +// Creates a console for the process, and redirects stdout and stderr to +// it for both the runner and the Flutter library. +void CreateAndAttachConsole(); + +// Takes a null-terminated wchar_t* encoded in UTF-16 and returns a std::string +// encoded in UTF-8. Returns an empty std::string on failure. +std::string Utf8FromUtf16(const wchar_t* utf16_string); + +// Gets the command line arguments passed in as a std::vector, +// encoded in UTF-8. Returns an empty std::vector on failure. +std::vector GetCommandLineArguments(); + +#endif // RUNNER_UTILS_H_ diff --git a/packages/firebase_core/firebase_core/example/windows/runner/win32_window.cpp b/packages/firebase_core/firebase_core/example/windows/runner/win32_window.cpp new file mode 100644 index 000000000000..041a38554745 --- /dev/null +++ b/packages/firebase_core/firebase_core/example/windows/runner/win32_window.cpp @@ -0,0 +1,288 @@ +#include "win32_window.h" + +#include +#include + +#include "resource.h" + +namespace { + +/// Window attribute that enables dark mode window decorations. +/// +/// Redefined in case the developer's machine has a Windows SDK older than +/// version 10.0.22000.0. +/// See: https://docs.microsoft.com/windows/win32/api/dwmapi/ne-dwmapi-dwmwindowattribute +#ifndef DWMWA_USE_IMMERSIVE_DARK_MODE +#define DWMWA_USE_IMMERSIVE_DARK_MODE 20 +#endif + +constexpr const wchar_t kWindowClassName[] = L"FLUTTER_RUNNER_WIN32_WINDOW"; + +/// Registry key for app theme preference. +/// +/// A value of 0 indicates apps should use dark mode. A non-zero or missing +/// value indicates apps should use light mode. +constexpr const wchar_t kGetPreferredBrightnessRegKey[] = + L"Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize"; +constexpr const wchar_t kGetPreferredBrightnessRegValue[] = L"AppsUseLightTheme"; + +// The number of Win32Window objects that currently exist. +static int g_active_window_count = 0; + +using EnableNonClientDpiScaling = BOOL __stdcall(HWND hwnd); + +// Scale helper to convert logical scaler values to physical using passed in +// scale factor +int Scale(int source, double scale_factor) { + return static_cast(source * scale_factor); +} + +// Dynamically loads the |EnableNonClientDpiScaling| from the User32 module. +// This API is only needed for PerMonitor V1 awareness mode. +void EnableFullDpiSupportIfAvailable(HWND hwnd) { + HMODULE user32_module = LoadLibraryA("User32.dll"); + if (!user32_module) { + return; + } + auto enable_non_client_dpi_scaling = + reinterpret_cast( + GetProcAddress(user32_module, "EnableNonClientDpiScaling")); + if (enable_non_client_dpi_scaling != nullptr) { + enable_non_client_dpi_scaling(hwnd); + } + FreeLibrary(user32_module); +} + +} // namespace + +// Manages the Win32Window's window class registration. +class WindowClassRegistrar { + public: + ~WindowClassRegistrar() = default; + + // Returns the singleton registar instance. + static WindowClassRegistrar* GetInstance() { + if (!instance_) { + instance_ = new WindowClassRegistrar(); + } + return instance_; + } + + // Returns the name of the window class, registering the class if it hasn't + // previously been registered. + const wchar_t* GetWindowClass(); + + // Unregisters the window class. Should only be called if there are no + // instances of the window. + void UnregisterWindowClass(); + + private: + WindowClassRegistrar() = default; + + static WindowClassRegistrar* instance_; + + bool class_registered_ = false; +}; + +WindowClassRegistrar* WindowClassRegistrar::instance_ = nullptr; + +const wchar_t* WindowClassRegistrar::GetWindowClass() { + if (!class_registered_) { + WNDCLASS window_class{}; + window_class.hCursor = LoadCursor(nullptr, IDC_ARROW); + window_class.lpszClassName = kWindowClassName; + window_class.style = CS_HREDRAW | CS_VREDRAW; + window_class.cbClsExtra = 0; + window_class.cbWndExtra = 0; + window_class.hInstance = GetModuleHandle(nullptr); + window_class.hIcon = + LoadIcon(window_class.hInstance, MAKEINTRESOURCE(IDI_APP_ICON)); + window_class.hbrBackground = 0; + window_class.lpszMenuName = nullptr; + window_class.lpfnWndProc = Win32Window::WndProc; + RegisterClass(&window_class); + class_registered_ = true; + } + return kWindowClassName; +} + +void WindowClassRegistrar::UnregisterWindowClass() { + UnregisterClass(kWindowClassName, nullptr); + class_registered_ = false; +} + +Win32Window::Win32Window() { + ++g_active_window_count; +} + +Win32Window::~Win32Window() { + --g_active_window_count; + Destroy(); +} + +bool Win32Window::Create(const std::wstring& title, + const Point& origin, + const Size& size) { + Destroy(); + + const wchar_t* window_class = + WindowClassRegistrar::GetInstance()->GetWindowClass(); + + const POINT target_point = {static_cast(origin.x), + static_cast(origin.y)}; + HMONITOR monitor = MonitorFromPoint(target_point, MONITOR_DEFAULTTONEAREST); + UINT dpi = FlutterDesktopGetDpiForMonitor(monitor); + double scale_factor = dpi / 96.0; + + HWND window = CreateWindow( + window_class, title.c_str(), WS_OVERLAPPEDWINDOW, + Scale(origin.x, scale_factor), Scale(origin.y, scale_factor), + Scale(size.width, scale_factor), Scale(size.height, scale_factor), + nullptr, nullptr, GetModuleHandle(nullptr), this); + + if (!window) { + return false; + } + + UpdateTheme(window); + + return OnCreate(); +} + +bool Win32Window::Show() { + return ShowWindow(window_handle_, SW_SHOWNORMAL); +} + +// static +LRESULT CALLBACK Win32Window::WndProc(HWND const window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + if (message == WM_NCCREATE) { + auto window_struct = reinterpret_cast(lparam); + SetWindowLongPtr(window, GWLP_USERDATA, + reinterpret_cast(window_struct->lpCreateParams)); + + auto that = static_cast(window_struct->lpCreateParams); + EnableFullDpiSupportIfAvailable(window); + that->window_handle_ = window; + } else if (Win32Window* that = GetThisFromHandle(window)) { + return that->MessageHandler(window, message, wparam, lparam); + } + + return DefWindowProc(window, message, wparam, lparam); +} + +LRESULT +Win32Window::MessageHandler(HWND hwnd, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + switch (message) { + case WM_DESTROY: + window_handle_ = nullptr; + Destroy(); + if (quit_on_close_) { + PostQuitMessage(0); + } + return 0; + + case WM_DPICHANGED: { + auto newRectSize = reinterpret_cast(lparam); + LONG newWidth = newRectSize->right - newRectSize->left; + LONG newHeight = newRectSize->bottom - newRectSize->top; + + SetWindowPos(hwnd, nullptr, newRectSize->left, newRectSize->top, newWidth, + newHeight, SWP_NOZORDER | SWP_NOACTIVATE); + + return 0; + } + case WM_SIZE: { + RECT rect = GetClientArea(); + if (child_content_ != nullptr) { + // Size and position the child window. + MoveWindow(child_content_, rect.left, rect.top, rect.right - rect.left, + rect.bottom - rect.top, TRUE); + } + return 0; + } + + case WM_ACTIVATE: + if (child_content_ != nullptr) { + SetFocus(child_content_); + } + return 0; + + case WM_DWMCOLORIZATIONCOLORCHANGED: + UpdateTheme(hwnd); + return 0; + } + + return DefWindowProc(window_handle_, message, wparam, lparam); +} + +void Win32Window::Destroy() { + OnDestroy(); + + if (window_handle_) { + DestroyWindow(window_handle_); + window_handle_ = nullptr; + } + if (g_active_window_count == 0) { + WindowClassRegistrar::GetInstance()->UnregisterWindowClass(); + } +} + +Win32Window* Win32Window::GetThisFromHandle(HWND const window) noexcept { + return reinterpret_cast( + GetWindowLongPtr(window, GWLP_USERDATA)); +} + +void Win32Window::SetChildContent(HWND content) { + child_content_ = content; + SetParent(content, window_handle_); + RECT frame = GetClientArea(); + + MoveWindow(content, frame.left, frame.top, frame.right - frame.left, + frame.bottom - frame.top, true); + + SetFocus(child_content_); +} + +RECT Win32Window::GetClientArea() { + RECT frame; + GetClientRect(window_handle_, &frame); + return frame; +} + +HWND Win32Window::GetHandle() { + return window_handle_; +} + +void Win32Window::SetQuitOnClose(bool quit_on_close) { + quit_on_close_ = quit_on_close; +} + +bool Win32Window::OnCreate() { + // No-op; provided for subclasses. + return true; +} + +void Win32Window::OnDestroy() { + // No-op; provided for subclasses. +} + +void Win32Window::UpdateTheme(HWND const window) { + DWORD light_mode; + DWORD light_mode_size = sizeof(light_mode); + LSTATUS result = RegGetValue(HKEY_CURRENT_USER, kGetPreferredBrightnessRegKey, + kGetPreferredBrightnessRegValue, + RRF_RT_REG_DWORD, nullptr, &light_mode, + &light_mode_size); + + if (result == ERROR_SUCCESS) { + BOOL enable_dark_mode = light_mode == 0; + DwmSetWindowAttribute(window, DWMWA_USE_IMMERSIVE_DARK_MODE, + &enable_dark_mode, sizeof(enable_dark_mode)); + } +} diff --git a/packages/firebase_core/firebase_core/example/windows/runner/win32_window.h b/packages/firebase_core/firebase_core/example/windows/runner/win32_window.h new file mode 100644 index 000000000000..c86632d8a6b9 --- /dev/null +++ b/packages/firebase_core/firebase_core/example/windows/runner/win32_window.h @@ -0,0 +1,102 @@ +#ifndef RUNNER_WIN32_WINDOW_H_ +#define RUNNER_WIN32_WINDOW_H_ + +#include + +#include +#include +#include + +// A class abstraction for a high DPI-aware Win32 Window. Intended to be +// inherited from by classes that wish to specialize with custom +// rendering and input handling +class Win32Window { + public: + struct Point { + unsigned int x; + unsigned int y; + Point(unsigned int x, unsigned int y) : x(x), y(y) {} + }; + + struct Size { + unsigned int width; + unsigned int height; + Size(unsigned int width, unsigned int height) + : width(width), height(height) {} + }; + + Win32Window(); + virtual ~Win32Window(); + + // Creates a win32 window with |title| that is positioned and sized using + // |origin| and |size|. New windows are created on the default monitor. Window + // sizes are specified to the OS in physical pixels, hence to ensure a + // consistent size this function will scale the inputted width and height as + // as appropriate for the default monitor. The window is invisible until + // |Show| is called. Returns true if the window was created successfully. + bool Create(const std::wstring& title, const Point& origin, const Size& size); + + // Show the current window. Returns true if the window was successfully shown. + bool Show(); + + // Release OS resources associated with window. + void Destroy(); + + // Inserts |content| into the window tree. + void SetChildContent(HWND content); + + // Returns the backing Window handle to enable clients to set icon and other + // window properties. Returns nullptr if the window has been destroyed. + HWND GetHandle(); + + // If true, closing this window will quit the application. + void SetQuitOnClose(bool quit_on_close); + + // Return a RECT representing the bounds of the current client area. + RECT GetClientArea(); + + protected: + // Processes and route salient window messages for mouse handling, + // size change and DPI. Delegates handling of these to member overloads that + // inheriting classes can handle. + virtual LRESULT MessageHandler(HWND window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept; + + // Called when CreateAndShow is called, allowing subclass window-related + // setup. Subclasses should return false if setup fails. + virtual bool OnCreate(); + + // Called when Destroy is called. + virtual void OnDestroy(); + + private: + friend class WindowClassRegistrar; + + // OS callback called by message pump. Handles the WM_NCCREATE message which + // is passed when the non-client area is being created and enables automatic + // non-client DPI scaling so that the non-client area automatically + // responsponds to changes in DPI. All other messages are handled by + // MessageHandler. + static LRESULT CALLBACK WndProc(HWND const window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept; + + // Retrieves a class instance pointer for |window| + static Win32Window* GetThisFromHandle(HWND const window) noexcept; + + // Update the window frame's theme to match the system theme. + static void UpdateTheme(HWND const window); + + bool quit_on_close_ = false; + + // window handle for top level window. + HWND window_handle_ = nullptr; + + // window handle for hosted content. + HWND child_content_ = nullptr; +}; + +#endif // RUNNER_WIN32_WINDOW_H_ From f702e7968a8398c975ecda2a6eb246241ff42404 Mon Sep 17 00:00:00 2001 From: Guillaume Bernos Date: Mon, 20 Mar 2023 15:06:39 +0100 Subject: [PATCH 40/65] add intializeApp --- .../firebase_core/windows/CMakeLists.txt | 2 + .../windows/firebase_core_plugin.cpp | 82 ++++++++++++------- .../windows/firebase_core_plugin.h | 37 +++++++-- .../windows/firebase_core_plugin_c_api.cpp | 2 +- 4 files changed, 87 insertions(+), 36 deletions(-) diff --git a/packages/firebase_core/firebase_core/windows/CMakeLists.txt b/packages/firebase_core/firebase_core/windows/CMakeLists.txt index 35c68f4a1910..efe90b40d4d1 100644 --- a/packages/firebase_core/firebase_core/windows/CMakeLists.txt +++ b/packages/firebase_core/firebase_core/windows/CMakeLists.txt @@ -16,6 +16,8 @@ set(PLUGIN_NAME "firebase_core_plugin") list(APPEND PLUGIN_SOURCES "firebase_core_plugin.cpp" "firebase_core_plugin.h" + "messages.g.cpp" + "messages.g.h" ) # Define the plugin library target. Its name must not be changed (see comment diff --git a/packages/firebase_core/firebase_core/windows/firebase_core_plugin.cpp b/packages/firebase_core/firebase_core/windows/firebase_core_plugin.cpp index 457e78e218b8..ee6d633395e7 100644 --- a/packages/firebase_core/firebase_core/windows/firebase_core_plugin.cpp +++ b/packages/firebase_core/firebase_core/windows/firebase_core_plugin.cpp @@ -4,6 +4,7 @@ #include #include "firebase/app.h" +#include "messages.g.h" // For getPlatformVersion; remove unless needed for your plugin implementation. #include @@ -11,50 +12,73 @@ #include #include +#include #include #include +#include using ::firebase::App; -namespace firebase_core { +namespace firebase_core_windows { // static void FirebaseCorePlugin::RegisterWithRegistrar( flutter::PluginRegistrarWindows *registrar) { - auto channel = - std::make_unique>( - registrar->messenger(), "firebase_core", - &flutter::StandardMethodCodec::GetInstance()); - auto plugin = std::make_unique(); - channel->SetMethodCallHandler( - [plugin_pointer = plugin.get()](const auto &call, auto result) { - plugin_pointer->HandleMethodCall(call, std::move(result)); - }); + FirebaseCoreHostApi::SetUp(registrar->messenger(), plugin.get()); registrar->AddPlugin(std::move(plugin)); } FirebaseCorePlugin::FirebaseCorePlugin() {} -FirebaseCorePlugin::~FirebaseCorePlugin() {} - -void FirebaseCorePlugin::HandleMethodCall( - const flutter::MethodCall &method_call, - std::unique_ptr> result) { - if (method_call.method_name().compare("getPlatformVersion") == 0) { - App *app = App::Create(); - std::cout << static_cast(reinterpret_cast(app)); - std::ostringstream version_stream; - if (IsWindows10OrGreater()) { - version_stream << "10+"; - } else if (IsWindows7OrGreater()) { - version_stream << "7"; - } - result->Success(flutter::EncodableValue(version_stream.str())); - } else { - result->NotImplemented(); - } +FirebaseCorePlugin::~FirebaseCorePlugin() = default; + +// Convert a Pigeon FirebaseOptions to a Firebase Options. +firebase::AppOptions PigeonFirebaseOptionsToAppOptions( + const PigeonFirebaseOptions &pigeon_options) { + firebase::AppOptions options; + options.set_api_key(pigeon_options.api_key().c_str()); + options.set_app_id(pigeon_options.app_id().c_str()); + options.set_database_url(pigeon_options.database_u_r_l()->c_str()); + options.set_messaging_sender_id(pigeon_options.messaging_sender_id().c_str()); + options.set_project_id(pigeon_options.project_id().c_str()); + options.set_storage_bucket(pigeon_options.storage_bucket()->c_str()); + return options; +} + +void FirebaseCorePlugin::InitializeApp( + const std::string &app_name, + const PigeonFirebaseOptions &initialize_app_request, + std::function reply)> result) { + // Create an app + App *app; + app = App::Create(PigeonFirebaseOptionsToAppOptions(initialize_app_request), + app_name.c_str()); + + // Send back the result to Flutter + result(PigeonInitializeResponse()); + + // Log everything is OK + std::cout << "FirebaseCorePlugin::InitializeApp: OK" << std::endl; } -} // namespace firebase_core +void FirebaseCorePlugin::InitializeCore( + std::function reply)> result) {} + +void FirebaseCorePlugin::OptionsFromResource( + std::function reply)> result) {} + +void FirebaseCorePlugin::SetAutomaticDataCollectionEnabled( + const std::string &app_name, bool enabled, + std::function reply)> result) {} + +void FirebaseCorePlugin::SetAutomaticResourceManagementEnabled( + const std::string &app_name, bool enabled, + std::function reply)> result) {} + +void FirebaseCorePlugin::Delete( + const std::string &app_name, + std::function reply)> result) {} + +} // namespace firebase_core_windows diff --git a/packages/firebase_core/firebase_core/windows/firebase_core_plugin.h b/packages/firebase_core/firebase_core/windows/firebase_core_plugin.h index 52794b6a0e51..f0fbfd29239d 100644 --- a/packages/firebase_core/firebase_core/windows/firebase_core_plugin.h +++ b/packages/firebase_core/firebase_core/windows/firebase_core_plugin.h @@ -5,10 +5,11 @@ #include #include +#include "messages.g.h" -namespace firebase_core { +namespace firebase_core_windows { -class FirebaseCorePlugin : public flutter::Plugin { +class FirebaseCorePlugin : public flutter::Plugin, public FirebaseCoreHostApi, public FirebaseAppHostApi { public: static void RegisterWithRegistrar(flutter::PluginRegistrarWindows *registrar); @@ -20,11 +21,35 @@ class FirebaseCorePlugin : public flutter::Plugin { FirebaseCorePlugin(const FirebaseCorePlugin &) = delete; FirebaseCorePlugin &operator=(const FirebaseCorePlugin &) = delete; + + // FirebaseCoreHostApi + virtual void InitializeApp( + const std::string &app_name, + const PigeonFirebaseOptions &initialize_app_request, + std::function reply)> result) override; + virtual void InitializeCore( + std::function reply)> result) + override; + virtual void OptionsFromResource( + std::function reply)> result) + override; + + + // FirebaseAppHostApi + virtual void SetAutomaticDataCollectionEnabled( + const std::string &app_name, bool enabled, + std::function reply)> result) override; + virtual void SetAutomaticResourceManagementEnabled( + const std::string &app_name, bool enabled, + std::function reply)> result) override; + virtual void Delete( + const std::string &app_name, + std::function reply)> result) override; + + + private: - // Called when a method is called on this plugin's channel from Dart. - void HandleMethodCall( - const flutter::MethodCall &method_call, - std::unique_ptr> result); + }; } // namespace firebase_core diff --git a/packages/firebase_core/firebase_core/windows/firebase_core_plugin_c_api.cpp b/packages/firebase_core/firebase_core/windows/firebase_core_plugin_c_api.cpp index f0ca223fcf26..478de00182e5 100644 --- a/packages/firebase_core/firebase_core/windows/firebase_core_plugin_c_api.cpp +++ b/packages/firebase_core/firebase_core/windows/firebase_core_plugin_c_api.cpp @@ -6,7 +6,7 @@ void FirebaseCorePluginCApiRegisterWithRegistrar( FlutterDesktopPluginRegistrarRef registrar) { - firebase_core::FirebaseCorePlugin::RegisterWithRegistrar( + firebase_core_windows::FirebaseCorePlugin::RegisterWithRegistrar( flutter::PluginRegistrarManager::GetInstance() ->GetRegistrar(registrar)); } From 73ce28a3ed69877d1392134ed7a35149fc368903 Mon Sep 17 00:00:00 2001 From: Guillaume Bernos Date: Mon, 20 Mar 2023 16:34:04 +0100 Subject: [PATCH 41/65] initalizeCore --- .../windows/firebase_core_plugin.cpp | 34 ++++++++++++++++--- .../windows/firebase_core_plugin.h | 4 +-- 2 files changed, 32 insertions(+), 6 deletions(-) diff --git a/packages/firebase_core/firebase_core/windows/firebase_core_plugin.cpp b/packages/firebase_core/firebase_core/windows/firebase_core_plugin.cpp index ee6d633395e7..68fccc1f6cd7 100644 --- a/packages/firebase_core/firebase_core/windows/firebase_core_plugin.cpp +++ b/packages/firebase_core/firebase_core/windows/firebase_core_plugin.cpp @@ -12,10 +12,13 @@ #include #include +#include #include #include #include +#include #include +#include using ::firebase::App; namespace firebase_core_windows { @@ -44,6 +47,7 @@ firebase::AppOptions PigeonFirebaseOptionsToAppOptions( options.set_messaging_sender_id(pigeon_options.messaging_sender_id().c_str()); options.set_project_id(pigeon_options.project_id().c_str()); options.set_storage_bucket(pigeon_options.storage_bucket()->c_str()); + options.set_ga_tracking_id(pigeon_options.tracking_id()->c_str()); return options; } @@ -64,21 +68,43 @@ void FirebaseCorePlugin::InitializeApp( } void FirebaseCorePlugin::InitializeCore( - std::function reply)> result) {} + std::function reply)> result) { + result(flutter::EncodableList()); +} void FirebaseCorePlugin::OptionsFromResource( std::function reply)> result) {} void FirebaseCorePlugin::SetAutomaticDataCollectionEnabled( const std::string &app_name, bool enabled, - std::function reply)> result) {} + std::function reply)> result) { + App *firebaseApp = App::GetInstance(app_name.c_str()); + if (firebaseApp != nullptr) { + // Missing method + } + result(std::nullopt); +} void FirebaseCorePlugin::SetAutomaticResourceManagementEnabled( const std::string &app_name, bool enabled, - std::function reply)> result) {} + std::function reply)> result) { + App *firebaseApp = App::GetInstance(app_name.c_str()); + if (firebaseApp != nullptr) { + // Missing method + } + + result(std::nullopt); +} void FirebaseCorePlugin::Delete( const std::string &app_name, - std::function reply)> result) {} + std::function reply)> result) { + App *firebaseApp = App::GetInstance(app_name.c_str()); + if (firebaseApp != nullptr) { + // Missing method + } + + result(std::nullopt); +} } // namespace firebase_core_windows diff --git a/packages/firebase_core/firebase_core/windows/firebase_core_plugin.h b/packages/firebase_core/firebase_core/windows/firebase_core_plugin.h index f0fbfd29239d..12161246ec4d 100644 --- a/packages/firebase_core/firebase_core/windows/firebase_core_plugin.h +++ b/packages/firebase_core/firebase_core/windows/firebase_core_plugin.h @@ -48,8 +48,8 @@ class FirebaseCorePlugin : public flutter::Plugin, public FirebaseCoreHostApi, p - private: - +private: + bool coreInitialized = false; }; } // namespace firebase_core From 0999c3e26f7b9e12f2a2dd3f07c66e02c75370d8 Mon Sep 17 00:00:00 2001 From: Guillaume Bernos Date: Tue, 21 Mar 2023 10:14:07 +0100 Subject: [PATCH 42/65] ready windows --- .../windows/firebase_core_plugin.cpp | 62 ++++++++++++++++--- 1 file changed, 52 insertions(+), 10 deletions(-) diff --git a/packages/firebase_core/firebase_core/windows/firebase_core_plugin.cpp b/packages/firebase_core/firebase_core/windows/firebase_core_plugin.cpp index 68fccc1f6cd7..21c0fac371f9 100644 --- a/packages/firebase_core/firebase_core/windows/firebase_core_plugin.cpp +++ b/packages/firebase_core/firebase_core/windows/firebase_core_plugin.cpp @@ -43,14 +43,50 @@ firebase::AppOptions PigeonFirebaseOptionsToAppOptions( firebase::AppOptions options; options.set_api_key(pigeon_options.api_key().c_str()); options.set_app_id(pigeon_options.app_id().c_str()); - options.set_database_url(pigeon_options.database_u_r_l()->c_str()); + if (pigeon_options.database_u_r_l() != nullptr) { + options.set_database_url(pigeon_options.database_u_r_l()->c_str()); + } + if (pigeon_options.tracking_id() != nullptr) { + options.set_ga_tracking_id(pigeon_options.tracking_id()->c_str()); + } options.set_messaging_sender_id(pigeon_options.messaging_sender_id().c_str()); + options.set_project_id(pigeon_options.project_id().c_str()); - options.set_storage_bucket(pigeon_options.storage_bucket()->c_str()); - options.set_ga_tracking_id(pigeon_options.tracking_id()->c_str()); + + if (pigeon_options.storage_bucket() != nullptr) { + options.set_storage_bucket(pigeon_options.storage_bucket()->c_str()); + } return options; } +// Convert a AppOptions to PigeonInitializeOption +PigeonFirebaseOptions optionsFromFIROptions( + const firebase::AppOptions &options) { + PigeonFirebaseOptions pigeon_options = PigeonFirebaseOptions(); + pigeon_options.set_api_key(options.api_key()); + pigeon_options.set_app_id(options.app_id()); + if (options.database_url() != nullptr) { + pigeon_options.set_database_u_r_l(options.database_url()); + } + if (options.ga_tracking_id() != nullptr) { + pigeon_options.set_tracking_id(options.ga_tracking_id()); + } + pigeon_options.set_messaging_sender_id(options.messaging_sender_id()); + pigeon_options.set_project_id(options.project_id()); + if (options.storage_bucket() != nullptr) { + pigeon_options.set_storage_bucket(options.storage_bucket()); + } + return pigeon_options; +} + +// Convert a firebase::App to PigeonInitializeResponse +PigeonInitializeResponse AppToPigeonInitializeResponse(const App &app) { + PigeonInitializeResponse response = PigeonInitializeResponse(); + response.set_name(app.name()); + response.set_options(optionsFromFIROptions(app.options())); + return response; +} + void FirebaseCorePlugin::InitializeApp( const std::string &app_name, const PigeonFirebaseOptions &initialize_app_request, @@ -61,14 +97,20 @@ void FirebaseCorePlugin::InitializeApp( app_name.c_str()); // Send back the result to Flutter - result(PigeonInitializeResponse()); - - // Log everything is OK - std::cout << "FirebaseCorePlugin::InitializeApp: OK" << std::endl; + result(AppToPigeonInitializeResponse(*app)); } void FirebaseCorePlugin::InitializeCore( std::function reply)> result) { + // TODO: Missing function to get the list of currently initialized apps + std::vector initializedApps; + + flutter::EncodableList encodableList; + + // Insert the contents of the vector into the EncodableList + // for (const auto &item : initializedApps) { + // encodableList.push_back(flutter::EncodableValue(item)); + //} result(flutter::EncodableList()); } @@ -80,7 +122,7 @@ void FirebaseCorePlugin::SetAutomaticDataCollectionEnabled( std::function reply)> result) { App *firebaseApp = App::GetInstance(app_name.c_str()); if (firebaseApp != nullptr) { - // Missing method + // TODO: Missing method } result(std::nullopt); } @@ -90,7 +132,7 @@ void FirebaseCorePlugin::SetAutomaticResourceManagementEnabled( std::function reply)> result) { App *firebaseApp = App::GetInstance(app_name.c_str()); if (firebaseApp != nullptr) { - // Missing method + // TODO: Missing method } result(std::nullopt); @@ -101,7 +143,7 @@ void FirebaseCorePlugin::Delete( std::function reply)> result) { App *firebaseApp = App::GetInstance(app_name.c_str()); if (firebaseApp != nullptr) { - // Missing method + // TODO: Missing method } result(std::nullopt); From e203061c35a570c06d0b30c054c8001f09863e45 Mon Sep 17 00:00:00 2001 From: Guillaume Bernos Date: Tue, 21 Mar 2023 10:25:20 +0100 Subject: [PATCH 43/65] app host --- .../firebase_core/firebase_core/windows/firebase_core_plugin.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/packages/firebase_core/firebase_core/windows/firebase_core_plugin.cpp b/packages/firebase_core/firebase_core/windows/firebase_core_plugin.cpp index 21c0fac371f9..37e9fee4e6fc 100644 --- a/packages/firebase_core/firebase_core/windows/firebase_core_plugin.cpp +++ b/packages/firebase_core/firebase_core/windows/firebase_core_plugin.cpp @@ -29,6 +29,7 @@ void FirebaseCorePlugin::RegisterWithRegistrar( auto plugin = std::make_unique(); FirebaseCoreHostApi::SetUp(registrar->messenger(), plugin.get()); + FirebaseAppHostApi::SetUp(registrar->messenger(), plugin.get()); registrar->AddPlugin(std::move(plugin)); } From 33f25803cba3304850c055f3c014b972b54bff39 Mon Sep 17 00:00:00 2001 From: Guillaume Bernos Date: Tue, 21 Mar 2023 10:29:20 +0100 Subject: [PATCH 44/65] add licence headers --- .../example/test/widget_test.dart | 30 ------------------- .../example/windows/runner/flutter_window.cpp | 4 +++ .../example/windows/runner/flutter_window.h | 6 ++++ .../example/windows/runner/main.cpp | 4 +++ .../example/windows/runner/resource.h | 6 ++++ .../example/windows/runner/utils.cpp | 4 +++ .../example/windows/runner/utils.h | 6 ++++ .../example/windows/runner/win32_window.cpp | 4 +++ .../example/windows/runner/win32_window.h | 6 ++++ .../windows/firebase_core_plugin.cpp | 4 +++ .../windows/firebase_core_plugin.h | 6 ++++ .../windows/firebase_core_plugin_c_api.cpp | 4 +++ .../firebase_core_plugin_c_api.h | 6 ++++ 13 files changed, 60 insertions(+), 30 deletions(-) delete mode 100644 packages/firebase_core/firebase_core/example/test/widget_test.dart diff --git a/packages/firebase_core/firebase_core/example/test/widget_test.dart b/packages/firebase_core/firebase_core/example/test/widget_test.dart deleted file mode 100644 index 092d222f7e16..000000000000 --- a/packages/firebase_core/firebase_core/example/test/widget_test.dart +++ /dev/null @@ -1,30 +0,0 @@ -// This is a basic Flutter widget test. -// -// To perform an interaction with a widget in your test, use the WidgetTester -// utility in the flutter_test package. For example, you can send tap and scroll -// gestures. You can also use WidgetTester to find child widgets in the widget -// tree, read text, and verify that the values of widget properties are correct. - -import 'package:flutter/material.dart'; -import 'package:flutter_test/flutter_test.dart'; - -import 'package:example/main.dart'; - -void main() { - testWidgets('Counter increments smoke test', (WidgetTester tester) async { - // Build our app and trigger a frame. - await tester.pumpWidget(const MyApp()); - - // Verify that our counter starts at 0. - expect(find.text('0'), findsOneWidget); - expect(find.text('1'), findsNothing); - - // Tap the '+' icon and trigger a frame. - await tester.tap(find.byIcon(Icons.add)); - await tester.pump(); - - // Verify that our counter has incremented. - expect(find.text('0'), findsNothing); - expect(find.text('1'), findsOneWidget); - }); -} diff --git a/packages/firebase_core/firebase_core/example/windows/runner/flutter_window.cpp b/packages/firebase_core/firebase_core/example/windows/runner/flutter_window.cpp index b25e363efa42..4e7e8292bfa8 100644 --- a/packages/firebase_core/firebase_core/example/windows/runner/flutter_window.cpp +++ b/packages/firebase_core/firebase_core/example/windows/runner/flutter_window.cpp @@ -1,3 +1,7 @@ +// Copyright 2023, the Chromium project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + #include "flutter_window.h" #include diff --git a/packages/firebase_core/firebase_core/example/windows/runner/flutter_window.h b/packages/firebase_core/firebase_core/example/windows/runner/flutter_window.h index 6da0652f05f2..2b30f421692a 100644 --- a/packages/firebase_core/firebase_core/example/windows/runner/flutter_window.h +++ b/packages/firebase_core/firebase_core/example/windows/runner/flutter_window.h @@ -1,3 +1,9 @@ +/* + * Copyright 2023, the Chromium project authors. Please see the AUTHORS file + * for details. All rights reserved. Use of this source code is governed by a + * BSD-style license that can be found in the LICENSE file. + */ + #ifndef RUNNER_FLUTTER_WINDOW_H_ #define RUNNER_FLUTTER_WINDOW_H_ diff --git a/packages/firebase_core/firebase_core/example/windows/runner/main.cpp b/packages/firebase_core/firebase_core/example/windows/runner/main.cpp index 2b640e48b2b0..8147273feb87 100644 --- a/packages/firebase_core/firebase_core/example/windows/runner/main.cpp +++ b/packages/firebase_core/firebase_core/example/windows/runner/main.cpp @@ -1,3 +1,7 @@ +// Copyright 2023, the Chromium project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + #include #include #include diff --git a/packages/firebase_core/firebase_core/example/windows/runner/resource.h b/packages/firebase_core/firebase_core/example/windows/runner/resource.h index 66a65d1e4a79..01543b168082 100644 --- a/packages/firebase_core/firebase_core/example/windows/runner/resource.h +++ b/packages/firebase_core/firebase_core/example/windows/runner/resource.h @@ -1,3 +1,9 @@ +/* + * Copyright 2023, the Chromium project authors. Please see the AUTHORS file + * for details. All rights reserved. Use of this source code is governed by a + * BSD-style license that can be found in the LICENSE file. + */ + //{{NO_DEPENDENCIES}} // Microsoft Visual C++ generated include file. // Used by Runner.rc diff --git a/packages/firebase_core/firebase_core/example/windows/runner/utils.cpp b/packages/firebase_core/firebase_core/example/windows/runner/utils.cpp index f5bf9fa0f536..7e940c4f2f46 100644 --- a/packages/firebase_core/firebase_core/example/windows/runner/utils.cpp +++ b/packages/firebase_core/firebase_core/example/windows/runner/utils.cpp @@ -1,3 +1,7 @@ +// Copyright 2023, the Chromium project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + #include "utils.h" #include diff --git a/packages/firebase_core/firebase_core/example/windows/runner/utils.h b/packages/firebase_core/firebase_core/example/windows/runner/utils.h index 3879d5475579..67b5c48b8d3d 100644 --- a/packages/firebase_core/firebase_core/example/windows/runner/utils.h +++ b/packages/firebase_core/firebase_core/example/windows/runner/utils.h @@ -1,3 +1,9 @@ +/* + * Copyright 2023, the Chromium project authors. Please see the AUTHORS file + * for details. All rights reserved. Use of this source code is governed by a + * BSD-style license that can be found in the LICENSE file. + */ + #ifndef RUNNER_UTILS_H_ #define RUNNER_UTILS_H_ diff --git a/packages/firebase_core/firebase_core/example/windows/runner/win32_window.cpp b/packages/firebase_core/firebase_core/example/windows/runner/win32_window.cpp index 041a38554745..9a7ec8a90036 100644 --- a/packages/firebase_core/firebase_core/example/windows/runner/win32_window.cpp +++ b/packages/firebase_core/firebase_core/example/windows/runner/win32_window.cpp @@ -1,3 +1,7 @@ +// Copyright 2023, the Chromium project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + #include "win32_window.h" #include diff --git a/packages/firebase_core/firebase_core/example/windows/runner/win32_window.h b/packages/firebase_core/firebase_core/example/windows/runner/win32_window.h index c86632d8a6b9..3726ca1ae1f5 100644 --- a/packages/firebase_core/firebase_core/example/windows/runner/win32_window.h +++ b/packages/firebase_core/firebase_core/example/windows/runner/win32_window.h @@ -1,3 +1,9 @@ +/* + * Copyright 2023, the Chromium project authors. Please see the AUTHORS file + * for details. All rights reserved. Use of this source code is governed by a + * BSD-style license that can be found in the LICENSE file. + */ + #ifndef RUNNER_WIN32_WINDOW_H_ #define RUNNER_WIN32_WINDOW_H_ diff --git a/packages/firebase_core/firebase_core/windows/firebase_core_plugin.cpp b/packages/firebase_core/firebase_core/windows/firebase_core_plugin.cpp index 37e9fee4e6fc..3ce88ac35ac0 100644 --- a/packages/firebase_core/firebase_core/windows/firebase_core_plugin.cpp +++ b/packages/firebase_core/firebase_core/windows/firebase_core_plugin.cpp @@ -1,3 +1,7 @@ +// Copyright 2023, the Chromium project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + #include "firebase_core_plugin.h" // This must be included before many other Windows headers. diff --git a/packages/firebase_core/firebase_core/windows/firebase_core_plugin.h b/packages/firebase_core/firebase_core/windows/firebase_core_plugin.h index 12161246ec4d..e20c84d5f9ef 100644 --- a/packages/firebase_core/firebase_core/windows/firebase_core_plugin.h +++ b/packages/firebase_core/firebase_core/windows/firebase_core_plugin.h @@ -1,3 +1,9 @@ +/* + * Copyright 2023, the Chromium project authors. Please see the AUTHORS file + * for details. All rights reserved. Use of this source code is governed by a + * BSD-style license that can be found in the LICENSE file. + */ + #ifndef FLUTTER_PLUGIN_FIREBASE_CORE_PLUGIN_H_ #define FLUTTER_PLUGIN_FIREBASE_CORE_PLUGIN_H_ diff --git a/packages/firebase_core/firebase_core/windows/firebase_core_plugin_c_api.cpp b/packages/firebase_core/firebase_core/windows/firebase_core_plugin_c_api.cpp index 478de00182e5..fa14aed47bd9 100644 --- a/packages/firebase_core/firebase_core/windows/firebase_core_plugin_c_api.cpp +++ b/packages/firebase_core/firebase_core/windows/firebase_core_plugin_c_api.cpp @@ -1,3 +1,7 @@ +// Copyright 2023, the Chromium project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + #include "include/firebase_core/firebase_core_plugin_c_api.h" #include diff --git a/packages/firebase_core/firebase_core/windows/include/firebase_core/firebase_core_plugin_c_api.h b/packages/firebase_core/firebase_core/windows/include/firebase_core/firebase_core_plugin_c_api.h index 4ef141db19bd..3f0d51a62c38 100644 --- a/packages/firebase_core/firebase_core/windows/include/firebase_core/firebase_core_plugin_c_api.h +++ b/packages/firebase_core/firebase_core/windows/include/firebase_core/firebase_core_plugin_c_api.h @@ -1,3 +1,9 @@ +/* + * Copyright 2023, the Chromium project authors. Please see the AUTHORS file + * for details. All rights reserved. Use of this source code is governed by a + * BSD-style license that can be found in the LICENSE file. + */ + #ifndef FLUTTER_PLUGIN_FIREBASE_CORE_PLUGIN_C_API_H_ #define FLUTTER_PLUGIN_FIREBASE_CORE_PLUGIN_C_API_H_ From d90af0d08c5f7153874874940cb8c950456475a7 Mon Sep 17 00:00:00 2001 From: Guillaume Bernos Date: Tue, 21 Mar 2023 10:42:20 +0100 Subject: [PATCH 45/65] format --- .../example/windows/runner/flutter_window.cpp | 4 +- .../example/windows/runner/main.cpp | 3 +- .../example/windows/runner/resource.h | 10 ++--- .../example/windows/runner/utils.cpp | 11 +++--- .../example/windows/runner/win32_window.cpp | 38 ++++++++----------- .../example/windows/runner/win32_window.h | 6 +-- .../windows/firebase_core_plugin.h | 16 ++++---- 7 files changed, 37 insertions(+), 51 deletions(-) diff --git a/packages/firebase_core/firebase_core/example/windows/runner/flutter_window.cpp b/packages/firebase_core/firebase_core/example/windows/runner/flutter_window.cpp index 4e7e8292bfa8..227a248924bf 100644 --- a/packages/firebase_core/firebase_core/example/windows/runner/flutter_window.cpp +++ b/packages/firebase_core/firebase_core/example/windows/runner/flutter_window.cpp @@ -31,9 +31,7 @@ bool FlutterWindow::OnCreate() { RegisterPlugins(flutter_controller_->engine()); SetChildContent(flutter_controller_->view()->GetNativeWindow()); - flutter_controller_->engine()->SetNextFrameCallback([&]() { - this->Show(); - }); + flutter_controller_->engine()->SetNextFrameCallback([&]() { this->Show(); }); return true; } diff --git a/packages/firebase_core/firebase_core/example/windows/runner/main.cpp b/packages/firebase_core/firebase_core/example/windows/runner/main.cpp index 8147273feb87..aa6bf684c007 100644 --- a/packages/firebase_core/firebase_core/example/windows/runner/main.cpp +++ b/packages/firebase_core/firebase_core/example/windows/runner/main.cpp @@ -23,8 +23,7 @@ int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev, flutter::DartProject project(L"data"); - std::vector command_line_arguments = - GetCommandLineArguments(); + std::vector command_line_arguments = GetCommandLineArguments(); project.set_dart_entrypoint_arguments(std::move(command_line_arguments)); diff --git a/packages/firebase_core/firebase_core/example/windows/runner/resource.h b/packages/firebase_core/firebase_core/example/windows/runner/resource.h index 01543b168082..3b8e4da19d6f 100644 --- a/packages/firebase_core/firebase_core/example/windows/runner/resource.h +++ b/packages/firebase_core/firebase_core/example/windows/runner/resource.h @@ -8,15 +8,15 @@ // Microsoft Visual C++ generated include file. // Used by Runner.rc // -#define IDI_APP_ICON 101 +#define IDI_APP_ICON 101 // Next default values for new objects // #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS -#define _APS_NEXT_RESOURCE_VALUE 102 -#define _APS_NEXT_COMMAND_VALUE 40001 -#define _APS_NEXT_CONTROL_VALUE 1001 -#define _APS_NEXT_SYMED_VALUE 101 +#define _APS_NEXT_RESOURCE_VALUE 102 +#define _APS_NEXT_COMMAND_VALUE 40001 +#define _APS_NEXT_CONTROL_VALUE 1001 +#define _APS_NEXT_SYMED_VALUE 101 #endif #endif diff --git a/packages/firebase_core/firebase_core/example/windows/runner/utils.cpp b/packages/firebase_core/firebase_core/example/windows/runner/utils.cpp index 7e940c4f2f46..605494e6c81c 100644 --- a/packages/firebase_core/firebase_core/example/windows/runner/utils.cpp +++ b/packages/firebase_core/firebase_core/example/windows/runner/utils.cpp @@ -13,7 +13,7 @@ void CreateAndAttachConsole() { if (::AllocConsole()) { - FILE *unused; + FILE* unused; if (freopen_s(&unused, "CONOUT$", "w", stdout)) { _dup2(_fileno(stdout), 1); } @@ -49,17 +49,16 @@ std::string Utf8FromUtf16(const wchar_t* utf16_string) { if (utf16_string == nullptr) { return std::string(); } - int target_length = ::WideCharToMultiByte( - CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, - -1, nullptr, 0, nullptr, nullptr); + int target_length = + ::WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, -1, + nullptr, 0, nullptr, nullptr); std::string utf8_string; if (target_length == 0 || target_length > utf8_string.max_size()) { return utf8_string; } utf8_string.resize(target_length); int converted_length = ::WideCharToMultiByte( - CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, - -1, utf8_string.data(), + CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, -1, utf8_string.data(), target_length, nullptr, nullptr); if (converted_length == 0) { return std::string(); diff --git a/packages/firebase_core/firebase_core/example/windows/runner/win32_window.cpp b/packages/firebase_core/firebase_core/example/windows/runner/win32_window.cpp index 9a7ec8a90036..2d3709236bd4 100644 --- a/packages/firebase_core/firebase_core/example/windows/runner/win32_window.cpp +++ b/packages/firebase_core/firebase_core/example/windows/runner/win32_window.cpp @@ -15,7 +15,8 @@ namespace { /// /// Redefined in case the developer's machine has a Windows SDK older than /// version 10.0.22000.0. -/// See: https://docs.microsoft.com/windows/win32/api/dwmapi/ne-dwmapi-dwmwindowattribute +/// See: +/// https://docs.microsoft.com/windows/win32/api/dwmapi/ne-dwmapi-dwmwindowattribute #ifndef DWMWA_USE_IMMERSIVE_DARK_MODE #define DWMWA_USE_IMMERSIVE_DARK_MODE 20 #endif @@ -27,8 +28,9 @@ constexpr const wchar_t kWindowClassName[] = L"FLUTTER_RUNNER_WIN32_WINDOW"; /// A value of 0 indicates apps should use dark mode. A non-zero or missing /// value indicates apps should use light mode. constexpr const wchar_t kGetPreferredBrightnessRegKey[] = - L"Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize"; -constexpr const wchar_t kGetPreferredBrightnessRegValue[] = L"AppsUseLightTheme"; + L"Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize"; +constexpr const wchar_t kGetPreferredBrightnessRegValue[] = + L"AppsUseLightTheme"; // The number of Win32Window objects that currently exist. static int g_active_window_count = 0; @@ -115,17 +117,14 @@ void WindowClassRegistrar::UnregisterWindowClass() { class_registered_ = false; } -Win32Window::Win32Window() { - ++g_active_window_count; -} +Win32Window::Win32Window() { ++g_active_window_count; } Win32Window::~Win32Window() { --g_active_window_count; Destroy(); } -bool Win32Window::Create(const std::wstring& title, - const Point& origin, +bool Win32Window::Create(const std::wstring& title, const Point& origin, const Size& size) { Destroy(); @@ -153,13 +152,10 @@ bool Win32Window::Create(const std::wstring& title, return OnCreate(); } -bool Win32Window::Show() { - return ShowWindow(window_handle_, SW_SHOWNORMAL); -} +bool Win32Window::Show() { return ShowWindow(window_handle_, SW_SHOWNORMAL); } // static -LRESULT CALLBACK Win32Window::WndProc(HWND const window, - UINT const message, +LRESULT CALLBACK Win32Window::WndProc(HWND const window, UINT const message, WPARAM const wparam, LPARAM const lparam) noexcept { if (message == WM_NCCREATE) { @@ -178,9 +174,7 @@ LRESULT CALLBACK Win32Window::WndProc(HWND const window, } LRESULT -Win32Window::MessageHandler(HWND hwnd, - UINT const message, - WPARAM const wparam, +Win32Window::MessageHandler(HWND hwnd, UINT const message, WPARAM const wparam, LPARAM const lparam) noexcept { switch (message) { case WM_DESTROY: @@ -259,9 +253,7 @@ RECT Win32Window::GetClientArea() { return frame; } -HWND Win32Window::GetHandle() { - return window_handle_; -} +HWND Win32Window::GetHandle() { return window_handle_; } void Win32Window::SetQuitOnClose(bool quit_on_close) { quit_on_close_ = quit_on_close; @@ -279,10 +271,10 @@ void Win32Window::OnDestroy() { void Win32Window::UpdateTheme(HWND const window) { DWORD light_mode; DWORD light_mode_size = sizeof(light_mode); - LSTATUS result = RegGetValue(HKEY_CURRENT_USER, kGetPreferredBrightnessRegKey, - kGetPreferredBrightnessRegValue, - RRF_RT_REG_DWORD, nullptr, &light_mode, - &light_mode_size); + LSTATUS result = + RegGetValue(HKEY_CURRENT_USER, kGetPreferredBrightnessRegKey, + kGetPreferredBrightnessRegValue, RRF_RT_REG_DWORD, nullptr, + &light_mode, &light_mode_size); if (result == ERROR_SUCCESS) { BOOL enable_dark_mode = light_mode == 0; diff --git a/packages/firebase_core/firebase_core/example/windows/runner/win32_window.h b/packages/firebase_core/firebase_core/example/windows/runner/win32_window.h index 3726ca1ae1f5..4e15bbde1058 100644 --- a/packages/firebase_core/firebase_core/example/windows/runner/win32_window.h +++ b/packages/firebase_core/firebase_core/example/windows/runner/win32_window.h @@ -65,8 +65,7 @@ class Win32Window { // Processes and route salient window messages for mouse handling, // size change and DPI. Delegates handling of these to member overloads that // inheriting classes can handle. - virtual LRESULT MessageHandler(HWND window, - UINT const message, + virtual LRESULT MessageHandler(HWND window, UINT const message, WPARAM const wparam, LPARAM const lparam) noexcept; @@ -85,8 +84,7 @@ class Win32Window { // non-client DPI scaling so that the non-client area automatically // responsponds to changes in DPI. All other messages are handled by // MessageHandler. - static LRESULT CALLBACK WndProc(HWND const window, - UINT const message, + static LRESULT CALLBACK WndProc(HWND const window, UINT const message, WPARAM const wparam, LPARAM const lparam) noexcept; diff --git a/packages/firebase_core/firebase_core/windows/firebase_core_plugin.h b/packages/firebase_core/firebase_core/windows/firebase_core_plugin.h index e20c84d5f9ef..a1f43ad21491 100644 --- a/packages/firebase_core/firebase_core/windows/firebase_core_plugin.h +++ b/packages/firebase_core/firebase_core/windows/firebase_core_plugin.h @@ -11,11 +11,14 @@ #include #include + #include "messages.g.h" namespace firebase_core_windows { -class FirebaseCorePlugin : public flutter::Plugin, public FirebaseCoreHostApi, public FirebaseAppHostApi { +class FirebaseCorePlugin : public flutter::Plugin, + public FirebaseCoreHostApi, + public FirebaseAppHostApi { public: static void RegisterWithRegistrar(flutter::PluginRegistrarWindows *registrar); @@ -27,12 +30,12 @@ class FirebaseCorePlugin : public flutter::Plugin, public FirebaseCoreHostApi, p FirebaseCorePlugin(const FirebaseCorePlugin &) = delete; FirebaseCorePlugin &operator=(const FirebaseCorePlugin &) = delete; - // FirebaseCoreHostApi virtual void InitializeApp( const std::string &app_name, const PigeonFirebaseOptions &initialize_app_request, - std::function reply)> result) override; + std::function reply)> result) + override; virtual void InitializeCore( std::function reply)> result) override; @@ -40,7 +43,6 @@ class FirebaseCorePlugin : public flutter::Plugin, public FirebaseCoreHostApi, p std::function reply)> result) override; - // FirebaseAppHostApi virtual void SetAutomaticDataCollectionEnabled( const std::string &app_name, bool enabled, @@ -52,12 +54,10 @@ class FirebaseCorePlugin : public flutter::Plugin, public FirebaseCoreHostApi, p const std::string &app_name, std::function reply)> result) override; - - -private: + private: bool coreInitialized = false; }; -} // namespace firebase_core +} // namespace firebase_core_windows #endif // FLUTTER_PLUGIN_FIREBASE_CORE_PLUGIN_H_ From cac387a2db06f1527be35e3f2e66680da95a3cde Mon Sep 17 00:00:00 2001 From: Guillaume Bernos Date: Tue, 21 Mar 2023 11:53:30 +0100 Subject: [PATCH 46/65] format --- packages/firebase_core/firebase_core/ios/Classes/messages.g.m | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/packages/firebase_core/firebase_core/ios/Classes/messages.g.m b/packages/firebase_core/firebase_core/ios/Classes/messages.g.m index 7d9fe2a2cee5..bc34b09524b1 100644 --- a/packages/firebase_core/firebase_core/ios/Classes/messages.g.m +++ b/packages/firebase_core/firebase_core/ios/Classes/messages.g.m @@ -5,7 +5,11 @@ // See also: https://pub.dev/packages/pigeon #import "messages.g.h" +#if TARGET_OS_OSX +#import +#else #import +#endif #if !__has_feature(objc_arc) #error File requires ARC to be enabled. From 883cc1264f168acd2928588f5582d4d7d6f9df89 Mon Sep 17 00:00:00 2001 From: Guillaume Bernos Date: Tue, 21 Mar 2023 15:10:00 +0100 Subject: [PATCH 47/65] formatting ui --- .../example/windows/flutter/generated_plugin_registrant.cc | 3 +++ .../example/windows/flutter/generated_plugins.cmake | 1 + .../example/windows/flutter/generated_plugin_registrant.cc | 3 +++ .../example/windows/flutter/generated_plugins.cmake | 1 + 4 files changed, 8 insertions(+) diff --git a/packages/firebase_ui_auth/example/windows/flutter/generated_plugin_registrant.cc b/packages/firebase_ui_auth/example/windows/flutter/generated_plugin_registrant.cc index 45e2647eb8a9..d71cf017823a 100644 --- a/packages/firebase_ui_auth/example/windows/flutter/generated_plugin_registrant.cc +++ b/packages/firebase_ui_auth/example/windows/flutter/generated_plugin_registrant.cc @@ -7,8 +7,11 @@ #include "generated_plugin_registrant.h" #include +#include void RegisterPlugins(flutter::PluginRegistry* registry) { DesktopWebviewAuthPluginRegisterWithRegistrar( registry->GetRegistrarForPlugin("DesktopWebviewAuthPlugin")); + FirebaseCorePluginCApiRegisterWithRegistrar( + registry->GetRegistrarForPlugin("FirebaseCorePluginCApi")); } diff --git a/packages/firebase_ui_auth/example/windows/flutter/generated_plugins.cmake b/packages/firebase_ui_auth/example/windows/flutter/generated_plugins.cmake index 67972319482d..e34ce28a5b68 100644 --- a/packages/firebase_ui_auth/example/windows/flutter/generated_plugins.cmake +++ b/packages/firebase_ui_auth/example/windows/flutter/generated_plugins.cmake @@ -4,6 +4,7 @@ list(APPEND FLUTTER_PLUGIN_LIST desktop_webview_auth + firebase_core ) list(APPEND FLUTTER_FFI_PLUGIN_LIST diff --git a/packages/firebase_ui_oauth/example/windows/flutter/generated_plugin_registrant.cc b/packages/firebase_ui_oauth/example/windows/flutter/generated_plugin_registrant.cc index 45e2647eb8a9..d71cf017823a 100644 --- a/packages/firebase_ui_oauth/example/windows/flutter/generated_plugin_registrant.cc +++ b/packages/firebase_ui_oauth/example/windows/flutter/generated_plugin_registrant.cc @@ -7,8 +7,11 @@ #include "generated_plugin_registrant.h" #include +#include void RegisterPlugins(flutter::PluginRegistry* registry) { DesktopWebviewAuthPluginRegisterWithRegistrar( registry->GetRegistrarForPlugin("DesktopWebviewAuthPlugin")); + FirebaseCorePluginCApiRegisterWithRegistrar( + registry->GetRegistrarForPlugin("FirebaseCorePluginCApi")); } diff --git a/packages/firebase_ui_oauth/example/windows/flutter/generated_plugins.cmake b/packages/firebase_ui_oauth/example/windows/flutter/generated_plugins.cmake index 67972319482d..e34ce28a5b68 100644 --- a/packages/firebase_ui_oauth/example/windows/flutter/generated_plugins.cmake +++ b/packages/firebase_ui_oauth/example/windows/flutter/generated_plugins.cmake @@ -4,6 +4,7 @@ list(APPEND FLUTTER_PLUGIN_LIST desktop_webview_auth + firebase_core ) list(APPEND FLUTTER_FFI_PLUGIN_LIST From e59e24168d763824430853a392734d580bbdb452 Mon Sep 17 00:00:00 2001 From: Guillaume Bernos Date: Tue, 21 Mar 2023 15:10:42 +0100 Subject: [PATCH 48/65] formatting ui --- .../example/windows/flutter/generated_plugin_registrant.cc | 3 +++ .../example/windows/flutter/generated_plugins.cmake | 1 + 2 files changed, 4 insertions(+) diff --git a/packages/firebase_ui_localizations/example/windows/flutter/generated_plugin_registrant.cc b/packages/firebase_ui_localizations/example/windows/flutter/generated_plugin_registrant.cc index 45e2647eb8a9..d71cf017823a 100644 --- a/packages/firebase_ui_localizations/example/windows/flutter/generated_plugin_registrant.cc +++ b/packages/firebase_ui_localizations/example/windows/flutter/generated_plugin_registrant.cc @@ -7,8 +7,11 @@ #include "generated_plugin_registrant.h" #include +#include void RegisterPlugins(flutter::PluginRegistry* registry) { DesktopWebviewAuthPluginRegisterWithRegistrar( registry->GetRegistrarForPlugin("DesktopWebviewAuthPlugin")); + FirebaseCorePluginCApiRegisterWithRegistrar( + registry->GetRegistrarForPlugin("FirebaseCorePluginCApi")); } diff --git a/packages/firebase_ui_localizations/example/windows/flutter/generated_plugins.cmake b/packages/firebase_ui_localizations/example/windows/flutter/generated_plugins.cmake index 67972319482d..e34ce28a5b68 100644 --- a/packages/firebase_ui_localizations/example/windows/flutter/generated_plugins.cmake +++ b/packages/firebase_ui_localizations/example/windows/flutter/generated_plugins.cmake @@ -4,6 +4,7 @@ list(APPEND FLUTTER_PLUGIN_LIST desktop_webview_auth + firebase_core ) list(APPEND FLUTTER_FFI_PLUGIN_LIST From b4b4ee4d8c103feb3dead3b25c6215509be1c1c5 Mon Sep 17 00:00:00 2001 From: Guillaume Bernos Date: Tue, 21 Mar 2023 15:12:03 +0100 Subject: [PATCH 49/65] formatting ui --- .../example/windows/flutter/generated_plugin_registrant.cc | 3 +++ .../example/windows/flutter/generated_plugins.cmake | 1 + .../example/windows/flutter/generated_plugin_registrant.cc | 3 +++ .../example/windows/flutter/generated_plugins.cmake | 1 + 4 files changed, 8 insertions(+) diff --git a/packages/firebase_ui_database/example/windows/flutter/generated_plugin_registrant.cc b/packages/firebase_ui_database/example/windows/flutter/generated_plugin_registrant.cc index 8b6d4680af38..1a82e7d01dce 100644 --- a/packages/firebase_ui_database/example/windows/flutter/generated_plugin_registrant.cc +++ b/packages/firebase_ui_database/example/windows/flutter/generated_plugin_registrant.cc @@ -6,6 +6,9 @@ #include "generated_plugin_registrant.h" +#include void RegisterPlugins(flutter::PluginRegistry* registry) { + FirebaseCorePluginCApiRegisterWithRegistrar( + registry->GetRegistrarForPlugin("FirebaseCorePluginCApi")); } diff --git a/packages/firebase_ui_database/example/windows/flutter/generated_plugins.cmake b/packages/firebase_ui_database/example/windows/flutter/generated_plugins.cmake index b93c4c30c167..fa8a39bab15e 100644 --- a/packages/firebase_ui_database/example/windows/flutter/generated_plugins.cmake +++ b/packages/firebase_ui_database/example/windows/flutter/generated_plugins.cmake @@ -3,6 +3,7 @@ # list(APPEND FLUTTER_PLUGIN_LIST + firebase_core ) list(APPEND FLUTTER_FFI_PLUGIN_LIST diff --git a/packages/firebase_ui_firestore/example/windows/flutter/generated_plugin_registrant.cc b/packages/firebase_ui_firestore/example/windows/flutter/generated_plugin_registrant.cc index 8b6d4680af38..1a82e7d01dce 100644 --- a/packages/firebase_ui_firestore/example/windows/flutter/generated_plugin_registrant.cc +++ b/packages/firebase_ui_firestore/example/windows/flutter/generated_plugin_registrant.cc @@ -6,6 +6,9 @@ #include "generated_plugin_registrant.h" +#include void RegisterPlugins(flutter::PluginRegistry* registry) { + FirebaseCorePluginCApiRegisterWithRegistrar( + registry->GetRegistrarForPlugin("FirebaseCorePluginCApi")); } diff --git a/packages/firebase_ui_firestore/example/windows/flutter/generated_plugins.cmake b/packages/firebase_ui_firestore/example/windows/flutter/generated_plugins.cmake index b93c4c30c167..fa8a39bab15e 100644 --- a/packages/firebase_ui_firestore/example/windows/flutter/generated_plugins.cmake +++ b/packages/firebase_ui_firestore/example/windows/flutter/generated_plugins.cmake @@ -3,6 +3,7 @@ # list(APPEND FLUTTER_PLUGIN_LIST + firebase_core ) list(APPEND FLUTTER_FFI_PLUGIN_LIST From 431403363f2a071cce7ea343663a324a94c4f613 Mon Sep 17 00:00:00 2001 From: Guillaume Bernos Date: Fri, 24 Mar 2023 10:53:45 +0100 Subject: [PATCH 50/65] feat: automatically download the C++ SDK --- .../example/windows/CMakeLists.txt | 1 - .../firebase_core/windows/CMakeLists.txt | 21 +++++++++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/packages/firebase_core/firebase_core/example/windows/CMakeLists.txt b/packages/firebase_core/firebase_core/example/windows/CMakeLists.txt index 55f6cda64bf2..ddf92aa378e1 100644 --- a/packages/firebase_core/firebase_core/example/windows/CMakeLists.txt +++ b/packages/firebase_core/firebase_core/example/windows/CMakeLists.txt @@ -28,7 +28,6 @@ set(CMAKE_EXE_LINKER_FLAGS_PROFILE "${CMAKE_EXE_LINKER_FLAGS_RELEASE}") set(CMAKE_SHARED_LINKER_FLAGS_PROFILE "${CMAKE_SHARED_LINKER_FLAGS_RELEASE}") set(CMAKE_C_FLAGS_PROFILE "${CMAKE_C_FLAGS_RELEASE}") set(CMAKE_CXX_FLAGS_PROFILE "${CMAKE_CXX_FLAGS_RELEASE}") -set(FIREBASE_CPP_SDK_DIR "c:/Users/guill/Downloads/firebase_cpp_sdk_10.5.0/firebase_cpp_sdk") # Use Unicode for all projects. add_definitions(-DUNICODE -D_UNICODE) diff --git a/packages/firebase_core/firebase_core/windows/CMakeLists.txt b/packages/firebase_core/firebase_core/windows/CMakeLists.txt index efe90b40d4d1..a894a7e05b1b 100644 --- a/packages/firebase_core/firebase_core/windows/CMakeLists.txt +++ b/packages/firebase_core/firebase_core/windows/CMakeLists.txt @@ -4,6 +4,27 @@ # customers of the plugin. cmake_minimum_required(VERSION 3.14) +include(ExternalProject) +# Setup the Firebase C++ SDK locally +set(FIREBASE_SDK_VERSION "10.6.0") # Replace with the desired version +set(FIREBASE_SDK_DOWNLOAD_URL "https://github.com/firebase/firebase-cpp-sdk/releases/download/${FIREBASE_SDK_VERSION}/firebase_cpp_sdk_${FIREBASE_SDK_VERSION}.zip") +set(FIREBASE_SDK_DOWNLOAD_DIR "${CMAKE_BINARY_DIR}/external/firebase_sdk") +set(FIREBASE_SDK_INSTALL_DIR "${CMAKE_BINARY_DIR}/firebase_sdk") +ExternalProject_Add( + firebase_cpp_sdk + URL ${FIREBASE_SDK_DOWNLOAD_URL} + DOWNLOAD_DIR ${FIREBASE_SDK_DOWNLOAD_DIR} + DOWNLOAD_NO_PROGRESS 1 + TIMEOUT 600 + LOG_DOWNLOAD 1 + PREFIX ${FIREBASE_SDK_INSTALL_DIR} + CONFIGURE_COMMAND "" # No configuration step + BUILD_COMMAND "" # No build step + INSTALL_COMMAND "" # No install step +) +set(FIREBASE_CPP_SDK_DIR "${CMAKE_BINARY_DIR}/firebase_sdk") + + # Project-level configuration. set(PROJECT_NAME "firebase_core") project(${PROJECT_NAME} LANGUAGES CXX) From 26674eb6fb986846b1940e2ff2c008133fa4b67d Mon Sep 17 00:00:00 2001 From: Guillaume Bernos Date: Thu, 13 Apr 2023 10:19:46 +0200 Subject: [PATCH 51/65] feat: auto download of the sdk --- .../example/windows/CMakeLists.txt | 1 - .../firebase_core/windows/CMakeLists.txt | 24 +++++++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/packages/firebase_core/firebase_core/example/windows/CMakeLists.txt b/packages/firebase_core/firebase_core/example/windows/CMakeLists.txt index 55f6cda64bf2..ddf92aa378e1 100644 --- a/packages/firebase_core/firebase_core/example/windows/CMakeLists.txt +++ b/packages/firebase_core/firebase_core/example/windows/CMakeLists.txt @@ -28,7 +28,6 @@ set(CMAKE_EXE_LINKER_FLAGS_PROFILE "${CMAKE_EXE_LINKER_FLAGS_RELEASE}") set(CMAKE_SHARED_LINKER_FLAGS_PROFILE "${CMAKE_SHARED_LINKER_FLAGS_RELEASE}") set(CMAKE_C_FLAGS_PROFILE "${CMAKE_C_FLAGS_RELEASE}") set(CMAKE_CXX_FLAGS_PROFILE "${CMAKE_CXX_FLAGS_RELEASE}") -set(FIREBASE_CPP_SDK_DIR "c:/Users/guill/Downloads/firebase_cpp_sdk_10.5.0/firebase_cpp_sdk") # Use Unicode for all projects. add_definitions(-DUNICODE -D_UNICODE) diff --git a/packages/firebase_core/firebase_core/windows/CMakeLists.txt b/packages/firebase_core/firebase_core/windows/CMakeLists.txt index efe90b40d4d1..e603228e14cd 100644 --- a/packages/firebase_core/firebase_core/windows/CMakeLists.txt +++ b/packages/firebase_core/firebase_core/windows/CMakeLists.txt @@ -4,6 +4,30 @@ # customers of the plugin. cmake_minimum_required(VERSION 3.14) +set(FIREBASE_SDK_VERSION "10.5.0") +set(FIREBASE_SDK_URL "https://dl.google.com/firebase/sdk/cpp/firebase_cpp_sdk_${FIREBASE_SDK_VERSION}.zip") +set(FIREBASE_SDK_FILENAME "${CMAKE_BINARY_DIR}/firebase_cpp_sdk_${FIREBASE_SDK_VERSION}.zip") +set(EXTRACTED_PATH "${CMAKE_BINARY_DIR}/extracted") + +if(NOT EXISTS ${FIREBASE_SDK_FILENAME}) + file(DOWNLOAD ${FIREBASE_SDK_URL} ${FIREBASE_SDK_FILENAME} + SHOW_PROGRESS + STATUS download_status + LOG download_log) + list(GET download_status 0 status_code) + if(NOT status_code EQUAL 0) + message(FATAL_ERROR "Download failed: ${download_log}") + endif() +endif() + +if(NOT EXISTS ${EXTRACTED_PATH}) + file(MAKE_DIRECTORY ${EXTRACTED_PATH}) + file(ARCHIVE_EXTRACT INPUT ${FIREBASE_SDK_FILENAME} + DESTINATION ${EXTRACTED_PATH}) +endif() +set(FIREBASE_CPP_SDK_DIR "${EXTRACTED_PATH}/firebase_cpp_sdk") + + # Project-level configuration. set(PROJECT_NAME "firebase_core") project(${PROJECT_NAME} LANGUAGES CXX) From 0e985b3befb016f03b992c42619114b74965b526 Mon Sep 17 00:00:00 2001 From: Guillaume Bernos Date: Thu, 13 Apr 2023 10:45:39 +0200 Subject: [PATCH 52/65] tests working --- .../example/lib/firebase_options.dart | 2 +- .../windows/firebase_core_plugin.cpp | 4 +-- tests/integration_test/e2e_test.dart | 32 ++++++++++++------- tests/lib/firebase_options.dart | 2 ++ tests/test/widget_test.dart | 30 ----------------- 5 files changed, 24 insertions(+), 46 deletions(-) delete mode 100644 tests/test/widget_test.dart diff --git a/packages/firebase_core/firebase_core/example/lib/firebase_options.dart b/packages/firebase_core/firebase_core/example/lib/firebase_options.dart index 63c4c8857ca7..58b54d65f5fa 100644 --- a/packages/firebase_core/firebase_core/example/lib/firebase_options.dart +++ b/packages/firebase_core/firebase_core/example/lib/firebase_options.dart @@ -30,7 +30,7 @@ class DefaultFirebaseOptions { return ios; case TargetPlatform.macOS: return macos; - // TODO(Lyokone): FIX + // TODO(Lyokone): Remove when FlutterFire CLI updated case TargetPlatform.windows: return android; default: diff --git a/packages/firebase_core/firebase_core/windows/firebase_core_plugin.cpp b/packages/firebase_core/firebase_core/windows/firebase_core_plugin.cpp index 3ce88ac35ac0..7e778c1a803f 100644 --- a/packages/firebase_core/firebase_core/windows/firebase_core_plugin.cpp +++ b/packages/firebase_core/firebase_core/windows/firebase_core_plugin.cpp @@ -73,9 +73,7 @@ PigeonFirebaseOptions optionsFromFIROptions( if (options.database_url() != nullptr) { pigeon_options.set_database_u_r_l(options.database_url()); } - if (options.ga_tracking_id() != nullptr) { - pigeon_options.set_tracking_id(options.ga_tracking_id()); - } + pigeon_options.set_tracking_id(nullptr); pigeon_options.set_messaging_sender_id(options.messaging_sender_id()); pigeon_options.set_project_id(options.project_id()); if (options.storage_bucket() != nullptr) { diff --git a/tests/integration_test/e2e_test.dart b/tests/integration_test/e2e_test.dart index 75e6da1fc5b5..4f8a150f6a4b 100644 --- a/tests/integration_test/e2e_test.dart +++ b/tests/integration_test/e2e_test.dart @@ -2,6 +2,9 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. +import 'dart:io'; + +import 'package:flutter/foundation.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:integration_test/integration_test.dart'; @@ -31,18 +34,23 @@ void main() { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); group('FlutterFire', () { + if (kIsWeb || !Platform.isWindows) { + firebase_core.main(); + firebase_database.main(); + firebase_crashlytics.main(); + firebase_auth.main(); + firebase_analytics.main(); + cloud_functions.main(); + firebase_app_check.main(); + firebase_app_installations.main(); + firebase_dynamic_links.main(); + firebase_messaging.main(); + firebase_ml_model_downloader.main(); + firebase_remote_config.main(); + firebase_storage.main(); + } else { + // Only tests available on Windows firebase_core.main(); - firebase_database.main(); - firebase_crashlytics.main(); - firebase_auth.main(); - firebase_analytics.main(); - cloud_functions.main(); - firebase_app_check.main(); - firebase_app_installations.main(); - firebase_dynamic_links.main(); - firebase_messaging.main(); - firebase_ml_model_downloader.main(); - firebase_remote_config.main(); - firebase_storage.main(); + } }); } diff --git a/tests/lib/firebase_options.dart b/tests/lib/firebase_options.dart index da380a3ec8bb..e032dff2be70 100644 --- a/tests/lib/firebase_options.dart +++ b/tests/lib/firebase_options.dart @@ -30,6 +30,8 @@ class DefaultFirebaseOptions { return ios; case TargetPlatform.macOS: return macos; + case TargetPlatform.windows: + return android; default: throw UnsupportedError( 'DefaultFirebaseOptions are not supported for this platform.', diff --git a/tests/test/widget_test.dart b/tests/test/widget_test.dart deleted file mode 100644 index 86b6bdf3ad0d..000000000000 --- a/tests/test/widget_test.dart +++ /dev/null @@ -1,30 +0,0 @@ -// This is a basic Flutter widget test. -// -// To perform an interaction with a widget in your test, use the WidgetTester -// utility in the flutter_test package. For example, you can send tap and scroll -// gestures. You can also use WidgetTester to find child widgets in the widget -// tree, read text, and verify that the values of widget properties are correct. - -import 'package:flutter/material.dart'; -import 'package:flutter_test/flutter_test.dart'; - -import 'package:tests/main.dart'; - -void main() { - testWidgets('Counter increments smoke test', (WidgetTester tester) async { - // Build our app and trigger a frame. - await tester.pumpWidget(const MyApp()); - - // Verify that our counter starts at 0. - expect(find.text('0'), findsOneWidget); - expect(find.text('1'), findsNothing); - - // Tap the '+' icon and trigger a frame. - await tester.tap(find.byIcon(Icons.add)); - await tester.pump(); - - // Verify that our counter has incremented. - expect(find.text('0'), findsNothing); - expect(find.text('1'), findsOneWidget); - }); -} From bec139fc69f849ed91741e7146f94aed9fd6718c Mon Sep 17 00:00:00 2001 From: Guillaume Bernos Date: Thu, 13 Apr 2023 10:56:14 +0200 Subject: [PATCH 53/65] ci: windows ci --- .github/workflows/e2e_tests.yaml | 39 ++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/.github/workflows/e2e_tests.yaml b/.github/workflows/e2e_tests.yaml index 099fd8230a62..846a0e0b10d6 100644 --- a/.github/workflows/e2e_tests.yaml +++ b/.github/workflows/e2e_tests.yaml @@ -297,3 +297,42 @@ jobs: --driver=test_driver/integration_test.dart \ --target=integration_test/e2e_test.dart \ --dart-define=CI=true + + windows: + runs-on: windows-latest + timeout-minutes: 45 + steps: + - uses: actions/checkout@ac593985615ec2ede58e132d2e21d2b1cbd6127c + - uses: actions/setup-node@64ed1c7eab4cce3362f8c340dee64e5eaeef8f7c + name: Install Node.js 16 + with: + node-version: "16" + - uses: subosito/flutter-action@dbf1fa04f4d2e52c33185153d06cdb5443aa189d + with: + channel: 'stable' + cache: true + - uses: bluefireteam/melos-action@dd3c344d731938d2ab2567a261f54a19a68b5f6a + with: + run-bootstrap: false + melos-version: '3.0.0' + - name: "Bootstrap package" + run: melos bootstrap --scope tests + - name: "Install Tools" + run: | + sudo npm i -g firebase-tools + - name: Cache Firebase Emulator + uses: actions/cache@69d9d449aced6a2ede0bc19182fadc3a0a42d2b0 + with: + path: ~/.cache/firebase/emulators + key: firebase-emulators-v1-${{ github.run_id }} + restore-keys: firebase-emulators-v1 + - name: Start Firebase Emulator + run: cd ./.github/workflows/scripts && ./start-firebase-emulator.sh + - name: "E2E Tests" + working-directory: tests + # Web devices are not supported for the `flutter test` command yet. As a + # workaround we can use the `flutter drive` command. Tracking issue: + # https://github.com/flutter/flutter/issues/66264 + run: | + chromedriver --port=4444 & + flutter test .\integration_test\e2e_test.dart -d windows From 2ae5a1196c83b5ae8a2197c1d88a695934f6b25d Mon Sep 17 00:00:00 2001 From: Guillaume Bernos Date: Thu, 13 Apr 2023 11:00:53 +0200 Subject: [PATCH 54/65] ci: windows --- .github/workflows/e2e_tests.yaml | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/.github/workflows/e2e_tests.yaml b/.github/workflows/e2e_tests.yaml index 846a0e0b10d6..632269a1197b 100644 --- a/.github/workflows/e2e_tests.yaml +++ b/.github/workflows/e2e_tests.yaml @@ -319,13 +319,7 @@ jobs: run: melos bootstrap --scope tests - name: "Install Tools" run: | - sudo npm i -g firebase-tools - - name: Cache Firebase Emulator - uses: actions/cache@69d9d449aced6a2ede0bc19182fadc3a0a42d2b0 - with: - path: ~/.cache/firebase/emulators - key: firebase-emulators-v1-${{ github.run_id }} - restore-keys: firebase-emulators-v1 + npm install -g firebase-tools - name: Start Firebase Emulator run: cd ./.github/workflows/scripts && ./start-firebase-emulator.sh - name: "E2E Tests" From 13a78b01d615cc240f7d1a7507cc7ed24e6ead70 Mon Sep 17 00:00:00 2001 From: Guillaume Bernos Date: Thu, 13 Apr 2023 11:08:06 +0200 Subject: [PATCH 55/65] ci: tests --- .github/workflows/e2e_tests.yaml | 1 - 1 file changed, 1 deletion(-) diff --git a/.github/workflows/e2e_tests.yaml b/.github/workflows/e2e_tests.yaml index 632269a1197b..f485982682ba 100644 --- a/.github/workflows/e2e_tests.yaml +++ b/.github/workflows/e2e_tests.yaml @@ -328,5 +328,4 @@ jobs: # workaround we can use the `flutter drive` command. Tracking issue: # https://github.com/flutter/flutter/issues/66264 run: | - chromedriver --port=4444 & flutter test .\integration_test\e2e_test.dart -d windows From 7852dd8960c98339579516376a0e46f27623dc64 Mon Sep 17 00:00:00 2001 From: Guillaume Bernos Date: Thu, 13 Apr 2023 11:28:24 +0200 Subject: [PATCH 56/65] remove old desktop service files --- .../example/google-services-desktop.json | 37 ------------------- .../runner/google-services-desktop.json | 37 ------------------- 2 files changed, 74 deletions(-) delete mode 100644 packages/firebase_core/firebase_core/example/google-services-desktop.json delete mode 100644 packages/firebase_core/firebase_core/example/windows/runner/google-services-desktop.json diff --git a/packages/firebase_core/firebase_core/example/google-services-desktop.json b/packages/firebase_core/firebase_core/example/google-services-desktop.json deleted file mode 100644 index a3bf216f4de0..000000000000 --- a/packages/firebase_core/firebase_core/example/google-services-desktop.json +++ /dev/null @@ -1,37 +0,0 @@ -{ - "project_info": { - "project_number": "406099696497", - "firebase_url": "https://flutterfire-e2e-tests-default-rtdb.europe-west1.firebasedatabase.app", - "project_id": "flutterfire-e2e-tests", - "storage_bucket": "flutterfire-e2e-tests.appspot.com" - }, - "client": [ - { - "client_info": { - "mobilesdk_app_id": "1:406099696497:ios:58cbc26aca8e5cf83574d0", - "android_client_info": { - "package_name": "io.flutter.plugins.firebase.auth.example" - } - }, - "oauth_client": [ - { - "client_id": "406099696497-134k3722m01rtrsklhf3b7k8sqa5r7in.apps.googleusercontent.com" - } - ], - "api_key": [ - { - "current_key": "AIzaSyDooSUGSf63Ghq02_iIhtnmwMDs4HlWS6c" - } - ], - "services": { - "analytics_service": { - "status": 0 - }, - "appinvite_service": { - "status": 1 - } - } - } - ], - "configuration_version": "1" -} \ No newline at end of file diff --git a/packages/firebase_core/firebase_core/example/windows/runner/google-services-desktop.json b/packages/firebase_core/firebase_core/example/windows/runner/google-services-desktop.json deleted file mode 100644 index a3bf216f4de0..000000000000 --- a/packages/firebase_core/firebase_core/example/windows/runner/google-services-desktop.json +++ /dev/null @@ -1,37 +0,0 @@ -{ - "project_info": { - "project_number": "406099696497", - "firebase_url": "https://flutterfire-e2e-tests-default-rtdb.europe-west1.firebasedatabase.app", - "project_id": "flutterfire-e2e-tests", - "storage_bucket": "flutterfire-e2e-tests.appspot.com" - }, - "client": [ - { - "client_info": { - "mobilesdk_app_id": "1:406099696497:ios:58cbc26aca8e5cf83574d0", - "android_client_info": { - "package_name": "io.flutter.plugins.firebase.auth.example" - } - }, - "oauth_client": [ - { - "client_id": "406099696497-134k3722m01rtrsklhf3b7k8sqa5r7in.apps.googleusercontent.com" - } - ], - "api_key": [ - { - "current_key": "AIzaSyDooSUGSf63Ghq02_iIhtnmwMDs4HlWS6c" - } - ], - "services": { - "analytics_service": { - "status": 0 - }, - "appinvite_service": { - "status": 1 - } - } - } - ], - "configuration_version": "1" -} \ No newline at end of file From 913186785bb857fbbb1f2235859da4417870eab1 Mon Sep 17 00:00:00 2001 From: Guillaume Bernos Date: Thu, 13 Apr 2023 11:34:15 +0200 Subject: [PATCH 57/65] add licence --- tests/windows/runner/flutter_window.cpp | 4 ++++ tests/windows/runner/flutter_window.h | 6 ++++++ tests/windows/runner/main.cpp | 4 ++++ tests/windows/runner/resource.h | 6 ++++++ tests/windows/runner/utils.cpp | 4 ++++ tests/windows/runner/utils.h | 6 ++++++ tests/windows/runner/win32_window.cpp | 4 ++++ tests/windows/runner/win32_window.h | 6 ++++++ 8 files changed, 40 insertions(+) diff --git a/tests/windows/runner/flutter_window.cpp b/tests/windows/runner/flutter_window.cpp index b25e363efa42..4e7e8292bfa8 100644 --- a/tests/windows/runner/flutter_window.cpp +++ b/tests/windows/runner/flutter_window.cpp @@ -1,3 +1,7 @@ +// Copyright 2023, the Chromium project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + #include "flutter_window.h" #include diff --git a/tests/windows/runner/flutter_window.h b/tests/windows/runner/flutter_window.h index 6da0652f05f2..2b30f421692a 100644 --- a/tests/windows/runner/flutter_window.h +++ b/tests/windows/runner/flutter_window.h @@ -1,3 +1,9 @@ +/* + * Copyright 2023, the Chromium project authors. Please see the AUTHORS file + * for details. All rights reserved. Use of this source code is governed by a + * BSD-style license that can be found in the LICENSE file. + */ + #ifndef RUNNER_FLUTTER_WINDOW_H_ #define RUNNER_FLUTTER_WINDOW_H_ diff --git a/tests/windows/runner/main.cpp b/tests/windows/runner/main.cpp index 42934ddc610b..10ad72ca4691 100644 --- a/tests/windows/runner/main.cpp +++ b/tests/windows/runner/main.cpp @@ -1,3 +1,7 @@ +// Copyright 2023, the Chromium project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + #include #include #include diff --git a/tests/windows/runner/resource.h b/tests/windows/runner/resource.h index 66a65d1e4a79..01543b168082 100644 --- a/tests/windows/runner/resource.h +++ b/tests/windows/runner/resource.h @@ -1,3 +1,9 @@ +/* + * Copyright 2023, the Chromium project authors. Please see the AUTHORS file + * for details. All rights reserved. Use of this source code is governed by a + * BSD-style license that can be found in the LICENSE file. + */ + //{{NO_DEPENDENCIES}} // Microsoft Visual C++ generated include file. // Used by Runner.rc diff --git a/tests/windows/runner/utils.cpp b/tests/windows/runner/utils.cpp index f5bf9fa0f536..7e940c4f2f46 100644 --- a/tests/windows/runner/utils.cpp +++ b/tests/windows/runner/utils.cpp @@ -1,3 +1,7 @@ +// Copyright 2023, the Chromium project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + #include "utils.h" #include diff --git a/tests/windows/runner/utils.h b/tests/windows/runner/utils.h index 3879d5475579..67b5c48b8d3d 100644 --- a/tests/windows/runner/utils.h +++ b/tests/windows/runner/utils.h @@ -1,3 +1,9 @@ +/* + * Copyright 2023, the Chromium project authors. Please see the AUTHORS file + * for details. All rights reserved. Use of this source code is governed by a + * BSD-style license that can be found in the LICENSE file. + */ + #ifndef RUNNER_UTILS_H_ #define RUNNER_UTILS_H_ diff --git a/tests/windows/runner/win32_window.cpp b/tests/windows/runner/win32_window.cpp index 041a38554745..9a7ec8a90036 100644 --- a/tests/windows/runner/win32_window.cpp +++ b/tests/windows/runner/win32_window.cpp @@ -1,3 +1,7 @@ +// Copyright 2023, the Chromium project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + #include "win32_window.h" #include diff --git a/tests/windows/runner/win32_window.h b/tests/windows/runner/win32_window.h index c86632d8a6b9..3726ca1ae1f5 100644 --- a/tests/windows/runner/win32_window.h +++ b/tests/windows/runner/win32_window.h @@ -1,3 +1,9 @@ +/* + * Copyright 2023, the Chromium project authors. Please see the AUTHORS file + * for details. All rights reserved. Use of this source code is governed by a + * BSD-style license that can be found in the LICENSE file. + */ + #ifndef RUNNER_WIN32_WINDOW_H_ #define RUNNER_WIN32_WINDOW_H_ From 68447291342d6c5f140603a0cc6a44033cf25392 Mon Sep 17 00:00:00 2001 From: Guillaume Bernos Date: Thu, 13 Apr 2023 11:35:51 +0200 Subject: [PATCH 58/65] remove comment --- .github/workflows/e2e_tests.yaml | 3 --- 1 file changed, 3 deletions(-) diff --git a/.github/workflows/e2e_tests.yaml b/.github/workflows/e2e_tests.yaml index f485982682ba..9e5d2d4b2ccb 100644 --- a/.github/workflows/e2e_tests.yaml +++ b/.github/workflows/e2e_tests.yaml @@ -324,8 +324,5 @@ jobs: run: cd ./.github/workflows/scripts && ./start-firebase-emulator.sh - name: "E2E Tests" working-directory: tests - # Web devices are not supported for the `flutter test` command yet. As a - # workaround we can use the `flutter drive` command. Tracking issue: - # https://github.com/flutter/flutter/issues/66264 run: | flutter test .\integration_test\e2e_test.dart -d windows From f138fadd538e3d5cd5481f61a9f6a704e0af1367 Mon Sep 17 00:00:00 2001 From: Guillaume Bernos Date: Thu, 13 Apr 2023 11:47:04 +0200 Subject: [PATCH 59/65] remove file --- tests/analysis_options.yaml | 29 ----------------------------- 1 file changed, 29 deletions(-) delete mode 100644 tests/analysis_options.yaml diff --git a/tests/analysis_options.yaml b/tests/analysis_options.yaml deleted file mode 100644 index 61b6c4de17c9..000000000000 --- a/tests/analysis_options.yaml +++ /dev/null @@ -1,29 +0,0 @@ -# This file configures the analyzer, which statically analyzes Dart code to -# check for errors, warnings, and lints. -# -# The issues identified by the analyzer are surfaced in the UI of Dart-enabled -# IDEs (https://dart.dev/tools#ides-and-editors). The analyzer can also be -# invoked from the command line by running `flutter analyze`. - -# The following line activates a set of recommended lints for Flutter apps, -# packages, and plugins designed to encourage good coding practices. -include: package:flutter_lints/flutter.yaml - -linter: - # The lint rules applied to this project can be customized in the - # section below to disable rules from the `package:flutter_lints/flutter.yaml` - # included above or to enable additional rules. A list of all available lints - # and their documentation is published at - # https://dart-lang.github.io/linter/lints/index.html. - # - # Instead of disabling a lint rule for the entire project in the - # section below, it can also be suppressed for a single line of code - # or a specific dart file by using the `// ignore: name_of_lint` and - # `// ignore_for_file: name_of_lint` syntax on the line or in the file - # producing the lint. - rules: - # avoid_print: false # Uncomment to disable the `avoid_print` rule - # prefer_single_quotes: true # Uncomment to enable the `prefer_single_quotes` rule - -# Additional information about this file can be found at -# https://dart.dev/guides/language/analysis-options From 773bcf2c250d13cddd21ade661dedc0fc802634a Mon Sep 17 00:00:00 2001 From: Cynthia J Date: Wed, 17 May 2023 14:37:43 -0700 Subject: [PATCH 60/65] init commit for remote_config windows --- .vscode/settings.json | 14 +- .../firebase_core/windows/CMakeLists.txt | 2 +- .../windows/firebase_core_plugin.cpp | 23 +- .../GeneratedAndroidFirebaseRemoteConfig.java | 719 ++++++++++++++++++ .../firebase_remote_config/example/.gitignore | 44 ++ .../firebase_remote_config/example/.metadata | 28 +- .../example/lib/firebase_options.dart | 9 +- .../example/test/widget_test.dart | 30 + .../example/windows/.gitignore | 17 + .../example/windows/CMakeLists.txt | 101 +++ .../example/windows/flutter/CMakeLists.txt | 104 +++ .../flutter/generated_plugin_registrant.cc | 17 + .../flutter/generated_plugin_registrant.h | 15 + .../windows/flutter/generated_plugins.cmake | 25 + .../example/windows/runner/CMakeLists.txt | 40 + .../example/windows/runner/Runner.rc | 121 +++ .../example/windows/runner/flutter_window.cpp | 66 ++ .../example/windows/runner/flutter_window.h | 33 + .../example/windows/runner/main.cpp | 43 ++ .../example/windows/runner/resource.h | 16 + .../windows/runner/resources/app_icon.ico | Bin 0 -> 33772 bytes .../windows/runner/runner.exe.manifest | 20 + .../example/windows/runner/utils.cpp | 64 ++ .../example/windows/runner/utils.h | 19 + .../example/windows/runner/win32_window.cpp | 288 +++++++ .../example/windows/runner/win32_window.h | 102 +++ .../ios/Classes/messages.g.h | 95 +++ .../ios/Classes/messages.g.m | 416 ++++++++++ .../lib/src/firebase_remote_config.dart | 10 +- .../firebase_remote_config/pubspec.yaml | 2 + .../windows/CMakeLists.txt | 69 ++ .../windows/firebase_remote_config_plugin.cpp | 184 +++++ .../windows/firebase_remote_config_plugin.h | 74 ++ .../firebase_remote_config_plugin_c_api.cpp | 16 + .../firebase_remote_config_plugin_c_api.h | 29 + .../windows/messages.g.cpp | 622 +++++++++++++++ .../windows/messages.g.h | 245 ++++++ ...method_channel_firebase_remote_config.dart | 217 +++++- .../lib/src/pigeon/messages.pigeon.dart | 460 +++++++++++ .../lib/src/pigeon/test_api.dart | 328 ++++++++ ...form_interface_firebase_remote_config.dart | 40 +- .../pigeons/copyright.txt | 3 + .../pigeons/messages.dart | 135 ++++ .../pubspec.yaml | 1 + .../run_pigeon.sh | 9 + 45 files changed, 4862 insertions(+), 53 deletions(-) create mode 100644 packages/firebase_remote_config/firebase_remote_config/android/src/main/java/io/flutter/plugins/firebase/firebaseremoteconfig/GeneratedAndroidFirebaseRemoteConfig.java create mode 100644 packages/firebase_remote_config/firebase_remote_config/example/.gitignore create mode 100644 packages/firebase_remote_config/firebase_remote_config/example/test/widget_test.dart create mode 100644 packages/firebase_remote_config/firebase_remote_config/example/windows/.gitignore create mode 100644 packages/firebase_remote_config/firebase_remote_config/example/windows/CMakeLists.txt create mode 100644 packages/firebase_remote_config/firebase_remote_config/example/windows/flutter/CMakeLists.txt create mode 100644 packages/firebase_remote_config/firebase_remote_config/example/windows/flutter/generated_plugin_registrant.cc create mode 100644 packages/firebase_remote_config/firebase_remote_config/example/windows/flutter/generated_plugin_registrant.h create mode 100644 packages/firebase_remote_config/firebase_remote_config/example/windows/flutter/generated_plugins.cmake create mode 100644 packages/firebase_remote_config/firebase_remote_config/example/windows/runner/CMakeLists.txt create mode 100644 packages/firebase_remote_config/firebase_remote_config/example/windows/runner/Runner.rc create mode 100644 packages/firebase_remote_config/firebase_remote_config/example/windows/runner/flutter_window.cpp create mode 100644 packages/firebase_remote_config/firebase_remote_config/example/windows/runner/flutter_window.h create mode 100644 packages/firebase_remote_config/firebase_remote_config/example/windows/runner/main.cpp create mode 100644 packages/firebase_remote_config/firebase_remote_config/example/windows/runner/resource.h create mode 100644 packages/firebase_remote_config/firebase_remote_config/example/windows/runner/resources/app_icon.ico create mode 100644 packages/firebase_remote_config/firebase_remote_config/example/windows/runner/runner.exe.manifest create mode 100644 packages/firebase_remote_config/firebase_remote_config/example/windows/runner/utils.cpp create mode 100644 packages/firebase_remote_config/firebase_remote_config/example/windows/runner/utils.h create mode 100644 packages/firebase_remote_config/firebase_remote_config/example/windows/runner/win32_window.cpp create mode 100644 packages/firebase_remote_config/firebase_remote_config/example/windows/runner/win32_window.h create mode 100644 packages/firebase_remote_config/firebase_remote_config/ios/Classes/messages.g.h create mode 100644 packages/firebase_remote_config/firebase_remote_config/ios/Classes/messages.g.m create mode 100644 packages/firebase_remote_config/firebase_remote_config/windows/CMakeLists.txt create mode 100644 packages/firebase_remote_config/firebase_remote_config/windows/firebase_remote_config_plugin.cpp create mode 100644 packages/firebase_remote_config/firebase_remote_config/windows/firebase_remote_config_plugin.h create mode 100644 packages/firebase_remote_config/firebase_remote_config/windows/firebase_remote_config_plugin_c_api.cpp create mode 100644 packages/firebase_remote_config/firebase_remote_config/windows/include/firebase_remote_config/firebase_remote_config_plugin_c_api.h create mode 100644 packages/firebase_remote_config/firebase_remote_config/windows/messages.g.cpp create mode 100644 packages/firebase_remote_config/firebase_remote_config/windows/messages.g.h create mode 100644 packages/firebase_remote_config/firebase_remote_config_platform_interface/lib/src/pigeon/messages.pigeon.dart create mode 100644 packages/firebase_remote_config/firebase_remote_config_platform_interface/lib/src/pigeon/test_api.dart create mode 100644 packages/firebase_remote_config/firebase_remote_config_platform_interface/pigeons/copyright.txt create mode 100644 packages/firebase_remote_config/firebase_remote_config_platform_interface/pigeons/messages.dart create mode 100644 packages/firebase_remote_config/firebase_remote_config_platform_interface/run_pigeon.sh diff --git a/.vscode/settings.json b/.vscode/settings.json index 192e749674be..0fe6bfd08e49 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -1,3 +1,15 @@ { "dart.runPubGetOnPubspecChanges": "always", -} + "C_Cpp.errorSquiggles": "disabled", + "files.associations": { + "chrono": "cpp", + "functional": "cpp", + "optional": "cpp", + "system_error": "cpp", + "type_traits": "cpp", + "xlocmon": "cpp", + "xlocnum": "cpp", + "xtr1common": "cpp", + "vector": "cpp" + }, +} \ No newline at end of file diff --git a/packages/firebase_core/firebase_core/windows/CMakeLists.txt b/packages/firebase_core/firebase_core/windows/CMakeLists.txt index e603228e14cd..84b51ee185fa 100644 --- a/packages/firebase_core/firebase_core/windows/CMakeLists.txt +++ b/packages/firebase_core/firebase_core/windows/CMakeLists.txt @@ -71,7 +71,7 @@ set(MSVC_RUNTIME_MODE MD) add_subdirectory(${FIREBASE_CPP_SDK_DIR} bin/ EXCLUDE_FROM_ALL) target_include_directories(${PLUGIN_NAME} INTERFACE "${FIREBASE_CPP_SDK_DIR}/include") -set(firebase_libs firebase_auth firebase_database firebase_app) +set(firebase_libs firebase_auth firebase_database firebase_app firebase_remote_config) target_link_libraries(${PLUGIN_NAME} PRIVATE "${firebase_libs}") target_include_directories(${PLUGIN_NAME} INTERFACE diff --git a/packages/firebase_core/firebase_core/windows/firebase_core_plugin.cpp b/packages/firebase_core/firebase_core/windows/firebase_core_plugin.cpp index 7e778c1a803f..607d16dc53b7 100644 --- a/packages/firebase_core/firebase_core/windows/firebase_core_plugin.cpp +++ b/packages/firebase_core/firebase_core/windows/firebase_core_plugin.cpp @@ -8,6 +8,7 @@ #include #include "firebase/app.h" +#include "firebase/log.h" #include "messages.g.h" // For getPlatformVersion; remove unless needed for your plugin implementation. @@ -38,7 +39,10 @@ void FirebaseCorePlugin::RegisterWithRegistrar( registrar->AddPlugin(std::move(plugin)); } -FirebaseCorePlugin::FirebaseCorePlugin() {} +FirebaseCorePlugin::FirebaseCorePlugin() { + firebase::SetLogLevel(firebase::kLogLevelVerbose); + std::cout << "[C++] FirebaseCorePlugin::FirebaseCorePlugin" << std::endl; +} FirebaseCorePlugin::~FirebaseCorePlugin() = default; @@ -99,22 +103,35 @@ void FirebaseCorePlugin::InitializeApp( app = App::Create(PigeonFirebaseOptionsToAppOptions(initialize_app_request), app_name.c_str()); + std::cout << "[C++] FirebaseCorePlugin::InitializeApp:" << app_name + << std::endl; // Send back the result to Flutter result(AppToPigeonInitializeResponse(*app)); } void FirebaseCorePlugin::InitializeCore( std::function reply)> result) { + std::cout << "[C++] FirebaseCorePlugin::InitializeCore" << std::endl; // TODO: Missing function to get the list of currently initialized apps std::vector initializedApps; - flutter::EncodableList encodableList; + flutter::EncodableList encodableList = flutter::EncodableList(); + + // Hack, only add default app for now. + // App *app = App::GetInstance(); + // std::cout << "[C++] FirebaseCorePlugin::InitializeCore, after get app:" + // << std::endl; + // char *app_name = app->name(); + // std::cout << "[C++] FirebaseCorePlugin::InitializeCore, app name is:" + // app_name << std::endl; + // PigeonInitializeResponse response = AppToPigeonInitializeResponse(*app); + // encodableList.push_back(flutter::CustomEncodableValue(response)); // Insert the contents of the vector into the EncodableList // for (const auto &item : initializedApps) { // encodableList.push_back(flutter::EncodableValue(item)); //} - result(flutter::EncodableList()); + result(encodableList); } void FirebaseCorePlugin::OptionsFromResource( diff --git a/packages/firebase_remote_config/firebase_remote_config/android/src/main/java/io/flutter/plugins/firebase/firebaseremoteconfig/GeneratedAndroidFirebaseRemoteConfig.java b/packages/firebase_remote_config/firebase_remote_config/android/src/main/java/io/flutter/plugins/firebase/firebaseremoteconfig/GeneratedAndroidFirebaseRemoteConfig.java new file mode 100644 index 000000000000..447a2f21b0bc --- /dev/null +++ b/packages/firebase_remote_config/firebase_remote_config/android/src/main/java/io/flutter/plugins/firebase/firebaseremoteconfig/GeneratedAndroidFirebaseRemoteConfig.java @@ -0,0 +1,719 @@ +// Copyright 2023, the Chromium project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Autogenerated from Pigeon (v9.2.5), do not edit directly. +// See also: https://pub.dev/packages/pigeon + +package io.flutter.plugins.firebase.remoteconfig; + +import android.util.Log; +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import io.flutter.plugin.common.BasicMessageChannel; +import io.flutter.plugin.common.BinaryMessenger; +import io.flutter.plugin.common.MessageCodec; +import io.flutter.plugin.common.StandardMessageCodec; +import java.io.ByteArrayOutputStream; +import java.nio.ByteBuffer; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** Generated class from Pigeon. */ +@SuppressWarnings({"unused", "unchecked", "CodeBlock2Expr", "RedundantSuppression", "serial"}) +public class GeneratedAndroidFirebaseRemoteConfig { + + /** Error class for passing custom error details to Flutter via a thrown PlatformException. */ + public static class FlutterError extends RuntimeException { + + /** The error code. */ + public final String code; + + /** The error details. Must be a datatype supported by the api codec. */ + public final Object details; + + public FlutterError(@NonNull String code, @Nullable String message, @Nullable Object details) + { + super(message); + this.code = code; + this.details = details; + } + } + + @NonNull + protected static ArrayList wrapError(@NonNull Throwable exception) { + ArrayList errorList = new ArrayList(3); + if (exception instanceof FlutterError) { + FlutterError error = (FlutterError) exception; + errorList.add(error.code); + errorList.add(error.getMessage()); + errorList.add(error.details); + } else { + errorList.add(exception.toString()); + errorList.add(exception.getClass().getSimpleName()); + errorList.add( + "Cause: " + exception.getCause() + ", Stacktrace: " + Log.getStackTraceString(exception)); + } + return errorList; + } + + /** ValueSource defines the possible sources of a config parameter value. */ + public enum PigeonValueSource { + /** The value was defined by a static constant. */ + VALUE_STATIC(0), + /** The value was defined by default config. */ + VALUE_DEFAULT(1), + /** The value was defined by fetched config. */ + VALUE_REMOTE(2); + + final int index; + + private PigeonValueSource(final int index) { + this.index = index; + } + } + + public enum PigeonRemoteConfigFetchStatus { + /** Indicates instance has not yet attempted a fetch. */ + NO_FETCH_YET(0), + /** Indicates the last fetch attempt succeeded. */ + SUCCESS(1), + /** Indicates the last fetch attempt failed. */ + FAILURE(2), + /** Indicates the last fetch attempt was rate-limited. */ + THROTTLE(3); + + final int index; + + private PigeonRemoteConfigFetchStatus(final int index) { + this.index = index; + } + } + + /** Generated class from Pigeon that represents data sent in messages. */ + public static final class PigeonRemoteConfigSettings { + private @NonNull Long fetchTimeout; + + public @NonNull Long getFetchTimeout() { + return fetchTimeout; + } + + public void setFetchTimeout(@NonNull Long setterArg) { + if (setterArg == null) { + throw new IllegalStateException("Nonnull field \"fetchTimeout\" is null."); + } + this.fetchTimeout = setterArg; + } + + private @NonNull Long minimumFetchInterval; + + public @NonNull Long getMinimumFetchInterval() { + return minimumFetchInterval; + } + + public void setMinimumFetchInterval(@NonNull Long setterArg) { + if (setterArg == null) { + throw new IllegalStateException("Nonnull field \"minimumFetchInterval\" is null."); + } + this.minimumFetchInterval = setterArg; + } + + /** Constructor is non-public to enforce null safety; use Builder. */ + PigeonRemoteConfigSettings() {} + + public static final class Builder { + + private @Nullable Long fetchTimeout; + + public @NonNull Builder setFetchTimeout(@NonNull Long setterArg) { + this.fetchTimeout = setterArg; + return this; + } + + private @Nullable Long minimumFetchInterval; + + public @NonNull Builder setMinimumFetchInterval(@NonNull Long setterArg) { + this.minimumFetchInterval = setterArg; + return this; + } + + public @NonNull PigeonRemoteConfigSettings build() { + PigeonRemoteConfigSettings pigeonReturn = new PigeonRemoteConfigSettings(); + pigeonReturn.setFetchTimeout(fetchTimeout); + pigeonReturn.setMinimumFetchInterval(minimumFetchInterval); + return pigeonReturn; + } + } + + @NonNull + ArrayList toList() { + ArrayList toListResult = new ArrayList(2); + toListResult.add(fetchTimeout); + toListResult.add(minimumFetchInterval); + return toListResult; + } + + static @NonNull PigeonRemoteConfigSettings fromList(@NonNull ArrayList list) { + PigeonRemoteConfigSettings pigeonResult = new PigeonRemoteConfigSettings(); + Object fetchTimeout = list.get(0); + pigeonResult.setFetchTimeout((fetchTimeout == null) ? null : ((fetchTimeout instanceof Integer) ? (Integer) fetchTimeout : (Long) fetchTimeout)); + Object minimumFetchInterval = list.get(1); + pigeonResult.setMinimumFetchInterval((minimumFetchInterval == null) ? null : ((minimumFetchInterval instanceof Integer) ? (Integer) minimumFetchInterval : (Long) minimumFetchInterval)); + return pigeonResult; + } + } + + /** Generated class from Pigeon that represents data sent in messages. */ + public static final class PigeonRemoteConfigValue { + private @Nullable List value; + + public @Nullable List getValue() { + return value; + } + + public void setValue(@Nullable List setterArg) { + this.value = setterArg; + } + + /** Indicates at which source this value came from. */ + private @NonNull PigeonValueSource source; + + public @NonNull PigeonValueSource getSource() { + return source; + } + + public void setSource(@NonNull PigeonValueSource setterArg) { + if (setterArg == null) { + throw new IllegalStateException("Nonnull field \"source\" is null."); + } + this.source = setterArg; + } + + /** Constructor is non-public to enforce null safety; use Builder. */ + PigeonRemoteConfigValue() {} + + public static final class Builder { + + private @Nullable List value; + + public @NonNull Builder setValue(@Nullable List setterArg) { + this.value = setterArg; + return this; + } + + private @Nullable PigeonValueSource source; + + public @NonNull Builder setSource(@NonNull PigeonValueSource setterArg) { + this.source = setterArg; + return this; + } + + public @NonNull PigeonRemoteConfigValue build() { + PigeonRemoteConfigValue pigeonReturn = new PigeonRemoteConfigValue(); + pigeonReturn.setValue(value); + pigeonReturn.setSource(source); + return pigeonReturn; + } + } + + @NonNull + ArrayList toList() { + ArrayList toListResult = new ArrayList(2); + toListResult.add(value); + toListResult.add(source == null ? null : source.index); + return toListResult; + } + + static @NonNull PigeonRemoteConfigValue fromList(@NonNull ArrayList list) { + PigeonRemoteConfigValue pigeonResult = new PigeonRemoteConfigValue(); + Object value = list.get(0); + pigeonResult.setValue((List) value); + Object source = list.get(1); + pigeonResult.setSource(source == null ? null : PigeonValueSource.values()[(int) source]); + return pigeonResult; + } + } + + /** Generated class from Pigeon that represents data sent in messages. */ + public static final class PigeonFirebaseApp { + private @NonNull String appName; + + public @NonNull String getAppName() { + return appName; + } + + public void setAppName(@NonNull String setterArg) { + if (setterArg == null) { + throw new IllegalStateException("Nonnull field \"appName\" is null."); + } + this.appName = setterArg; + } + + private @Nullable String tenantId; + + public @Nullable String getTenantId() { + return tenantId; + } + + public void setTenantId(@Nullable String setterArg) { + this.tenantId = setterArg; + } + + /** Constructor is non-public to enforce null safety; use Builder. */ + PigeonFirebaseApp() {} + + public static final class Builder { + + private @Nullable String appName; + + public @NonNull Builder setAppName(@NonNull String setterArg) { + this.appName = setterArg; + return this; + } + + private @Nullable String tenantId; + + public @NonNull Builder setTenantId(@Nullable String setterArg) { + this.tenantId = setterArg; + return this; + } + + public @NonNull PigeonFirebaseApp build() { + PigeonFirebaseApp pigeonReturn = new PigeonFirebaseApp(); + pigeonReturn.setAppName(appName); + pigeonReturn.setTenantId(tenantId); + return pigeonReturn; + } + } + + @NonNull + ArrayList toList() { + ArrayList toListResult = new ArrayList(2); + toListResult.add(appName); + toListResult.add(tenantId); + return toListResult; + } + + static @NonNull PigeonFirebaseApp fromList(@NonNull ArrayList list) { + PigeonFirebaseApp pigeonResult = new PigeonFirebaseApp(); + Object appName = list.get(0); + pigeonResult.setAppName((String) appName); + Object tenantId = list.get(1); + pigeonResult.setTenantId((String) tenantId); + return pigeonResult; + } + } + + public interface Result { + @SuppressWarnings("UnknownNullness") + void success(T result); + + void error(@NonNull Throwable error); + } + + private static class FirebaseRemoteConfigHostApiCodec extends StandardMessageCodec { + public static final FirebaseRemoteConfigHostApiCodec INSTANCE = new FirebaseRemoteConfigHostApiCodec(); + + private FirebaseRemoteConfigHostApiCodec() {} + + @Override + protected Object readValueOfType(byte type, @NonNull ByteBuffer buffer) { + switch (type) { + case (byte) 128: + return PigeonFirebaseApp.fromList((ArrayList) readValue(buffer)); + case (byte) 129: + return PigeonRemoteConfigSettings.fromList((ArrayList) readValue(buffer)); + case (byte) 130: + return PigeonRemoteConfigValue.fromList((ArrayList) readValue(buffer)); + default: + return super.readValueOfType(type, buffer); + } + } + + @Override + protected void writeValue(@NonNull ByteArrayOutputStream stream, Object value) { + if (value instanceof PigeonFirebaseApp) { + stream.write(128); + writeValue(stream, ((PigeonFirebaseApp) value).toList()); + } else if (value instanceof PigeonRemoteConfigSettings) { + stream.write(129); + writeValue(stream, ((PigeonRemoteConfigSettings) value).toList()); + } else if (value instanceof PigeonRemoteConfigValue) { + stream.write(130); + writeValue(stream, ((PigeonRemoteConfigValue) value).toList()); + } else { + super.writeValue(stream, value); + } + } + } + + /** Generated interface from Pigeon that represents a handler of messages from Flutter. */ + public interface FirebaseRemoteConfigHostApi { + + void activate(@NonNull PigeonFirebaseApp app, @NonNull Result result); + + void ensureInitialized(@NonNull PigeonFirebaseApp app, @NonNull Result result); + + void fetch(@NonNull PigeonFirebaseApp app, @NonNull Result result); + + void fetchAndActivate(@NonNull PigeonFirebaseApp app, @NonNull Result result); + + @NonNull + Map getAll(@NonNull PigeonFirebaseApp app); + + @NonNull + Boolean getBool(@NonNull PigeonFirebaseApp app, @NonNull String key); + + @NonNull + Long getInt(@NonNull PigeonFirebaseApp app, @NonNull String key); + + @NonNull + Double getDouble(@NonNull PigeonFirebaseApp app, @NonNull String key); + + @NonNull + String getString(@NonNull PigeonFirebaseApp app, @NonNull String key); + + @NonNull + PigeonRemoteConfigValue getValue(@NonNull PigeonFirebaseApp app, @NonNull String key); + + void setConfigSettings(@NonNull PigeonFirebaseApp app, @NonNull PigeonRemoteConfigSettings remoteConfigSettings, @NonNull Result result); + + void setDefaults(@NonNull PigeonFirebaseApp app, @NonNull Map defaultParameters, @NonNull Result result); + + /** The codec used by FirebaseRemoteConfigHostApi. */ + static @NonNull MessageCodec getCodec() { + return FirebaseRemoteConfigHostApiCodec.INSTANCE; + } + /**Sets up an instance of `FirebaseRemoteConfigHostApi` to handle messages through the `binaryMessenger`. */ + static void setup(@NonNull BinaryMessenger binaryMessenger, @Nullable FirebaseRemoteConfigHostApi api) { + { + BasicMessageChannel channel = + new BasicMessageChannel<>( + binaryMessenger, "dev.flutter.pigeon.FirebaseRemoteConfigHostApi.activate", getCodec()); + if (api != null) { + channel.setMessageHandler( + (message, reply) -> { + ArrayList wrapped = new ArrayList(); + ArrayList args = (ArrayList) message; + PigeonFirebaseApp appArg = (PigeonFirebaseApp) args.get(0); + Result resultCallback = + new Result() { + public void success(Boolean result) { + wrapped.add(0, result); + reply.reply(wrapped); + } + + public void error(Throwable error) { + ArrayList wrappedError = wrapError(error); + reply.reply(wrappedError); + } + }; + + api.activate(appArg, resultCallback); + }); + } else { + channel.setMessageHandler(null); + } + } + { + BasicMessageChannel channel = + new BasicMessageChannel<>( + binaryMessenger, "dev.flutter.pigeon.FirebaseRemoteConfigHostApi.ensureInitialized", getCodec()); + if (api != null) { + channel.setMessageHandler( + (message, reply) -> { + ArrayList wrapped = new ArrayList(); + ArrayList args = (ArrayList) message; + PigeonFirebaseApp appArg = (PigeonFirebaseApp) args.get(0); + Result resultCallback = + new Result() { + public void success(Void result) { + wrapped.add(0, null); + reply.reply(wrapped); + } + + public void error(Throwable error) { + ArrayList wrappedError = wrapError(error); + reply.reply(wrappedError); + } + }; + + api.ensureInitialized(appArg, resultCallback); + }); + } else { + channel.setMessageHandler(null); + } + } + { + BasicMessageChannel channel = + new BasicMessageChannel<>( + binaryMessenger, "dev.flutter.pigeon.FirebaseRemoteConfigHostApi.fetch", getCodec()); + if (api != null) { + channel.setMessageHandler( + (message, reply) -> { + ArrayList wrapped = new ArrayList(); + ArrayList args = (ArrayList) message; + PigeonFirebaseApp appArg = (PigeonFirebaseApp) args.get(0); + Result resultCallback = + new Result() { + public void success(Void result) { + wrapped.add(0, null); + reply.reply(wrapped); + } + + public void error(Throwable error) { + ArrayList wrappedError = wrapError(error); + reply.reply(wrappedError); + } + }; + + api.fetch(appArg, resultCallback); + }); + } else { + channel.setMessageHandler(null); + } + } + { + BasicMessageChannel channel = + new BasicMessageChannel<>( + binaryMessenger, "dev.flutter.pigeon.FirebaseRemoteConfigHostApi.fetchAndActivate", getCodec()); + if (api != null) { + channel.setMessageHandler( + (message, reply) -> { + ArrayList wrapped = new ArrayList(); + ArrayList args = (ArrayList) message; + PigeonFirebaseApp appArg = (PigeonFirebaseApp) args.get(0); + Result resultCallback = + new Result() { + public void success(Boolean result) { + wrapped.add(0, result); + reply.reply(wrapped); + } + + public void error(Throwable error) { + ArrayList wrappedError = wrapError(error); + reply.reply(wrappedError); + } + }; + + api.fetchAndActivate(appArg, resultCallback); + }); + } else { + channel.setMessageHandler(null); + } + } + { + BasicMessageChannel channel = + new BasicMessageChannel<>( + binaryMessenger, "dev.flutter.pigeon.FirebaseRemoteConfigHostApi.getAll", getCodec()); + if (api != null) { + channel.setMessageHandler( + (message, reply) -> { + ArrayList wrapped = new ArrayList(); + ArrayList args = (ArrayList) message; + PigeonFirebaseApp appArg = (PigeonFirebaseApp) args.get(0); + try { + Map output = api.getAll(appArg); + wrapped.add(0, output); + } + catch (Throwable exception) { + ArrayList wrappedError = wrapError(exception); + wrapped = wrappedError; + } + reply.reply(wrapped); + }); + } else { + channel.setMessageHandler(null); + } + } + { + BasicMessageChannel channel = + new BasicMessageChannel<>( + binaryMessenger, "dev.flutter.pigeon.FirebaseRemoteConfigHostApi.getBool", getCodec()); + if (api != null) { + channel.setMessageHandler( + (message, reply) -> { + ArrayList wrapped = new ArrayList(); + ArrayList args = (ArrayList) message; + PigeonFirebaseApp appArg = (PigeonFirebaseApp) args.get(0); + String keyArg = (String) args.get(1); + try { + Boolean output = api.getBool(appArg, keyArg); + wrapped.add(0, output); + } + catch (Throwable exception) { + ArrayList wrappedError = wrapError(exception); + wrapped = wrappedError; + } + reply.reply(wrapped); + }); + } else { + channel.setMessageHandler(null); + } + } + { + BasicMessageChannel channel = + new BasicMessageChannel<>( + binaryMessenger, "dev.flutter.pigeon.FirebaseRemoteConfigHostApi.getInt", getCodec()); + if (api != null) { + channel.setMessageHandler( + (message, reply) -> { + ArrayList wrapped = new ArrayList(); + ArrayList args = (ArrayList) message; + PigeonFirebaseApp appArg = (PigeonFirebaseApp) args.get(0); + String keyArg = (String) args.get(1); + try { + Long output = api.getInt(appArg, keyArg); + wrapped.add(0, output); + } + catch (Throwable exception) { + ArrayList wrappedError = wrapError(exception); + wrapped = wrappedError; + } + reply.reply(wrapped); + }); + } else { + channel.setMessageHandler(null); + } + } + { + BasicMessageChannel channel = + new BasicMessageChannel<>( + binaryMessenger, "dev.flutter.pigeon.FirebaseRemoteConfigHostApi.getDouble", getCodec()); + if (api != null) { + channel.setMessageHandler( + (message, reply) -> { + ArrayList wrapped = new ArrayList(); + ArrayList args = (ArrayList) message; + PigeonFirebaseApp appArg = (PigeonFirebaseApp) args.get(0); + String keyArg = (String) args.get(1); + try { + Double output = api.getDouble(appArg, keyArg); + wrapped.add(0, output); + } + catch (Throwable exception) { + ArrayList wrappedError = wrapError(exception); + wrapped = wrappedError; + } + reply.reply(wrapped); + }); + } else { + channel.setMessageHandler(null); + } + } + { + BasicMessageChannel channel = + new BasicMessageChannel<>( + binaryMessenger, "dev.flutter.pigeon.FirebaseRemoteConfigHostApi.getString", getCodec()); + if (api != null) { + channel.setMessageHandler( + (message, reply) -> { + ArrayList wrapped = new ArrayList(); + ArrayList args = (ArrayList) message; + PigeonFirebaseApp appArg = (PigeonFirebaseApp) args.get(0); + String keyArg = (String) args.get(1); + try { + String output = api.getString(appArg, keyArg); + wrapped.add(0, output); + } + catch (Throwable exception) { + ArrayList wrappedError = wrapError(exception); + wrapped = wrappedError; + } + reply.reply(wrapped); + }); + } else { + channel.setMessageHandler(null); + } + } + { + BasicMessageChannel channel = + new BasicMessageChannel<>( + binaryMessenger, "dev.flutter.pigeon.FirebaseRemoteConfigHostApi.getValue", getCodec()); + if (api != null) { + channel.setMessageHandler( + (message, reply) -> { + ArrayList wrapped = new ArrayList(); + ArrayList args = (ArrayList) message; + PigeonFirebaseApp appArg = (PigeonFirebaseApp) args.get(0); + String keyArg = (String) args.get(1); + try { + PigeonRemoteConfigValue output = api.getValue(appArg, keyArg); + wrapped.add(0, output); + } + catch (Throwable exception) { + ArrayList wrappedError = wrapError(exception); + wrapped = wrappedError; + } + reply.reply(wrapped); + }); + } else { + channel.setMessageHandler(null); + } + } + { + BasicMessageChannel channel = + new BasicMessageChannel<>( + binaryMessenger, "dev.flutter.pigeon.FirebaseRemoteConfigHostApi.setConfigSettings", getCodec()); + if (api != null) { + channel.setMessageHandler( + (message, reply) -> { + ArrayList wrapped = new ArrayList(); + ArrayList args = (ArrayList) message; + PigeonFirebaseApp appArg = (PigeonFirebaseApp) args.get(0); + PigeonRemoteConfigSettings remoteConfigSettingsArg = (PigeonRemoteConfigSettings) args.get(1); + Result resultCallback = + new Result() { + public void success(Void result) { + wrapped.add(0, null); + reply.reply(wrapped); + } + + public void error(Throwable error) { + ArrayList wrappedError = wrapError(error); + reply.reply(wrappedError); + } + }; + + api.setConfigSettings(appArg, remoteConfigSettingsArg, resultCallback); + }); + } else { + channel.setMessageHandler(null); + } + } + { + BasicMessageChannel channel = + new BasicMessageChannel<>( + binaryMessenger, "dev.flutter.pigeon.FirebaseRemoteConfigHostApi.setDefaults", getCodec()); + if (api != null) { + channel.setMessageHandler( + (message, reply) -> { + ArrayList wrapped = new ArrayList(); + ArrayList args = (ArrayList) message; + PigeonFirebaseApp appArg = (PigeonFirebaseApp) args.get(0); + Map defaultParametersArg = (Map) args.get(1); + Result resultCallback = + new Result() { + public void success(Void result) { + wrapped.add(0, null); + reply.reply(wrapped); + } + + public void error(Throwable error) { + ArrayList wrappedError = wrapError(error); + reply.reply(wrappedError); + } + }; + + api.setDefaults(appArg, defaultParametersArg, resultCallback); + }); + } else { + channel.setMessageHandler(null); + } + } + } + } +} diff --git a/packages/firebase_remote_config/firebase_remote_config/example/.gitignore b/packages/firebase_remote_config/firebase_remote_config/example/.gitignore new file mode 100644 index 000000000000..24476c5d1eb5 --- /dev/null +++ b/packages/firebase_remote_config/firebase_remote_config/example/.gitignore @@ -0,0 +1,44 @@ +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.buildlog/ +.history +.svn/ +migrate_working_dir/ + +# IntelliJ related +*.iml +*.ipr +*.iws +.idea/ + +# The .vscode folder contains launch configuration and tasks you configure in +# VS Code which you may wish to be included in version control, so this line +# is commented out by default. +#.vscode/ + +# Flutter/Dart/Pub related +**/doc/api/ +**/ios/Flutter/.last_build_id +.dart_tool/ +.flutter-plugins +.flutter-plugins-dependencies +.packages +.pub-cache/ +.pub/ +/build/ + +# Symbolication related +app.*.symbols + +# Obfuscation related +app.*.map.json + +# Android Studio will place build artifacts here +/android/app/debug +/android/app/profile +/android/app/release diff --git a/packages/firebase_remote_config/firebase_remote_config/example/.metadata b/packages/firebase_remote_config/firebase_remote_config/example/.metadata index bdd1083db148..0b30307203f7 100644 --- a/packages/firebase_remote_config/firebase_remote_config/example/.metadata +++ b/packages/firebase_remote_config/firebase_remote_config/example/.metadata @@ -1,8 +1,30 @@ # This file tracks properties of this Flutter project. # Used by Flutter tool to assess capabilities and perform upgrades etc. # -# This file should be version controlled and should not be manually edited. +# This file should be version controlled. version: - revision: 538ba522eeeffb8a754ecb12b77eddac3452ed74 - channel: master + revision: 4d9e56e694b656610ab87fcf2efbcd226e0ed8cf + channel: stable + +project_type: app + +# Tracks metadata for the flutter migrate command +migration: + platforms: + - platform: root + create_revision: 4d9e56e694b656610ab87fcf2efbcd226e0ed8cf + base_revision: 4d9e56e694b656610ab87fcf2efbcd226e0ed8cf + - platform: windows + create_revision: 4d9e56e694b656610ab87fcf2efbcd226e0ed8cf + base_revision: 4d9e56e694b656610ab87fcf2efbcd226e0ed8cf + + # User provided section + + # List of Local paths (relative to this file) that should be + # ignored by the migrate tool. + # + # Files that are not part of the templates will be ignored by default. + unmanaged_files: + - 'lib/main.dart' + - 'ios/Runner.xcodeproj/project.pbxproj' diff --git a/packages/firebase_remote_config/firebase_remote_config/example/lib/firebase_options.dart b/packages/firebase_remote_config/firebase_remote_config/example/lib/firebase_options.dart index af4b4130e962..d924f779faad 100644 --- a/packages/firebase_remote_config/firebase_remote_config/example/lib/firebase_options.dart +++ b/packages/firebase_remote_config/firebase_remote_config/example/lib/firebase_options.dart @@ -31,10 +31,11 @@ class DefaultFirebaseOptions { case TargetPlatform.macOS: return macos; case TargetPlatform.windows: - throw UnsupportedError( - 'DefaultFirebaseOptions have not been configured for windows - ' - 'you can reconfigure this by running the FlutterFire CLI again.', - ); + return android; + // throw UnsupportedError( + // 'DefaultFirebaseOptions have not been configured for windows - ' + // 'you can reconfigure this by running the FlutterFire CLI again.', + // ); case TargetPlatform.linux: throw UnsupportedError( 'DefaultFirebaseOptions have not been configured for linux - ' diff --git a/packages/firebase_remote_config/firebase_remote_config/example/test/widget_test.dart b/packages/firebase_remote_config/firebase_remote_config/example/test/widget_test.dart new file mode 100644 index 000000000000..092d222f7e16 --- /dev/null +++ b/packages/firebase_remote_config/firebase_remote_config/example/test/widget_test.dart @@ -0,0 +1,30 @@ +// This is a basic Flutter widget test. +// +// To perform an interaction with a widget in your test, use the WidgetTester +// utility in the flutter_test package. For example, you can send tap and scroll +// gestures. You can also use WidgetTester to find child widgets in the widget +// tree, read text, and verify that the values of widget properties are correct. + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'package:example/main.dart'; + +void main() { + testWidgets('Counter increments smoke test', (WidgetTester tester) async { + // Build our app and trigger a frame. + await tester.pumpWidget(const MyApp()); + + // Verify that our counter starts at 0. + expect(find.text('0'), findsOneWidget); + expect(find.text('1'), findsNothing); + + // Tap the '+' icon and trigger a frame. + await tester.tap(find.byIcon(Icons.add)); + await tester.pump(); + + // Verify that our counter has incremented. + expect(find.text('0'), findsNothing); + expect(find.text('1'), findsOneWidget); + }); +} diff --git a/packages/firebase_remote_config/firebase_remote_config/example/windows/.gitignore b/packages/firebase_remote_config/firebase_remote_config/example/windows/.gitignore new file mode 100644 index 000000000000..d492d0d98c8f --- /dev/null +++ b/packages/firebase_remote_config/firebase_remote_config/example/windows/.gitignore @@ -0,0 +1,17 @@ +flutter/ephemeral/ + +# Visual Studio user-specific files. +*.suo +*.user +*.userosscache +*.sln.docstates + +# Visual Studio build-related files. +x64/ +x86/ + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!*.[Cc]ache/ diff --git a/packages/firebase_remote_config/firebase_remote_config/example/windows/CMakeLists.txt b/packages/firebase_remote_config/firebase_remote_config/example/windows/CMakeLists.txt new file mode 100644 index 000000000000..b63432b834a7 --- /dev/null +++ b/packages/firebase_remote_config/firebase_remote_config/example/windows/CMakeLists.txt @@ -0,0 +1,101 @@ +# Project-level configuration. +cmake_minimum_required(VERSION 3.14) +project(firebaes_remote_config_example LANGUAGES CXX) + +# The name of the executable created for the application. Change this to change +# the on-disk name of your application. +set(BINARY_NAME "firebase_remote_config_example") + +# Explicitly opt in to modern CMake behaviors to avoid warnings with recent +# versions of CMake. +cmake_policy(SET CMP0063 NEW) + +# Define build configuration option. +get_property(IS_MULTICONFIG GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG) +if(IS_MULTICONFIG) + set(CMAKE_CONFIGURATION_TYPES "Debug;Profile;Release" + CACHE STRING "" FORCE) +else() + if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) + set(CMAKE_BUILD_TYPE "Debug" CACHE + STRING "Flutter build mode" FORCE) + set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS + "Debug" "Profile" "Release") + endif() +endif() +# Define settings for the Profile build mode. +set(CMAKE_EXE_LINKER_FLAGS_PROFILE "${CMAKE_EXE_LINKER_FLAGS_RELEASE}") +set(CMAKE_SHARED_LINKER_FLAGS_PROFILE "${CMAKE_SHARED_LINKER_FLAGS_RELEASE}") +set(CMAKE_C_FLAGS_PROFILE "${CMAKE_C_FLAGS_RELEASE}") +set(CMAKE_CXX_FLAGS_PROFILE "${CMAKE_CXX_FLAGS_RELEASE}") + +# Use Unicode for all projects. +add_definitions(-DUNICODE -D_UNICODE) + +# Compilation settings that should be applied to most targets. +# +# Be cautious about adding new options here, as plugins use this function by +# default. In most cases, you should add new options to specific targets instead +# of modifying this function. +function(APPLY_STANDARD_SETTINGS TARGET) + target_compile_features(${TARGET} PUBLIC cxx_std_17) + target_compile_options(${TARGET} PRIVATE /W4 /WX /wd"4100") + target_compile_options(${TARGET} PRIVATE /EHsc) + target_compile_definitions(${TARGET} PRIVATE "_HAS_EXCEPTIONS=0") + target_compile_definitions(${TARGET} PRIVATE "$<$:_DEBUG>") +endfunction() + +# Flutter library and tool build rules. +set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") +add_subdirectory(${FLUTTER_MANAGED_DIR}) + +# Application build; see runner/CMakeLists.txt. +add_subdirectory("runner") + +# Generated plugin build rules, which manage building the plugins and adding +# them to the application. +include(flutter/generated_plugins.cmake) + + +# === Installation === +# Support files are copied into place next to the executable, so that it can +# run in place. This is done instead of making a separate bundle (as on Linux) +# so that building and running from within Visual Studio will work. +set(BUILD_BUNDLE_DIR "$") +# Make the "install" step default, as it's required to run. +set(CMAKE_VS_INCLUDE_INSTALL_TO_DEFAULT_BUILD 1) +if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) + set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) +endif() + +set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") +set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}") + +install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +if(PLUGIN_BUNDLED_LIBRARIES) + install(FILES "${PLUGIN_BUNDLED_LIBRARIES}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endif() + +# Fully re-copy the assets directory on each build to avoid having stale files +# from a previous install. +set(FLUTTER_ASSET_DIR_NAME "flutter_assets") +install(CODE " + file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") + " COMPONENT Runtime) +install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" + DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) + +# Install the AOT library on non-Debug builds only. +install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + CONFIGURATIONS Profile;Release + COMPONENT Runtime) diff --git a/packages/firebase_remote_config/firebase_remote_config/example/windows/flutter/CMakeLists.txt b/packages/firebase_remote_config/firebase_remote_config/example/windows/flutter/CMakeLists.txt new file mode 100644 index 000000000000..930d2071a324 --- /dev/null +++ b/packages/firebase_remote_config/firebase_remote_config/example/windows/flutter/CMakeLists.txt @@ -0,0 +1,104 @@ +# This file controls Flutter-level build steps. It should not be edited. +cmake_minimum_required(VERSION 3.14) + +set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") + +# Configuration provided via flutter tool. +include(${EPHEMERAL_DIR}/generated_config.cmake) + +# TODO: Move the rest of this into files in ephemeral. See +# https://github.com/flutter/flutter/issues/57146. +set(WRAPPER_ROOT "${EPHEMERAL_DIR}/cpp_client_wrapper") + +# === Flutter Library === +set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/flutter_windows.dll") + +# Published to parent scope for install step. +set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) +set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) +set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) +set(AOT_LIBRARY "${PROJECT_DIR}/build/windows/app.so" PARENT_SCOPE) + +list(APPEND FLUTTER_LIBRARY_HEADERS + "flutter_export.h" + "flutter_windows.h" + "flutter_messenger.h" + "flutter_plugin_registrar.h" + "flutter_texture_registrar.h" +) +list(TRANSFORM FLUTTER_LIBRARY_HEADERS PREPEND "${EPHEMERAL_DIR}/") +add_library(flutter INTERFACE) +target_include_directories(flutter INTERFACE + "${EPHEMERAL_DIR}" +) +target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}.lib") +add_dependencies(flutter flutter_assemble) + +# === Wrapper === +list(APPEND CPP_WRAPPER_SOURCES_CORE + "core_implementations.cc" + "standard_codec.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_CORE PREPEND "${WRAPPER_ROOT}/") +list(APPEND CPP_WRAPPER_SOURCES_PLUGIN + "plugin_registrar.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_PLUGIN PREPEND "${WRAPPER_ROOT}/") +list(APPEND CPP_WRAPPER_SOURCES_APP + "flutter_engine.cc" + "flutter_view_controller.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_APP PREPEND "${WRAPPER_ROOT}/") + +# Wrapper sources needed for a plugin. +add_library(flutter_wrapper_plugin STATIC + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_PLUGIN} +) +apply_standard_settings(flutter_wrapper_plugin) +set_target_properties(flutter_wrapper_plugin PROPERTIES + POSITION_INDEPENDENT_CODE ON) +set_target_properties(flutter_wrapper_plugin PROPERTIES + CXX_VISIBILITY_PRESET hidden) +target_link_libraries(flutter_wrapper_plugin PUBLIC flutter) +target_include_directories(flutter_wrapper_plugin PUBLIC + "${WRAPPER_ROOT}/include" +) +add_dependencies(flutter_wrapper_plugin flutter_assemble) + +# Wrapper sources needed for the runner. +add_library(flutter_wrapper_app STATIC + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_APP} +) +apply_standard_settings(flutter_wrapper_app) +target_link_libraries(flutter_wrapper_app PUBLIC flutter) +target_include_directories(flutter_wrapper_app PUBLIC + "${WRAPPER_ROOT}/include" +) +add_dependencies(flutter_wrapper_app flutter_assemble) + +# === Flutter tool backend === +# _phony_ is a non-existent file to force this command to run every time, +# since currently there's no way to get a full input/output list from the +# flutter tool. +set(PHONY_OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/_phony_") +set_source_files_properties("${PHONY_OUTPUT}" PROPERTIES SYMBOLIC TRUE) +add_custom_command( + OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} + ${CPP_WRAPPER_SOURCES_CORE} ${CPP_WRAPPER_SOURCES_PLUGIN} + ${CPP_WRAPPER_SOURCES_APP} + ${PHONY_OUTPUT} + COMMAND ${CMAKE_COMMAND} -E env + ${FLUTTER_TOOL_ENVIRONMENT} + "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.bat" + windows-x64 $ + VERBATIM +) +add_custom_target(flutter_assemble DEPENDS + "${FLUTTER_LIBRARY}" + ${FLUTTER_LIBRARY_HEADERS} + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_PLUGIN} + ${CPP_WRAPPER_SOURCES_APP} +) diff --git a/packages/firebase_remote_config/firebase_remote_config/example/windows/flutter/generated_plugin_registrant.cc b/packages/firebase_remote_config/firebase_remote_config/example/windows/flutter/generated_plugin_registrant.cc new file mode 100644 index 000000000000..2de46391571e --- /dev/null +++ b/packages/firebase_remote_config/firebase_remote_config/example/windows/flutter/generated_plugin_registrant.cc @@ -0,0 +1,17 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#include "generated_plugin_registrant.h" + +#include +#include + +void RegisterPlugins(flutter::PluginRegistry* registry) { + FirebaseCorePluginCApiRegisterWithRegistrar( + registry->GetRegistrarForPlugin("FirebaseCorePluginCApi")); + FirebaseRemoteConfigPluginCApiRegisterWithRegistrar( + registry->GetRegistrarForPlugin("FirebaseRemoteConfigPluginCApi")); +} diff --git a/packages/firebase_remote_config/firebase_remote_config/example/windows/flutter/generated_plugin_registrant.h b/packages/firebase_remote_config/firebase_remote_config/example/windows/flutter/generated_plugin_registrant.h new file mode 100644 index 000000000000..dc139d85a931 --- /dev/null +++ b/packages/firebase_remote_config/firebase_remote_config/example/windows/flutter/generated_plugin_registrant.h @@ -0,0 +1,15 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#ifndef GENERATED_PLUGIN_REGISTRANT_ +#define GENERATED_PLUGIN_REGISTRANT_ + +#include + +// Registers Flutter plugins. +void RegisterPlugins(flutter::PluginRegistry* registry); + +#endif // GENERATED_PLUGIN_REGISTRANT_ diff --git a/packages/firebase_remote_config/firebase_remote_config/example/windows/flutter/generated_plugins.cmake b/packages/firebase_remote_config/firebase_remote_config/example/windows/flutter/generated_plugins.cmake new file mode 100644 index 000000000000..a78d7e70f4ae --- /dev/null +++ b/packages/firebase_remote_config/firebase_remote_config/example/windows/flutter/generated_plugins.cmake @@ -0,0 +1,25 @@ +# +# Generated file, do not edit. +# + +list(APPEND FLUTTER_PLUGIN_LIST + firebase_core + firebase_remote_config +) + +list(APPEND FLUTTER_FFI_PLUGIN_LIST +) + +set(PLUGIN_BUNDLED_LIBRARIES) + +foreach(plugin ${FLUTTER_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/windows plugins/${plugin}) + target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) + list(APPEND PLUGIN_BUNDLED_LIBRARIES $) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) +endforeach(plugin) + +foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/windows plugins/${ffi_plugin}) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries}) +endforeach(ffi_plugin) diff --git a/packages/firebase_remote_config/firebase_remote_config/example/windows/runner/CMakeLists.txt b/packages/firebase_remote_config/firebase_remote_config/example/windows/runner/CMakeLists.txt new file mode 100644 index 000000000000..394917c053a0 --- /dev/null +++ b/packages/firebase_remote_config/firebase_remote_config/example/windows/runner/CMakeLists.txt @@ -0,0 +1,40 @@ +cmake_minimum_required(VERSION 3.14) +project(runner LANGUAGES CXX) + +# Define the application target. To change its name, change BINARY_NAME in the +# top-level CMakeLists.txt, not the value here, or `flutter run` will no longer +# work. +# +# Any new source files that you add to the application should be added here. +add_executable(${BINARY_NAME} WIN32 + "flutter_window.cpp" + "main.cpp" + "utils.cpp" + "win32_window.cpp" + "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" + "Runner.rc" + "runner.exe.manifest" +) + +# Apply the standard set of build settings. This can be removed for applications +# that need different build settings. +apply_standard_settings(${BINARY_NAME}) + +# Add preprocessor definitions for the build version. +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION=\"${FLUTTER_VERSION}\"") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MAJOR=${FLUTTER_VERSION_MAJOR}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MINOR=${FLUTTER_VERSION_MINOR}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_PATCH=${FLUTTER_VERSION_PATCH}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_BUILD=${FLUTTER_VERSION_BUILD}") + +# Disable Windows macros that collide with C++ standard library functions. +target_compile_definitions(${BINARY_NAME} PRIVATE "NOMINMAX") + +# Add dependency libraries and include directories. Add any application-specific +# dependencies here. +target_link_libraries(${BINARY_NAME} PRIVATE flutter flutter_wrapper_app) +target_link_libraries(${BINARY_NAME} PRIVATE "dwmapi.lib") +target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") + +# Run the Flutter tool portions of the build. This must not be removed. +add_dependencies(${BINARY_NAME} flutter_assemble) diff --git a/packages/firebase_remote_config/firebase_remote_config/example/windows/runner/Runner.rc b/packages/firebase_remote_config/firebase_remote_config/example/windows/runner/Runner.rc new file mode 100644 index 000000000000..423a96f5504a --- /dev/null +++ b/packages/firebase_remote_config/firebase_remote_config/example/windows/runner/Runner.rc @@ -0,0 +1,121 @@ +// Microsoft Visual C++ generated resource script. +// +#pragma code_page(65001) +#include "resource.h" + +#define APSTUDIO_READONLY_SYMBOLS +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 2 resource. +// +#include "winres.h" + +///////////////////////////////////////////////////////////////////////////// +#undef APSTUDIO_READONLY_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +// English (United States) resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) +LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US + +#ifdef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// TEXTINCLUDE +// + +1 TEXTINCLUDE +BEGIN + "resource.h\0" +END + +2 TEXTINCLUDE +BEGIN + "#include ""winres.h""\r\n" + "\0" +END + +3 TEXTINCLUDE +BEGIN + "\r\n" + "\0" +END + +#endif // APSTUDIO_INVOKED + + +///////////////////////////////////////////////////////////////////////////// +// +// Icon +// + +// Icon with lowest ID value placed first to ensure application icon +// remains consistent on all systems. +IDI_APP_ICON ICON "resources\\app_icon.ico" + + +///////////////////////////////////////////////////////////////////////////// +// +// Version +// + +#if defined(FLUTTER_VERSION_MAJOR) && defined(FLUTTER_VERSION_MINOR) && defined(FLUTTER_VERSION_PATCH) && defined(FLUTTER_VERSION_BUILD) +#define VERSION_AS_NUMBER FLUTTER_VERSION_MAJOR,FLUTTER_VERSION_MINOR,FLUTTER_VERSION_PATCH,FLUTTER_VERSION_BUILD +#else +#define VERSION_AS_NUMBER 1,0,0,0 +#endif + +#if defined(FLUTTER_VERSION) +#define VERSION_AS_STRING FLUTTER_VERSION +#else +#define VERSION_AS_STRING "1.0.0" +#endif + +VS_VERSION_INFO VERSIONINFO + FILEVERSION VERSION_AS_NUMBER + PRODUCTVERSION VERSION_AS_NUMBER + FILEFLAGSMASK VS_FFI_FILEFLAGSMASK +#ifdef _DEBUG + FILEFLAGS VS_FF_DEBUG +#else + FILEFLAGS 0x0L +#endif + FILEOS VOS__WINDOWS32 + FILETYPE VFT_APP + FILESUBTYPE 0x0L +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "040904e4" + BEGIN + VALUE "CompanyName", "io.flutter.plugins.firebase.remoteconfig" "\0" + VALUE "FileDescription", "example" "\0" + VALUE "FileVersion", VERSION_AS_STRING "\0" + VALUE "InternalName", "example" "\0" + VALUE "LegalCopyright", "Copyright (C) 2023 io.flutter.plugins.firebase.remoteconfig. All rights reserved." "\0" + VALUE "OriginalFilename", "example.exe" "\0" + VALUE "ProductName", "example" "\0" + VALUE "ProductVersion", VERSION_AS_STRING "\0" + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x409, 1252 + END +END + +#endif // English (United States) resources +///////////////////////////////////////////////////////////////////////////// + + + +#ifndef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 3 resource. +// + + +///////////////////////////////////////////////////////////////////////////// +#endif // not APSTUDIO_INVOKED diff --git a/packages/firebase_remote_config/firebase_remote_config/example/windows/runner/flutter_window.cpp b/packages/firebase_remote_config/firebase_remote_config/example/windows/runner/flutter_window.cpp new file mode 100644 index 000000000000..b25e363efa42 --- /dev/null +++ b/packages/firebase_remote_config/firebase_remote_config/example/windows/runner/flutter_window.cpp @@ -0,0 +1,66 @@ +#include "flutter_window.h" + +#include + +#include "flutter/generated_plugin_registrant.h" + +FlutterWindow::FlutterWindow(const flutter::DartProject& project) + : project_(project) {} + +FlutterWindow::~FlutterWindow() {} + +bool FlutterWindow::OnCreate() { + if (!Win32Window::OnCreate()) { + return false; + } + + RECT frame = GetClientArea(); + + // The size here must match the window dimensions to avoid unnecessary surface + // creation / destruction in the startup path. + flutter_controller_ = std::make_unique( + frame.right - frame.left, frame.bottom - frame.top, project_); + // Ensure that basic setup of the controller was successful. + if (!flutter_controller_->engine() || !flutter_controller_->view()) { + return false; + } + RegisterPlugins(flutter_controller_->engine()); + SetChildContent(flutter_controller_->view()->GetNativeWindow()); + + flutter_controller_->engine()->SetNextFrameCallback([&]() { + this->Show(); + }); + + return true; +} + +void FlutterWindow::OnDestroy() { + if (flutter_controller_) { + flutter_controller_ = nullptr; + } + + Win32Window::OnDestroy(); +} + +LRESULT +FlutterWindow::MessageHandler(HWND hwnd, UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + // Give Flutter, including plugins, an opportunity to handle window messages. + if (flutter_controller_) { + std::optional result = + flutter_controller_->HandleTopLevelWindowProc(hwnd, message, wparam, + lparam); + if (result) { + return *result; + } + } + + switch (message) { + case WM_FONTCHANGE: + flutter_controller_->engine()->ReloadSystemFonts(); + break; + } + + return Win32Window::MessageHandler(hwnd, message, wparam, lparam); +} diff --git a/packages/firebase_remote_config/firebase_remote_config/example/windows/runner/flutter_window.h b/packages/firebase_remote_config/firebase_remote_config/example/windows/runner/flutter_window.h new file mode 100644 index 000000000000..6da0652f05f2 --- /dev/null +++ b/packages/firebase_remote_config/firebase_remote_config/example/windows/runner/flutter_window.h @@ -0,0 +1,33 @@ +#ifndef RUNNER_FLUTTER_WINDOW_H_ +#define RUNNER_FLUTTER_WINDOW_H_ + +#include +#include + +#include + +#include "win32_window.h" + +// A window that does nothing but host a Flutter view. +class FlutterWindow : public Win32Window { + public: + // Creates a new FlutterWindow hosting a Flutter view running |project|. + explicit FlutterWindow(const flutter::DartProject& project); + virtual ~FlutterWindow(); + + protected: + // Win32Window: + bool OnCreate() override; + void OnDestroy() override; + LRESULT MessageHandler(HWND window, UINT const message, WPARAM const wparam, + LPARAM const lparam) noexcept override; + + private: + // The project to run. + flutter::DartProject project_; + + // The Flutter instance hosted by this window. + std::unique_ptr flutter_controller_; +}; + +#endif // RUNNER_FLUTTER_WINDOW_H_ diff --git a/packages/firebase_remote_config/firebase_remote_config/example/windows/runner/main.cpp b/packages/firebase_remote_config/firebase_remote_config/example/windows/runner/main.cpp new file mode 100644 index 000000000000..a61bf80d31fb --- /dev/null +++ b/packages/firebase_remote_config/firebase_remote_config/example/windows/runner/main.cpp @@ -0,0 +1,43 @@ +#include +#include +#include + +#include "flutter_window.h" +#include "utils.h" + +int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev, + _In_ wchar_t *command_line, _In_ int show_command) { + // Attach to console when present (e.g., 'flutter run') or create a + // new console when running with a debugger. + if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent()) { + CreateAndAttachConsole(); + } + + // Initialize COM, so that it is available for use in the library and/or + // plugins. + ::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED); + + flutter::DartProject project(L"data"); + + std::vector command_line_arguments = + GetCommandLineArguments(); + + project.set_dart_entrypoint_arguments(std::move(command_line_arguments)); + + FlutterWindow window(project); + Win32Window::Point origin(10, 10); + Win32Window::Size size(1280, 720); + if (!window.Create(L"example", origin, size)) { + return EXIT_FAILURE; + } + window.SetQuitOnClose(true); + + ::MSG msg; + while (::GetMessage(&msg, nullptr, 0, 0)) { + ::TranslateMessage(&msg); + ::DispatchMessage(&msg); + } + + ::CoUninitialize(); + return EXIT_SUCCESS; +} diff --git a/packages/firebase_remote_config/firebase_remote_config/example/windows/runner/resource.h b/packages/firebase_remote_config/firebase_remote_config/example/windows/runner/resource.h new file mode 100644 index 000000000000..66a65d1e4a79 --- /dev/null +++ b/packages/firebase_remote_config/firebase_remote_config/example/windows/runner/resource.h @@ -0,0 +1,16 @@ +//{{NO_DEPENDENCIES}} +// Microsoft Visual C++ generated include file. +// Used by Runner.rc +// +#define IDI_APP_ICON 101 + +// Next default values for new objects +// +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_NEXT_RESOURCE_VALUE 102 +#define _APS_NEXT_COMMAND_VALUE 40001 +#define _APS_NEXT_CONTROL_VALUE 1001 +#define _APS_NEXT_SYMED_VALUE 101 +#endif +#endif diff --git a/packages/firebase_remote_config/firebase_remote_config/example/windows/runner/resources/app_icon.ico b/packages/firebase_remote_config/firebase_remote_config/example/windows/runner/resources/app_icon.ico new file mode 100644 index 0000000000000000000000000000000000000000..c04e20caf6370ebb9253ad831cc31de4a9c965f6 GIT binary patch literal 33772 zcmeHQc|26z|35SKE&G-*mXah&B~fFkXr)DEO&hIfqby^T&>|8^_Ub8Vp#`BLl3lbZ zvPO!8k!2X>cg~Elr=IVxo~J*a`+9wR=A83c-k-DFd(XM&UI1VKCqM@V;DDtJ09WB} zRaHKiW(GT00brH|0EeTeKVbpbGZg?nK6-j827q-+NFM34gXjqWxJ*a#{b_apGN<-L_m3#8Z26atkEn& ze87Bvv^6vVmM+p+cQ~{u%=NJF>#(d;8{7Q{^rWKWNtf14H}>#&y7$lqmY6xmZryI& z($uy?c5-+cPnt2%)R&(KIWEXww>Cnz{OUpT>W$CbO$h1= z#4BPMkFG1Y)x}Ui+WXr?Z!w!t_hjRq8qTaWpu}FH{MsHlU{>;08goVLm{V<&`itk~ zE_Ys=D(hjiy+5=?=$HGii=Y5)jMe9|wWoD_K07(}edAxh`~LBorOJ!Cf@f{_gNCC| z%{*04ViE!#>@hc1t5bb+NO>ncf@@Dv01K!NxH$3Eg1%)|wLyMDF8^d44lV!_Sr}iEWefOaL z8f?ud3Q%Sen39u|%00W<#!E=-RpGa+H8}{ulxVl4mwpjaU+%2pzmi{3HM)%8vb*~-M9rPUAfGCSos8GUXp02|o~0BTV2l#`>>aFV&_P$ejS;nGwSVP8 zMbOaG7<7eKD>c12VdGH;?2@q7535sa7MN*L@&!m?L`ASG%boY7(&L5imY#EQ$KrBB z4@_tfP5m50(T--qv1BJcD&aiH#b-QC>8#7Fx@3yXlonJI#aEIi=8&ChiVpc#N=5le zM*?rDIdcpawoc5kizv$GEjnveyrp3sY>+5_R5;>`>erS%JolimF=A^EIsAK zsPoVyyUHCgf0aYr&alx`<)eb6Be$m&`JYSuBu=p8j%QlNNp$-5C{b4#RubPb|CAIS zGE=9OFLP7?Hgc{?k45)84biT0k&-C6C%Q}aI~q<(7BL`C#<6HyxaR%!dFx7*o^laG z=!GBF^cwK$IA(sn9y6>60Rw{mYRYkp%$jH z*xQM~+bp)G$_RhtFPYx2HTsWk80+p(uqv9@I9)y{b$7NK53rYL$ezbmRjdXS?V}fj zWxX_feWoLFNm3MG7pMUuFPs$qrQWO9!l2B(SIuy2}S|lHNbHzoE+M2|Zxhjq9+Ws8c{*}x^VAib7SbxJ*Q3EnY5lgI9 z=U^f3IW6T=TWaVj+2N%K3<%Un;CF(wUp`TC&Y|ZjyFu6co^uqDDB#EP?DV5v_dw~E zIRK*BoY9y-G_ToU2V_XCX4nJ32~`czdjT!zwme zGgJ0nOk3U4@IE5JwtM}pwimLjk{ln^*4HMU%Fl4~n(cnsLB}Ja-jUM>xIB%aY;Nq8 z)Fp8dv1tkqKanv<68o@cN|%thj$+f;zGSO7H#b+eMAV8xH$hLggtt?O?;oYEgbq@= zV(u9bbd12^%;?nyk6&$GPI%|+<_mEpJGNfl*`!KV;VfmZWw{n{rnZ51?}FDh8we_L z8OI9nE31skDqJ5Oa_ybn7|5@ui>aC`s34p4ZEu6-s!%{uU45$Zd1=p$^^dZBh zu<*pDDPLW+c>iWO$&Z_*{VSQKg7=YEpS3PssPn1U!lSm6eZIho*{@&20e4Y_lRklKDTUCKI%o4Pc<|G^Xgu$J^Q|B87U;`c1zGwf^-zH*VQ^x+i^OUWE0yd z;{FJq)2w!%`x7yg@>uGFFf-XJl4H`YtUG%0slGKOlXV`q?RP>AEWg#x!b{0RicxGhS!3$p7 zij;{gm!_u@D4$Ox%>>bPtLJ> zwKtYz?T_DR1jN>DkkfGU^<#6sGz|~p*I{y`aZ>^Di#TC|Z!7j_O1=Wo8thuit?WxR zh9_S>kw^{V^|g}HRUF=dcq>?q(pHxw!8rx4dC6vbQVmIhmICF#zU!HkHpQ>9S%Uo( zMw{eC+`&pb=GZRou|3;Po1}m46H6NGd$t<2mQh}kaK-WFfmj_66_17BX0|j-E2fe3Jat}ijpc53 zJV$$;PC<5aW`{*^Z6e5##^`Ed#a0nwJDT#Qq~^e8^JTA=z^Kl>La|(UQ!bI@#ge{Dzz@61p-I)kc2?ZxFt^QQ}f%ldLjO*GPj(5)V9IyuUakJX=~GnTgZ4$5!3E=V#t`yOG4U z(gphZB6u2zsj=qNFLYShhg$}lNpO`P9xOSnO*$@@UdMYES*{jJVj|9z-}F^riksLK zbsU+4-{281P9e2UjY6tse^&a)WM1MFw;p#_dHhWI7p&U*9TR0zKdVuQed%6{otTsq z$f~S!;wg#Bd9kez=Br{m|66Wv z#g1xMup<0)H;c2ZO6su_ii&m8j&+jJz4iKnGZ&wxoQX|5a>v&_e#6WA!MB_4asTxLRGQCC5cI(em z%$ZfeqP>!*q5kU>a+BO&ln=4Jm>Ef(QE8o&RgLkk%2}4Tf}U%IFP&uS7}&|Q-)`5< z+e>;s#4cJ-z%&-^&!xsYx777Wt(wZY9(3(avmr|gRe4cD+a8&!LY`1^T?7x{E<=kdY9NYw>A;FtTvQ=Y&1M%lyZPl$ss1oY^Sl8we}n}Aob#6 zl4jERwnt9BlSoWb@3HxYgga(752Vu6Y)k4yk9u~Kw>cA5&LHcrvn1Y-HoIuFWg~}4 zEw4bR`mXZQIyOAzo)FYqg?$5W<;^+XX%Uz61{-L6@eP|lLH%|w?g=rFc;OvEW;^qh z&iYXGhVt(G-q<+_j}CTbPS_=K>RKN0&;dubh0NxJyDOHFF;<1k!{k#7b{|Qok9hac z;gHz}6>H6C6RnB`Tt#oaSrX0p-j-oRJ;_WvS-qS--P*8}V943RT6kou-G=A+7QPGQ z!ze^UGxtW3FC0$|(lY9^L!Lx^?Q8cny(rR`es5U;-xBhphF%_WNu|aO<+e9%6LuZq zt(0PoagJG<%hyuf;te}n+qIl_Ej;czWdc{LX^pS>77s9t*2b4s5dvP_!L^3cwlc)E!(!kGrg~FescVT zZCLeua3f4;d;Tk4iXzt}g}O@nlK3?_o91_~@UMIl?@77Qc$IAlLE95#Z=TES>2E%z zxUKpK{_HvGF;5%Q7n&vA?`{%8ohlYT_?(3A$cZSi)MvIJygXD}TS-3UwyUxGLGiJP znblO~G|*uA^|ac8E-w#}uBtg|s_~s&t>-g0X%zIZ@;o_wNMr_;{KDg^O=rg`fhDZu zFp(VKd1Edj%F zWHPl+)FGj%J1BO3bOHVfH^3d1F{)*PL&sRX`~(-Zy3&9UQX)Z;c51tvaI2E*E7!)q zcz|{vpK7bjxix(k&6=OEIBJC!9lTkUbgg?4-yE{9+pFS)$Ar@vrIf`D0Bnsed(Cf? zObt2CJ>BKOl>q8PyFO6w)+6Iz`LW%T5^R`U_NIW0r1dWv6OY=TVF?N=EfA(k(~7VBW(S;Tu5m4Lg8emDG-(mOSSs=M9Q&N8jc^Y4&9RqIsk(yO_P(mcCr}rCs%1MW1VBrn=0-oQN(Xj!k%iKV zb%ricBF3G4S1;+8lzg5PbZ|$Se$)I=PwiK=cDpHYdov2QO1_a-*dL4KUi|g&oh>(* zq$<`dQ^fat`+VW?m)?_KLn&mp^-@d=&7yGDt<=XwZZC=1scwxO2^RRI7n@g-1o8ps z)&+et_~)vr8aIF1VY1Qrq~Xe``KJrQSnAZ{CSq3yP;V*JC;mmCT6oRLSs7=GA?@6g zUooM}@tKtx(^|aKK8vbaHlUQqwE0}>j&~YlN3H#vKGm@u)xxS?n9XrOWUfCRa< z`20Fld2f&;gg7zpo{Adh+mqNntMc-D$N^yWZAZRI+u1T1zWHPxk{+?vcS1D>08>@6 zLhE@`gt1Y9mAK6Z4p|u(5I%EkfU7rKFSM=E4?VG9tI;a*@?6!ey{lzN5=Y-!$WFSe z&2dtO>^0@V4WRc#L&P%R(?@KfSblMS+N+?xUN$u3K4Ys%OmEh+tq}fnU}i>6YHM?< zlnL2gl~sF!j!Y4E;j3eIU-lfa`RsOL*Tt<%EFC0gPzoHfNWAfKFIKZN8}w~(Yi~=q z>=VNLO2|CjkxP}RkutxjV#4fWYR1KNrPYq5ha9Wl+u>ipsk*I(HS@iLnmGH9MFlTU zaFZ*KSR0px>o+pL7BbhB2EC1%PJ{67_ z#kY&#O4@P=OV#-79y_W>Gv2dxL*@G7%LksNSqgId9v;2xJ zrh8uR!F-eU$NMx@S*+sk=C~Dxr9Qn7TfWnTupuHKuQ$;gGiBcU>GF5sWx(~4IP3`f zWE;YFO*?jGwYh%C3X<>RKHC-DZ!*r;cIr}GLOno^3U4tFSSoJp%oHPiSa%nh=Zgn% z14+8v@ygy0>UgEN1bczD6wK45%M>psM)y^)IfG*>3ItX|TzV*0i%@>L(VN!zdKb8S?Qf7BhjNpziA zR}?={-eu>9JDcl*R=OP9B8N$IcCETXah9SUDhr{yrld{G;PnCWRsPD7!eOOFBTWUQ=LrA_~)mFf&!zJX!Oc-_=kT<}m|K52 z)M=G#;p;Rdb@~h5D{q^K;^fX-m5V}L%!wVC2iZ1uu401Ll}#rocTeK|7FAeBRhNdQ zCc2d^aQnQp=MpOmak60N$OgS}a;p(l9CL`o4r(e-nN}mQ?M&isv-P&d$!8|1D1I(3-z!wi zTgoo)*Mv`gC?~bm?S|@}I|m-E2yqPEvYybiD5azInexpK8?9q*$9Yy9-t%5jU8~ym zgZDx>!@ujQ=|HJnwp^wv-FdD{RtzO9SnyfB{mH_(c!jHL*$>0o-(h(eqe*ZwF6Lvu z{7rkk%PEqaA>o+f{H02tzZ@TWy&su?VNw43! z-X+rN`6llvpUms3ZiSt)JMeztB~>9{J8SPmYs&qohxdYFi!ra8KR$35Zp9oR)eFC4 zE;P31#3V)n`w$fZ|4X-|%MX`xZDM~gJyl2W;O$H25*=+1S#%|53>|LyH za@yh+;325%Gq3;J&a)?%7X%t@WXcWL*BaaR*7UEZad4I8iDt7^R_Fd`XeUo256;sAo2F!HcIQKk;h})QxEsPE5BcKc7WyerTchgKmrfRX z!x#H_%cL#B9TWAqkA4I$R^8{%do3Y*&(;WFmJ zU7Dih{t1<{($VtJRl9|&EB?|cJ)xse!;}>6mSO$o5XIx@V|AA8ZcoD88ZM?C*;{|f zZVmf94_l1OmaICt`2sTyG!$^UeTHx9YuUP!omj(r|7zpm5475|yXI=rR>>fteLI+| z)MoiGho0oEt=*J(;?VY0QzwCqw@cVm?d7Y!z0A@u#H?sCJ*ecvyhj& z-F77lO;SH^dmf?L>3i>?Z*U}Em4ZYV_CjgfvzYsRZ+1B!Uo6H6mbS<-FFL`ytqvb& zE7+)2ahv-~dz(Hs+f})z{*4|{)b=2!RZK;PWwOnO=hG7xG`JU5>bAvUbdYd_CjvtHBHgtGdlO+s^9ca^Bv3`t@VRX2_AD$Ckg36OcQRF zXD6QtGfHdw*hx~V(MV-;;ZZF#dJ-piEF+s27z4X1qi5$!o~xBnvf=uopcn7ftfsZc zy@(PuOk`4GL_n(H9(E2)VUjqRCk9kR?w)v@xO6Jm_Mx})&WGEl=GS0#)0FAq^J*o! zAClhvoTsNP*-b~rN{8Yym3g{01}Ep^^Omf=SKqvN?{Q*C4HNNAcrowIa^mf+3PRy! z*_G-|3i8a;+q;iP@~Of_$(vtFkB8yOyWt2*K)vAn9El>=D;A$CEx6b*XF@4y_6M+2 zpeW`RHoI_p(B{%(&jTHI->hmNmZjHUj<@;7w0mx3&koy!2$@cfX{sN19Y}euYJFn& z1?)+?HCkD0MRI$~uB2UWri})0bru_B;klFdwsLc!ne4YUE;t41JqfG# zZJq6%vbsdx!wYeE<~?>o4V`A3?lN%MnKQ`z=uUivQN^vzJ|C;sdQ37Qn?;lpzg})y z)_2~rUdH}zNwX;Tp0tJ78+&I=IwOQ-fl30R79O8@?Ub8IIA(6I`yHn%lARVL`%b8+ z4$8D-|MZZWxc_)vu6@VZN!HsI$*2NOV&uMxBNzIbRgy%ob_ zhwEH{J9r$!dEix9XM7n&c{S(h>nGm?el;gaX0@|QnzFD@bne`el^CO$yXC?BDJ|Qg z+y$GRoR`?ST1z^e*>;!IS@5Ovb7*RlN>BV_UC!7E_F;N#ky%1J{+iixp(dUJj93aK zzHNN>R-oN7>kykHClPnoPTIj7zc6KM(Pnlb(|s??)SMb)4!sMHU^-ntJwY5Big7xv zb1Ew`Xj;|D2kzGja*C$eS44(d&RMU~c_Y14V9_TLTz0J#uHlsx`S6{nhsA0dWZ#cG zJ?`fO50E>*X4TQLv#nl%3GOk*UkAgt=IY+u0LNXqeln3Z zv$~&Li`ZJOKkFuS)dJRA>)b_Da%Q~axwA_8zNK{BH{#}#m}zGcuckz}riDE-z_Ms> zR8-EqAMcfyGJCtvTpaUVQtajhUS%c@Yj}&6Zz;-M7MZzqv3kA7{SuW$oW#=0az2wQ zg-WG@Vb4|D`pl~Il54N7Hmsauc_ne-a!o5#j3WaBBh@Wuefb!QJIOn5;d)%A#s+5% zuD$H=VNux9bE-}1&bcYGZ+>1Fo;3Z@e&zX^n!?JK*adSbONm$XW9z;Q^L>9U!}Toj2WdafJ%oL#h|yWWwyAGxzfrAWdDTtaKl zK4`5tDpPg5>z$MNv=X0LZ0d6l%D{(D8oT@+w0?ce$DZ6pv>{1&Ok67Ix1 zH}3=IEhPJEhItCC8E=`T`N5(k?G=B4+xzZ?<4!~ ze~z6Wk9!CHTI(0rLJ4{JU?E-puc;xusR?>G?;4vt;q~iI9=kDL=z0Rr%O$vU`30X$ zDZRFyZ`(omOy@u|i6h;wtJlP;+}$|Ak|k2dea7n?U1*$T!sXqqOjq^NxLPMmk~&qI zYg0W?yK8T(6+Ea+$YyspKK?kP$+B`~t3^Pib_`!6xCs32!i@pqXfFV6PmBIR<-QW= zN8L{pt0Vap0x`Gzn#E@zh@H)0FfVfA_Iu4fjYZ+umO1LXIbVc$pY+E234u)ttcrl$ z>s92z4vT%n6cMb>=XT6;l0+9e(|CZG)$@C7t7Z7Ez@a)h)!hyuV&B5K%%)P5?Lk|C zZZSVzdXp{@OXSP0hoU-gF8s8Um(#xzjP2Vem zec#-^JqTa&Y#QJ>-FBxd7tf`XB6e^JPUgagB8iBSEps;92KG`!#mvVcPQ5yNC-GEG zTiHEDYfH+0O15}r^+ z#jxj=@x8iNHWALe!P3R67TwmhItn**0JwnzSV2O&KE8KcT+0hWH^OPD1pwiuyx=b@ zNf5Jh0{9X)8;~Es)$t@%(3!OnbY+`@?i{mGX7Yy}8T_*0a6g;kaFPq;*=px5EhO{Cp%1kI<0?*|h8v!6WnO3cCJRF2-CRrU3JiLJnj@6;L)!0kWYAc_}F{2P))3HmCrz zQ&N&gE70;`!6*eJ4^1IR{f6j4(-l&X!tjHxkbHA^Zhrnhr9g{exN|xrS`5Pq=#Xf& zG%P=#ra-TyVFfgW%cZo5OSIwFL9WtXAlFOa+ubmI5t*3=g#Y zF%;70p5;{ZeFL}&}yOY1N1*Q;*<(kTB!7vM$QokF)yr2FlIU@$Ph58$Bz z0J?xQG=MlS4L6jA22eS42g|9*9pX@$#*sUeM(z+t?hr@r5J&D1rx}2pW&m*_`VDCW zUYY@v-;bAO0HqoAgbbiGGC<=ryf96}3pouhy3XJrX+!!u*O_>Si38V{uJmQ&USptX zKp#l(?>%^7;2%h(q@YWS#9;a!JhKlkR#Vd)ERILlgu!Hr@jA@V;sk4BJ-H#p*4EqC zDGjC*tl=@3Oi6)Bn^QwFpul18fpkbpg0+peH$xyPBqb%`$OUhPKyWb32o7clB*9Z< zN=i~NLjavrLtwgJ01bufP+>p-jR2I95|TpmKpQL2!oV>g(4RvS2pK4*ou%m(h6r3A zX#s&`9LU1ZG&;{CkOK!4fLDTnBys`M!vuz>Q&9OZ0hGQl!~!jSDg|~s*w52opC{sB ze|Cf2luD(*G13LcOAGA!s2FjSK8&IE5#W%J25w!vM0^VyQM!t)inj&RTiJ!wXzFgz z3^IqzB7I0L$llljsGq})thBy9UOyjtFO_*hYM_sgcMk>44jeH0V1FDyELc{S1F-;A zS;T^k^~4biG&V*Irq}O;e}j$$+E_#G?HKIn05iP3j|87TkGK~SqG!-KBg5+mN(aLm z8ybhIM`%C19UX$H$KY6JgXbY$0AT%rEpHC;u`rQ$Y=rxUdsc5*Kvc8jaYaO$^)cI6){P6K0r)I6DY4Wr4&B zLQUBraey#0HV|&c4v7PVo3n$zHj99(TZO^3?Ly%C4nYvJTL9eLBLHsM3WKKD>5!B` zQ=BsR3aR6PD(Fa>327E2HAu5TM~Wusc!)>~(gM)+3~m;92Jd;FnSib=M5d6;;5{%R zb4V7DEJ0V!CP-F*oU?gkc>ksUtAYP&V4ND5J>J2^jt*vcFflQWCrB&fLdT%O59PVJ zhid#toR=FNgD!q3&r8#wEBr`!wzvQu5zX?Q>nlSJ4i@WC*CN*-xU66F^V5crWevQ9gsq$I@z1o(a=k7LL~ z7m_~`o;_Ozha1$8Q}{WBehvAlO4EL60y5}8GDrZ< zXh&F}71JbW2A~8KfEWj&UWV#4+Z4p`b{uAj4&WC zha`}X@3~+Iz^WRlOHU&KngK>#j}+_o@LdBC1H-`gT+krWX3-;!)6?{FBp~%20a}FL zFP9%Emqcwa#(`=G>BBZ0qZDQhmZKJg_g8<=bBFKWr!dyg(YkpE+|R*SGpDVU!+VlU zFC54^DLv}`qa%49T>nNiA9Q7Ips#!Xx90tCU2gvK`(F+GPcL=J^>No{)~we#o@&mUb6c$ zCc*<|NJBk-#+{j9xkQ&ujB zI~`#kN~7W!f*-}wkG~Ld!JqZ@tK}eeSnsS5J1fMFXm|`LJx&}5`@dK3W^7#Wnm+_P zBZkp&j1fa2Y=eIjJ0}gh85jt43kaIXXv?xmo@eHrka!Z|vQv12HN#+!I5E z`(fbuW>gFiJL|uXJ!vKt#z3e3HlVdboH7;e#i3(2<)Fg-I@BR!qY#eof3MFZ&*Y@l zI|KJf&ge@p2Dq09Vu$$Qxb7!}{m-iRk@!)%KL)txi3;~Z4Pb}u@GsW;ELiWeG9V51 znX#}B&4Y2E7-H=OpNE@q{%hFLxwIpBF2t{vPREa8_{linXT;#1vMRWjOzLOP$-hf( z>=?$0;~~PnkqY;~K{EM6Vo-T(0K{A0}VUGmu*hR z{tw3hvBN%N3G3Yw`X5Te+F{J`(3w1s3-+1EbnFQKcrgrX1Jqvs@ADGe%M0s$EbK$$ zK)=y=upBc6SjGYAACCcI=Y*6Fi8_jgwZlLxD26fnQfJmb8^gHRN5(TemhX@0e=vr> zg`W}6U>x6VhoA3DqsGGD9uL1DhB3!OXO=k}59TqD@(0Nb{)Ut_luTioK_>7wjc!5C zIr@w}b`Fez3)0wQfKl&bae7;PcTA7%?f2xucM0G)wt_KO!Ewx>F~;=BI0j=Fb4>pp zv}0R^xM4eti~+^+gE$6b81p(kwzuDti(-K9bc|?+pJEl@H+jSYuxZQV8rl8 zjp@M{#%qItIUFN~KcO9Hed*`$5A-2~pAo~K&<-Q+`9`$CK>rzqAI4w~$F%vs9s{~x zg4BP%Gy*@m?;D6=SRX?888Q6peF@_4Z->8wAH~Cn!R$|Hhq2cIzFYqT_+cDourHbY z0qroxJnrZ4Gh+Ay+F`_c%+KRT>y3qw{)89?=hJ@=KO=@ep)aBJ$c!JHfBMJpsP*3G za7|)VJJ8B;4?n{~ldJF7%jmb`-ftIvNd~ekoufG(`K(3=LNc;HBY& z(lp#q8XAD#cIf}k49zX_i`*fO+#!zKA&%T3j@%)R+#yag067CU%yUEe47>wzGU8^` z1EXFT^@I!{J!F8!X?S6ph8J=gUi5tl93*W>7}_uR<2N2~e}FaG?}KPyugQ=-OGEZs z!GBoyYY+H*ANn4?Z)X4l+7H%`17i5~zRlRIX?t)6_eu=g2Q`3WBhxSUeea+M-S?RL zX9oBGKn%a!H+*hx4d2(I!gsi+@SQK%<{X22M~2tMulJoa)0*+z9=-YO+;DFEm5eE1U9b^B(Z}2^9!Qk`!A$wUE z7$Ar5?NRg2&G!AZqnmE64eh^Anss3i!{}%6@Et+4rr!=}!SBF8eZ2*J3ujCWbl;3; z48H~goPSv(8X61fKKdpP!Z7$88NL^Z?j`!^*I?-P4X^pMxyWz~@$(UeAcTSDd(`vO z{~rc;9|GfMJcApU3k}22a!&)k4{CU!e_ny^Y3cO;tOvOMKEyWz!vG(Kp*;hB?d|R3`2X~=5a6#^o5@qn?J-bI8Ppip{-yG z!k|VcGsq!jF~}7DMr49Wap-s&>o=U^T0!Lcy}!(bhtYsPQy z4|EJe{12QL#=c(suQ89Mhw9<`bui%nx7Nep`C&*M3~vMEACmcRYYRGtANq$F%zh&V zc)cEVeHz*Z1N)L7k-(k3np#{GcDh2Q@ya0YHl*n7fl*ZPAsbU-a94MYYtA#&!c`xGIaV;yzsmrjfieTEtqB_WgZp2*NplHx=$O{M~2#i_vJ{ps-NgK zQsxKK_CBM2PP_je+Xft`(vYfXXgIUr{=PA=7a8`2EHk)Ym2QKIforz# tySWtj{oF3N9@_;i*Fv5S)9x^z=nlWP>jpp-9)52ZmLVA=i*%6g{{fxOO~wEK literal 0 HcmV?d00001 diff --git a/packages/firebase_remote_config/firebase_remote_config/example/windows/runner/runner.exe.manifest b/packages/firebase_remote_config/firebase_remote_config/example/windows/runner/runner.exe.manifest new file mode 100644 index 000000000000..a42ea7687cb6 --- /dev/null +++ b/packages/firebase_remote_config/firebase_remote_config/example/windows/runner/runner.exe.manifest @@ -0,0 +1,20 @@ + + + + + PerMonitorV2 + + + + + + + + + + + + + + + diff --git a/packages/firebase_remote_config/firebase_remote_config/example/windows/runner/utils.cpp b/packages/firebase_remote_config/firebase_remote_config/example/windows/runner/utils.cpp new file mode 100644 index 000000000000..f5bf9fa0f536 --- /dev/null +++ b/packages/firebase_remote_config/firebase_remote_config/example/windows/runner/utils.cpp @@ -0,0 +1,64 @@ +#include "utils.h" + +#include +#include +#include +#include + +#include + +void CreateAndAttachConsole() { + if (::AllocConsole()) { + FILE *unused; + if (freopen_s(&unused, "CONOUT$", "w", stdout)) { + _dup2(_fileno(stdout), 1); + } + if (freopen_s(&unused, "CONOUT$", "w", stderr)) { + _dup2(_fileno(stdout), 2); + } + std::ios::sync_with_stdio(); + FlutterDesktopResyncOutputStreams(); + } +} + +std::vector GetCommandLineArguments() { + // Convert the UTF-16 command line arguments to UTF-8 for the Engine to use. + int argc; + wchar_t** argv = ::CommandLineToArgvW(::GetCommandLineW(), &argc); + if (argv == nullptr) { + return std::vector(); + } + + std::vector command_line_arguments; + + // Skip the first argument as it's the binary name. + for (int i = 1; i < argc; i++) { + command_line_arguments.push_back(Utf8FromUtf16(argv[i])); + } + + ::LocalFree(argv); + + return command_line_arguments; +} + +std::string Utf8FromUtf16(const wchar_t* utf16_string) { + if (utf16_string == nullptr) { + return std::string(); + } + int target_length = ::WideCharToMultiByte( + CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, + -1, nullptr, 0, nullptr, nullptr); + std::string utf8_string; + if (target_length == 0 || target_length > utf8_string.max_size()) { + return utf8_string; + } + utf8_string.resize(target_length); + int converted_length = ::WideCharToMultiByte( + CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, + -1, utf8_string.data(), + target_length, nullptr, nullptr); + if (converted_length == 0) { + return std::string(); + } + return utf8_string; +} diff --git a/packages/firebase_remote_config/firebase_remote_config/example/windows/runner/utils.h b/packages/firebase_remote_config/firebase_remote_config/example/windows/runner/utils.h new file mode 100644 index 000000000000..3879d5475579 --- /dev/null +++ b/packages/firebase_remote_config/firebase_remote_config/example/windows/runner/utils.h @@ -0,0 +1,19 @@ +#ifndef RUNNER_UTILS_H_ +#define RUNNER_UTILS_H_ + +#include +#include + +// Creates a console for the process, and redirects stdout and stderr to +// it for both the runner and the Flutter library. +void CreateAndAttachConsole(); + +// Takes a null-terminated wchar_t* encoded in UTF-16 and returns a std::string +// encoded in UTF-8. Returns an empty std::string on failure. +std::string Utf8FromUtf16(const wchar_t* utf16_string); + +// Gets the command line arguments passed in as a std::vector, +// encoded in UTF-8. Returns an empty std::vector on failure. +std::vector GetCommandLineArguments(); + +#endif // RUNNER_UTILS_H_ diff --git a/packages/firebase_remote_config/firebase_remote_config/example/windows/runner/win32_window.cpp b/packages/firebase_remote_config/firebase_remote_config/example/windows/runner/win32_window.cpp new file mode 100644 index 000000000000..041a38554745 --- /dev/null +++ b/packages/firebase_remote_config/firebase_remote_config/example/windows/runner/win32_window.cpp @@ -0,0 +1,288 @@ +#include "win32_window.h" + +#include +#include + +#include "resource.h" + +namespace { + +/// Window attribute that enables dark mode window decorations. +/// +/// Redefined in case the developer's machine has a Windows SDK older than +/// version 10.0.22000.0. +/// See: https://docs.microsoft.com/windows/win32/api/dwmapi/ne-dwmapi-dwmwindowattribute +#ifndef DWMWA_USE_IMMERSIVE_DARK_MODE +#define DWMWA_USE_IMMERSIVE_DARK_MODE 20 +#endif + +constexpr const wchar_t kWindowClassName[] = L"FLUTTER_RUNNER_WIN32_WINDOW"; + +/// Registry key for app theme preference. +/// +/// A value of 0 indicates apps should use dark mode. A non-zero or missing +/// value indicates apps should use light mode. +constexpr const wchar_t kGetPreferredBrightnessRegKey[] = + L"Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize"; +constexpr const wchar_t kGetPreferredBrightnessRegValue[] = L"AppsUseLightTheme"; + +// The number of Win32Window objects that currently exist. +static int g_active_window_count = 0; + +using EnableNonClientDpiScaling = BOOL __stdcall(HWND hwnd); + +// Scale helper to convert logical scaler values to physical using passed in +// scale factor +int Scale(int source, double scale_factor) { + return static_cast(source * scale_factor); +} + +// Dynamically loads the |EnableNonClientDpiScaling| from the User32 module. +// This API is only needed for PerMonitor V1 awareness mode. +void EnableFullDpiSupportIfAvailable(HWND hwnd) { + HMODULE user32_module = LoadLibraryA("User32.dll"); + if (!user32_module) { + return; + } + auto enable_non_client_dpi_scaling = + reinterpret_cast( + GetProcAddress(user32_module, "EnableNonClientDpiScaling")); + if (enable_non_client_dpi_scaling != nullptr) { + enable_non_client_dpi_scaling(hwnd); + } + FreeLibrary(user32_module); +} + +} // namespace + +// Manages the Win32Window's window class registration. +class WindowClassRegistrar { + public: + ~WindowClassRegistrar() = default; + + // Returns the singleton registar instance. + static WindowClassRegistrar* GetInstance() { + if (!instance_) { + instance_ = new WindowClassRegistrar(); + } + return instance_; + } + + // Returns the name of the window class, registering the class if it hasn't + // previously been registered. + const wchar_t* GetWindowClass(); + + // Unregisters the window class. Should only be called if there are no + // instances of the window. + void UnregisterWindowClass(); + + private: + WindowClassRegistrar() = default; + + static WindowClassRegistrar* instance_; + + bool class_registered_ = false; +}; + +WindowClassRegistrar* WindowClassRegistrar::instance_ = nullptr; + +const wchar_t* WindowClassRegistrar::GetWindowClass() { + if (!class_registered_) { + WNDCLASS window_class{}; + window_class.hCursor = LoadCursor(nullptr, IDC_ARROW); + window_class.lpszClassName = kWindowClassName; + window_class.style = CS_HREDRAW | CS_VREDRAW; + window_class.cbClsExtra = 0; + window_class.cbWndExtra = 0; + window_class.hInstance = GetModuleHandle(nullptr); + window_class.hIcon = + LoadIcon(window_class.hInstance, MAKEINTRESOURCE(IDI_APP_ICON)); + window_class.hbrBackground = 0; + window_class.lpszMenuName = nullptr; + window_class.lpfnWndProc = Win32Window::WndProc; + RegisterClass(&window_class); + class_registered_ = true; + } + return kWindowClassName; +} + +void WindowClassRegistrar::UnregisterWindowClass() { + UnregisterClass(kWindowClassName, nullptr); + class_registered_ = false; +} + +Win32Window::Win32Window() { + ++g_active_window_count; +} + +Win32Window::~Win32Window() { + --g_active_window_count; + Destroy(); +} + +bool Win32Window::Create(const std::wstring& title, + const Point& origin, + const Size& size) { + Destroy(); + + const wchar_t* window_class = + WindowClassRegistrar::GetInstance()->GetWindowClass(); + + const POINT target_point = {static_cast(origin.x), + static_cast(origin.y)}; + HMONITOR monitor = MonitorFromPoint(target_point, MONITOR_DEFAULTTONEAREST); + UINT dpi = FlutterDesktopGetDpiForMonitor(monitor); + double scale_factor = dpi / 96.0; + + HWND window = CreateWindow( + window_class, title.c_str(), WS_OVERLAPPEDWINDOW, + Scale(origin.x, scale_factor), Scale(origin.y, scale_factor), + Scale(size.width, scale_factor), Scale(size.height, scale_factor), + nullptr, nullptr, GetModuleHandle(nullptr), this); + + if (!window) { + return false; + } + + UpdateTheme(window); + + return OnCreate(); +} + +bool Win32Window::Show() { + return ShowWindow(window_handle_, SW_SHOWNORMAL); +} + +// static +LRESULT CALLBACK Win32Window::WndProc(HWND const window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + if (message == WM_NCCREATE) { + auto window_struct = reinterpret_cast(lparam); + SetWindowLongPtr(window, GWLP_USERDATA, + reinterpret_cast(window_struct->lpCreateParams)); + + auto that = static_cast(window_struct->lpCreateParams); + EnableFullDpiSupportIfAvailable(window); + that->window_handle_ = window; + } else if (Win32Window* that = GetThisFromHandle(window)) { + return that->MessageHandler(window, message, wparam, lparam); + } + + return DefWindowProc(window, message, wparam, lparam); +} + +LRESULT +Win32Window::MessageHandler(HWND hwnd, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + switch (message) { + case WM_DESTROY: + window_handle_ = nullptr; + Destroy(); + if (quit_on_close_) { + PostQuitMessage(0); + } + return 0; + + case WM_DPICHANGED: { + auto newRectSize = reinterpret_cast(lparam); + LONG newWidth = newRectSize->right - newRectSize->left; + LONG newHeight = newRectSize->bottom - newRectSize->top; + + SetWindowPos(hwnd, nullptr, newRectSize->left, newRectSize->top, newWidth, + newHeight, SWP_NOZORDER | SWP_NOACTIVATE); + + return 0; + } + case WM_SIZE: { + RECT rect = GetClientArea(); + if (child_content_ != nullptr) { + // Size and position the child window. + MoveWindow(child_content_, rect.left, rect.top, rect.right - rect.left, + rect.bottom - rect.top, TRUE); + } + return 0; + } + + case WM_ACTIVATE: + if (child_content_ != nullptr) { + SetFocus(child_content_); + } + return 0; + + case WM_DWMCOLORIZATIONCOLORCHANGED: + UpdateTheme(hwnd); + return 0; + } + + return DefWindowProc(window_handle_, message, wparam, lparam); +} + +void Win32Window::Destroy() { + OnDestroy(); + + if (window_handle_) { + DestroyWindow(window_handle_); + window_handle_ = nullptr; + } + if (g_active_window_count == 0) { + WindowClassRegistrar::GetInstance()->UnregisterWindowClass(); + } +} + +Win32Window* Win32Window::GetThisFromHandle(HWND const window) noexcept { + return reinterpret_cast( + GetWindowLongPtr(window, GWLP_USERDATA)); +} + +void Win32Window::SetChildContent(HWND content) { + child_content_ = content; + SetParent(content, window_handle_); + RECT frame = GetClientArea(); + + MoveWindow(content, frame.left, frame.top, frame.right - frame.left, + frame.bottom - frame.top, true); + + SetFocus(child_content_); +} + +RECT Win32Window::GetClientArea() { + RECT frame; + GetClientRect(window_handle_, &frame); + return frame; +} + +HWND Win32Window::GetHandle() { + return window_handle_; +} + +void Win32Window::SetQuitOnClose(bool quit_on_close) { + quit_on_close_ = quit_on_close; +} + +bool Win32Window::OnCreate() { + // No-op; provided for subclasses. + return true; +} + +void Win32Window::OnDestroy() { + // No-op; provided for subclasses. +} + +void Win32Window::UpdateTheme(HWND const window) { + DWORD light_mode; + DWORD light_mode_size = sizeof(light_mode); + LSTATUS result = RegGetValue(HKEY_CURRENT_USER, kGetPreferredBrightnessRegKey, + kGetPreferredBrightnessRegValue, + RRF_RT_REG_DWORD, nullptr, &light_mode, + &light_mode_size); + + if (result == ERROR_SUCCESS) { + BOOL enable_dark_mode = light_mode == 0; + DwmSetWindowAttribute(window, DWMWA_USE_IMMERSIVE_DARK_MODE, + &enable_dark_mode, sizeof(enable_dark_mode)); + } +} diff --git a/packages/firebase_remote_config/firebase_remote_config/example/windows/runner/win32_window.h b/packages/firebase_remote_config/firebase_remote_config/example/windows/runner/win32_window.h new file mode 100644 index 000000000000..c86632d8a6b9 --- /dev/null +++ b/packages/firebase_remote_config/firebase_remote_config/example/windows/runner/win32_window.h @@ -0,0 +1,102 @@ +#ifndef RUNNER_WIN32_WINDOW_H_ +#define RUNNER_WIN32_WINDOW_H_ + +#include + +#include +#include +#include + +// A class abstraction for a high DPI-aware Win32 Window. Intended to be +// inherited from by classes that wish to specialize with custom +// rendering and input handling +class Win32Window { + public: + struct Point { + unsigned int x; + unsigned int y; + Point(unsigned int x, unsigned int y) : x(x), y(y) {} + }; + + struct Size { + unsigned int width; + unsigned int height; + Size(unsigned int width, unsigned int height) + : width(width), height(height) {} + }; + + Win32Window(); + virtual ~Win32Window(); + + // Creates a win32 window with |title| that is positioned and sized using + // |origin| and |size|. New windows are created on the default monitor. Window + // sizes are specified to the OS in physical pixels, hence to ensure a + // consistent size this function will scale the inputted width and height as + // as appropriate for the default monitor. The window is invisible until + // |Show| is called. Returns true if the window was created successfully. + bool Create(const std::wstring& title, const Point& origin, const Size& size); + + // Show the current window. Returns true if the window was successfully shown. + bool Show(); + + // Release OS resources associated with window. + void Destroy(); + + // Inserts |content| into the window tree. + void SetChildContent(HWND content); + + // Returns the backing Window handle to enable clients to set icon and other + // window properties. Returns nullptr if the window has been destroyed. + HWND GetHandle(); + + // If true, closing this window will quit the application. + void SetQuitOnClose(bool quit_on_close); + + // Return a RECT representing the bounds of the current client area. + RECT GetClientArea(); + + protected: + // Processes and route salient window messages for mouse handling, + // size change and DPI. Delegates handling of these to member overloads that + // inheriting classes can handle. + virtual LRESULT MessageHandler(HWND window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept; + + // Called when CreateAndShow is called, allowing subclass window-related + // setup. Subclasses should return false if setup fails. + virtual bool OnCreate(); + + // Called when Destroy is called. + virtual void OnDestroy(); + + private: + friend class WindowClassRegistrar; + + // OS callback called by message pump. Handles the WM_NCCREATE message which + // is passed when the non-client area is being created and enables automatic + // non-client DPI scaling so that the non-client area automatically + // responsponds to changes in DPI. All other messages are handled by + // MessageHandler. + static LRESULT CALLBACK WndProc(HWND const window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept; + + // Retrieves a class instance pointer for |window| + static Win32Window* GetThisFromHandle(HWND const window) noexcept; + + // Update the window frame's theme to match the system theme. + static void UpdateTheme(HWND const window); + + bool quit_on_close_ = false; + + // window handle for top level window. + HWND window_handle_ = nullptr; + + // window handle for hosted content. + HWND child_content_ = nullptr; +}; + +#endif // RUNNER_WIN32_WINDOW_H_ diff --git a/packages/firebase_remote_config/firebase_remote_config/ios/Classes/messages.g.h b/packages/firebase_remote_config/firebase_remote_config/ios/Classes/messages.g.h new file mode 100644 index 000000000000..ad79bad9f8db --- /dev/null +++ b/packages/firebase_remote_config/firebase_remote_config/ios/Classes/messages.g.h @@ -0,0 +1,95 @@ +// Copyright 2023, the Chromium project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Autogenerated from Pigeon (v9.2.5), do not edit directly. +// See also: https://pub.dev/packages/pigeon + +#import + +@protocol FlutterBinaryMessenger; +@protocol FlutterMessageCodec; +@class FlutterError; +@class FlutterStandardTypedData; + +NS_ASSUME_NONNULL_BEGIN + +/// ValueSource defines the possible sources of a config parameter value. +typedef NS_ENUM(NSUInteger, PigeonValueSource) { + /// The value was defined by a static constant. + PigeonValueSourceValueStatic = 0, + /// The value was defined by default config. + PigeonValueSourceValueDefault = 1, + /// The value was defined by fetched config. + PigeonValueSourceValueRemote = 2, +}; + +typedef NS_ENUM(NSUInteger, PigeonRemoteConfigFetchStatus) { + /// Indicates instance has not yet attempted a fetch. + PigeonRemoteConfigFetchStatusNoFetchYet = 0, + /// Indicates the last fetch attempt succeeded. + PigeonRemoteConfigFetchStatusSuccess = 1, + /// Indicates the last fetch attempt failed. + PigeonRemoteConfigFetchStatusFailure = 2, + /// Indicates the last fetch attempt was rate-limited. + PigeonRemoteConfigFetchStatusThrottle = 3, +}; + +@class PigeonRemoteConfigSettings; +@class PigeonRemoteConfigValue; +@class PigeonFirebaseApp; + +@interface PigeonRemoteConfigSettings : NSObject +/// `init` unavailable to enforce nonnull fields, see the `make` class method. +- (instancetype)init NS_UNAVAILABLE; ++ (instancetype)makeWithFetchTimeout:(NSNumber *)fetchTimeout + minimumFetchInterval:(NSNumber *)minimumFetchInterval; +@property(nonatomic, strong) NSNumber * fetchTimeout; +@property(nonatomic, strong) NSNumber * minimumFetchInterval; +@end + +@interface PigeonRemoteConfigValue : NSObject +/// `init` unavailable to enforce nonnull fields, see the `make` class method. +- (instancetype)init NS_UNAVAILABLE; ++ (instancetype)makeWithValue:(nullable NSArray *)value + source:(PigeonValueSource)source; +@property(nonatomic, strong, nullable) NSArray * value; +/// Indicates at which source this value came from. +@property(nonatomic, assign) PigeonValueSource source; +@end + +@interface PigeonFirebaseApp : NSObject +/// `init` unavailable to enforce nonnull fields, see the `make` class method. +- (instancetype)init NS_UNAVAILABLE; ++ (instancetype)makeWithAppName:(NSString *)appName + tenantId:(nullable NSString *)tenantId; +@property(nonatomic, copy) NSString * appName; +@property(nonatomic, copy, nullable) NSString * tenantId; +@end + +/// The codec used by FirebaseRemoteConfigHostApi. +NSObject *FirebaseRemoteConfigHostApiGetCodec(void); + +@protocol FirebaseRemoteConfigHostApi +- (void)activateApp:(PigeonFirebaseApp *)app completion:(void (^)(NSNumber *_Nullable, FlutterError *_Nullable))completion; +- (void)ensureInitializedApp:(PigeonFirebaseApp *)app completion:(void (^)(FlutterError *_Nullable))completion; +- (void)fetchApp:(PigeonFirebaseApp *)app completion:(void (^)(FlutterError *_Nullable))completion; +- (void)fetchAndActivateApp:(PigeonFirebaseApp *)app completion:(void (^)(NSNumber *_Nullable, FlutterError *_Nullable))completion; +/// @return `nil` only when `error != nil`. +- (nullable NSDictionary *)getAllApp:(PigeonFirebaseApp *)app error:(FlutterError *_Nullable *_Nonnull)error; +/// @return `nil` only when `error != nil`. +- (nullable NSNumber *)getBoolApp:(PigeonFirebaseApp *)app key:(NSString *)key error:(FlutterError *_Nullable *_Nonnull)error; +/// @return `nil` only when `error != nil`. +- (nullable NSNumber *)getIntApp:(PigeonFirebaseApp *)app key:(NSString *)key error:(FlutterError *_Nullable *_Nonnull)error; +/// @return `nil` only when `error != nil`. +- (nullable NSNumber *)getDoubleApp:(PigeonFirebaseApp *)app key:(NSString *)key error:(FlutterError *_Nullable *_Nonnull)error; +/// @return `nil` only when `error != nil`. +- (nullable NSString *)getStringApp:(PigeonFirebaseApp *)app key:(NSString *)key error:(FlutterError *_Nullable *_Nonnull)error; +/// @return `nil` only when `error != nil`. +- (nullable PigeonRemoteConfigValue *)getValueApp:(PigeonFirebaseApp *)app key:(NSString *)key error:(FlutterError *_Nullable *_Nonnull)error; +- (void)setConfigSettingsApp:(PigeonFirebaseApp *)app remoteConfigSettings:(PigeonRemoteConfigSettings *)remoteConfigSettings completion:(void (^)(FlutterError *_Nullable))completion; +- (void)setDefaultsApp:(PigeonFirebaseApp *)app defaultParameters:(NSDictionary *)defaultParameters completion:(void (^)(FlutterError *_Nullable))completion; +@end + +extern void FirebaseRemoteConfigHostApiSetup(id binaryMessenger, NSObject *_Nullable api); + +NS_ASSUME_NONNULL_END diff --git a/packages/firebase_remote_config/firebase_remote_config/ios/Classes/messages.g.m b/packages/firebase_remote_config/firebase_remote_config/ios/Classes/messages.g.m new file mode 100644 index 000000000000..e2817ce711e3 --- /dev/null +++ b/packages/firebase_remote_config/firebase_remote_config/ios/Classes/messages.g.m @@ -0,0 +1,416 @@ +// Copyright 2023, the Chromium project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Autogenerated from Pigeon (v9.2.5), do not edit directly. +// See also: https://pub.dev/packages/pigeon + +#import "messages.g.h" +#import + +#if !__has_feature(objc_arc) +#error File requires ARC to be enabled. +#endif + +static NSArray *wrapResult(id result, FlutterError *error) { + if (error) { + return @[ + error.code ?: [NSNull null], error.message ?: [NSNull null], error.details ?: [NSNull null] + ]; + } + return @[ result ?: [NSNull null] ]; +} +static id GetNullableObjectAtIndex(NSArray *array, NSInteger key) { + id result = array[key]; + return (result == [NSNull null]) ? nil : result; +} + +@interface PigeonRemoteConfigSettings () ++ (PigeonRemoteConfigSettings *)fromList:(NSArray *)list; ++ (nullable PigeonRemoteConfigSettings *)nullableFromList:(NSArray *)list; +- (NSArray *)toList; +@end + +@interface PigeonRemoteConfigValue () ++ (PigeonRemoteConfigValue *)fromList:(NSArray *)list; ++ (nullable PigeonRemoteConfigValue *)nullableFromList:(NSArray *)list; +- (NSArray *)toList; +@end + +@interface PigeonFirebaseApp () ++ (PigeonFirebaseApp *)fromList:(NSArray *)list; ++ (nullable PigeonFirebaseApp *)nullableFromList:(NSArray *)list; +- (NSArray *)toList; +@end + +@implementation PigeonRemoteConfigSettings ++ (instancetype)makeWithFetchTimeout:(NSNumber *)fetchTimeout + minimumFetchInterval:(NSNumber *)minimumFetchInterval { + PigeonRemoteConfigSettings* pigeonResult = [[PigeonRemoteConfigSettings alloc] init]; + pigeonResult.fetchTimeout = fetchTimeout; + pigeonResult.minimumFetchInterval = minimumFetchInterval; + return pigeonResult; +} ++ (PigeonRemoteConfigSettings *)fromList:(NSArray *)list { + PigeonRemoteConfigSettings *pigeonResult = [[PigeonRemoteConfigSettings alloc] init]; + pigeonResult.fetchTimeout = GetNullableObjectAtIndex(list, 0); + NSAssert(pigeonResult.fetchTimeout != nil, @""); + pigeonResult.minimumFetchInterval = GetNullableObjectAtIndex(list, 1); + NSAssert(pigeonResult.minimumFetchInterval != nil, @""); + return pigeonResult; +} ++ (nullable PigeonRemoteConfigSettings *)nullableFromList:(NSArray *)list { + return (list) ? [PigeonRemoteConfigSettings fromList:list] : nil; +} +- (NSArray *)toList { + return @[ + (self.fetchTimeout ?: [NSNull null]), + (self.minimumFetchInterval ?: [NSNull null]), + ]; +} +@end + +@implementation PigeonRemoteConfigValue ++ (instancetype)makeWithValue:(nullable NSArray *)value + source:(PigeonValueSource)source { + PigeonRemoteConfigValue* pigeonResult = [[PigeonRemoteConfigValue alloc] init]; + pigeonResult.value = value; + pigeonResult.source = source; + return pigeonResult; +} ++ (PigeonRemoteConfigValue *)fromList:(NSArray *)list { + PigeonRemoteConfigValue *pigeonResult = [[PigeonRemoteConfigValue alloc] init]; + pigeonResult.value = GetNullableObjectAtIndex(list, 0); + pigeonResult.source = [GetNullableObjectAtIndex(list, 1) integerValue]; + return pigeonResult; +} ++ (nullable PigeonRemoteConfigValue *)nullableFromList:(NSArray *)list { + return (list) ? [PigeonRemoteConfigValue fromList:list] : nil; +} +- (NSArray *)toList { + return @[ + (self.value ?: [NSNull null]), + @(self.source), + ]; +} +@end + +@implementation PigeonFirebaseApp ++ (instancetype)makeWithAppName:(NSString *)appName + tenantId:(nullable NSString *)tenantId { + PigeonFirebaseApp* pigeonResult = [[PigeonFirebaseApp alloc] init]; + pigeonResult.appName = appName; + pigeonResult.tenantId = tenantId; + return pigeonResult; +} ++ (PigeonFirebaseApp *)fromList:(NSArray *)list { + PigeonFirebaseApp *pigeonResult = [[PigeonFirebaseApp alloc] init]; + pigeonResult.appName = GetNullableObjectAtIndex(list, 0); + NSAssert(pigeonResult.appName != nil, @""); + pigeonResult.tenantId = GetNullableObjectAtIndex(list, 1); + return pigeonResult; +} ++ (nullable PigeonFirebaseApp *)nullableFromList:(NSArray *)list { + return (list) ? [PigeonFirebaseApp fromList:list] : nil; +} +- (NSArray *)toList { + return @[ + (self.appName ?: [NSNull null]), + (self.tenantId ?: [NSNull null]), + ]; +} +@end + +@interface FirebaseRemoteConfigHostApiCodecReader : FlutterStandardReader +@end +@implementation FirebaseRemoteConfigHostApiCodecReader +- (nullable id)readValueOfType:(UInt8)type { + switch (type) { + case 128: + return [PigeonFirebaseApp fromList:[self readValue]]; + case 129: + return [PigeonRemoteConfigSettings fromList:[self readValue]]; + case 130: + return [PigeonRemoteConfigValue fromList:[self readValue]]; + default: + return [super readValueOfType:type]; + } +} +@end + +@interface FirebaseRemoteConfigHostApiCodecWriter : FlutterStandardWriter +@end +@implementation FirebaseRemoteConfigHostApiCodecWriter +- (void)writeValue:(id)value { + if ([value isKindOfClass:[PigeonFirebaseApp class]]) { + [self writeByte:128]; + [self writeValue:[value toList]]; + } else if ([value isKindOfClass:[PigeonRemoteConfigSettings class]]) { + [self writeByte:129]; + [self writeValue:[value toList]]; + } else if ([value isKindOfClass:[PigeonRemoteConfigValue class]]) { + [self writeByte:130]; + [self writeValue:[value toList]]; + } else { + [super writeValue:value]; + } +} +@end + +@interface FirebaseRemoteConfigHostApiCodecReaderWriter : FlutterStandardReaderWriter +@end +@implementation FirebaseRemoteConfigHostApiCodecReaderWriter +- (FlutterStandardWriter *)writerWithData:(NSMutableData *)data { + return [[FirebaseRemoteConfigHostApiCodecWriter alloc] initWithData:data]; +} +- (FlutterStandardReader *)readerWithData:(NSData *)data { + return [[FirebaseRemoteConfigHostApiCodecReader alloc] initWithData:data]; +} +@end + +NSObject *FirebaseRemoteConfigHostApiGetCodec(void) { + static FlutterStandardMessageCodec *sSharedObject = nil; + static dispatch_once_t sPred = 0; + dispatch_once(&sPred, ^{ + FirebaseRemoteConfigHostApiCodecReaderWriter *readerWriter = [[FirebaseRemoteConfigHostApiCodecReaderWriter alloc] init]; + sSharedObject = [FlutterStandardMessageCodec codecWithReaderWriter:readerWriter]; + }); + return sSharedObject; +} + +void FirebaseRemoteConfigHostApiSetup(id binaryMessenger, NSObject *api) { + { + FlutterBasicMessageChannel *channel = + [[FlutterBasicMessageChannel alloc] + initWithName:@"dev.flutter.pigeon.FirebaseRemoteConfigHostApi.activate" + binaryMessenger:binaryMessenger + codec:FirebaseRemoteConfigHostApiGetCodec()]; + if (api) { + NSCAssert([api respondsToSelector:@selector(activateApp:completion:)], @"FirebaseRemoteConfigHostApi api (%@) doesn't respond to @selector(activateApp:completion:)", api); + [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { + NSArray *args = message; + PigeonFirebaseApp *arg_app = GetNullableObjectAtIndex(args, 0); + [api activateApp:arg_app completion:^(NSNumber *_Nullable output, FlutterError *_Nullable error) { + callback(wrapResult(output, error)); + }]; + }]; + } else { + [channel setMessageHandler:nil]; + } + } + { + FlutterBasicMessageChannel *channel = + [[FlutterBasicMessageChannel alloc] + initWithName:@"dev.flutter.pigeon.FirebaseRemoteConfigHostApi.ensureInitialized" + binaryMessenger:binaryMessenger + codec:FirebaseRemoteConfigHostApiGetCodec()]; + if (api) { + NSCAssert([api respondsToSelector:@selector(ensureInitializedApp:completion:)], @"FirebaseRemoteConfigHostApi api (%@) doesn't respond to @selector(ensureInitializedApp:completion:)", api); + [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { + NSArray *args = message; + PigeonFirebaseApp *arg_app = GetNullableObjectAtIndex(args, 0); + [api ensureInitializedApp:arg_app completion:^(FlutterError *_Nullable error) { + callback(wrapResult(nil, error)); + }]; + }]; + } else { + [channel setMessageHandler:nil]; + } + } + { + FlutterBasicMessageChannel *channel = + [[FlutterBasicMessageChannel alloc] + initWithName:@"dev.flutter.pigeon.FirebaseRemoteConfigHostApi.fetch" + binaryMessenger:binaryMessenger + codec:FirebaseRemoteConfigHostApiGetCodec()]; + if (api) { + NSCAssert([api respondsToSelector:@selector(fetchApp:completion:)], @"FirebaseRemoteConfigHostApi api (%@) doesn't respond to @selector(fetchApp:completion:)", api); + [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { + NSArray *args = message; + PigeonFirebaseApp *arg_app = GetNullableObjectAtIndex(args, 0); + [api fetchApp:arg_app completion:^(FlutterError *_Nullable error) { + callback(wrapResult(nil, error)); + }]; + }]; + } else { + [channel setMessageHandler:nil]; + } + } + { + FlutterBasicMessageChannel *channel = + [[FlutterBasicMessageChannel alloc] + initWithName:@"dev.flutter.pigeon.FirebaseRemoteConfigHostApi.fetchAndActivate" + binaryMessenger:binaryMessenger + codec:FirebaseRemoteConfigHostApiGetCodec()]; + if (api) { + NSCAssert([api respondsToSelector:@selector(fetchAndActivateApp:completion:)], @"FirebaseRemoteConfigHostApi api (%@) doesn't respond to @selector(fetchAndActivateApp:completion:)", api); + [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { + NSArray *args = message; + PigeonFirebaseApp *arg_app = GetNullableObjectAtIndex(args, 0); + [api fetchAndActivateApp:arg_app completion:^(NSNumber *_Nullable output, FlutterError *_Nullable error) { + callback(wrapResult(output, error)); + }]; + }]; + } else { + [channel setMessageHandler:nil]; + } + } + { + FlutterBasicMessageChannel *channel = + [[FlutterBasicMessageChannel alloc] + initWithName:@"dev.flutter.pigeon.FirebaseRemoteConfigHostApi.getAll" + binaryMessenger:binaryMessenger + codec:FirebaseRemoteConfigHostApiGetCodec()]; + if (api) { + NSCAssert([api respondsToSelector:@selector(getAllApp:error:)], @"FirebaseRemoteConfigHostApi api (%@) doesn't respond to @selector(getAllApp:error:)", api); + [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { + NSArray *args = message; + PigeonFirebaseApp *arg_app = GetNullableObjectAtIndex(args, 0); + FlutterError *error; + NSDictionary *output = [api getAllApp:arg_app error:&error]; + callback(wrapResult(output, error)); + }]; + } else { + [channel setMessageHandler:nil]; + } + } + { + FlutterBasicMessageChannel *channel = + [[FlutterBasicMessageChannel alloc] + initWithName:@"dev.flutter.pigeon.FirebaseRemoteConfigHostApi.getBool" + binaryMessenger:binaryMessenger + codec:FirebaseRemoteConfigHostApiGetCodec()]; + if (api) { + NSCAssert([api respondsToSelector:@selector(getBoolApp:key:error:)], @"FirebaseRemoteConfigHostApi api (%@) doesn't respond to @selector(getBoolApp:key:error:)", api); + [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { + NSArray *args = message; + PigeonFirebaseApp *arg_app = GetNullableObjectAtIndex(args, 0); + NSString *arg_key = GetNullableObjectAtIndex(args, 1); + FlutterError *error; + NSNumber *output = [api getBoolApp:arg_app key:arg_key error:&error]; + callback(wrapResult(output, error)); + }]; + } else { + [channel setMessageHandler:nil]; + } + } + { + FlutterBasicMessageChannel *channel = + [[FlutterBasicMessageChannel alloc] + initWithName:@"dev.flutter.pigeon.FirebaseRemoteConfigHostApi.getInt" + binaryMessenger:binaryMessenger + codec:FirebaseRemoteConfigHostApiGetCodec()]; + if (api) { + NSCAssert([api respondsToSelector:@selector(getIntApp:key:error:)], @"FirebaseRemoteConfigHostApi api (%@) doesn't respond to @selector(getIntApp:key:error:)", api); + [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { + NSArray *args = message; + PigeonFirebaseApp *arg_app = GetNullableObjectAtIndex(args, 0); + NSString *arg_key = GetNullableObjectAtIndex(args, 1); + FlutterError *error; + NSNumber *output = [api getIntApp:arg_app key:arg_key error:&error]; + callback(wrapResult(output, error)); + }]; + } else { + [channel setMessageHandler:nil]; + } + } + { + FlutterBasicMessageChannel *channel = + [[FlutterBasicMessageChannel alloc] + initWithName:@"dev.flutter.pigeon.FirebaseRemoteConfigHostApi.getDouble" + binaryMessenger:binaryMessenger + codec:FirebaseRemoteConfigHostApiGetCodec()]; + if (api) { + NSCAssert([api respondsToSelector:@selector(getDoubleApp:key:error:)], @"FirebaseRemoteConfigHostApi api (%@) doesn't respond to @selector(getDoubleApp:key:error:)", api); + [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { + NSArray *args = message; + PigeonFirebaseApp *arg_app = GetNullableObjectAtIndex(args, 0); + NSString *arg_key = GetNullableObjectAtIndex(args, 1); + FlutterError *error; + NSNumber *output = [api getDoubleApp:arg_app key:arg_key error:&error]; + callback(wrapResult(output, error)); + }]; + } else { + [channel setMessageHandler:nil]; + } + } + { + FlutterBasicMessageChannel *channel = + [[FlutterBasicMessageChannel alloc] + initWithName:@"dev.flutter.pigeon.FirebaseRemoteConfigHostApi.getString" + binaryMessenger:binaryMessenger + codec:FirebaseRemoteConfigHostApiGetCodec()]; + if (api) { + NSCAssert([api respondsToSelector:@selector(getStringApp:key:error:)], @"FirebaseRemoteConfigHostApi api (%@) doesn't respond to @selector(getStringApp:key:error:)", api); + [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { + NSArray *args = message; + PigeonFirebaseApp *arg_app = GetNullableObjectAtIndex(args, 0); + NSString *arg_key = GetNullableObjectAtIndex(args, 1); + FlutterError *error; + NSString *output = [api getStringApp:arg_app key:arg_key error:&error]; + callback(wrapResult(output, error)); + }]; + } else { + [channel setMessageHandler:nil]; + } + } + { + FlutterBasicMessageChannel *channel = + [[FlutterBasicMessageChannel alloc] + initWithName:@"dev.flutter.pigeon.FirebaseRemoteConfigHostApi.getValue" + binaryMessenger:binaryMessenger + codec:FirebaseRemoteConfigHostApiGetCodec()]; + if (api) { + NSCAssert([api respondsToSelector:@selector(getValueApp:key:error:)], @"FirebaseRemoteConfigHostApi api (%@) doesn't respond to @selector(getValueApp:key:error:)", api); + [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { + NSArray *args = message; + PigeonFirebaseApp *arg_app = GetNullableObjectAtIndex(args, 0); + NSString *arg_key = GetNullableObjectAtIndex(args, 1); + FlutterError *error; + PigeonRemoteConfigValue *output = [api getValueApp:arg_app key:arg_key error:&error]; + callback(wrapResult(output, error)); + }]; + } else { + [channel setMessageHandler:nil]; + } + } + { + FlutterBasicMessageChannel *channel = + [[FlutterBasicMessageChannel alloc] + initWithName:@"dev.flutter.pigeon.FirebaseRemoteConfigHostApi.setConfigSettings" + binaryMessenger:binaryMessenger + codec:FirebaseRemoteConfigHostApiGetCodec()]; + if (api) { + NSCAssert([api respondsToSelector:@selector(setConfigSettingsApp:remoteConfigSettings:completion:)], @"FirebaseRemoteConfigHostApi api (%@) doesn't respond to @selector(setConfigSettingsApp:remoteConfigSettings:completion:)", api); + [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { + NSArray *args = message; + PigeonFirebaseApp *arg_app = GetNullableObjectAtIndex(args, 0); + PigeonRemoteConfigSettings *arg_remoteConfigSettings = GetNullableObjectAtIndex(args, 1); + [api setConfigSettingsApp:arg_app remoteConfigSettings:arg_remoteConfigSettings completion:^(FlutterError *_Nullable error) { + callback(wrapResult(nil, error)); + }]; + }]; + } else { + [channel setMessageHandler:nil]; + } + } + { + FlutterBasicMessageChannel *channel = + [[FlutterBasicMessageChannel alloc] + initWithName:@"dev.flutter.pigeon.FirebaseRemoteConfigHostApi.setDefaults" + binaryMessenger:binaryMessenger + codec:FirebaseRemoteConfigHostApiGetCodec()]; + if (api) { + NSCAssert([api respondsToSelector:@selector(setDefaultsApp:defaultParameters:completion:)], @"FirebaseRemoteConfigHostApi api (%@) doesn't respond to @selector(setDefaultsApp:defaultParameters:completion:)", api); + [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { + NSArray *args = message; + PigeonFirebaseApp *arg_app = GetNullableObjectAtIndex(args, 0); + NSDictionary *arg_defaultParameters = GetNullableObjectAtIndex(args, 1); + [api setDefaultsApp:arg_app defaultParameters:arg_defaultParameters completion:^(FlutterError *_Nullable error) { + callback(wrapResult(nil, error)); + }]; + }]; + } else { + [channel setMessageHandler:nil]; + } + } +} diff --git a/packages/firebase_remote_config/firebase_remote_config/lib/src/firebase_remote_config.dart b/packages/firebase_remote_config/firebase_remote_config/lib/src/firebase_remote_config.dart index 3388c3d9a1d1..1de03cc70918 100644 --- a/packages/firebase_remote_config/firebase_remote_config/lib/src/firebase_remote_config.dart +++ b/packages/firebase_remote_config/firebase_remote_config/lib/src/firebase_remote_config.dart @@ -51,12 +51,12 @@ class FirebaseRemoteConfig extends FirebasePluginPlatform with ChangeNotifier { /// Returns the status of the last fetch attempt. RemoteConfigFetchStatus get lastFetchStatus { - return _delegate.lastFetchStatus; + return _delegate.getFetchStatus(); } /// Returns the [RemoteConfigSettings] of the current instance. RemoteConfigSettings get settings { - return _delegate.settings; + return _delegate.getSettings(); } /// Makes the last fetched config available to getters. @@ -94,7 +94,7 @@ class FirebaseRemoteConfig extends FirebasePluginPlatform with ChangeNotifier { /// Returns a Map of all Remote Config parameters. Map getAll() { - return _delegate.getAll(); + return _delegate.getAllConverted(); } /// Gets the value for a given key as a bool. @@ -119,7 +119,7 @@ class FirebaseRemoteConfig extends FirebasePluginPlatform with ChangeNotifier { /// Gets the [RemoteConfigValue] for a given key. RemoteConfigValue getValue(String key) { - return _delegate.getValue(key); + return _delegate.getValueConverted(key); } /// Sets the [RemoteConfigSettings] for the current instance. @@ -131,7 +131,7 @@ class FirebaseRemoteConfig extends FirebasePluginPlatform with ChangeNotifier { if (remoteConfigSettings.fetchTimeout.inSeconds == 0) { remoteConfigSettings.fetchTimeout = const Duration(seconds: 60); } - return _delegate.setConfigSettings(remoteConfigSettings); + return _delegate.setConfigSettingsConverted(remoteConfigSettings); } /// Sets the default parameter values for the current instance. diff --git a/packages/firebase_remote_config/firebase_remote_config/pubspec.yaml b/packages/firebase_remote_config/firebase_remote_config/pubspec.yaml index 3ead67e06970..659243ec54dd 100644 --- a/packages/firebase_remote_config/firebase_remote_config/pubspec.yaml +++ b/packages/firebase_remote_config/firebase_remote_config/pubspec.yaml @@ -40,3 +40,5 @@ flutter: pluginClass: FLTFirebaseRemoteConfigPlugin web: default_package: firebase_remote_config_web + windows: + pluginClass: FirebaseRemoteConfigPluginCApi diff --git a/packages/firebase_remote_config/firebase_remote_config/windows/CMakeLists.txt b/packages/firebase_remote_config/firebase_remote_config/windows/CMakeLists.txt new file mode 100644 index 000000000000..51f67ed7ba33 --- /dev/null +++ b/packages/firebase_remote_config/firebase_remote_config/windows/CMakeLists.txt @@ -0,0 +1,69 @@ +# The Flutter tooling requires that developers have a version of Visual Studio +# installed that includes CMake 3.14 or later. You should not increase this +# version, as doing so will cause the plugin to fail to compile for some +# customers of the plugin. +cmake_minimum_required(VERSION 3.14) + + +# Project-level configuration. +set(PROJECT_NAME "flutterfire_remote_config") +project(${PROJECT_NAME} LANGUAGES CXX) + +# This value is used when generating builds using this plugin, so it must +# not be changed +set(PLUGIN_NAME "firebase_remote_config_plugin") + +# Any new source files that you add to the plugin should be added here. +list(APPEND PLUGIN_SOURCES + "firebase_remote_config_plugin.cpp" + "firebase_remote_config_plugin.h" + "messages.g.cpp" + "messages.g.h" +) + +# Define the plugin library target. Its name must not be changed (see comment +# on PLUGIN_NAME above). +add_library(${PLUGIN_NAME} SHARED + "include/firebase_remote_config/firebase_remote_config_plugin_c_api.h" + "firebase_remote_config_plugin_c_api.cpp" + ${PLUGIN_SOURCES} +) + + +# Apply a standard set of build settings that are configured in the +# application-level CMakeLists.txt. This can be removed for plugins that want +# full control over build settings. +apply_standard_settings(${PLUGIN_NAME}) + +# Symbols are hidden by default to reduce the chance of accidental conflicts +# between plugins. This should not be removed; any symbols that should be +# exported should be explicitly exported with the FLUTTER_PLUGIN_EXPORT macro. +set_target_properties(${PLUGIN_NAME} PROPERTIES + CXX_VISIBILITY_PRESET hidden) +target_compile_definitions(${PLUGIN_NAME} PRIVATE FLUTTER_PLUGIN_IMPL) + +# Source include directories and library dependencies. Add any plugin-specific +# dependencies here. +set(MSVC_RUNTIME_MODE MD) +message("CMAKE_CURRENT_SOURCE_DIR is ${CMAKE_CURRENT_SOURCE_DIR}") +# set(FIREBASE_CORE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../../firebase_core") +# message("FIREBASE_CORE_DIR is ${FIREBASE_CORE_DIR}") +# add_subdirectory(${FIREBASE_CORE_DIR}) +#add_subdirectory(${FIREBASE_CPP_SDK_DIR} bin/ EXCLUDE_FROM_ALL) +# target_include_directories(${PLUGIN_NAME} INTERFACE +# "${FIREBASE_CPP_SDK_DIR}/include") +set(firebase_libs firebase_core_plugin firebase_remote_config firebase_app) +set(ADDITIONAL_LIBS advapi32 ws2_32 crypt32 rpcrt4 ole32) +target_link_libraries(${PLUGIN_NAME} PRIVATE "${firebase_libs}" "${ADDITIONAL_LIBS}") + +target_include_directories(${PLUGIN_NAME} INTERFACE + "${CMAKE_CURRENT_SOURCE_DIR}/include") +target_link_libraries(${PLUGIN_NAME} PRIVATE flutter flutter_wrapper_plugin) + +# List of absolute paths to libraries that should be bundled with the plugin. +# This list could contain prebuilt libraries, or libraries created by an +# external build triggered from this build file. +set(firebase_remote_config_bundled_libraries + "" + PARENT_SCOPE +) diff --git a/packages/firebase_remote_config/firebase_remote_config/windows/firebase_remote_config_plugin.cpp b/packages/firebase_remote_config/firebase_remote_config/windows/firebase_remote_config_plugin.cpp new file mode 100644 index 000000000000..5a18983fe682 --- /dev/null +++ b/packages/firebase_remote_config/firebase_remote_config/windows/firebase_remote_config_plugin.cpp @@ -0,0 +1,184 @@ +// Copyright 2023, the Chromium project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +#include "firebase_remote_config_plugin.h" + +// This must be included before many other Windows headers. +#include + +#include "firebase/app.h" +#include "firebase/future.h" +#include "firebase/remote_config.h" +#include "messages.g.h" + +// For getPlatformVersion; remove unless needed for your plugin implementation. +#include +#include +#include +#include +#include + +// #include +#include +#include +#include +#include +#include +#include +// #include +#include +using ::firebase::App; +using ::firebase::Future; +using ::firebase::remote_config::RemoteConfig; + +namespace firebase_remote_config_windows { + +// static +void FirebaseRemoteConfigPlugin::RegisterWithRegistrar( + flutter::PluginRegistrarWindows* registrar) { + auto plugin = std::make_unique(); + + FirebaseRemoteConfigHostApi::SetUp(registrar->messenger(), plugin.get()); + + registrar->AddPlugin(std::move(plugin)); +} + +FirebaseRemoteConfigPlugin::FirebaseRemoteConfigPlugin() {} + +FirebaseRemoteConfigPlugin::~FirebaseRemoteConfigPlugin() = default; + +void FirebaseRemoteConfigPlugin::Activate( + const PigeonFirebaseApp& app, + std::function reply)> result) { + App* cpp_app = App::GetInstance(app.app_name().c_str()); + RemoteConfig* rc = RemoteConfig::GetInstance(cpp_app); + + bool flutter_result; + + Future activated_result = rc->Activate(); + activated_result.OnCompletion( + [](const Future& bool_result, void* user_data) { + bool* casted_result = static_cast(user_data); + *casted_result = bool_result.result(); + }, + &flutter_result); + + while (activated_result.status() == ::firebase::kFutureStatusPending) { + Sleep(1000); + } + + result(flutter_result); +} + +void FirebaseRemoteConfigPlugin::EnsureInitialized( + const PigeonFirebaseApp& app, + std::function reply)> result) { + App* cpp_app = App::GetInstance(app.app_name().c_str()); + RemoteConfig* rc = RemoteConfig::GetInstance(cpp_app); + + Future<::firebase::remote_config::ConfigInfo> init_result = + rc->EnsureInitialized(); +} + +void FirebaseRemoteConfigPlugin::Fetch( + const PigeonFirebaseApp& app, + std::function reply)> result) { + App* cpp_app = App::GetInstance(app.app_name().c_str()); + RemoteConfig* rc = RemoteConfig::GetInstance(cpp_app); + + Future fetch_result = rc->Fetch(); + fetch_result.OnCompletion([](const Future& void_result) { + // print message? + }); + + while (fetch_result.status() == ::firebase::kFutureStatusPending) { + Sleep(1000); + } + + result(std::nullopt); +} + +void FirebaseRemoteConfigPlugin::FetchAndActivate( + const PigeonFirebaseApp& app, + std::function reply)> result) { + App* cpp_app = App::GetInstance(app.app_name().c_str()); + RemoteConfig* rc = RemoteConfig::GetInstance(cpp_app); + + bool flutter_result; + + Future fa_result = rc->FetchAndActivate(); + fa_result.OnCompletion( + [](const Future& bool_result, void* user_data) { + bool* casted_result = static_cast(user_data); + *casted_result = bool_result.result(); + }, + &flutter_result); + + while (fa_result.status() == ::firebase::kFutureStatusPending) { + Sleep(1000); + } + + result(flutter_result); +} + +ErrorOr FirebaseRemoteConfigPlugin::GetAll( + const PigeonFirebaseApp& app) { + return flutter::EncodableMap(); +} + +ErrorOr FirebaseRemoteConfigPlugin::GetBool(const PigeonFirebaseApp& app, + const std::string& key) { + App* cpp_app = App::GetInstance(app.app_name().c_str()); + RemoteConfig* rc = RemoteConfig::GetInstance(cpp_app); + + return rc->GetBoolean(key.c_str()); +} + +ErrorOr FirebaseRemoteConfigPlugin::GetInt( + const PigeonFirebaseApp& app, const std::string& key) { + App* cpp_app = App::GetInstance(app.app_name().c_str()); + RemoteConfig* rc = RemoteConfig::GetInstance(cpp_app); + + return rc->GetLong(key.c_str()); +} + +ErrorOr FirebaseRemoteConfigPlugin::GetDouble( + const PigeonFirebaseApp& app, const std::string& key) { + App* cpp_app = App::GetInstance(app.app_name().c_str()); + RemoteConfig* rc = RemoteConfig::GetInstance(cpp_app); + + return rc->GetDouble(key.c_str()); +} + +ErrorOr FirebaseRemoteConfigPlugin::GetString( + const PigeonFirebaseApp& app, const std::string& key) { + App* cpp_app = App::GetInstance(app.app_name().c_str()); + RemoteConfig* rc = RemoteConfig::GetInstance(cpp_app); + + return rc->GetString(key.c_str()); +} + +ErrorOr FirebaseRemoteConfigPlugin::GetValue( + const PigeonFirebaseApp& app, const std::string& key) { + // App* cpp_app = App::GetInstance(app.app_name().c_str()); + // RemoteConfig* rc = RemoteConfig::GetInstance(cpp_app); + + // std::vector data = rc->GetData(key.c_str()); + + PigeonRemoteConfigValue* value_ptr = + new PigeonRemoteConfigValue(PigeonValueSource::valueStatic); + return *value_ptr; +} + +void FirebaseRemoteConfigPlugin::SetConfigSettings( + const PigeonFirebaseApp& app, + const PigeonRemoteConfigSettings& remote_config_settings, + std::function reply)> result) {} + +void FirebaseRemoteConfigPlugin::SetDefaults( + const PigeonFirebaseApp& app, + const flutter::EncodableMap& default_parameters, + std::function reply)> result) {} + +} // namespace firebase_remote_config_windows diff --git a/packages/firebase_remote_config/firebase_remote_config/windows/firebase_remote_config_plugin.h b/packages/firebase_remote_config/firebase_remote_config/windows/firebase_remote_config_plugin.h new file mode 100644 index 000000000000..a7fa477e4cbc --- /dev/null +++ b/packages/firebase_remote_config/firebase_remote_config/windows/firebase_remote_config_plugin.h @@ -0,0 +1,74 @@ +/* + * Copyright 2023, the Chromium project authors. Please see the AUTHORS file + * for details. All rights reserved. Use of this source code is governed by a + * BSD-style license that can be found in the LICENSE file. + */ + +#ifndef FLUTTER_PLUGIN_FIREBASE_REMOTE_CONFIG_PLUGIN_H_ +#define FLUTTER_PLUGIN_FIREBASE_REMOTE_CONFIG_PLUGIN_H_ + +#include +#include + +#include + +#include "messages.g.h" + +namespace firebase_remote_config_windows { + +class FirebaseRemoteConfigPlugin : public flutter::Plugin, + public FirebaseRemoteConfigHostApi { + public: + static void RegisterWithRegistrar(flutter::PluginRegistrarWindows* registrar); + + FirebaseRemoteConfigPlugin(); + + virtual ~FirebaseRemoteConfigPlugin(); + + // Disallow copy and assign. + FirebaseRemoteConfigPlugin(const FirebaseRemoteConfigPlugin&) = delete; + FirebaseRemoteConfigPlugin& operator=(const FirebaseRemoteConfigPlugin&) = + delete; + + // FirebaseRemoteConfigHostApi + virtual void Activate( + const PigeonFirebaseApp& app, + std::function reply)> result) override; + virtual void EnsureInitialized( + const PigeonFirebaseApp& app, + std::function reply)> result) override; + virtual void Fetch( + const PigeonFirebaseApp& app, + std::function reply)> result) override; + virtual void FetchAndActivate( + const PigeonFirebaseApp& app, + std::function reply)> result) override; + + virtual ErrorOr GetAll( + const PigeonFirebaseApp& app) override; + virtual ErrorOr GetBool(const PigeonFirebaseApp& app, + const std::string& key) override; + virtual ErrorOr GetInt(const PigeonFirebaseApp& app, + const std::string& key) override; + virtual ErrorOr GetDouble(const PigeonFirebaseApp& app, + const std::string& key) override; + virtual ErrorOr GetString(const PigeonFirebaseApp& app, + const std::string& key) override; + virtual ErrorOr GetValue( + const PigeonFirebaseApp& app, const std::string& key) override; + virtual void SetConfigSettings( + const PigeonFirebaseApp& app, + const PigeonRemoteConfigSettings& remote_config_settings, + std::function reply)> result) override; + virtual void SetDefaults( + const PigeonFirebaseApp& app, + const flutter::EncodableMap& default_parameters, + std::function reply)> result) override; + + private: + bool rcInitialized = false; +}; + +} // namespace firebase_remote_config_windows + +#endif // FLUTTER_PLUGIN_FIREBASE_REMOTE_CONFIG_PLUGIN_H_ diff --git a/packages/firebase_remote_config/firebase_remote_config/windows/firebase_remote_config_plugin_c_api.cpp b/packages/firebase_remote_config/firebase_remote_config/windows/firebase_remote_config_plugin_c_api.cpp new file mode 100644 index 000000000000..f20b22164198 --- /dev/null +++ b/packages/firebase_remote_config/firebase_remote_config/windows/firebase_remote_config_plugin_c_api.cpp @@ -0,0 +1,16 @@ +// Copyright 2023, the Chromium project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +#include "include/firebase_remote_config/firebase_remote_config_plugin_c_api.h" + +#include + +#include "firebase_remote_config_plugin.h" + +void FirebaseRemoteConfigPluginCApiRegisterWithRegistrar( + FlutterDesktopPluginRegistrarRef registrar) { + firebase_remote_config_windows::FirebaseRemoteConfigPlugin::RegisterWithRegistrar( + flutter::PluginRegistrarManager::GetInstance() + ->GetRegistrar(registrar)); +} diff --git a/packages/firebase_remote_config/firebase_remote_config/windows/include/firebase_remote_config/firebase_remote_config_plugin_c_api.h b/packages/firebase_remote_config/firebase_remote_config/windows/include/firebase_remote_config/firebase_remote_config_plugin_c_api.h new file mode 100644 index 000000000000..f2b5d9b7d085 --- /dev/null +++ b/packages/firebase_remote_config/firebase_remote_config/windows/include/firebase_remote_config/firebase_remote_config_plugin_c_api.h @@ -0,0 +1,29 @@ +/* + * Copyright 2023, the Chromium project authors. Please see the AUTHORS file + * for details. All rights reserved. Use of this source code is governed by a + * BSD-style license that can be found in the LICENSE file. + */ + +#ifndef FLUTTER_PLUGIN_FIREBASE_REMOTE_CONFIG_PLUGIN_C_API_H_ +#define FLUTTER_PLUGIN_FIREBASE_REMOTE_CONFIG_PLUGIN_C_API_H_ + +#include + +#ifdef FLUTTER_PLUGIN_IMPL +#define FLUTTER_PLUGIN_EXPORT __declspec(dllexport) +#else +#define FLUTTER_PLUGIN_EXPORT __declspec(dllimport) +#endif + +#if defined(__cplusplus) +extern "C" { +#endif + +FLUTTER_PLUGIN_EXPORT void FirebaseRemoteConfigPluginCApiRegisterWithRegistrar( + FlutterDesktopPluginRegistrarRef registrar); + +#if defined(__cplusplus) +} // extern "C" +#endif + +#endif // FLUTTER_PLUGIN_FIREBASE_REMOTE_CONFIG_PLUGIN_C_API_H_ diff --git a/packages/firebase_remote_config/firebase_remote_config/windows/messages.g.cpp b/packages/firebase_remote_config/firebase_remote_config/windows/messages.g.cpp new file mode 100644 index 000000000000..287ae2b59430 --- /dev/null +++ b/packages/firebase_remote_config/firebase_remote_config/windows/messages.g.cpp @@ -0,0 +1,622 @@ +// Copyright 2023, the Chromium project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Autogenerated from Pigeon (v9.2.5), do not edit directly. +// See also: https://pub.dev/packages/pigeon + +#undef _HAS_EXCEPTIONS + +#include "messages.g.h" + +#include +#include +#include +#include + +#include +#include +#include + +namespace firebase_remote_config_windows { +using flutter::BasicMessageChannel; +using flutter::CustomEncodableValue; +using flutter::EncodableList; +using flutter::EncodableMap; +using flutter::EncodableValue; + +// PigeonRemoteConfigSettings + +PigeonRemoteConfigSettings::PigeonRemoteConfigSettings( + int64_t fetch_timeout, + int64_t minimum_fetch_interval) + : fetch_timeout_(fetch_timeout), + minimum_fetch_interval_(minimum_fetch_interval) {} + +int64_t PigeonRemoteConfigSettings::fetch_timeout() const { + return fetch_timeout_; +} + +void PigeonRemoteConfigSettings::set_fetch_timeout(int64_t value_arg) { + fetch_timeout_ = value_arg; +} + + +int64_t PigeonRemoteConfigSettings::minimum_fetch_interval() const { + return minimum_fetch_interval_; +} + +void PigeonRemoteConfigSettings::set_minimum_fetch_interval(int64_t value_arg) { + minimum_fetch_interval_ = value_arg; +} + + +EncodableList PigeonRemoteConfigSettings::ToEncodableList() const { + EncodableList list; + list.reserve(2); + list.push_back(EncodableValue(fetch_timeout_)); + list.push_back(EncodableValue(minimum_fetch_interval_)); + return list; +} + +PigeonRemoteConfigSettings PigeonRemoteConfigSettings::FromEncodableList(const EncodableList& list) { + PigeonRemoteConfigSettings decoded( + list[0].LongValue(), + list[1].LongValue()); + return decoded; +} + +// PigeonRemoteConfigValue + +PigeonRemoteConfigValue::PigeonRemoteConfigValue(const PigeonValueSource& source) + : source_(source) {} + +PigeonRemoteConfigValue::PigeonRemoteConfigValue( + const EncodableList* value, + const PigeonValueSource& source) + : value_(value ? std::optional(*value) : std::nullopt), + source_(source) {} + +const EncodableList* PigeonRemoteConfigValue::value() const { + return value_ ? &(*value_) : nullptr; +} + +void PigeonRemoteConfigValue::set_value(const EncodableList* value_arg) { + value_ = value_arg ? std::optional(*value_arg) : std::nullopt; +} + +void PigeonRemoteConfigValue::set_value(const EncodableList& value_arg) { + value_ = value_arg; +} + + +const PigeonValueSource& PigeonRemoteConfigValue::source() const { + return source_; +} + +void PigeonRemoteConfigValue::set_source(const PigeonValueSource& value_arg) { + source_ = value_arg; +} + + +EncodableList PigeonRemoteConfigValue::ToEncodableList() const { + EncodableList list; + list.reserve(2); + list.push_back(value_ ? EncodableValue(*value_) : EncodableValue()); + list.push_back(EncodableValue((int)source_)); + return list; +} + +PigeonRemoteConfigValue PigeonRemoteConfigValue::FromEncodableList(const EncodableList& list) { + PigeonRemoteConfigValue decoded( + (PigeonValueSource)(std::get(list[1]))); + auto& encodable_value = list[0]; + if (!encodable_value.IsNull()) { + decoded.set_value(std::get(encodable_value)); + } + return decoded; +} + +// PigeonFirebaseApp + +PigeonFirebaseApp::PigeonFirebaseApp(const std::string& app_name) + : app_name_(app_name) {} + +PigeonFirebaseApp::PigeonFirebaseApp( + const std::string& app_name, + const std::string* tenant_id) + : app_name_(app_name), + tenant_id_(tenant_id ? std::optional(*tenant_id) : std::nullopt) {} + +const std::string& PigeonFirebaseApp::app_name() const { + return app_name_; +} + +void PigeonFirebaseApp::set_app_name(std::string_view value_arg) { + app_name_ = value_arg; +} + + +const std::string* PigeonFirebaseApp::tenant_id() const { + return tenant_id_ ? &(*tenant_id_) : nullptr; +} + +void PigeonFirebaseApp::set_tenant_id(const std::string_view* value_arg) { + tenant_id_ = value_arg ? std::optional(*value_arg) : std::nullopt; +} + +void PigeonFirebaseApp::set_tenant_id(std::string_view value_arg) { + tenant_id_ = value_arg; +} + + +EncodableList PigeonFirebaseApp::ToEncodableList() const { + EncodableList list; + list.reserve(2); + list.push_back(EncodableValue(app_name_)); + list.push_back(tenant_id_ ? EncodableValue(*tenant_id_) : EncodableValue()); + return list; +} + +PigeonFirebaseApp PigeonFirebaseApp::FromEncodableList(const EncodableList& list) { + PigeonFirebaseApp decoded( + std::get(list[0])); + auto& encodable_tenant_id = list[1]; + if (!encodable_tenant_id.IsNull()) { + decoded.set_tenant_id(std::get(encodable_tenant_id)); + } + return decoded; +} + + +FirebaseRemoteConfigHostApiCodecSerializer::FirebaseRemoteConfigHostApiCodecSerializer() {} + +EncodableValue FirebaseRemoteConfigHostApiCodecSerializer::ReadValueOfType( + uint8_t type, + flutter::ByteStreamReader* stream) const { + switch (type) { + case 128: + return CustomEncodableValue(PigeonFirebaseApp::FromEncodableList(std::get(ReadValue(stream)))); + case 129: + return CustomEncodableValue(PigeonRemoteConfigSettings::FromEncodableList(std::get(ReadValue(stream)))); + case 130: + return CustomEncodableValue(PigeonRemoteConfigValue::FromEncodableList(std::get(ReadValue(stream)))); + default: + return flutter::StandardCodecSerializer::ReadValueOfType(type, stream); + } +} + +void FirebaseRemoteConfigHostApiCodecSerializer::WriteValue( + const EncodableValue& value, + flutter::ByteStreamWriter* stream) const { + if (const CustomEncodableValue* custom_value = std::get_if(&value)) { + if (custom_value->type() == typeid(PigeonFirebaseApp)) { + stream->WriteByte(128); + WriteValue(EncodableValue(std::any_cast(*custom_value).ToEncodableList()), stream); + return; + } + if (custom_value->type() == typeid(PigeonRemoteConfigSettings)) { + stream->WriteByte(129); + WriteValue(EncodableValue(std::any_cast(*custom_value).ToEncodableList()), stream); + return; + } + if (custom_value->type() == typeid(PigeonRemoteConfigValue)) { + stream->WriteByte(130); + WriteValue(EncodableValue(std::any_cast(*custom_value).ToEncodableList()), stream); + return; + } + } + flutter::StandardCodecSerializer::WriteValue(value, stream); +} + +/// The codec used by FirebaseRemoteConfigHostApi. +const flutter::StandardMessageCodec& FirebaseRemoteConfigHostApi::GetCodec() { + return flutter::StandardMessageCodec::GetInstance(&FirebaseRemoteConfigHostApiCodecSerializer::GetInstance()); +} + +// Sets up an instance of `FirebaseRemoteConfigHostApi` to handle messages through the `binary_messenger`. +void FirebaseRemoteConfigHostApi::SetUp( + flutter::BinaryMessenger* binary_messenger, + FirebaseRemoteConfigHostApi* api) { + { + auto channel = std::make_unique>(binary_messenger, "dev.flutter.pigeon.FirebaseRemoteConfigHostApi.activate", &GetCodec()); + if (api != nullptr) { + channel->SetMessageHandler([api](const EncodableValue& message, const flutter::MessageReply& reply) { + try { + const auto& args = std::get(message); + const auto& encodable_app_arg = args.at(0); + if (encodable_app_arg.IsNull()) { + reply(WrapError("app_arg unexpectedly null.")); + return; + } + const auto& app_arg = std::any_cast(std::get(encodable_app_arg)); + api->Activate(app_arg, [reply](ErrorOr&& output) { + if (output.has_error()) { + reply(WrapError(output.error())); + return; + } + EncodableList wrapped; + wrapped.push_back(EncodableValue(std::move(output).TakeValue())); + reply(EncodableValue(std::move(wrapped))); + }); + } catch (const std::exception& exception) { + reply(WrapError(exception.what())); + } + }); + } else { + channel->SetMessageHandler(nullptr); + } + } + { + auto channel = std::make_unique>(binary_messenger, "dev.flutter.pigeon.FirebaseRemoteConfigHostApi.ensureInitialized", &GetCodec()); + if (api != nullptr) { + channel->SetMessageHandler([api](const EncodableValue& message, const flutter::MessageReply& reply) { + try { + const auto& args = std::get(message); + const auto& encodable_app_arg = args.at(0); + if (encodable_app_arg.IsNull()) { + reply(WrapError("app_arg unexpectedly null.")); + return; + } + const auto& app_arg = std::any_cast(std::get(encodable_app_arg)); + api->EnsureInitialized(app_arg, [reply](std::optional&& output) { + if (output.has_value()) { + reply(WrapError(output.value())); + return; + } + EncodableList wrapped; + wrapped.push_back(EncodableValue()); + reply(EncodableValue(std::move(wrapped))); + }); + } catch (const std::exception& exception) { + reply(WrapError(exception.what())); + } + }); + } else { + channel->SetMessageHandler(nullptr); + } + } + { + auto channel = std::make_unique>(binary_messenger, "dev.flutter.pigeon.FirebaseRemoteConfigHostApi.fetch", &GetCodec()); + if (api != nullptr) { + channel->SetMessageHandler([api](const EncodableValue& message, const flutter::MessageReply& reply) { + try { + const auto& args = std::get(message); + const auto& encodable_app_arg = args.at(0); + if (encodable_app_arg.IsNull()) { + reply(WrapError("app_arg unexpectedly null.")); + return; + } + const auto& app_arg = std::any_cast(std::get(encodable_app_arg)); + api->Fetch(app_arg, [reply](std::optional&& output) { + if (output.has_value()) { + reply(WrapError(output.value())); + return; + } + EncodableList wrapped; + wrapped.push_back(EncodableValue()); + reply(EncodableValue(std::move(wrapped))); + }); + } catch (const std::exception& exception) { + reply(WrapError(exception.what())); + } + }); + } else { + channel->SetMessageHandler(nullptr); + } + } + { + auto channel = std::make_unique>(binary_messenger, "dev.flutter.pigeon.FirebaseRemoteConfigHostApi.fetchAndActivate", &GetCodec()); + if (api != nullptr) { + channel->SetMessageHandler([api](const EncodableValue& message, const flutter::MessageReply& reply) { + try { + const auto& args = std::get(message); + const auto& encodable_app_arg = args.at(0); + if (encodable_app_arg.IsNull()) { + reply(WrapError("app_arg unexpectedly null.")); + return; + } + const auto& app_arg = std::any_cast(std::get(encodable_app_arg)); + api->FetchAndActivate(app_arg, [reply](ErrorOr&& output) { + if (output.has_error()) { + reply(WrapError(output.error())); + return; + } + EncodableList wrapped; + wrapped.push_back(EncodableValue(std::move(output).TakeValue())); + reply(EncodableValue(std::move(wrapped))); + }); + } catch (const std::exception& exception) { + reply(WrapError(exception.what())); + } + }); + } else { + channel->SetMessageHandler(nullptr); + } + } + { + auto channel = std::make_unique>(binary_messenger, "dev.flutter.pigeon.FirebaseRemoteConfigHostApi.getAll", &GetCodec()); + if (api != nullptr) { + channel->SetMessageHandler([api](const EncodableValue& message, const flutter::MessageReply& reply) { + try { + const auto& args = std::get(message); + const auto& encodable_app_arg = args.at(0); + if (encodable_app_arg.IsNull()) { + reply(WrapError("app_arg unexpectedly null.")); + return; + } + const auto& app_arg = std::any_cast(std::get(encodable_app_arg)); + ErrorOr output = api->GetAll(app_arg); + if (output.has_error()) { + reply(WrapError(output.error())); + return; + } + EncodableList wrapped; + wrapped.push_back(EncodableValue(std::move(output).TakeValue())); + reply(EncodableValue(std::move(wrapped))); + } catch (const std::exception& exception) { + reply(WrapError(exception.what())); + } + }); + } else { + channel->SetMessageHandler(nullptr); + } + } + { + auto channel = std::make_unique>(binary_messenger, "dev.flutter.pigeon.FirebaseRemoteConfigHostApi.getBool", &GetCodec()); + if (api != nullptr) { + channel->SetMessageHandler([api](const EncodableValue& message, const flutter::MessageReply& reply) { + try { + const auto& args = std::get(message); + const auto& encodable_app_arg = args.at(0); + if (encodable_app_arg.IsNull()) { + reply(WrapError("app_arg unexpectedly null.")); + return; + } + const auto& app_arg = std::any_cast(std::get(encodable_app_arg)); + const auto& encodable_key_arg = args.at(1); + if (encodable_key_arg.IsNull()) { + reply(WrapError("key_arg unexpectedly null.")); + return; + } + const auto& key_arg = std::get(encodable_key_arg); + ErrorOr output = api->GetBool(app_arg, key_arg); + if (output.has_error()) { + reply(WrapError(output.error())); + return; + } + EncodableList wrapped; + wrapped.push_back(EncodableValue(std::move(output).TakeValue())); + reply(EncodableValue(std::move(wrapped))); + } catch (const std::exception& exception) { + reply(WrapError(exception.what())); + } + }); + } else { + channel->SetMessageHandler(nullptr); + } + } + { + auto channel = std::make_unique>(binary_messenger, "dev.flutter.pigeon.FirebaseRemoteConfigHostApi.getInt", &GetCodec()); + if (api != nullptr) { + channel->SetMessageHandler([api](const EncodableValue& message, const flutter::MessageReply& reply) { + try { + const auto& args = std::get(message); + const auto& encodable_app_arg = args.at(0); + if (encodable_app_arg.IsNull()) { + reply(WrapError("app_arg unexpectedly null.")); + return; + } + const auto& app_arg = std::any_cast(std::get(encodable_app_arg)); + const auto& encodable_key_arg = args.at(1); + if (encodable_key_arg.IsNull()) { + reply(WrapError("key_arg unexpectedly null.")); + return; + } + const auto& key_arg = std::get(encodable_key_arg); + ErrorOr output = api->GetInt(app_arg, key_arg); + if (output.has_error()) { + reply(WrapError(output.error())); + return; + } + EncodableList wrapped; + wrapped.push_back(EncodableValue(std::move(output).TakeValue())); + reply(EncodableValue(std::move(wrapped))); + } catch (const std::exception& exception) { + reply(WrapError(exception.what())); + } + }); + } else { + channel->SetMessageHandler(nullptr); + } + } + { + auto channel = std::make_unique>(binary_messenger, "dev.flutter.pigeon.FirebaseRemoteConfigHostApi.getDouble", &GetCodec()); + if (api != nullptr) { + channel->SetMessageHandler([api](const EncodableValue& message, const flutter::MessageReply& reply) { + try { + const auto& args = std::get(message); + const auto& encodable_app_arg = args.at(0); + if (encodable_app_arg.IsNull()) { + reply(WrapError("app_arg unexpectedly null.")); + return; + } + const auto& app_arg = std::any_cast(std::get(encodable_app_arg)); + const auto& encodable_key_arg = args.at(1); + if (encodable_key_arg.IsNull()) { + reply(WrapError("key_arg unexpectedly null.")); + return; + } + const auto& key_arg = std::get(encodable_key_arg); + ErrorOr output = api->GetDouble(app_arg, key_arg); + if (output.has_error()) { + reply(WrapError(output.error())); + return; + } + EncodableList wrapped; + wrapped.push_back(EncodableValue(std::move(output).TakeValue())); + reply(EncodableValue(std::move(wrapped))); + } catch (const std::exception& exception) { + reply(WrapError(exception.what())); + } + }); + } else { + channel->SetMessageHandler(nullptr); + } + } + { + auto channel = std::make_unique>(binary_messenger, "dev.flutter.pigeon.FirebaseRemoteConfigHostApi.getString", &GetCodec()); + if (api != nullptr) { + channel->SetMessageHandler([api](const EncodableValue& message, const flutter::MessageReply& reply) { + try { + const auto& args = std::get(message); + const auto& encodable_app_arg = args.at(0); + if (encodable_app_arg.IsNull()) { + reply(WrapError("app_arg unexpectedly null.")); + return; + } + const auto& app_arg = std::any_cast(std::get(encodable_app_arg)); + const auto& encodable_key_arg = args.at(1); + if (encodable_key_arg.IsNull()) { + reply(WrapError("key_arg unexpectedly null.")); + return; + } + const auto& key_arg = std::get(encodable_key_arg); + ErrorOr output = api->GetString(app_arg, key_arg); + if (output.has_error()) { + reply(WrapError(output.error())); + return; + } + EncodableList wrapped; + wrapped.push_back(EncodableValue(std::move(output).TakeValue())); + reply(EncodableValue(std::move(wrapped))); + } catch (const std::exception& exception) { + reply(WrapError(exception.what())); + } + }); + } else { + channel->SetMessageHandler(nullptr); + } + } + { + auto channel = std::make_unique>(binary_messenger, "dev.flutter.pigeon.FirebaseRemoteConfigHostApi.getValue", &GetCodec()); + if (api != nullptr) { + channel->SetMessageHandler([api](const EncodableValue& message, const flutter::MessageReply& reply) { + try { + const auto& args = std::get(message); + const auto& encodable_app_arg = args.at(0); + if (encodable_app_arg.IsNull()) { + reply(WrapError("app_arg unexpectedly null.")); + return; + } + const auto& app_arg = std::any_cast(std::get(encodable_app_arg)); + const auto& encodable_key_arg = args.at(1); + if (encodable_key_arg.IsNull()) { + reply(WrapError("key_arg unexpectedly null.")); + return; + } + const auto& key_arg = std::get(encodable_key_arg); + ErrorOr output = api->GetValue(app_arg, key_arg); + if (output.has_error()) { + reply(WrapError(output.error())); + return; + } + EncodableList wrapped; + wrapped.push_back(CustomEncodableValue(std::move(output).TakeValue())); + reply(EncodableValue(std::move(wrapped))); + } catch (const std::exception& exception) { + reply(WrapError(exception.what())); + } + }); + } else { + channel->SetMessageHandler(nullptr); + } + } + { + auto channel = std::make_unique>(binary_messenger, "dev.flutter.pigeon.FirebaseRemoteConfigHostApi.setConfigSettings", &GetCodec()); + if (api != nullptr) { + channel->SetMessageHandler([api](const EncodableValue& message, const flutter::MessageReply& reply) { + try { + const auto& args = std::get(message); + const auto& encodable_app_arg = args.at(0); + if (encodable_app_arg.IsNull()) { + reply(WrapError("app_arg unexpectedly null.")); + return; + } + const auto& app_arg = std::any_cast(std::get(encodable_app_arg)); + const auto& encodable_remote_config_settings_arg = args.at(1); + if (encodable_remote_config_settings_arg.IsNull()) { + reply(WrapError("remote_config_settings_arg unexpectedly null.")); + return; + } + const auto& remote_config_settings_arg = std::any_cast(std::get(encodable_remote_config_settings_arg)); + api->SetConfigSettings(app_arg, remote_config_settings_arg, [reply](std::optional&& output) { + if (output.has_value()) { + reply(WrapError(output.value())); + return; + } + EncodableList wrapped; + wrapped.push_back(EncodableValue()); + reply(EncodableValue(std::move(wrapped))); + }); + } catch (const std::exception& exception) { + reply(WrapError(exception.what())); + } + }); + } else { + channel->SetMessageHandler(nullptr); + } + } + { + auto channel = std::make_unique>(binary_messenger, "dev.flutter.pigeon.FirebaseRemoteConfigHostApi.setDefaults", &GetCodec()); + if (api != nullptr) { + channel->SetMessageHandler([api](const EncodableValue& message, const flutter::MessageReply& reply) { + try { + const auto& args = std::get(message); + const auto& encodable_app_arg = args.at(0); + if (encodable_app_arg.IsNull()) { + reply(WrapError("app_arg unexpectedly null.")); + return; + } + const auto& app_arg = std::any_cast(std::get(encodable_app_arg)); + const auto& encodable_default_parameters_arg = args.at(1); + if (encodable_default_parameters_arg.IsNull()) { + reply(WrapError("default_parameters_arg unexpectedly null.")); + return; + } + const auto& default_parameters_arg = std::get(encodable_default_parameters_arg); + api->SetDefaults(app_arg, default_parameters_arg, [reply](std::optional&& output) { + if (output.has_value()) { + reply(WrapError(output.value())); + return; + } + EncodableList wrapped; + wrapped.push_back(EncodableValue()); + reply(EncodableValue(std::move(wrapped))); + }); + } catch (const std::exception& exception) { + reply(WrapError(exception.what())); + } + }); + } else { + channel->SetMessageHandler(nullptr); + } + } +} + +EncodableValue FirebaseRemoteConfigHostApi::WrapError(std::string_view error_message) { + return EncodableValue(EncodableList{ + EncodableValue(std::string(error_message)), + EncodableValue("Error"), + EncodableValue() + }); +} + +EncodableValue FirebaseRemoteConfigHostApi::WrapError(const FlutterError& error) { + return EncodableValue(EncodableList{ + EncodableValue(error.code()), + EncodableValue(error.message()), + error.details() + }); +} + +} // namespace firebase_remote_config_windows diff --git a/packages/firebase_remote_config/firebase_remote_config/windows/messages.g.h b/packages/firebase_remote_config/firebase_remote_config/windows/messages.g.h new file mode 100644 index 000000000000..373c43811797 --- /dev/null +++ b/packages/firebase_remote_config/firebase_remote_config/windows/messages.g.h @@ -0,0 +1,245 @@ +// Copyright 2023, the Chromium project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Autogenerated from Pigeon (v9.2.5), do not edit directly. +// See also: https://pub.dev/packages/pigeon + +#ifndef PIGEON_MESSAGES_G_H_ +#define PIGEON_MESSAGES_G_H_ +#include +#include +#include +#include + +#include +#include +#include + +namespace firebase_remote_config_windows { + + +// Generated class from Pigeon. + +class FlutterError { + public: + explicit FlutterError(const std::string& code) + : code_(code) {} + explicit FlutterError(const std::string& code, const std::string& message) + : code_(code), message_(message) {} + explicit FlutterError(const std::string& code, const std::string& message, const flutter::EncodableValue& details) + : code_(code), message_(message), details_(details) {} + + const std::string& code() const { return code_; } + const std::string& message() const { return message_; } + const flutter::EncodableValue& details() const { return details_; } + + private: + std::string code_; + std::string message_; + flutter::EncodableValue details_; +}; + +template class ErrorOr { + public: + ErrorOr(const T& rhs) : v_(rhs) {} + ErrorOr(const T&& rhs) : v_(std::move(rhs)) {} + ErrorOr(const FlutterError& rhs) : v_(rhs) {} + ErrorOr(const FlutterError&& rhs) : v_(std::move(rhs)) {} + + bool has_error() const { return std::holds_alternative(v_); } + const T& value() const { return std::get(v_); }; + const FlutterError& error() const { return std::get(v_); }; + + private: + friend class FirebaseRemoteConfigHostApi; + ErrorOr() = default; + T TakeValue() && { return std::get(std::move(v_)); } + + std::variant v_; +}; + + +// ValueSource defines the possible sources of a config parameter value. +enum class PigeonValueSource { + // The value was defined by a static constant. + valueStatic = 0, + // The value was defined by default config. + valueDefault = 1, + // The value was defined by fetched config. + valueRemote = 2 +}; + +enum class PigeonRemoteConfigFetchStatus { + // Indicates instance has not yet attempted a fetch. + noFetchYet = 0, + // Indicates the last fetch attempt succeeded. + success = 1, + // Indicates the last fetch attempt failed. + failure = 2, + // Indicates the last fetch attempt was rate-limited. + throttle = 3 +}; + +// Generated class from Pigeon that represents data sent in messages. +class PigeonRemoteConfigSettings { + public: + // Constructs an object setting all fields. + explicit PigeonRemoteConfigSettings( + int64_t fetch_timeout, + int64_t minimum_fetch_interval); + + int64_t fetch_timeout() const; + void set_fetch_timeout(int64_t value_arg); + + int64_t minimum_fetch_interval() const; + void set_minimum_fetch_interval(int64_t value_arg); + + + private: + static PigeonRemoteConfigSettings FromEncodableList(const flutter::EncodableList& list); + flutter::EncodableList ToEncodableList() const; + friend class FirebaseRemoteConfigHostApi; + friend class FirebaseRemoteConfigHostApiCodecSerializer; + int64_t fetch_timeout_; + int64_t minimum_fetch_interval_; + +}; + + +// Generated class from Pigeon that represents data sent in messages. +class PigeonRemoteConfigValue { + public: + // Constructs an object setting all non-nullable fields. + explicit PigeonRemoteConfigValue(const PigeonValueSource& source); + + // Constructs an object setting all fields. + explicit PigeonRemoteConfigValue( + const flutter::EncodableList* value, + const PigeonValueSource& source); + + const flutter::EncodableList* value() const; + void set_value(const flutter::EncodableList* value_arg); + void set_value(const flutter::EncodableList& value_arg); + + // Indicates at which source this value came from. + const PigeonValueSource& source() const; + void set_source(const PigeonValueSource& value_arg); + + + private: + static PigeonRemoteConfigValue FromEncodableList(const flutter::EncodableList& list); + flutter::EncodableList ToEncodableList() const; + friend class FirebaseRemoteConfigHostApi; + friend class FirebaseRemoteConfigHostApiCodecSerializer; + std::optional value_; + PigeonValueSource source_; + +}; + + +// Generated class from Pigeon that represents data sent in messages. +class PigeonFirebaseApp { + public: + // Constructs an object setting all non-nullable fields. + explicit PigeonFirebaseApp(const std::string& app_name); + + // Constructs an object setting all fields. + explicit PigeonFirebaseApp( + const std::string& app_name, + const std::string* tenant_id); + + const std::string& app_name() const; + void set_app_name(std::string_view value_arg); + + const std::string* tenant_id() const; + void set_tenant_id(const std::string_view* value_arg); + void set_tenant_id(std::string_view value_arg); + + + private: + static PigeonFirebaseApp FromEncodableList(const flutter::EncodableList& list); + flutter::EncodableList ToEncodableList() const; + friend class FirebaseRemoteConfigHostApi; + friend class FirebaseRemoteConfigHostApiCodecSerializer; + std::string app_name_; + std::optional tenant_id_; + +}; + +class FirebaseRemoteConfigHostApiCodecSerializer : public flutter::StandardCodecSerializer { + public: + FirebaseRemoteConfigHostApiCodecSerializer(); + inline static FirebaseRemoteConfigHostApiCodecSerializer& GetInstance() { + static FirebaseRemoteConfigHostApiCodecSerializer sInstance; + return sInstance; + } + + void WriteValue( + const flutter::EncodableValue& value, + flutter::ByteStreamWriter* stream) const override; + + protected: + flutter::EncodableValue ReadValueOfType( + uint8_t type, + flutter::ByteStreamReader* stream) const override; + +}; + +// Generated interface from Pigeon that represents a handler of messages from Flutter. +class FirebaseRemoteConfigHostApi { + public: + FirebaseRemoteConfigHostApi(const FirebaseRemoteConfigHostApi&) = delete; + FirebaseRemoteConfigHostApi& operator=(const FirebaseRemoteConfigHostApi&) = delete; + virtual ~FirebaseRemoteConfigHostApi() {} + virtual void Activate( + const PigeonFirebaseApp& app, + std::function reply)> result) = 0; + virtual void EnsureInitialized( + const PigeonFirebaseApp& app, + std::function reply)> result) = 0; + virtual void Fetch( + const PigeonFirebaseApp& app, + std::function reply)> result) = 0; + virtual void FetchAndActivate( + const PigeonFirebaseApp& app, + std::function reply)> result) = 0; + virtual ErrorOr GetAll(const PigeonFirebaseApp& app) = 0; + virtual ErrorOr GetBool( + const PigeonFirebaseApp& app, + const std::string& key) = 0; + virtual ErrorOr GetInt( + const PigeonFirebaseApp& app, + const std::string& key) = 0; + virtual ErrorOr GetDouble( + const PigeonFirebaseApp& app, + const std::string& key) = 0; + virtual ErrorOr GetString( + const PigeonFirebaseApp& app, + const std::string& key) = 0; + virtual ErrorOr GetValue( + const PigeonFirebaseApp& app, + const std::string& key) = 0; + virtual void SetConfigSettings( + const PigeonFirebaseApp& app, + const PigeonRemoteConfigSettings& remote_config_settings, + std::function reply)> result) = 0; + virtual void SetDefaults( + const PigeonFirebaseApp& app, + const flutter::EncodableMap& default_parameters, + std::function reply)> result) = 0; + + // The codec used by FirebaseRemoteConfigHostApi. + static const flutter::StandardMessageCodec& GetCodec(); + // Sets up an instance of `FirebaseRemoteConfigHostApi` to handle messages through the `binary_messenger`. + static void SetUp( + flutter::BinaryMessenger* binary_messenger, + FirebaseRemoteConfigHostApi* api); + static flutter::EncodableValue WrapError(std::string_view error_message); + static flutter::EncodableValue WrapError(const FlutterError& error); + + protected: + FirebaseRemoteConfigHostApi() = default; + +}; +} // namespace firebase_remote_config_windows +#endif // PIGEON_MESSAGES_G_H_ diff --git a/packages/firebase_remote_config/firebase_remote_config_platform_interface/lib/src/method_channel/method_channel_firebase_remote_config.dart b/packages/firebase_remote_config/firebase_remote_config_platform_interface/lib/src/method_channel/method_channel_firebase_remote_config.dart index ebf6835f9693..4f2b22b30e67 100644 --- a/packages/firebase_remote_config/firebase_remote_config_platform_interface/lib/src/method_channel/method_channel_firebase_remote_config.dart +++ b/packages/firebase_remote_config/firebase_remote_config_platform_interface/lib/src/method_channel/method_channel_firebase_remote_config.dart @@ -4,9 +4,11 @@ // ignore_for_file: require_trailing_commas import 'dart:async'; +import 'dart:convert'; import 'package:firebase_core/firebase_core.dart'; import 'package:flutter/services.dart'; +import 'package:firebase_remote_config_platform_interface/src/pigeon/messages.pigeon.dart'; import '../../firebase_remote_config_platform_interface.dart'; import 'utils/exception.dart'; @@ -23,6 +25,8 @@ class MethodChannelFirebaseRemoteConfig extends FirebaseRemoteConfigPlatform { /// is initialized via the [delegateFor] method. MethodChannelFirebaseRemoteConfig._() : super(appInstance: null); + final _api = FirebaseRemoteConfigHostApi(); + /// Keeps an internal handle ID for the channel. static int _methodChannelHandleId = 0; @@ -43,10 +47,41 @@ class MethodChannelFirebaseRemoteConfig extends FirebaseRemoteConfigPlatform { return MethodChannelFirebaseRemoteConfig._(); } - late Map _activeParameters; - late RemoteConfigSettings _settings; + late Map _activeParameters; + late PigeonRemoteConfigSettings _settings; late DateTime _lastFetchTime; - late RemoteConfigFetchStatus _lastFetchStatus; + late PigeonRemoteConfigFetchStatus _lastFetchStatus; + + PigeonFirebaseApp get pigeonDefault { + return PigeonFirebaseApp( + appName: app.name, + tenantId: tenantId, + ); + } + + @override + RemoteConfigSettings getSettings() { + return RemoteConfigSettings( + fetchTimeout: Duration(seconds: _settings.fetchTimeout), + minimumFetchInterval: + Duration(seconds: _settings.minimumFetchInterval)); + } + + @override + RemoteConfigFetchStatus getFetchStatus() { + switch (_lastFetchStatus) { + case PigeonRemoteConfigFetchStatus.noFetchYet: + return RemoteConfigFetchStatus.noFetchYet; + case PigeonRemoteConfigFetchStatus.success: + return RemoteConfigFetchStatus.success; + case PigeonRemoteConfigFetchStatus.failure: + return RemoteConfigFetchStatus.failure; + case PigeonRemoteConfigFetchStatus.throttle: + return RemoteConfigFetchStatus.throttle; + default: + return RemoteConfigFetchStatus.noFetchYet; + } + } /// Gets a [FirebaseRemoteConfigPlatform] instance for a specific /// [FirebaseApp]. @@ -70,28 +105,29 @@ class MethodChannelFirebaseRemoteConfig extends FirebaseRemoteConfigPlatform { final lastFetchMillis = remoteConfigValues['lastFetchTime']; final lastFetchStatus = remoteConfigValues['lastFetchStatus']; - _settings = RemoteConfigSettings( - fetchTimeout: fetchTimeout, - minimumFetchInterval: minimumFetchInterval, + _settings = PigeonRemoteConfigSettings( + fetchTimeout: fetchTimeout.inSeconds, + minimumFetchInterval: minimumFetchInterval.inSeconds, ); _lastFetchTime = DateTime.fromMillisecondsSinceEpoch(lastFetchMillis); _lastFetchStatus = _parseFetchStatus(lastFetchStatus); - _activeParameters = _parseParameters(remoteConfigValues['parameters']); + _activeParameters = + _parsePigeonParameters(remoteConfigValues['parameters']); return this; } - RemoteConfigFetchStatus _parseFetchStatus(String? status) { + PigeonRemoteConfigFetchStatus _parseFetchStatus(String? status) { switch (status) { case 'noFetchYet': - return RemoteConfigFetchStatus.noFetchYet; + return PigeonRemoteConfigFetchStatus.noFetchYet; case 'success': - return RemoteConfigFetchStatus.success; + return PigeonRemoteConfigFetchStatus.success; case 'failure': - return RemoteConfigFetchStatus.failure; + return PigeonRemoteConfigFetchStatus.failure; case 'throttle': - return RemoteConfigFetchStatus.throttle; + return PigeonRemoteConfigFetchStatus.throttle; default: - return RemoteConfigFetchStatus.noFetchYet; + return PigeonRemoteConfigFetchStatus.noFetchYet; } } @@ -99,10 +135,10 @@ class MethodChannelFirebaseRemoteConfig extends FirebaseRemoteConfigPlatform { DateTime get lastFetchTime => _lastFetchTime; @override - RemoteConfigFetchStatus get lastFetchStatus => _lastFetchStatus; + PigeonRemoteConfigFetchStatus get lastFetchStatus => _lastFetchStatus; @override - RemoteConfigSettings get settings => _settings; + PigeonRemoteConfigSettings get settings => _settings; @override Future ensureInitialized() async { @@ -162,16 +198,28 @@ class MethodChannelFirebaseRemoteConfig extends FirebaseRemoteConfigPlatform { } @override - Map getAll() { + Map getAll() { return _activeParameters; } + @override + Map getAllConverted() { + var parameters = {}; + for (final key in _activeParameters.keys) { + final rawValue = _activeParameters[key]!.value; + + parameters[key] = RemoteConfigValue(_pigoenListIntToListInt(rawValue!), + _pigeonToValueSource(_activeParameters[key]!.source)); + } + return parameters; + } + @override bool getBool(String key) { if (!_activeParameters.containsKey(key)) { return RemoteConfigValue.defaultValueForBool; } - return _activeParameters[key]!.asBool(); + return _pigeonValueToBool(_activeParameters[key]!); } @override @@ -179,7 +227,7 @@ class MethodChannelFirebaseRemoteConfig extends FirebaseRemoteConfigPlatform { if (!_activeParameters.containsKey(key)) { return RemoteConfigValue.defaultValueForInt; } - return _activeParameters[key]!.asInt(); + return _pigeonValueToInt(_activeParameters[key]!); } @override @@ -187,7 +235,7 @@ class MethodChannelFirebaseRemoteConfig extends FirebaseRemoteConfigPlatform { if (!_activeParameters.containsKey(key)) { return RemoteConfigValue.defaultValueForDouble; } - return _activeParameters[key]!.asDouble(); + return _pigeonValueToDouble(_activeParameters[key]!); } @override @@ -195,28 +243,44 @@ class MethodChannelFirebaseRemoteConfig extends FirebaseRemoteConfigPlatform { if (!_activeParameters.containsKey(key)) { return RemoteConfigValue.defaultValueForString; } - return _activeParameters[key]!.asString(); + return _pigeonValueToString(_activeParameters[key]!); } @override - RemoteConfigValue getValue(String key) { + PigeonRemoteConfigValue getValue(String key) { if (!_activeParameters.containsKey(key)) { - return RemoteConfigValue(null, ValueSource.valueStatic); + return PigeonRemoteConfigValue(source: PigeonValueSource.valueStatic); } return _activeParameters[key]!; } + @override + RemoteConfigValue getValueConverted(String key) { + var pigeonValue = getValue(key); + return RemoteConfigValue(_pigoenListIntToListInt(pigeonValue.value!), + _pigeonToValueSource(pigeonValue.source)); + } + + @override + Future setConfigSettingsConverted( + RemoteConfigSettings remoteConfigSettings) { + var pigeonSettings = PigeonRemoteConfigSettings( + fetchTimeout: remoteConfigSettings.fetchTimeout.inSeconds, + minimumFetchInterval: + remoteConfigSettings.minimumFetchInterval.inSeconds); + return setConfigSettings(pigeonSettings); + } + @override Future setConfigSettings( - RemoteConfigSettings remoteConfigSettings, + PigeonRemoteConfigSettings remoteConfigSettings, ) async { try { await channel .invokeMethod('RemoteConfig#setConfigSettings', { 'appName': app.name, - 'fetchTimeout': remoteConfigSettings.fetchTimeout.inSeconds, - 'minimumFetchInterval': - remoteConfigSettings.minimumFetchInterval.inSeconds, + 'fetchTimeout': remoteConfigSettings.fetchTimeout, + 'minimumFetchInterval': remoteConfigSettings.minimumFetchInterval, }); await _updateConfigProperties(); } catch (exception, stackTrace) { @@ -243,7 +307,7 @@ class MethodChannelFirebaseRemoteConfig extends FirebaseRemoteConfigPlatform { 'RemoteConfig#getAll', { 'appName': app.name, }); - _activeParameters = _parseParameters(parameters!); + _activeParameters = _parsePigeonParameters(parameters!); } Future _updateConfigProperties() async { @@ -258,9 +322,9 @@ class MethodChannelFirebaseRemoteConfig extends FirebaseRemoteConfigPlatform { final lastFetchMillis = properties['lastFetchTime']; final lastFetchStatus = properties['lastFetchStatus']; - _settings = RemoteConfigSettings( - fetchTimeout: fetchTimeout, - minimumFetchInterval: minimumFetchInterval, + _settings = PigeonRemoteConfigSettings( + fetchTimeout: fetchTimeout.inSeconds, + minimumFetchInterval: minimumFetchInterval.inSeconds, ); _lastFetchTime = DateTime.fromMillisecondsSinceEpoch(lastFetchMillis); _lastFetchStatus = _parseFetchStatus(lastFetchStatus); @@ -277,6 +341,18 @@ class MethodChannelFirebaseRemoteConfig extends FirebaseRemoteConfigPlatform { return parameters; } + Map _parsePigeonParameters( + Map rawParameters) { + var parameters = {}; + for (final key in rawParameters.keys) { + final rawValue = rawParameters[key]; + parameters[key] = PigeonRemoteConfigValue( + value: rawValue['value'], + source: _valueSourceToPigeon(_parseValueSource(rawValue['source']))); + } + return parameters; + } + ValueSource _parseValueSource(String? sourceStr) { switch (sourceStr) { case 'static': @@ -289,4 +365,85 @@ class MethodChannelFirebaseRemoteConfig extends FirebaseRemoteConfigPlatform { return ValueSource.valueStatic; } } + + PigeonValueSource _valueSourceToPigeon(ValueSource source) { + switch (source) { + case ValueSource.valueDefault: + return PigeonValueSource.valueDefault; + case ValueSource.valueRemote: + return PigeonValueSource.valueRemote; + case ValueSource.valueStatic: + default: + return PigeonValueSource.valueStatic; + } + } + + ValueSource _pigeonToValueSource(PigeonValueSource source) { + switch (source) { + case PigeonValueSource.valueDefault: + return ValueSource.valueDefault; + case PigeonValueSource.valueRemote: + return ValueSource.valueRemote; + case PigeonValueSource.valueStatic: + default: + return ValueSource.valueStatic; + } + } + + static int _pigeonValueToInt(PigeonRemoteConfigValue pigeonValue) { + final value = pigeonValue.value; + if (value != null) { + final String strValue = + const Utf8Codec().decode(_pigoenListIntToListInt(value)); + final int intValue = + int.tryParse(strValue) ?? RemoteConfigValue.defaultValueForInt; + return intValue; + } else { + return RemoteConfigValue.defaultValueForInt; + } + } + + static String _pigeonValueToString(PigeonRemoteConfigValue pigeonValue) { + final value = pigeonValue.value; + return value != null + ? const Utf8Codec().decode(_pigoenListIntToListInt(value)) + : RemoteConfigValue.defaultValueForString; + } + + /// Decode value to double. + static double _pigeonValueToDouble(PigeonRemoteConfigValue pigeonValue) { + final value = pigeonValue.value; + if (value != null) { + final String strValue = + const Utf8Codec().decode(_pigoenListIntToListInt(value)); + final double doubleValue = + double.tryParse(strValue) ?? RemoteConfigValue.defaultValueForDouble; + return doubleValue; + } else { + return RemoteConfigValue.defaultValueForDouble; + } + } + + /// Decode value to bool. + static bool _pigeonValueToBool(PigeonRemoteConfigValue pigeonValue) { + final value = pigeonValue.value; + if (value != null) { + final String strValue = + const Utf8Codec().decode(_pigoenListIntToListInt(value)); + final lowerCase = strValue.toLowerCase(); + return lowerCase == 'true' || lowerCase == '1'; + } else { + return RemoteConfigValue.defaultValueForBool; + } + } + + static List _pigoenListIntToListInt(List list) { + List newList = []; + for (final int? element in list) { + if (element != null) { + newList.add(element); + } + } + return newList; + } } diff --git a/packages/firebase_remote_config/firebase_remote_config_platform_interface/lib/src/pigeon/messages.pigeon.dart b/packages/firebase_remote_config/firebase_remote_config_platform_interface/lib/src/pigeon/messages.pigeon.dart new file mode 100644 index 000000000000..7658b6c4404a --- /dev/null +++ b/packages/firebase_remote_config/firebase_remote_config_platform_interface/lib/src/pigeon/messages.pigeon.dart @@ -0,0 +1,460 @@ +// Copyright 2023, the Chromium project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Autogenerated from Pigeon (v9.2.5), do not edit directly. +// See also: https://pub.dev/packages/pigeon +// ignore_for_file: public_member_api_docs, non_constant_identifier_names, avoid_as, unused_import, unnecessary_parenthesis, prefer_null_aware_operators, omit_local_variable_types, unused_shown_name, unnecessary_import + +import 'dart:async'; +import 'dart:typed_data' show Float64List, Int32List, Int64List, Uint8List; + +import 'package:flutter/foundation.dart' show ReadBuffer, WriteBuffer; +import 'package:flutter/services.dart'; + +/// ValueSource defines the possible sources of a config parameter value. +enum PigeonValueSource { + /// The value was defined by a static constant. + valueStatic, + /// The value was defined by default config. + valueDefault, + /// The value was defined by fetched config. + valueRemote, +} + +enum PigeonRemoteConfigFetchStatus { + /// Indicates instance has not yet attempted a fetch. + noFetchYet, + /// Indicates the last fetch attempt succeeded. + success, + /// Indicates the last fetch attempt failed. + failure, + /// Indicates the last fetch attempt was rate-limited. + throttle, +} + +class PigeonRemoteConfigSettings { + PigeonRemoteConfigSettings({ + required this.fetchTimeout, + required this.minimumFetchInterval, + }); + + int fetchTimeout; + + int minimumFetchInterval; + + Object encode() { + return [ + fetchTimeout, + minimumFetchInterval, + ]; + } + + static PigeonRemoteConfigSettings decode(Object result) { + result as List; + return PigeonRemoteConfigSettings( + fetchTimeout: result[0]! as int, + minimumFetchInterval: result[1]! as int, + ); + } +} + +class PigeonRemoteConfigValue { + PigeonRemoteConfigValue({ + this.value, + required this.source, + }); + + List? value; + + /// Indicates at which source this value came from. + PigeonValueSource source; + + Object encode() { + return [ + value, + source.index, + ]; + } + + static PigeonRemoteConfigValue decode(Object result) { + result as List; + return PigeonRemoteConfigValue( + value: (result[0] as List?)?.cast(), + source: PigeonValueSource.values[result[1]! as int], + ); + } +} + +class PigeonFirebaseApp { + PigeonFirebaseApp({ + required this.appName, + this.tenantId, + }); + + String appName; + + String? tenantId; + + Object encode() { + return [ + appName, + tenantId, + ]; + } + + static PigeonFirebaseApp decode(Object result) { + result as List; + return PigeonFirebaseApp( + appName: result[0]! as String, + tenantId: result[1] as String?, + ); + } +} + +class _FirebaseRemoteConfigHostApiCodec extends StandardMessageCodec { + const _FirebaseRemoteConfigHostApiCodec(); + @override + void writeValue(WriteBuffer buffer, Object? value) { + if (value is PigeonFirebaseApp) { + buffer.putUint8(128); + writeValue(buffer, value.encode()); + } else if (value is PigeonRemoteConfigSettings) { + buffer.putUint8(129); + writeValue(buffer, value.encode()); + } else if (value is PigeonRemoteConfigValue) { + buffer.putUint8(130); + writeValue(buffer, value.encode()); + } else { + super.writeValue(buffer, value); + } + } + + @override + Object? readValueOfType(int type, ReadBuffer buffer) { + switch (type) { + case 128: + return PigeonFirebaseApp.decode(readValue(buffer)!); + case 129: + return PigeonRemoteConfigSettings.decode(readValue(buffer)!); + case 130: + return PigeonRemoteConfigValue.decode(readValue(buffer)!); + default: + return super.readValueOfType(type, buffer); + } + } +} + +class FirebaseRemoteConfigHostApi { + /// Constructor for [FirebaseRemoteConfigHostApi]. The [binaryMessenger] named argument is + /// available for dependency injection. If it is left null, the default + /// BinaryMessenger will be used which routes to the host platform. + FirebaseRemoteConfigHostApi({BinaryMessenger? binaryMessenger}) + : _binaryMessenger = binaryMessenger; + final BinaryMessenger? _binaryMessenger; + + static const MessageCodec codec = _FirebaseRemoteConfigHostApiCodec(); + + Future activate(PigeonFirebaseApp arg_app) async { + final BasicMessageChannel channel = BasicMessageChannel( + 'dev.flutter.pigeon.FirebaseRemoteConfigHostApi.activate', codec, + binaryMessenger: _binaryMessenger); + final List? replyList = + await channel.send([arg_app]) as List?; + if (replyList == null) { + throw PlatformException( + code: 'channel-error', + message: 'Unable to establish connection on channel.', + ); + } else if (replyList.length > 1) { + throw PlatformException( + code: replyList[0]! as String, + message: replyList[1] as String?, + details: replyList[2], + ); + } else if (replyList[0] == null) { + throw PlatformException( + code: 'null-error', + message: 'Host platform returned null value for non-null return value.', + ); + } else { + return (replyList[0] as bool?)!; + } + } + + Future ensureInitialized(PigeonFirebaseApp arg_app) async { + final BasicMessageChannel channel = BasicMessageChannel( + 'dev.flutter.pigeon.FirebaseRemoteConfigHostApi.ensureInitialized', codec, + binaryMessenger: _binaryMessenger); + final List? replyList = + await channel.send([arg_app]) as List?; + if (replyList == null) { + throw PlatformException( + code: 'channel-error', + message: 'Unable to establish connection on channel.', + ); + } else if (replyList.length > 1) { + throw PlatformException( + code: replyList[0]! as String, + message: replyList[1] as String?, + details: replyList[2], + ); + } else { + return; + } + } + + Future fetch(PigeonFirebaseApp arg_app) async { + final BasicMessageChannel channel = BasicMessageChannel( + 'dev.flutter.pigeon.FirebaseRemoteConfigHostApi.fetch', codec, + binaryMessenger: _binaryMessenger); + final List? replyList = + await channel.send([arg_app]) as List?; + if (replyList == null) { + throw PlatformException( + code: 'channel-error', + message: 'Unable to establish connection on channel.', + ); + } else if (replyList.length > 1) { + throw PlatformException( + code: replyList[0]! as String, + message: replyList[1] as String?, + details: replyList[2], + ); + } else { + return; + } + } + + Future fetchAndActivate(PigeonFirebaseApp arg_app) async { + final BasicMessageChannel channel = BasicMessageChannel( + 'dev.flutter.pigeon.FirebaseRemoteConfigHostApi.fetchAndActivate', codec, + binaryMessenger: _binaryMessenger); + final List? replyList = + await channel.send([arg_app]) as List?; + if (replyList == null) { + throw PlatformException( + code: 'channel-error', + message: 'Unable to establish connection on channel.', + ); + } else if (replyList.length > 1) { + throw PlatformException( + code: replyList[0]! as String, + message: replyList[1] as String?, + details: replyList[2], + ); + } else if (replyList[0] == null) { + throw PlatformException( + code: 'null-error', + message: 'Host platform returned null value for non-null return value.', + ); + } else { + return (replyList[0] as bool?)!; + } + } + + Future> getAll(PigeonFirebaseApp arg_app) async { + final BasicMessageChannel channel = BasicMessageChannel( + 'dev.flutter.pigeon.FirebaseRemoteConfigHostApi.getAll', codec, + binaryMessenger: _binaryMessenger); + final List? replyList = + await channel.send([arg_app]) as List?; + if (replyList == null) { + throw PlatformException( + code: 'channel-error', + message: 'Unable to establish connection on channel.', + ); + } else if (replyList.length > 1) { + throw PlatformException( + code: replyList[0]! as String, + message: replyList[1] as String?, + details: replyList[2], + ); + } else if (replyList[0] == null) { + throw PlatformException( + code: 'null-error', + message: 'Host platform returned null value for non-null return value.', + ); + } else { + return (replyList[0] as Map?)!.cast(); + } + } + + Future getBool(PigeonFirebaseApp arg_app, String arg_key) async { + final BasicMessageChannel channel = BasicMessageChannel( + 'dev.flutter.pigeon.FirebaseRemoteConfigHostApi.getBool', codec, + binaryMessenger: _binaryMessenger); + final List? replyList = + await channel.send([arg_app, arg_key]) as List?; + if (replyList == null) { + throw PlatformException( + code: 'channel-error', + message: 'Unable to establish connection on channel.', + ); + } else if (replyList.length > 1) { + throw PlatformException( + code: replyList[0]! as String, + message: replyList[1] as String?, + details: replyList[2], + ); + } else if (replyList[0] == null) { + throw PlatformException( + code: 'null-error', + message: 'Host platform returned null value for non-null return value.', + ); + } else { + return (replyList[0] as bool?)!; + } + } + + Future getInt(PigeonFirebaseApp arg_app, String arg_key) async { + final BasicMessageChannel channel = BasicMessageChannel( + 'dev.flutter.pigeon.FirebaseRemoteConfigHostApi.getInt', codec, + binaryMessenger: _binaryMessenger); + final List? replyList = + await channel.send([arg_app, arg_key]) as List?; + if (replyList == null) { + throw PlatformException( + code: 'channel-error', + message: 'Unable to establish connection on channel.', + ); + } else if (replyList.length > 1) { + throw PlatformException( + code: replyList[0]! as String, + message: replyList[1] as String?, + details: replyList[2], + ); + } else if (replyList[0] == null) { + throw PlatformException( + code: 'null-error', + message: 'Host platform returned null value for non-null return value.', + ); + } else { + return (replyList[0] as int?)!; + } + } + + Future getDouble(PigeonFirebaseApp arg_app, String arg_key) async { + final BasicMessageChannel channel = BasicMessageChannel( + 'dev.flutter.pigeon.FirebaseRemoteConfigHostApi.getDouble', codec, + binaryMessenger: _binaryMessenger); + final List? replyList = + await channel.send([arg_app, arg_key]) as List?; + if (replyList == null) { + throw PlatformException( + code: 'channel-error', + message: 'Unable to establish connection on channel.', + ); + } else if (replyList.length > 1) { + throw PlatformException( + code: replyList[0]! as String, + message: replyList[1] as String?, + details: replyList[2], + ); + } else if (replyList[0] == null) { + throw PlatformException( + code: 'null-error', + message: 'Host platform returned null value for non-null return value.', + ); + } else { + return (replyList[0] as double?)!; + } + } + + Future getString(PigeonFirebaseApp arg_app, String arg_key) async { + final BasicMessageChannel channel = BasicMessageChannel( + 'dev.flutter.pigeon.FirebaseRemoteConfigHostApi.getString', codec, + binaryMessenger: _binaryMessenger); + final List? replyList = + await channel.send([arg_app, arg_key]) as List?; + if (replyList == null) { + throw PlatformException( + code: 'channel-error', + message: 'Unable to establish connection on channel.', + ); + } else if (replyList.length > 1) { + throw PlatformException( + code: replyList[0]! as String, + message: replyList[1] as String?, + details: replyList[2], + ); + } else if (replyList[0] == null) { + throw PlatformException( + code: 'null-error', + message: 'Host platform returned null value for non-null return value.', + ); + } else { + return (replyList[0] as String?)!; + } + } + + Future getValue(PigeonFirebaseApp arg_app, String arg_key) async { + final BasicMessageChannel channel = BasicMessageChannel( + 'dev.flutter.pigeon.FirebaseRemoteConfigHostApi.getValue', codec, + binaryMessenger: _binaryMessenger); + final List? replyList = + await channel.send([arg_app, arg_key]) as List?; + if (replyList == null) { + throw PlatformException( + code: 'channel-error', + message: 'Unable to establish connection on channel.', + ); + } else if (replyList.length > 1) { + throw PlatformException( + code: replyList[0]! as String, + message: replyList[1] as String?, + details: replyList[2], + ); + } else if (replyList[0] == null) { + throw PlatformException( + code: 'null-error', + message: 'Host platform returned null value for non-null return value.', + ); + } else { + return (replyList[0] as PigeonRemoteConfigValue?)!; + } + } + + Future setConfigSettings(PigeonFirebaseApp arg_app, PigeonRemoteConfigSettings arg_remoteConfigSettings) async { + final BasicMessageChannel channel = BasicMessageChannel( + 'dev.flutter.pigeon.FirebaseRemoteConfigHostApi.setConfigSettings', codec, + binaryMessenger: _binaryMessenger); + final List? replyList = + await channel.send([arg_app, arg_remoteConfigSettings]) as List?; + if (replyList == null) { + throw PlatformException( + code: 'channel-error', + message: 'Unable to establish connection on channel.', + ); + } else if (replyList.length > 1) { + throw PlatformException( + code: replyList[0]! as String, + message: replyList[1] as String?, + details: replyList[2], + ); + } else { + return; + } + } + + Future setDefaults(PigeonFirebaseApp arg_app, Map arg_defaultParameters) async { + final BasicMessageChannel channel = BasicMessageChannel( + 'dev.flutter.pigeon.FirebaseRemoteConfigHostApi.setDefaults', codec, + binaryMessenger: _binaryMessenger); + final List? replyList = + await channel.send([arg_app, arg_defaultParameters]) as List?; + if (replyList == null) { + throw PlatformException( + code: 'channel-error', + message: 'Unable to establish connection on channel.', + ); + } else if (replyList.length > 1) { + throw PlatformException( + code: replyList[0]! as String, + message: replyList[1] as String?, + details: replyList[2], + ); + } else { + return; + } + } +} diff --git a/packages/firebase_remote_config/firebase_remote_config_platform_interface/lib/src/pigeon/test_api.dart b/packages/firebase_remote_config/firebase_remote_config_platform_interface/lib/src/pigeon/test_api.dart new file mode 100644 index 000000000000..f0e8b0365a0b --- /dev/null +++ b/packages/firebase_remote_config/firebase_remote_config_platform_interface/lib/src/pigeon/test_api.dart @@ -0,0 +1,328 @@ +// Copyright 2023, the Chromium project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. +// Autogenerated from Pigeon (v9.2.5), do not edit directly. +// See also: https://pub.dev/packages/pigeon +// ignore_for_file: public_member_api_docs, non_constant_identifier_names, avoid_as, unused_import, unnecessary_parenthesis, unnecessary_import +// ignore_for_file: avoid_relative_lib_imports +import 'dart:async'; +import 'dart:typed_data' show Float64List, Int32List, Int64List, Uint8List; +import 'package:flutter/foundation.dart' show ReadBuffer, WriteBuffer; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'messages.pigeon.dart'; + +class _TestFirebaseRemoteConfigHostApiCodec extends StandardMessageCodec { + const _TestFirebaseRemoteConfigHostApiCodec(); + @override + void writeValue(WriteBuffer buffer, Object? value) { + if (value is PigeonFirebaseApp) { + buffer.putUint8(128); + writeValue(buffer, value.encode()); + } else if (value is PigeonRemoteConfigSettings) { + buffer.putUint8(129); + writeValue(buffer, value.encode()); + } else if (value is PigeonRemoteConfigValue) { + buffer.putUint8(130); + writeValue(buffer, value.encode()); + } else { + super.writeValue(buffer, value); + } + } + + @override + Object? readValueOfType(int type, ReadBuffer buffer) { + switch (type) { + case 128: + return PigeonFirebaseApp.decode(readValue(buffer)!); + case 129: + return PigeonRemoteConfigSettings.decode(readValue(buffer)!); + case 130: + return PigeonRemoteConfigValue.decode(readValue(buffer)!); + default: + return super.readValueOfType(type, buffer); + } + } +} + +abstract class TestFirebaseRemoteConfigHostApi { + static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding => TestDefaultBinaryMessengerBinding.instance; + static const MessageCodec codec = _TestFirebaseRemoteConfigHostApiCodec(); + + Future activate(PigeonFirebaseApp app); + + Future ensureInitialized(PigeonFirebaseApp app); + + Future fetch(PigeonFirebaseApp app); + + Future fetchAndActivate(PigeonFirebaseApp app); + + Map getAll(PigeonFirebaseApp app); + + bool getBool(PigeonFirebaseApp app, String key); + + int getInt(PigeonFirebaseApp app, String key); + + double getDouble(PigeonFirebaseApp app, String key); + + String getString(PigeonFirebaseApp app, String key); + + PigeonRemoteConfigValue getValue(PigeonFirebaseApp app, String key); + + Future setConfigSettings(PigeonFirebaseApp app, PigeonRemoteConfigSettings remoteConfigSettings); + + Future setDefaults(PigeonFirebaseApp app, Map defaultParameters); + + static void setup(TestFirebaseRemoteConfigHostApi? api, {BinaryMessenger? binaryMessenger}) { + { + final BasicMessageChannel channel = BasicMessageChannel( + 'dev.flutter.pigeon.FirebaseRemoteConfigHostApi.activate', codec, + binaryMessenger: binaryMessenger); + if (api == null) { + _testBinaryMessengerBinding!.defaultBinaryMessenger.setMockDecodedMessageHandler(channel, null); + } else { + _testBinaryMessengerBinding!.defaultBinaryMessenger.setMockDecodedMessageHandler(channel, (Object? message) async { + assert(message != null, + 'Argument for dev.flutter.pigeon.FirebaseRemoteConfigHostApi.activate was null.'); + final List args = (message as List?)!; + final PigeonFirebaseApp? arg_app = (args[0] as PigeonFirebaseApp?); + assert(arg_app != null, + 'Argument for dev.flutter.pigeon.FirebaseRemoteConfigHostApi.activate was null, expected non-null PigeonFirebaseApp.'); + final bool output = await api.activate(arg_app!); + return [output]; + }); + } + } + { + final BasicMessageChannel channel = BasicMessageChannel( + 'dev.flutter.pigeon.FirebaseRemoteConfigHostApi.ensureInitialized', codec, + binaryMessenger: binaryMessenger); + if (api == null) { + _testBinaryMessengerBinding!.defaultBinaryMessenger.setMockDecodedMessageHandler(channel, null); + } else { + _testBinaryMessengerBinding!.defaultBinaryMessenger.setMockDecodedMessageHandler(channel, (Object? message) async { + assert(message != null, + 'Argument for dev.flutter.pigeon.FirebaseRemoteConfigHostApi.ensureInitialized was null.'); + final List args = (message as List?)!; + final PigeonFirebaseApp? arg_app = (args[0] as PigeonFirebaseApp?); + assert(arg_app != null, + 'Argument for dev.flutter.pigeon.FirebaseRemoteConfigHostApi.ensureInitialized was null, expected non-null PigeonFirebaseApp.'); + await api.ensureInitialized(arg_app!); + return []; + }); + } + } + { + final BasicMessageChannel channel = BasicMessageChannel( + 'dev.flutter.pigeon.FirebaseRemoteConfigHostApi.fetch', codec, + binaryMessenger: binaryMessenger); + if (api == null) { + _testBinaryMessengerBinding!.defaultBinaryMessenger.setMockDecodedMessageHandler(channel, null); + } else { + _testBinaryMessengerBinding!.defaultBinaryMessenger.setMockDecodedMessageHandler(channel, (Object? message) async { + assert(message != null, + 'Argument for dev.flutter.pigeon.FirebaseRemoteConfigHostApi.fetch was null.'); + final List args = (message as List?)!; + final PigeonFirebaseApp? arg_app = (args[0] as PigeonFirebaseApp?); + assert(arg_app != null, + 'Argument for dev.flutter.pigeon.FirebaseRemoteConfigHostApi.fetch was null, expected non-null PigeonFirebaseApp.'); + await api.fetch(arg_app!); + return []; + }); + } + } + { + final BasicMessageChannel channel = BasicMessageChannel( + 'dev.flutter.pigeon.FirebaseRemoteConfigHostApi.fetchAndActivate', codec, + binaryMessenger: binaryMessenger); + if (api == null) { + _testBinaryMessengerBinding!.defaultBinaryMessenger.setMockDecodedMessageHandler(channel, null); + } else { + _testBinaryMessengerBinding!.defaultBinaryMessenger.setMockDecodedMessageHandler(channel, (Object? message) async { + assert(message != null, + 'Argument for dev.flutter.pigeon.FirebaseRemoteConfigHostApi.fetchAndActivate was null.'); + final List args = (message as List?)!; + final PigeonFirebaseApp? arg_app = (args[0] as PigeonFirebaseApp?); + assert(arg_app != null, + 'Argument for dev.flutter.pigeon.FirebaseRemoteConfigHostApi.fetchAndActivate was null, expected non-null PigeonFirebaseApp.'); + final bool output = await api.fetchAndActivate(arg_app!); + return [output]; + }); + } + } + { + final BasicMessageChannel channel = BasicMessageChannel( + 'dev.flutter.pigeon.FirebaseRemoteConfigHostApi.getAll', codec, + binaryMessenger: binaryMessenger); + if (api == null) { + _testBinaryMessengerBinding!.defaultBinaryMessenger.setMockDecodedMessageHandler(channel, null); + } else { + _testBinaryMessengerBinding!.defaultBinaryMessenger.setMockDecodedMessageHandler(channel, (Object? message) async { + assert(message != null, + 'Argument for dev.flutter.pigeon.FirebaseRemoteConfigHostApi.getAll was null.'); + final List args = (message as List?)!; + final PigeonFirebaseApp? arg_app = (args[0] as PigeonFirebaseApp?); + assert(arg_app != null, + 'Argument for dev.flutter.pigeon.FirebaseRemoteConfigHostApi.getAll was null, expected non-null PigeonFirebaseApp.'); + final Map output = api.getAll(arg_app!); + return [output]; + }); + } + } + { + final BasicMessageChannel channel = BasicMessageChannel( + 'dev.flutter.pigeon.FirebaseRemoteConfigHostApi.getBool', codec, + binaryMessenger: binaryMessenger); + if (api == null) { + _testBinaryMessengerBinding!.defaultBinaryMessenger.setMockDecodedMessageHandler(channel, null); + } else { + _testBinaryMessengerBinding!.defaultBinaryMessenger.setMockDecodedMessageHandler(channel, (Object? message) async { + assert(message != null, + 'Argument for dev.flutter.pigeon.FirebaseRemoteConfigHostApi.getBool was null.'); + final List args = (message as List?)!; + final PigeonFirebaseApp? arg_app = (args[0] as PigeonFirebaseApp?); + assert(arg_app != null, + 'Argument for dev.flutter.pigeon.FirebaseRemoteConfigHostApi.getBool was null, expected non-null PigeonFirebaseApp.'); + final String? arg_key = (args[1] as String?); + assert(arg_key != null, + 'Argument for dev.flutter.pigeon.FirebaseRemoteConfigHostApi.getBool was null, expected non-null String.'); + final bool output = api.getBool(arg_app!, arg_key!); + return [output]; + }); + } + } + { + final BasicMessageChannel channel = BasicMessageChannel( + 'dev.flutter.pigeon.FirebaseRemoteConfigHostApi.getInt', codec, + binaryMessenger: binaryMessenger); + if (api == null) { + _testBinaryMessengerBinding!.defaultBinaryMessenger.setMockDecodedMessageHandler(channel, null); + } else { + _testBinaryMessengerBinding!.defaultBinaryMessenger.setMockDecodedMessageHandler(channel, (Object? message) async { + assert(message != null, + 'Argument for dev.flutter.pigeon.FirebaseRemoteConfigHostApi.getInt was null.'); + final List args = (message as List?)!; + final PigeonFirebaseApp? arg_app = (args[0] as PigeonFirebaseApp?); + assert(arg_app != null, + 'Argument for dev.flutter.pigeon.FirebaseRemoteConfigHostApi.getInt was null, expected non-null PigeonFirebaseApp.'); + final String? arg_key = (args[1] as String?); + assert(arg_key != null, + 'Argument for dev.flutter.pigeon.FirebaseRemoteConfigHostApi.getInt was null, expected non-null String.'); + final int output = api.getInt(arg_app!, arg_key!); + return [output]; + }); + } + } + { + final BasicMessageChannel channel = BasicMessageChannel( + 'dev.flutter.pigeon.FirebaseRemoteConfigHostApi.getDouble', codec, + binaryMessenger: binaryMessenger); + if (api == null) { + _testBinaryMessengerBinding!.defaultBinaryMessenger.setMockDecodedMessageHandler(channel, null); + } else { + _testBinaryMessengerBinding!.defaultBinaryMessenger.setMockDecodedMessageHandler(channel, (Object? message) async { + assert(message != null, + 'Argument for dev.flutter.pigeon.FirebaseRemoteConfigHostApi.getDouble was null.'); + final List args = (message as List?)!; + final PigeonFirebaseApp? arg_app = (args[0] as PigeonFirebaseApp?); + assert(arg_app != null, + 'Argument for dev.flutter.pigeon.FirebaseRemoteConfigHostApi.getDouble was null, expected non-null PigeonFirebaseApp.'); + final String? arg_key = (args[1] as String?); + assert(arg_key != null, + 'Argument for dev.flutter.pigeon.FirebaseRemoteConfigHostApi.getDouble was null, expected non-null String.'); + final double output = api.getDouble(arg_app!, arg_key!); + return [output]; + }); + } + } + { + final BasicMessageChannel channel = BasicMessageChannel( + 'dev.flutter.pigeon.FirebaseRemoteConfigHostApi.getString', codec, + binaryMessenger: binaryMessenger); + if (api == null) { + _testBinaryMessengerBinding!.defaultBinaryMessenger.setMockDecodedMessageHandler(channel, null); + } else { + _testBinaryMessengerBinding!.defaultBinaryMessenger.setMockDecodedMessageHandler(channel, (Object? message) async { + assert(message != null, + 'Argument for dev.flutter.pigeon.FirebaseRemoteConfigHostApi.getString was null.'); + final List args = (message as List?)!; + final PigeonFirebaseApp? arg_app = (args[0] as PigeonFirebaseApp?); + assert(arg_app != null, + 'Argument for dev.flutter.pigeon.FirebaseRemoteConfigHostApi.getString was null, expected non-null PigeonFirebaseApp.'); + final String? arg_key = (args[1] as String?); + assert(arg_key != null, + 'Argument for dev.flutter.pigeon.FirebaseRemoteConfigHostApi.getString was null, expected non-null String.'); + final String output = api.getString(arg_app!, arg_key!); + return [output]; + }); + } + } + { + final BasicMessageChannel channel = BasicMessageChannel( + 'dev.flutter.pigeon.FirebaseRemoteConfigHostApi.getValue', codec, + binaryMessenger: binaryMessenger); + if (api == null) { + _testBinaryMessengerBinding!.defaultBinaryMessenger.setMockDecodedMessageHandler(channel, null); + } else { + _testBinaryMessengerBinding!.defaultBinaryMessenger.setMockDecodedMessageHandler(channel, (Object? message) async { + assert(message != null, + 'Argument for dev.flutter.pigeon.FirebaseRemoteConfigHostApi.getValue was null.'); + final List args = (message as List?)!; + final PigeonFirebaseApp? arg_app = (args[0] as PigeonFirebaseApp?); + assert(arg_app != null, + 'Argument for dev.flutter.pigeon.FirebaseRemoteConfigHostApi.getValue was null, expected non-null PigeonFirebaseApp.'); + final String? arg_key = (args[1] as String?); + assert(arg_key != null, + 'Argument for dev.flutter.pigeon.FirebaseRemoteConfigHostApi.getValue was null, expected non-null String.'); + final PigeonRemoteConfigValue output = api.getValue(arg_app!, arg_key!); + return [output]; + }); + } + } + { + final BasicMessageChannel channel = BasicMessageChannel( + 'dev.flutter.pigeon.FirebaseRemoteConfigHostApi.setConfigSettings', codec, + binaryMessenger: binaryMessenger); + if (api == null) { + _testBinaryMessengerBinding!.defaultBinaryMessenger.setMockDecodedMessageHandler(channel, null); + } else { + _testBinaryMessengerBinding!.defaultBinaryMessenger.setMockDecodedMessageHandler(channel, (Object? message) async { + assert(message != null, + 'Argument for dev.flutter.pigeon.FirebaseRemoteConfigHostApi.setConfigSettings was null.'); + final List args = (message as List?)!; + final PigeonFirebaseApp? arg_app = (args[0] as PigeonFirebaseApp?); + assert(arg_app != null, + 'Argument for dev.flutter.pigeon.FirebaseRemoteConfigHostApi.setConfigSettings was null, expected non-null PigeonFirebaseApp.'); + final PigeonRemoteConfigSettings? arg_remoteConfigSettings = (args[1] as PigeonRemoteConfigSettings?); + assert(arg_remoteConfigSettings != null, + 'Argument for dev.flutter.pigeon.FirebaseRemoteConfigHostApi.setConfigSettings was null, expected non-null PigeonRemoteConfigSettings.'); + await api.setConfigSettings(arg_app!, arg_remoteConfigSettings!); + return []; + }); + } + } + { + final BasicMessageChannel channel = BasicMessageChannel( + 'dev.flutter.pigeon.FirebaseRemoteConfigHostApi.setDefaults', codec, + binaryMessenger: binaryMessenger); + if (api == null) { + _testBinaryMessengerBinding!.defaultBinaryMessenger.setMockDecodedMessageHandler(channel, null); + } else { + _testBinaryMessengerBinding!.defaultBinaryMessenger.setMockDecodedMessageHandler(channel, (Object? message) async { + assert(message != null, + 'Argument for dev.flutter.pigeon.FirebaseRemoteConfigHostApi.setDefaults was null.'); + final List args = (message as List?)!; + final PigeonFirebaseApp? arg_app = (args[0] as PigeonFirebaseApp?); + assert(arg_app != null, + 'Argument for dev.flutter.pigeon.FirebaseRemoteConfigHostApi.setDefaults was null, expected non-null PigeonFirebaseApp.'); + final Map? arg_defaultParameters = (args[1] as Map?)?.cast(); + assert(arg_defaultParameters != null, + 'Argument for dev.flutter.pigeon.FirebaseRemoteConfigHostApi.setDefaults was null, expected non-null Map.'); + await api.setDefaults(arg_app!, arg_defaultParameters!); + return []; + }); + } + } + } +} diff --git a/packages/firebase_remote_config/firebase_remote_config_platform_interface/lib/src/platform_interface/platform_interface_firebase_remote_config.dart b/packages/firebase_remote_config/firebase_remote_config_platform_interface/lib/src/platform_interface/platform_interface_firebase_remote_config.dart index 167154c8383c..6dc580116214 100644 --- a/packages/firebase_remote_config/firebase_remote_config_platform_interface/lib/src/platform_interface/platform_interface_firebase_remote_config.dart +++ b/packages/firebase_remote_config/firebase_remote_config_platform_interface/lib/src/platform_interface/platform_interface_firebase_remote_config.dart @@ -9,6 +9,7 @@ import 'package:firebase_core/firebase_core.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:plugin_platform_interface/plugin_platform_interface.dart'; +import 'package:firebase_remote_config_platform_interface/src/pigeon/messages.pigeon.dart'; import '../../firebase_remote_config_platform_interface.dart'; import '../method_channel/method_channel_firebase_remote_config.dart'; @@ -42,6 +43,11 @@ abstract class FirebaseRemoteConfigPlatform extends PlatformInterface { static FirebaseRemoteConfigPlatform? _instance; + /// The current RemoteConfig instance's tenant ID. + /// + /// When you set the tenant ID of an RemoteConfig instance. + String? tenantId; + /// The current default [FirebaseRemoteConfigPlatform] instance. /// /// It will always default to [MethodChannelFirebaseRemoteConfig] @@ -91,12 +97,12 @@ abstract class FirebaseRemoteConfigPlatform extends PlatformInterface { } /// Returns the status of the last fetch attempt. - RemoteConfigFetchStatus get lastFetchStatus { + PigeonRemoteConfigFetchStatus get lastFetchStatus { throw UnimplementedError('lastFetchStatus getter not implemented'); } - /// Returns the [RemoteConfigSettings] of the current instance. - RemoteConfigSettings get settings { + /// Returns the [PigeonRemoteConfigSettings] of the current instance. + PigeonRemoteConfigSettings get settings { throw UnimplementedError('settings getter not implemented'); } @@ -130,7 +136,7 @@ abstract class FirebaseRemoteConfigPlatform extends PlatformInterface { } /// Returns a Map of all Remote Config parameters. - Map getAll() { + Map getAll() { throw UnimplementedError('getAll() is not implemented'); } @@ -155,12 +161,13 @@ abstract class FirebaseRemoteConfigPlatform extends PlatformInterface { } /// Gets the [RemoteConfigValue] for a given key. - RemoteConfigValue getValue(String key) { + PigeonRemoteConfigValue getValue(String key) { throw UnimplementedError('getValue() is not implemented'); } /// Sets the [RemoteConfigSettings] for the current instance. - Future setConfigSettings(RemoteConfigSettings remoteConfigSettings) { + Future setConfigSettings( + PigeonRemoteConfigSettings remoteConfigSettings) { throw UnimplementedError('setConfigSettings() is not implemented'); } @@ -168,4 +175,25 @@ abstract class FirebaseRemoteConfigPlatform extends PlatformInterface { Future setDefaults(Map defaultParameters) { throw UnimplementedError('setDefaults() is not implemented'); } + + RemoteConfigSettings getSettings() { + throw UnimplementedError('getSettings() is not implemented'); + } + + RemoteConfigFetchStatus getFetchStatus() { + throw UnimplementedError('getFetchStatus() is not implemented'); + } + + Map getAllConverted() { + throw UnimplementedError('getAllConverted() is not implemented'); + } + + RemoteConfigValue getValueConverted(String key) { + throw UnimplementedError('getValueConverted() is not implemented'); + } + + Future setConfigSettingsConverted( + RemoteConfigSettings remoteConfigSettings) { + throw UnimplementedError('setConfigSettingsConverted() is not implemented'); + } } diff --git a/packages/firebase_remote_config/firebase_remote_config_platform_interface/pigeons/copyright.txt b/packages/firebase_remote_config/firebase_remote_config_platform_interface/pigeons/copyright.txt new file mode 100644 index 000000000000..42fc84b1210b --- /dev/null +++ b/packages/firebase_remote_config/firebase_remote_config_platform_interface/pigeons/copyright.txt @@ -0,0 +1,3 @@ +Copyright 2023, the Chromium project authors. Please see the AUTHORS file +for details. All rights reserved. Use of this source code is governed by a +BSD-style license that can be found in the LICENSE file. \ No newline at end of file diff --git a/packages/firebase_remote_config/firebase_remote_config_platform_interface/pigeons/messages.dart b/packages/firebase_remote_config/firebase_remote_config_platform_interface/pigeons/messages.dart new file mode 100644 index 000000000000..b4ad4ddae011 --- /dev/null +++ b/packages/firebase_remote_config/firebase_remote_config_platform_interface/pigeons/messages.dart @@ -0,0 +1,135 @@ +// Copyright 2022, the Chromium project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +import 'package:pigeon/pigeon.dart'; + +@ConfigurePigeon( + PigeonOptions( + dartOut: 'lib/src/pigeon/messages.pigeon.dart', + // We export in the lib folder to expose the class to other packages. + dartTestOut: 'lib/src/pigeon/test_api.dart', + javaOut: + '../firebase_remote_config/android/src/main/java/io/flutter/plugins/firebase/firebaseremoteconfig/GeneratedAndroidFirebaseRemoteConfig.java', + javaOptions: JavaOptions( + package: 'io.flutter.plugins.firebase.remoteconfig', + className: 'GeneratedAndroidFirebaseRemoteConfig', + ), + objcHeaderOut: '../firebase_remote_config/ios/Classes/messages.g.h', + objcSourceOut: '../firebase_remote_config/ios/Classes/messages.g.m', + cppHeaderOut: '../firebase_remote_config/windows/messages.g.h', + cppSourceOut: '../firebase_remote_config/windows/messages.g.cpp', + cppOptions: CppOptions(namespace: 'firebase_remote_config_windows'), + copyrightHeader: 'pigeons/copyright.txt', + ), +) + +/// ValueSource defines the possible sources of a config parameter value. +enum PigeonValueSource { + /// The value was defined by a static constant. + valueStatic, + + /// The value was defined by default config. + valueDefault, + + /// The value was defined by fetched config. + valueRemote, +} + +enum PigeonRemoteConfigFetchStatus { + /// Indicates instance has not yet attempted a fetch. + noFetchYet, + + /// Indicates the last fetch attempt succeeded. + success, + + /// Indicates the last fetch attempt failed. + failure, + + /// Indicates the last fetch attempt was rate-limited. + throttle +} + +class PigeonRemoteConfigSettings { + PigeonRemoteConfigSettings({ + required this.fetchTimeout, + required this.minimumFetchInterval, + }); + + final int fetchTimeout; + + final int minimumFetchInterval; +} + +class PigeonRemoteConfigValue { + PigeonRemoteConfigValue(this.value, this.source); + + List? value; + + /// Indicates at which source this value came from. + final PigeonValueSource source; +} + +class PigeonFirebaseApp { + const PigeonFirebaseApp({ + required this.appName, + required this.tenantId, + }); + + final String appName; + final String? tenantId; +} + +@HostApi(dartHostTestHandler: 'TestFirebaseRemoteConfigHostApi') +abstract class FirebaseRemoteConfigHostApi { + @async + bool activate(PigeonFirebaseApp app); + + @async + void ensureInitialized(PigeonFirebaseApp app); + + @async + void fetch(PigeonFirebaseApp app); + + @async + bool fetchAndActivate(PigeonFirebaseApp app); + + Map getAll(PigeonFirebaseApp app); + + bool getBool( + PigeonFirebaseApp app, + String key, + ); + + int getInt( + PigeonFirebaseApp app, + String key, + ); + + double getDouble( + PigeonFirebaseApp app, + String key, + ); + + String getString( + PigeonFirebaseApp app, + String key, + ); + + PigeonRemoteConfigValue getValue( + PigeonFirebaseApp app, + String key, + ); + + @async + void setConfigSettings( + PigeonFirebaseApp app, + PigeonRemoteConfigSettings remoteConfigSettings, + ); + + @async + void setDefaults( + PigeonFirebaseApp app, + Map defaultParameters, + ); +} diff --git a/packages/firebase_remote_config/firebase_remote_config_platform_interface/pubspec.yaml b/packages/firebase_remote_config/firebase_remote_config_platform_interface/pubspec.yaml index 150fe7f51b1d..8abfd9a5faf5 100644 --- a/packages/firebase_remote_config/firebase_remote_config_platform_interface/pubspec.yaml +++ b/packages/firebase_remote_config/firebase_remote_config_platform_interface/pubspec.yaml @@ -24,3 +24,4 @@ dev_dependencies: sdk: flutter mockito: ^5.0.0 pedantic: ^1.8.0 + pigeon: ^9.0.6 diff --git a/packages/firebase_remote_config/firebase_remote_config_platform_interface/run_pigeon.sh b/packages/firebase_remote_config/firebase_remote_config_platform_interface/run_pigeon.sh new file mode 100644 index 000000000000..c6854102c961 --- /dev/null +++ b/packages/firebase_remote_config/firebase_remote_config_platform_interface/run_pigeon.sh @@ -0,0 +1,9 @@ +flutter pub run pigeon \ + --input pigeons/messages.dart + + + # \ + # --dart_out lib/src/pigeon/messages.pigeon.dart \ + # --cpp_header_out ../firebase_remote_config/windows/messages.g.h \ + # --cpp_source_out ../firebase_remote_config/windows/messages.g.cpp \ + # --cpp_namespace firebase_remote_config_windows \ No newline at end of file From 4361fd9cba8626b1503d372c37d3afff66499a9b Mon Sep 17 00:00:00 2001 From: Cynthia J Date: Sat, 20 May 2023 16:53:48 -0700 Subject: [PATCH 61/65] more pigoen change --- ...method_channel_firebase_remote_config.dart | 45 +++++-------------- ...form_interface_firebase_remote_config.dart | 2 +- 2 files changed, 13 insertions(+), 34 deletions(-) diff --git a/packages/firebase_remote_config/firebase_remote_config_platform_interface/lib/src/method_channel/method_channel_firebase_remote_config.dart b/packages/firebase_remote_config/firebase_remote_config_platform_interface/lib/src/method_channel/method_channel_firebase_remote_config.dart index 714e9cd51f7a..19a97ac0be70 100644 --- a/packages/firebase_remote_config/firebase_remote_config_platform_interface/lib/src/method_channel/method_channel_firebase_remote_config.dart +++ b/packages/firebase_remote_config/firebase_remote_config_platform_interface/lib/src/method_channel/method_channel_firebase_remote_config.dart @@ -5,6 +5,7 @@ // ignore_for_file: require_trailing_commas import 'dart:async'; import 'dart:convert'; +import 'dart:developer'; import 'package:firebase_core/firebase_core.dart'; import 'package:flutter/services.dart'; @@ -143,10 +144,7 @@ class MethodChannelFirebaseRemoteConfig extends FirebaseRemoteConfigPlatform { @override Future ensureInitialized() async { try { - await channel.invokeMethod( - 'RemoteConfig#ensureInitialized', { - 'appName': app.name, - }); + await _api.ensureInitialized(pigeonDefault); } catch (exception, stackTrace) { convertPlatformException(exception, stackTrace); } @@ -155,12 +153,9 @@ class MethodChannelFirebaseRemoteConfig extends FirebaseRemoteConfigPlatform { @override Future activate() async { try { - bool? configChanged = await channel - .invokeMethod('RemoteConfig#activate', { - 'appName': app.name, - }); + bool configChanged = await _api.activate(pigeonDefault); await _updateConfigParameters(); - return configChanged!; + return configChanged; } catch (exception, stackTrace) { convertPlatformException(exception, stackTrace); } @@ -169,9 +164,7 @@ class MethodChannelFirebaseRemoteConfig extends FirebaseRemoteConfigPlatform { @override Future fetch() async { try { - await channel.invokeMethod('RemoteConfig#fetch', { - 'appName': app.name, - }); + await _api.fetch(pigeonDefault); await _updateConfigProperties(); } catch (exception, stackTrace) { // Ensure that fetch status is updated. @@ -183,13 +176,10 @@ class MethodChannelFirebaseRemoteConfig extends FirebaseRemoteConfigPlatform { @override Future fetchAndActivate() async { try { - bool? configChanged = await channel.invokeMethod( - 'RemoteConfig#fetchAndActivate', { - 'appName': app.name, - }); + bool configChanged = await _api.fetchAndActivate(pigeonDefault); await _updateConfigParameters(); await _updateConfigProperties(); - return configChanged!; + return configChanged; } catch (exception, stackTrace) { // Ensure that fetch status is updated. await _updateConfigProperties(); @@ -264,6 +254,7 @@ class MethodChannelFirebaseRemoteConfig extends FirebaseRemoteConfigPlatform { @override Future setConfigSettingsConverted( RemoteConfigSettings remoteConfigSettings) { + log('method remote config setConfigSettingsConverted'); var pigeonSettings = PigeonRemoteConfigSettings( fetchTimeout: remoteConfigSettings.fetchTimeout.inSeconds, minimumFetchInterval: @@ -273,15 +264,10 @@ class MethodChannelFirebaseRemoteConfig extends FirebaseRemoteConfigPlatform { @override Future setConfigSettings( - PigeonRemoteConfigSettings remoteConfigSettings, + PigeonRemoteConfigSettings pigeonRemoteConfigSettings, ) async { try { - await channel - .invokeMethod('RemoteConfig#setConfigSettings', { - 'appName': app.name, - 'fetchTimeout': remoteConfigSettings.fetchTimeout, - 'minimumFetchInterval': remoteConfigSettings.minimumFetchInterval, - }); + await _api.setConfigSettings(pigeonDefault, pigeonRemoteConfigSettings); await _updateConfigProperties(); } catch (exception, stackTrace) { convertPlatformException(exception, stackTrace); @@ -291,10 +277,7 @@ class MethodChannelFirebaseRemoteConfig extends FirebaseRemoteConfigPlatform { @override Future setDefaults(Map defaultParameters) async { try { - await channel.invokeMethod('RemoteConfig#setDefaults', { - 'appName': app.name, - 'defaults': defaultParameters - }); + await _api.setDefaults(pigeonDefault, defaultParameters); await _updateConfigParameters(); } catch (exception, stackTrace) { convertPlatformException(exception, stackTrace); @@ -302,11 +285,7 @@ class MethodChannelFirebaseRemoteConfig extends FirebaseRemoteConfigPlatform { } Future _updateConfigParameters() async { - Map? parameters = await channel - .invokeMapMethod( - 'RemoteConfig#getAll', { - 'appName': app.name, - }); + Map? parameters = await _api.getAll(pigeonDefault); _activeParameters = _parsePigeonParameters(parameters!); } diff --git a/packages/firebase_remote_config/firebase_remote_config_platform_interface/lib/src/platform_interface/platform_interface_firebase_remote_config.dart b/packages/firebase_remote_config/firebase_remote_config_platform_interface/lib/src/platform_interface/platform_interface_firebase_remote_config.dart index 844678643aa8..c678963f260a 100644 --- a/packages/firebase_remote_config/firebase_remote_config_platform_interface/lib/src/platform_interface/platform_interface_firebase_remote_config.dart +++ b/packages/firebase_remote_config/firebase_remote_config_platform_interface/lib/src/platform_interface/platform_interface_firebase_remote_config.dart @@ -175,7 +175,7 @@ abstract class FirebaseRemoteConfigPlatform extends PlatformInterface { /// Sets the [RemoteConfigSettings] for the current instance. Future setConfigSettings( - PigeonRemoteConfigSettings remoteConfigSettings) { + PigeonRemoteConfigSettings pigeonRemoteConfigSettings) { throw UnimplementedError('setConfigSettings() is not implemented'); } From ac5d4c4c3f56609a1ce4c252eea60016d743d6d6 Mon Sep 17 00:00:00 2001 From: Cynthia J Date: Fri, 26 May 2023 10:19:35 -0700 Subject: [PATCH 62/65] update on the async result handle and more --- .../firebase_core/windows/CMakeLists.txt | 2 +- .../windows/firebase_core_plugin.cpp | 18 ++-- .../example/windows/runner/flutter_window.cpp | 5 ++ .../lib/firebase_remote_config.dart | 1 + .../lib/src/firebase_remote_config.dart | 1 + .../windows/CMakeLists.txt | 7 -- .../windows/firebase_remote_config_plugin.cpp | 83 ++++++++++--------- ...method_channel_firebase_remote_config.dart | 34 +++++--- 8 files changed, 88 insertions(+), 63 deletions(-) diff --git a/packages/firebase_core/firebase_core/windows/CMakeLists.txt b/packages/firebase_core/firebase_core/windows/CMakeLists.txt index 9356251b509a..3082e942c2b6 100644 --- a/packages/firebase_core/firebase_core/windows/CMakeLists.txt +++ b/packages/firebase_core/firebase_core/windows/CMakeLists.txt @@ -4,7 +4,7 @@ # customers of the plugin. cmake_minimum_required(VERSION 3.14) -set(FIREBASE_SDK_VERSION "10.5.0") +set(FIREBASE_SDK_VERSION "11.0.1") if (EXISTS $ENV{FIREBASE_CPP_SDK_DIR}/include/firebase/version.h) file(READ "$ENV{FIREBASE_CPP_SDK_DIR}/include/firebase/version.h" existing_version) diff --git a/packages/firebase_core/firebase_core/windows/firebase_core_plugin.cpp b/packages/firebase_core/firebase_core/windows/firebase_core_plugin.cpp index 2fbed3feb157..d5f209a71aa5 100644 --- a/packages/firebase_core/firebase_core/windows/firebase_core_plugin.cpp +++ b/packages/firebase_core/firebase_core/windows/firebase_core_plugin.cpp @@ -91,6 +91,8 @@ PigeonInitializeResponse AppToPigeonInitializeResponse(const App &app) { PigeonInitializeResponse response = PigeonInitializeResponse(); response.set_name(app.name()); response.set_options(optionsFromFIROptions(app.options())); + + // response.set_plugin_constants(registrar.); return response; } @@ -104,21 +106,27 @@ void FirebaseCorePlugin::InitializeApp( app_name.c_str()); // Send back the result to Flutter + std::cout << "[C++] FirebaseCorePlugin::InitializeApp():" << app_name + << std::endl; result(AppToPigeonInitializeResponse(*app)); } void FirebaseCorePlugin::InitializeCore( std::function reply)> result) { - // TODO: Missing function to get the list of currently initialized apps std::vector initializedApps; + std::vector all_apps = App::GetApps(); + for (const App *app : all_apps) { + initializedApps.push_back(AppToPigeonInitializeResponse(*app)); + } + flutter::EncodableList encodableList; // Insert the contents of the vector into the EncodableList - // for (const auto &item : initializedApps) { - // encodableList.push_back(flutter::EncodableValue(item)); - //} - result(flutter::EncodableList()); + for (const auto &item : initializedApps) { + encodableList.push_back(flutter::CustomEncodableValue(item)); + } + result(encodableList); } void FirebaseCorePlugin::OptionsFromResource( diff --git a/packages/firebase_remote_config/firebase_remote_config/example/windows/runner/flutter_window.cpp b/packages/firebase_remote_config/firebase_remote_config/example/windows/runner/flutter_window.cpp index b25e363efa42..46c3e636f1e8 100644 --- a/packages/firebase_remote_config/firebase_remote_config/example/windows/runner/flutter_window.cpp +++ b/packages/firebase_remote_config/firebase_remote_config/example/windows/runner/flutter_window.cpp @@ -31,6 +31,11 @@ bool FlutterWindow::OnCreate() { this->Show(); }); + // Flutter can complete the first frame before the "show window" callback is + // registered. Ensure a frame is pending to ensure the window is shown. + // This no-ops if the first frame hasn't completed yet. + flutter_controller_->ForceRedraw(); + return true; } diff --git a/packages/firebase_remote_config/firebase_remote_config/lib/firebase_remote_config.dart b/packages/firebase_remote_config/firebase_remote_config/lib/firebase_remote_config.dart index fbef39b99cec..4d80e5dd2e71 100644 --- a/packages/firebase_remote_config/firebase_remote_config/lib/firebase_remote_config.dart +++ b/packages/firebase_remote_config/firebase_remote_config/lib/firebase_remote_config.dart @@ -5,6 +5,7 @@ library firebase_remote_config; import 'dart:async'; +import 'dart:developer'; import 'package:firebase_core/firebase_core.dart'; import 'package:firebase_core_platform_interface/firebase_core_platform_interface.dart' diff --git a/packages/firebase_remote_config/firebase_remote_config/lib/src/firebase_remote_config.dart b/packages/firebase_remote_config/firebase_remote_config/lib/src/firebase_remote_config.dart index c228cb39c39e..be78e1a2e9e0 100644 --- a/packages/firebase_remote_config/firebase_remote_config/lib/src/firebase_remote_config.dart +++ b/packages/firebase_remote_config/firebase_remote_config/lib/src/firebase_remote_config.dart @@ -86,6 +86,7 @@ class FirebaseRemoteConfig extends FirebasePluginPlatform { /// - **forbidden**: /// - Thrown if the Google Cloud Platform Firebase Remote Config API is disabled Future fetchAndActivate() async { + log('remote_config_dart fetchAndActivate'); bool configChanged = await _delegate.fetchAndActivate(); return configChanged; } diff --git a/packages/firebase_remote_config/firebase_remote_config/windows/CMakeLists.txt b/packages/firebase_remote_config/firebase_remote_config/windows/CMakeLists.txt index 51f67ed7ba33..4b3476bbad83 100644 --- a/packages/firebase_remote_config/firebase_remote_config/windows/CMakeLists.txt +++ b/packages/firebase_remote_config/firebase_remote_config/windows/CMakeLists.txt @@ -45,13 +45,6 @@ target_compile_definitions(${PLUGIN_NAME} PRIVATE FLUTTER_PLUGIN_IMPL) # Source include directories and library dependencies. Add any plugin-specific # dependencies here. set(MSVC_RUNTIME_MODE MD) -message("CMAKE_CURRENT_SOURCE_DIR is ${CMAKE_CURRENT_SOURCE_DIR}") -# set(FIREBASE_CORE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../../firebase_core") -# message("FIREBASE_CORE_DIR is ${FIREBASE_CORE_DIR}") -# add_subdirectory(${FIREBASE_CORE_DIR}) -#add_subdirectory(${FIREBASE_CPP_SDK_DIR} bin/ EXCLUDE_FROM_ALL) -# target_include_directories(${PLUGIN_NAME} INTERFACE -# "${FIREBASE_CPP_SDK_DIR}/include") set(firebase_libs firebase_core_plugin firebase_remote_config firebase_app) set(ADDITIONAL_LIBS advapi32 ws2_32 crypt32 rpcrt4 ole32) target_link_libraries(${PLUGIN_NAME} PRIVATE "${firebase_libs}" "${ADDITIONAL_LIBS}") diff --git a/packages/firebase_remote_config/firebase_remote_config/windows/firebase_remote_config_plugin.cpp b/packages/firebase_remote_config/firebase_remote_config/windows/firebase_remote_config_plugin.cpp index 5a18983fe682..57a9cc1aceda 100644 --- a/packages/firebase_remote_config/firebase_remote_config/windows/firebase_remote_config_plugin.cpp +++ b/packages/firebase_remote_config/firebase_remote_config/windows/firebase_remote_config_plugin.cpp @@ -51,29 +51,25 @@ FirebaseRemoteConfigPlugin::~FirebaseRemoteConfigPlugin() = default; void FirebaseRemoteConfigPlugin::Activate( const PigeonFirebaseApp& app, std::function reply)> result) { + std::cout << "[C++] FirebaseRemoteConfigPlugin::Activate() START" + << std::endl; App* cpp_app = App::GetInstance(app.app_name().c_str()); RemoteConfig* rc = RemoteConfig::GetInstance(cpp_app); - bool flutter_result; - Future activated_result = rc->Activate(); - activated_result.OnCompletion( - [](const Future& bool_result, void* user_data) { - bool* casted_result = static_cast(user_data); - *casted_result = bool_result.result(); - }, - &flutter_result); - - while (activated_result.status() == ::firebase::kFutureStatusPending) { - Sleep(1000); - } - - result(flutter_result); + activated_result.OnCompletion([result](const Future& bool_result) { + // TODO error handling + result(bool_result.result()); + std::cout << "[C++] FirebaseRemoteConfigPlugin::Activate() COMPLETE" + << std::endl; + }); } void FirebaseRemoteConfigPlugin::EnsureInitialized( const PigeonFirebaseApp& app, std::function reply)> result) { + std::cout << "[C++] FirebaseRemoteConfigPlugin::EnsureInitialized() START" + << std::endl; App* cpp_app = App::GetInstance(app.app_name().c_str()); RemoteConfig* rc = RemoteConfig::GetInstance(cpp_app); @@ -84,42 +80,47 @@ void FirebaseRemoteConfigPlugin::EnsureInitialized( void FirebaseRemoteConfigPlugin::Fetch( const PigeonFirebaseApp& app, std::function reply)> result) { + std::cout << "[C++] FirebaseRemoteConfigPlugin::Fetch() START" << std::endl; App* cpp_app = App::GetInstance(app.app_name().c_str()); RemoteConfig* rc = RemoteConfig::GetInstance(cpp_app); Future fetch_result = rc->Fetch(); - fetch_result.OnCompletion([](const Future& void_result) { - // print message? + fetch_result.OnCompletion([result](const Future& void_result) { + // TODO error handling + std::cout << "[C++] FirebaseRemoteConfigPlugin::Fetch() COMPLETE" + << std::endl; + result(std::nullopt); }); - - while (fetch_result.status() == ::firebase::kFutureStatusPending) { - Sleep(1000); - } - - result(std::nullopt); } void FirebaseRemoteConfigPlugin::FetchAndActivate( const PigeonFirebaseApp& app, std::function reply)> result) { - App* cpp_app = App::GetInstance(app.app_name().c_str()); + std::cout << "[C++] FirebaseRemoteConfigPlugin::FetchAndActivate() START" + << std::endl; + // App* cpp_app = App::GetInstance(app.app_name().c_str()); + App* cpp_app = App::GetInstance(); + // std::cout << "[C++] get cpp_app:" << app.app_name() << std::endl; + std::vector all_apps = App::GetApps(); + std::cout << "[C++] all apps size is: " << all_apps.size() << std::endl; + if (cpp_app == nullptr) { + std::cout << "[C++] cannot get FirebaseApp:" << app.app_name() << std::endl; + result(false); + return; + } RemoteConfig* rc = RemoteConfig::GetInstance(cpp_app); - bool flutter_result; + std::cout << "[C++] Get rc instance" << std::endl; Future fa_result = rc->FetchAndActivate(); - fa_result.OnCompletion( - [](const Future& bool_result, void* user_data) { - bool* casted_result = static_cast(user_data); - *casted_result = bool_result.result(); - }, - &flutter_result); - - while (fa_result.status() == ::firebase::kFutureStatusPending) { - Sleep(1000); - } - - result(flutter_result); + std::cout << "[C++] rc->FetchAndActivate()" << std::endl; + fa_result.OnCompletion([result](const Future& bool_result, + void* user_data) { + // TODO error handling + result(bool_result.result()); + std::cout << "[C++] FirebaseRemoteConfigPlugin::FetchAndActivate() COMPLETE" + << std::endl; + }); } ErrorOr FirebaseRemoteConfigPlugin::GetAll( @@ -174,11 +175,17 @@ ErrorOr FirebaseRemoteConfigPlugin::GetValue( void FirebaseRemoteConfigPlugin::SetConfigSettings( const PigeonFirebaseApp& app, const PigeonRemoteConfigSettings& remote_config_settings, - std::function reply)> result) {} + std::function reply)> result) { + // TODO + result(std::nullopt); +} void FirebaseRemoteConfigPlugin::SetDefaults( const PigeonFirebaseApp& app, const flutter::EncodableMap& default_parameters, - std::function reply)> result) {} + std::function reply)> result) { + // TODO + result(std::nullopt); +} } // namespace firebase_remote_config_windows diff --git a/packages/firebase_remote_config/firebase_remote_config_platform_interface/lib/src/method_channel/method_channel_firebase_remote_config.dart b/packages/firebase_remote_config/firebase_remote_config_platform_interface/lib/src/method_channel/method_channel_firebase_remote_config.dart index 19a97ac0be70..16d852169a0d 100644 --- a/packages/firebase_remote_config/firebase_remote_config_platform_interface/lib/src/method_channel/method_channel_firebase_remote_config.dart +++ b/packages/firebase_remote_config/firebase_remote_config_platform_interface/lib/src/method_channel/method_channel_firebase_remote_config.dart @@ -100,11 +100,17 @@ class MethodChannelFirebaseRemoteConfig extends FirebaseRemoteConfigPlatform { FirebaseRemoteConfigPlatform setInitialValues({ required Map remoteConfigValues, }) { - final fetchTimeout = Duration(seconds: remoteConfigValues['fetchTimeout']); - final minimumFetchInterval = - Duration(seconds: remoteConfigValues['minimumFetchInterval']); - final lastFetchMillis = remoteConfigValues['lastFetchTime']; - final lastFetchStatus = remoteConfigValues['lastFetchStatus']; + final fetchTimeout = remoteConfigValues.isEmpty + ? const Duration(seconds: 60) + : Duration(seconds: remoteConfigValues['fetchTimeout']); + final minimumFetchInterval = remoteConfigValues.isEmpty + ? const Duration(hours: 12) + : Duration(seconds: remoteConfigValues['minimumFetchInterval']); + final lastFetchMillis = + remoteConfigValues.isEmpty ? 0 : remoteConfigValues['lastFetchTime']; + final lastFetchStatus = remoteConfigValues.isEmpty + ? 'noFetchYet' + : remoteConfigValues['lastFetchStatus']; _settings = PigeonRemoteConfigSettings( fetchTimeout: fetchTimeout.inSeconds, @@ -112,8 +118,11 @@ class MethodChannelFirebaseRemoteConfig extends FirebaseRemoteConfigPlatform { ); _lastFetchTime = DateTime.fromMillisecondsSinceEpoch(lastFetchMillis); _lastFetchStatus = _parseFetchStatus(lastFetchStatus); - _activeParameters = - _parsePigeonParameters(remoteConfigValues['parameters']); + if (remoteConfigValues.isNotEmpty) { + _activeParameters = + _parsePigeonParameters(remoteConfigValues['parameters']); + } + return this; } @@ -165,10 +174,10 @@ class MethodChannelFirebaseRemoteConfig extends FirebaseRemoteConfigPlatform { Future fetch() async { try { await _api.fetch(pigeonDefault); - await _updateConfigProperties(); + // await _updateConfigProperties(); } catch (exception, stackTrace) { // Ensure that fetch status is updated. - await _updateConfigProperties(); + // await _updateConfigProperties(); convertPlatformException(exception, stackTrace); } } @@ -176,13 +185,14 @@ class MethodChannelFirebaseRemoteConfig extends FirebaseRemoteConfigPlatform { @override Future fetchAndActivate() async { try { + log('method_remote_config fetchAndActivate'); bool configChanged = await _api.fetchAndActivate(pigeonDefault); await _updateConfigParameters(); - await _updateConfigProperties(); + //await _updateConfigProperties(); return configChanged; } catch (exception, stackTrace) { // Ensure that fetch status is updated. - await _updateConfigProperties(); + // await _updateConfigProperties(); convertPlatformException(exception, stackTrace); } } @@ -268,7 +278,7 @@ class MethodChannelFirebaseRemoteConfig extends FirebaseRemoteConfigPlatform { ) async { try { await _api.setConfigSettings(pigeonDefault, pigeonRemoteConfigSettings); - await _updateConfigProperties(); + //await _updateConfigProperties(); } catch (exception, stackTrace) { convertPlatformException(exception, stackTrace); } From 0e90b9fe9409113871b5a315bc1c6c331ab17a7e Mon Sep 17 00:00:00 2001 From: Cynthia J Date: Fri, 26 May 2023 14:09:09 -0700 Subject: [PATCH 63/65] fix a compile error --- .../windows/firebase_remote_config_plugin.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/packages/firebase_remote_config/firebase_remote_config/windows/firebase_remote_config_plugin.cpp b/packages/firebase_remote_config/firebase_remote_config/windows/firebase_remote_config_plugin.cpp index 57a9cc1aceda..c461b4f2c00e 100644 --- a/packages/firebase_remote_config/firebase_remote_config/windows/firebase_remote_config_plugin.cpp +++ b/packages/firebase_remote_config/firebase_remote_config/windows/firebase_remote_config_plugin.cpp @@ -114,8 +114,7 @@ void FirebaseRemoteConfigPlugin::FetchAndActivate( Future fa_result = rc->FetchAndActivate(); std::cout << "[C++] rc->FetchAndActivate()" << std::endl; - fa_result.OnCompletion([result](const Future& bool_result, - void* user_data) { + fa_result.OnCompletion([result](const Future& bool_result) { // TODO error handling result(bool_result.result()); std::cout << "[C++] FirebaseRemoteConfigPlugin::FetchAndActivate() COMPLETE" From ad3ab0ebfbefe9284a74eab396802f0b7e9da610 Mon Sep 17 00:00:00 2001 From: Cynthia J Date: Fri, 23 Jun 2023 13:59:16 -0700 Subject: [PATCH 64/65] hack to create firebaseApp --- .../windows/firebase_core_plugin.cpp | 45 +++++++++-- .../windows/firebase_core_plugin.h | 2 + .../windows/firebase_core_plugin_c_api.cpp | 5 ++ .../firebase_core_plugin_c_api.h | 13 ++- .../test/firebase_remote_config_test.dart | 79 +++++++++++-------- .../windows/firebase_remote_config_plugin.cpp | 57 ++++++++++--- ...base_remote_config_platform_interface.dart | 6 ++ 7 files changed, 151 insertions(+), 56 deletions(-) diff --git a/packages/firebase_core/firebase_core/windows/firebase_core_plugin.cpp b/packages/firebase_core/firebase_core/windows/firebase_core_plugin.cpp index d5f209a71aa5..cb8b6e794417 100644 --- a/packages/firebase_core/firebase_core/windows/firebase_core_plugin.cpp +++ b/packages/firebase_core/firebase_core/windows/firebase_core_plugin.cpp @@ -1,7 +1,7 @@ // Copyright 2023, the Chromium project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. - +#define _CRT_SECURE_NO_WARNINGS #include "firebase_core_plugin.h" // This must be included before many other Windows headers. @@ -19,6 +19,7 @@ #include #include +#include #include #include #include @@ -96,18 +97,52 @@ PigeonInitializeResponse AppToPigeonInitializeResponse(const App &app) { return response; } +std::map> g_apps_; + +std::vector FirebaseCorePlugin::GetFirebaseApp( + std::string appName) { + auto app_it = g_apps_.find(appName); + + // If the app is already in the map, return the stored shared_ptr + if (app_it != g_apps_.end()) { + return app_it->second; + } + + std::vector app_vector; + return app_vector; +} + void FirebaseCorePlugin::InitializeApp( const std::string &app_name, const PigeonFirebaseOptions &initialize_app_request, std::function reply)> result) { // Create an app - App *app; - app = App::Create(PigeonFirebaseOptionsToAppOptions(initialize_app_request), - app_name.c_str()); + App *app = + App::Create(PigeonFirebaseOptionsToAppOptions(initialize_app_request), + app_name.c_str()); - // Send back the result to Flutter std::cout << "[C++] FirebaseCorePlugin::InitializeApp():" << app_name << std::endl; + + auto app_it = g_apps_.find(app_name); + + // // If the app is already in the map, return the stored shared_ptr + if (app_it == g_apps_.end()) { + std::vector app_vector; + app_vector.push_back(app_name); + app_vector.push_back(initialize_app_request.api_key()); + app_vector.push_back(initialize_app_request.app_id()); + app_vector.push_back(*initialize_app_request.database_u_r_l()); + + // app_vector.push_back(*initialize_app_request.tracking_id()); + app_vector.push_back(initialize_app_request.messaging_sender_id()); + app_vector.push_back(initialize_app_request.project_id()); + app_vector.push_back(*initialize_app_request.storage_bucket()); + + g_apps_[app_name] = app_vector; + } + + // Send back the result to Flutter result(AppToPigeonInitializeResponse(*app)); } diff --git a/packages/firebase_core/firebase_core/windows/firebase_core_plugin.h b/packages/firebase_core/firebase_core/windows/firebase_core_plugin.h index a1f43ad21491..3261130f08dd 100644 --- a/packages/firebase_core/firebase_core/windows/firebase_core_plugin.h +++ b/packages/firebase_core/firebase_core/windows/firebase_core_plugin.h @@ -30,6 +30,8 @@ class FirebaseCorePlugin : public flutter::Plugin, FirebaseCorePlugin(const FirebaseCorePlugin &) = delete; FirebaseCorePlugin &operator=(const FirebaseCorePlugin &) = delete; + static std::vector GetFirebaseApp(std::string appName); + // FirebaseCoreHostApi virtual void InitializeApp( const std::string &app_name, diff --git a/packages/firebase_core/firebase_core/windows/firebase_core_plugin_c_api.cpp b/packages/firebase_core/firebase_core/windows/firebase_core_plugin_c_api.cpp index fa14aed47bd9..96dd4d7febbe 100644 --- a/packages/firebase_core/firebase_core/windows/firebase_core_plugin_c_api.cpp +++ b/packages/firebase_core/firebase_core/windows/firebase_core_plugin_c_api.cpp @@ -14,3 +14,8 @@ void FirebaseCorePluginCApiRegisterWithRegistrar( flutter::PluginRegistrarManager::GetInstance() ->GetRegistrar(registrar)); } + +FLUTTER_PLUGIN_EXPORT std::vector GetFirebaseApp( + std::string appName) { + return firebase_core_windows::FirebaseCorePlugin::GetFirebaseApp(appName); +} diff --git a/packages/firebase_core/firebase_core/windows/include/firebase_core/firebase_core_plugin_c_api.h b/packages/firebase_core/firebase_core/windows/include/firebase_core/firebase_core_plugin_c_api.h index 3f0d51a62c38..b1c0b75644a8 100644 --- a/packages/firebase_core/firebase_core/windows/include/firebase_core/firebase_core_plugin_c_api.h +++ b/packages/firebase_core/firebase_core/windows/include/firebase_core/firebase_core_plugin_c_api.h @@ -9,21 +9,20 @@ #include +#include +#include +#include + #ifdef FLUTTER_PLUGIN_IMPL #define FLUTTER_PLUGIN_EXPORT __declspec(dllexport) #else #define FLUTTER_PLUGIN_EXPORT __declspec(dllimport) #endif -#if defined(__cplusplus) -extern "C" { -#endif - FLUTTER_PLUGIN_EXPORT void FirebaseCorePluginCApiRegisterWithRegistrar( FlutterDesktopPluginRegistrarRef registrar); -#if defined(__cplusplus) -} // extern "C" -#endif +FLUTTER_PLUGIN_EXPORT std::vector GetFirebaseApp( + std::string appName); #endif // FLUTTER_PLUGIN_FIREBASE_CORE_PLUGIN_C_API_H_ diff --git a/packages/firebase_remote_config/firebase_remote_config/test/firebase_remote_config_test.dart b/packages/firebase_remote_config/firebase_remote_config/test/firebase_remote_config_test.dart index c01592ad5f02..2dd193af7503 100644 --- a/packages/firebase_remote_config/firebase_remote_config/test/firebase_remote_config_test.dart +++ b/packages/firebase_remote_config/firebase_remote_config/test/firebase_remote_config_test.dart @@ -19,11 +19,11 @@ void main() { late FirebaseRemoteConfig remoteConfig; late DateTime mockLastFetchTime; - late RemoteConfigFetchStatus mockLastFetchStatus; - late RemoteConfigSettings mockRemoteConfigSettings; - late Map mockParameters; + late PigeonRemoteConfigFetchStatus mockLastFetchStatus; + late PigeonRemoteConfigSettings mockRemoteConfigSettings; + late Map mockParameters; late Map mockDefaultParameters; - late RemoteConfigValue mockRemoteConfigValue; + late PigeonRemoteConfigValue mockRemoteConfigValue; group('FirebaseRemoteConfig', () { FirebaseRemoteConfigPlatform.instance = mockRemoteConfigPlatform; @@ -33,16 +33,16 @@ void main() { remoteConfig = FirebaseRemoteConfig.instance; mockLastFetchTime = DateTime(2020); - mockLastFetchStatus = RemoteConfigFetchStatus.noFetchYet; - mockRemoteConfigSettings = RemoteConfigSettings( - fetchTimeout: const Duration(seconds: 10), - minimumFetchInterval: const Duration(hours: 1), + mockLastFetchStatus = PigeonRemoteConfigFetchStatus.noFetchYet; + mockRemoteConfigSettings = PigeonRemoteConfigSettings( + fetchTimeout: 10, + minimumFetchInterval: 3600, ); - mockParameters = {}; + mockParameters = {}; mockDefaultParameters = {}; - mockRemoteConfigValue = RemoteConfigValue( - [], - ValueSource.valueStatic, + mockRemoteConfigValue = PigeonRemoteConfigValue( + value: [], + source: PigeonValueSource.valueStatic, ); when( @@ -137,9 +137,14 @@ void main() { fetchTimeout: const Duration(seconds: 8), minimumFetchInterval: Duration.zero, ); + final pigeonRemoteConfigSettings = PigeonRemoteConfigSettings( + fetchTimeout: 8, + minimumFetchInterval: 0, + ); await remoteConfig.setConfigSettings(remoteConfigSettings); verify( - mockRemoteConfigPlatform.setConfigSettings(remoteConfigSettings), + mockRemoteConfigPlatform + .setConfigSettings(pigeonRemoteConfigSettings), ); }); }); @@ -301,7 +306,8 @@ class MockFirebaseRemoteConfig extends Mock } @override - Future setConfigSettings(RemoteConfigSettings? remoteConfigSettings) { + Future setConfigSettings( + PigeonRemoteConfigSettings? remoteConfigSettings) { return super.noSuchMethod( Invocation.method(#setConfigSettings, [remoteConfigSettings]), returnValue: Future.value(), @@ -319,11 +325,11 @@ class MockFirebaseRemoteConfig extends Mock } @override - Map getAll() { + Map getAll() { return super.noSuchMethod( Invocation.method(#getAll, []), - returnValue: {}, - returnValueForMissingStub: {}, + returnValue: {}, + returnValueForMissingStub: {}, ); } @@ -364,24 +370,33 @@ class MockFirebaseRemoteConfig extends Mock } @override - RemoteConfigValue getValue(String key) { + PigeonRemoteConfigValue getValue(String key) { return super.noSuchMethod( Invocation.method(#getValue, [key]), - returnValue: RemoteConfigValue( - [], - ValueSource.valueStatic, + returnValue: PigeonRemoteConfigValue( + value: [], + source: PigeonValueSource.valueStatic, ), - returnValueForMissingStub: RemoteConfigValue( - [], - ValueSource.valueStatic, + returnValueForMissingStub: PigeonRemoteConfigValue( + value: [], + source: PigeonValueSource.valueStatic, ), ); } @override - RemoteConfigFetchStatus get lastFetchStatus { + PigeonRemoteConfigFetchStatus get lastFetchStatus { return super.noSuchMethod( Invocation.getter(#lastFetchStatus), + returnValue: PigeonRemoteConfigFetchStatus.success, + returnValueForMissingStub: PigeonRemoteConfigFetchStatus.success, + ); + } + + @override + RemoteConfigFetchStatus getFetchStatus() { + return super.noSuchMethod( + Invocation.getter(#getFetchStatus), returnValue: RemoteConfigFetchStatus.success, returnValueForMissingStub: RemoteConfigFetchStatus.success, ); @@ -397,16 +412,16 @@ class MockFirebaseRemoteConfig extends Mock } @override - RemoteConfigSettings get settings { + PigeonRemoteConfigSettings get settings { return super.noSuchMethod( Invocation.getter(#settings), - returnValue: RemoteConfigSettings( - fetchTimeout: const Duration(seconds: 10), - minimumFetchInterval: const Duration(hours: 1), + returnValue: PigeonRemoteConfigSettings( + fetchTimeout: 10, + minimumFetchInterval: 3600, ), - returnValueForMissingStub: RemoteConfigSettings( - fetchTimeout: const Duration(seconds: 10), - minimumFetchInterval: const Duration(hours: 1), + returnValueForMissingStub: PigeonRemoteConfigSettings( + fetchTimeout: 10, + minimumFetchInterval: 3600, ), ); } diff --git a/packages/firebase_remote_config/firebase_remote_config/windows/firebase_remote_config_plugin.cpp b/packages/firebase_remote_config/firebase_remote_config/windows/firebase_remote_config_plugin.cpp index c461b4f2c00e..280ff8e2c598 100644 --- a/packages/firebase_remote_config/firebase_remote_config/windows/firebase_remote_config_plugin.cpp +++ b/packages/firebase_remote_config/firebase_remote_config/windows/firebase_remote_config_plugin.cpp @@ -1,7 +1,7 @@ // Copyright 2023, the Chromium project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. - +#define _CRT_SECURE_NO_WARNINGS #include "firebase_remote_config_plugin.h" // This must be included before many other Windows headers. @@ -10,6 +10,7 @@ #include "firebase/app.h" #include "firebase/future.h" #include "firebase/remote_config.h" +#include "firebase_core/firebase_core_plugin_c_api.h" #include "messages.g.h" // For getPlatformVersion; remove unless needed for your plugin implementation. @@ -65,6 +66,36 @@ void FirebaseRemoteConfigPlugin::Activate( }); } +RemoteConfig* GetRCFromPigeon(const PigeonFirebaseApp& pigeonApp) { + std::vector app_vector = GetFirebaseApp(pigeonApp.app_name()); + + // print vector lenghts + std::cout << app_vector.size() << std::endl; + + // print the vector + for (std::string n : app_vector) { + std::cout << n << std::endl; + } + + firebase::AppOptions options; + + options.set_api_key(app_vector[1].c_str()); + options.set_app_id(app_vector[2].c_str()); + options.set_database_url(app_vector[3].c_str()); + + options.set_messaging_sender_id(app_vector[4].c_str()); + + options.set_project_id(app_vector[5].c_str()); + + options.set_storage_bucket(app_vector[6].c_str()); + + App* cpp_app = App::Create(options, pigeonApp.app_name().c_str()); + + RemoteConfig* rc = RemoteConfig::GetInstance(cpp_app); + + return rc; +} + void FirebaseRemoteConfigPlugin::EnsureInitialized( const PigeonFirebaseApp& app, std::function reply)> result) { @@ -98,17 +129,17 @@ void FirebaseRemoteConfigPlugin::FetchAndActivate( std::function reply)> result) { std::cout << "[C++] FirebaseRemoteConfigPlugin::FetchAndActivate() START" << std::endl; - // App* cpp_app = App::GetInstance(app.app_name().c_str()); - App* cpp_app = App::GetInstance(); - // std::cout << "[C++] get cpp_app:" << app.app_name() << std::endl; - std::vector all_apps = App::GetApps(); - std::cout << "[C++] all apps size is: " << all_apps.size() << std::endl; - if (cpp_app == nullptr) { - std::cout << "[C++] cannot get FirebaseApp:" << app.app_name() << std::endl; - result(false); - return; - } - RemoteConfig* rc = RemoteConfig::GetInstance(cpp_app); + // // App* cpp_app = App::GetInstance(app.app_name().c_str()); + // App* cpp_app = App::GetInstance(); + // // std::cout << "[C++] get cpp_app:" << app.app_name() << std::endl; + // std::vector all_apps = App::GetApps(); + // std::cout << "[C++] all apps size is: " << all_apps.size() << std::endl; + // if (cpp_app == nullptr) { + // std::cout << "[C++] cannot get FirebaseApp:" << app.app_name() << + // std::endl; result(false); return; + // } + // RemoteConfig* rc = RemoteConfig::GetInstance(cpp_app); + RemoteConfig* rc = GetRCFromPigeon(app); std::cout << "[C++] Get rc instance" << std::endl; @@ -176,6 +207,8 @@ void FirebaseRemoteConfigPlugin::SetConfigSettings( const PigeonRemoteConfigSettings& remote_config_settings, std::function reply)> result) { // TODO + std::cout << "[C++] FirebaseRemoteConfigPlugin::SetConfigSettings()" + << std::endl; result(std::nullopt); } diff --git a/packages/firebase_remote_config/firebase_remote_config_platform_interface/lib/firebase_remote_config_platform_interface.dart b/packages/firebase_remote_config/firebase_remote_config_platform_interface/lib/firebase_remote_config_platform_interface.dart index c21f3d5a68c2..612869d44898 100644 --- a/packages/firebase_remote_config/firebase_remote_config_platform_interface/lib/firebase_remote_config_platform_interface.dart +++ b/packages/firebase_remote_config/firebase_remote_config_platform_interface/lib/firebase_remote_config_platform_interface.dart @@ -10,3 +10,9 @@ export 'src/remote_config_settings.dart'; export 'src/remote_config_status.dart'; export 'src/remote_config_update.dart'; export 'src/remote_config_value.dart'; +export 'src/pigeon/messages.pigeon.dart' + show + PigeonRemoteConfigSettings, + PigeonRemoteConfigValue, + PigeonRemoteConfigFetchStatus, + PigeonValueSource; From acb2af4ecf25f4cd14b5e9723ec5af51e4d7dce8 Mon Sep 17 00:00:00 2001 From: Cynthia J Date: Tue, 27 Jun 2023 16:06:27 -0700 Subject: [PATCH 65/65] better way to access FirebaseApp and FirebaseRemoteConfig --- .../firebase_core/windows/CMakeLists.txt | 3 +- .../windows/firebase_core_plugin.cpp | 42 +++------- .../windows/firebase_core_plugin.h | 4 +- .../windows/firebase_core_plugin_c_api.cpp | 7 +- .../firebase_core_plugin_c_api.h | 5 +- .../windows/firebase_remote_config_plugin.cpp | 80 ++++--------------- 6 files changed, 36 insertions(+), 105 deletions(-) diff --git a/packages/firebase_core/firebase_core/windows/CMakeLists.txt b/packages/firebase_core/firebase_core/windows/CMakeLists.txt index 3082e942c2b6..773ec6781e52 100644 --- a/packages/firebase_core/firebase_core/windows/CMakeLists.txt +++ b/packages/firebase_core/firebase_core/windows/CMakeLists.txt @@ -99,8 +99,9 @@ foreach(firebase_lib IN ITEMS ${firebase_libs}) IMPORTED_LOCATION_RELEASE "${firebase_lib_release_path}" ) endforeach() +set(ADDITIONAL_LIBS advapi32 ws2_32 crypt32 rpcrt4 ole32) -target_link_libraries(${PLUGIN_NAME} PRIVATE "${firebase_libs}") +target_link_libraries(${PLUGIN_NAME} PRIVATE "${firebase_libs}" "${ADDITIONAL_LIBS}") target_include_directories(${PLUGIN_NAME} INTERFACE "${CMAKE_CURRENT_SOURCE_DIR}/include") diff --git a/packages/firebase_core/firebase_core/windows/firebase_core_plugin.cpp b/packages/firebase_core/firebase_core/windows/firebase_core_plugin.cpp index cb8b6e794417..16a4f2d1801a 100644 --- a/packages/firebase_core/firebase_core/windows/firebase_core_plugin.cpp +++ b/packages/firebase_core/firebase_core/windows/firebase_core_plugin.cpp @@ -9,6 +9,7 @@ #include "firebase/app.h" #include "firebase/log.h" +#include "firebase/remote_config.h" #include "messages.g.h" // For getPlatformVersion; remove unless needed for your plugin implementation. @@ -26,6 +27,7 @@ #include #include using ::firebase::App; +using ::firebase::remote_config::RemoteConfig; namespace firebase_core_windows { @@ -97,19 +99,14 @@ PigeonInitializeResponse AppToPigeonInitializeResponse(const App &app) { return response; } -std::map> g_apps_; - -std::vector FirebaseCorePlugin::GetFirebaseApp( - std::string appName) { - auto app_it = g_apps_.find(appName); - - // If the app is already in the map, return the stored shared_ptr - if (app_it != g_apps_.end()) { - return app_it->second; - } +void *FirebaseCorePlugin::GetFirebaseApp(std::string appName) { + return App::GetInstance(appName.c_str()); +} - std::vector app_vector; - return app_vector; +void *FirebaseCorePlugin::GetFirebaseRemoteConfig(std::string appName) { + App *app = App::GetInstance(appName.c_str()); + RemoteConfig *rc = RemoteConfig::GetInstance(app); + return rc; } void FirebaseCorePlugin::InitializeApp( @@ -121,27 +118,6 @@ void FirebaseCorePlugin::InitializeApp( App::Create(PigeonFirebaseOptionsToAppOptions(initialize_app_request), app_name.c_str()); - std::cout << "[C++] FirebaseCorePlugin::InitializeApp():" << app_name - << std::endl; - - auto app_it = g_apps_.find(app_name); - - // // If the app is already in the map, return the stored shared_ptr - if (app_it == g_apps_.end()) { - std::vector app_vector; - app_vector.push_back(app_name); - app_vector.push_back(initialize_app_request.api_key()); - app_vector.push_back(initialize_app_request.app_id()); - app_vector.push_back(*initialize_app_request.database_u_r_l()); - - // app_vector.push_back(*initialize_app_request.tracking_id()); - app_vector.push_back(initialize_app_request.messaging_sender_id()); - app_vector.push_back(initialize_app_request.project_id()); - app_vector.push_back(*initialize_app_request.storage_bucket()); - - g_apps_[app_name] = app_vector; - } - // Send back the result to Flutter result(AppToPigeonInitializeResponse(*app)); } diff --git a/packages/firebase_core/firebase_core/windows/firebase_core_plugin.h b/packages/firebase_core/firebase_core/windows/firebase_core_plugin.h index 3261130f08dd..cf24b865779a 100644 --- a/packages/firebase_core/firebase_core/windows/firebase_core_plugin.h +++ b/packages/firebase_core/firebase_core/windows/firebase_core_plugin.h @@ -21,6 +21,8 @@ class FirebaseCorePlugin : public flutter::Plugin, public FirebaseAppHostApi { public: static void RegisterWithRegistrar(flutter::PluginRegistrarWindows *registrar); + static void *GetFirebaseApp(std::string appName); + static void *GetFirebaseRemoteConfig(std::string appName); FirebaseCorePlugin(); @@ -30,8 +32,6 @@ class FirebaseCorePlugin : public flutter::Plugin, FirebaseCorePlugin(const FirebaseCorePlugin &) = delete; FirebaseCorePlugin &operator=(const FirebaseCorePlugin &) = delete; - static std::vector GetFirebaseApp(std::string appName); - // FirebaseCoreHostApi virtual void InitializeApp( const std::string &app_name, diff --git a/packages/firebase_core/firebase_core/windows/firebase_core_plugin_c_api.cpp b/packages/firebase_core/firebase_core/windows/firebase_core_plugin_c_api.cpp index 96dd4d7febbe..4c52ed4e696d 100644 --- a/packages/firebase_core/firebase_core/windows/firebase_core_plugin_c_api.cpp +++ b/packages/firebase_core/firebase_core/windows/firebase_core_plugin_c_api.cpp @@ -15,7 +15,10 @@ void FirebaseCorePluginCApiRegisterWithRegistrar( ->GetRegistrar(registrar)); } -FLUTTER_PLUGIN_EXPORT std::vector GetFirebaseApp( - std::string appName) { +FLUTTER_PLUGIN_EXPORT void* GetFirebaseApp(std::string appName) { + return firebase_core_windows::FirebaseCorePlugin::GetFirebaseApp(appName); +} + +FLUTTER_PLUGIN_EXPORT void* GetFirebaseRemoteConfig(std::string appName) { return firebase_core_windows::FirebaseCorePlugin::GetFirebaseApp(appName); } diff --git a/packages/firebase_core/firebase_core/windows/include/firebase_core/firebase_core_plugin_c_api.h b/packages/firebase_core/firebase_core/windows/include/firebase_core/firebase_core_plugin_c_api.h index b1c0b75644a8..61fffe72cf22 100644 --- a/packages/firebase_core/firebase_core/windows/include/firebase_core/firebase_core_plugin_c_api.h +++ b/packages/firebase_core/firebase_core/windows/include/firebase_core/firebase_core_plugin_c_api.h @@ -22,7 +22,8 @@ FLUTTER_PLUGIN_EXPORT void FirebaseCorePluginCApiRegisterWithRegistrar( FlutterDesktopPluginRegistrarRef registrar); -FLUTTER_PLUGIN_EXPORT std::vector GetFirebaseApp( - std::string appName); +FLUTTER_PLUGIN_EXPORT void* GetFirebaseApp(std::string appName); + +FLUTTER_PLUGIN_EXPORT void* GetFirebaseRemoteConfig(std::string appName); #endif // FLUTTER_PLUGIN_FIREBASE_CORE_PLUGIN_C_API_H_ diff --git a/packages/firebase_remote_config/firebase_remote_config/windows/firebase_remote_config_plugin.cpp b/packages/firebase_remote_config/firebase_remote_config/windows/firebase_remote_config_plugin.cpp index 280ff8e2c598..ba52f61ecc3d 100644 --- a/packages/firebase_remote_config/firebase_remote_config/windows/firebase_remote_config_plugin.cpp +++ b/packages/firebase_remote_config/firebase_remote_config/windows/firebase_remote_config_plugin.cpp @@ -49,13 +49,17 @@ FirebaseRemoteConfigPlugin::FirebaseRemoteConfigPlugin() {} FirebaseRemoteConfigPlugin::~FirebaseRemoteConfigPlugin() = default; +RemoteConfig* GetRCFromPigeon(const PigeonFirebaseApp& pigeonApp) { + void* rc_ptr = GetFirebaseRemoteConfig(pigeonApp.app_name()); + RemoteConfig* rc = static_cast(rc_ptr); + + return rc; +} + void FirebaseRemoteConfigPlugin::Activate( const PigeonFirebaseApp& app, std::function reply)> result) { - std::cout << "[C++] FirebaseRemoteConfigPlugin::Activate() START" - << std::endl; - App* cpp_app = App::GetInstance(app.app_name().c_str()); - RemoteConfig* rc = RemoteConfig::GetInstance(cpp_app); + RemoteConfig* rc = GetRCFromPigeon(app); Future activated_result = rc->Activate(); activated_result.OnCompletion([result](const Future& bool_result) { @@ -66,43 +70,10 @@ void FirebaseRemoteConfigPlugin::Activate( }); } -RemoteConfig* GetRCFromPigeon(const PigeonFirebaseApp& pigeonApp) { - std::vector app_vector = GetFirebaseApp(pigeonApp.app_name()); - - // print vector lenghts - std::cout << app_vector.size() << std::endl; - - // print the vector - for (std::string n : app_vector) { - std::cout << n << std::endl; - } - - firebase::AppOptions options; - - options.set_api_key(app_vector[1].c_str()); - options.set_app_id(app_vector[2].c_str()); - options.set_database_url(app_vector[3].c_str()); - - options.set_messaging_sender_id(app_vector[4].c_str()); - - options.set_project_id(app_vector[5].c_str()); - - options.set_storage_bucket(app_vector[6].c_str()); - - App* cpp_app = App::Create(options, pigeonApp.app_name().c_str()); - - RemoteConfig* rc = RemoteConfig::GetInstance(cpp_app); - - return rc; -} - void FirebaseRemoteConfigPlugin::EnsureInitialized( const PigeonFirebaseApp& app, std::function reply)> result) { - std::cout << "[C++] FirebaseRemoteConfigPlugin::EnsureInitialized() START" - << std::endl; - App* cpp_app = App::GetInstance(app.app_name().c_str()); - RemoteConfig* rc = RemoteConfig::GetInstance(cpp_app); + RemoteConfig* rc = GetRCFromPigeon(app); Future<::firebase::remote_config::ConfigInfo> init_result = rc->EnsureInitialized(); @@ -111,9 +82,7 @@ void FirebaseRemoteConfigPlugin::EnsureInitialized( void FirebaseRemoteConfigPlugin::Fetch( const PigeonFirebaseApp& app, std::function reply)> result) { - std::cout << "[C++] FirebaseRemoteConfigPlugin::Fetch() START" << std::endl; - App* cpp_app = App::GetInstance(app.app_name().c_str()); - RemoteConfig* rc = RemoteConfig::GetInstance(cpp_app); + RemoteConfig* rc = GetRCFromPigeon(app); Future fetch_result = rc->Fetch(); fetch_result.OnCompletion([result](const Future& void_result) { @@ -127,22 +96,8 @@ void FirebaseRemoteConfigPlugin::Fetch( void FirebaseRemoteConfigPlugin::FetchAndActivate( const PigeonFirebaseApp& app, std::function reply)> result) { - std::cout << "[C++] FirebaseRemoteConfigPlugin::FetchAndActivate() START" - << std::endl; - // // App* cpp_app = App::GetInstance(app.app_name().c_str()); - // App* cpp_app = App::GetInstance(); - // // std::cout << "[C++] get cpp_app:" << app.app_name() << std::endl; - // std::vector all_apps = App::GetApps(); - // std::cout << "[C++] all apps size is: " << all_apps.size() << std::endl; - // if (cpp_app == nullptr) { - // std::cout << "[C++] cannot get FirebaseApp:" << app.app_name() << - // std::endl; result(false); return; - // } - // RemoteConfig* rc = RemoteConfig::GetInstance(cpp_app); RemoteConfig* rc = GetRCFromPigeon(app); - std::cout << "[C++] Get rc instance" << std::endl; - Future fa_result = rc->FetchAndActivate(); std::cout << "[C++] rc->FetchAndActivate()" << std::endl; fa_result.OnCompletion([result](const Future& bool_result) { @@ -160,40 +115,35 @@ ErrorOr FirebaseRemoteConfigPlugin::GetAll( ErrorOr FirebaseRemoteConfigPlugin::GetBool(const PigeonFirebaseApp& app, const std::string& key) { - App* cpp_app = App::GetInstance(app.app_name().c_str()); - RemoteConfig* rc = RemoteConfig::GetInstance(cpp_app); + RemoteConfig* rc = GetRCFromPigeon(app); return rc->GetBoolean(key.c_str()); } ErrorOr FirebaseRemoteConfigPlugin::GetInt( const PigeonFirebaseApp& app, const std::string& key) { - App* cpp_app = App::GetInstance(app.app_name().c_str()); - RemoteConfig* rc = RemoteConfig::GetInstance(cpp_app); + RemoteConfig* rc = GetRCFromPigeon(app); return rc->GetLong(key.c_str()); } ErrorOr FirebaseRemoteConfigPlugin::GetDouble( const PigeonFirebaseApp& app, const std::string& key) { - App* cpp_app = App::GetInstance(app.app_name().c_str()); - RemoteConfig* rc = RemoteConfig::GetInstance(cpp_app); + RemoteConfig* rc = GetRCFromPigeon(app); return rc->GetDouble(key.c_str()); } ErrorOr FirebaseRemoteConfigPlugin::GetString( const PigeonFirebaseApp& app, const std::string& key) { - App* cpp_app = App::GetInstance(app.app_name().c_str()); - RemoteConfig* rc = RemoteConfig::GetInstance(cpp_app); + RemoteConfig* rc = GetRCFromPigeon(app); return rc->GetString(key.c_str()); } ErrorOr FirebaseRemoteConfigPlugin::GetValue( const PigeonFirebaseApp& app, const std::string& key) { - // App* cpp_app = App::GetInstance(app.app_name().c_str()); - // RemoteConfig* rc = RemoteConfig::GetInstance(cpp_app); + // RemoteConfig* rc = GetRCFromPigeon(app); // std::vector data = rc->GetData(key.c_str());