Merge commit 'bc92ace8edef9d5ae4f9e5d6af5eccb8cfca4443' into firestore-types

# Conflicts:
#	android/src/main/java/io/invertase/firebase/firestore/FirestoreSerialize.java
This commit is contained in:
Chris Bianca 2017-10-08 19:44:39 +01:00
commit 1c81da466c
13 changed files with 354 additions and 168 deletions

View File

@ -1,22 +1,23 @@
package io.invertase.firebase;
import android.util.Log;
import android.app.Activity;
import android.content.IntentSender;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.List;
import java.util.HashMap;
import java.util.ArrayList;
// react
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.bridge.LifecycleEventListener;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
// play services
import com.google.android.gms.common.ConnectionResult;
@ -25,7 +26,7 @@ import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
@SuppressWarnings("WeakerAccess")
public class RNFirebaseModule extends ReactContextBaseJavaModule implements LifecycleEventListener {
public class RNFirebaseModule extends ReactContextBaseJavaModule {
private static final String TAG = "RNFirebase";
public RNFirebaseModule(ReactApplicationContext reactContext) {
@ -42,12 +43,12 @@ public class RNFirebaseModule extends ReactContextBaseJavaModule implements Life
public void initializeApp(String appName, ReadableMap options, Callback callback) {
FirebaseOptions.Builder builder = new FirebaseOptions.Builder();
builder.setApplicationId(options.getString("appId"));
builder.setGcmSenderId(options.getString("messagingSenderId"));
builder.setApiKey(options.getString("apiKey"));
builder.setApplicationId(options.getString("appId"));
builder.setProjectId(options.getString("projectId"));
builder.setDatabaseUrl(options.getString("databaseURL"));
builder.setStorageBucket(options.getString("storageBucket"));
builder.setGcmSenderId(options.getString("messagingSenderId"));
// todo firebase sdk has no client id setter
FirebaseApp.initializeApp(getReactApplicationContext(), builder.build(), appName);
@ -84,8 +85,9 @@ public class RNFirebaseModule extends ReactContextBaseJavaModule implements Life
result.putBoolean("isAvailable", true);
} else {
result.putBoolean("isAvailable", false);
result.putBoolean("isUserResolvableError", gapi.isUserResolvableError(status));
result.putString("error", gapi.getErrorString(status));
result.putBoolean("isUserResolvableError", gapi.isUserResolvableError(status));
result.putBoolean("hasResolution", new ConnectionResult(status).hasResolution());
}
return result;
}
@ -94,7 +96,7 @@ public class RNFirebaseModule extends ReactContextBaseJavaModule implements Life
* Prompt the device user to update play services
*/
@ReactMethod
public void promptPlayServices() {
public void promptForPlayServices() {
GoogleApiAvailability gapi = GoogleApiAvailability.getInstance();
int status = gapi.isGooglePlayServicesAvailable(getReactApplicationContext());
@ -106,6 +108,27 @@ public class RNFirebaseModule extends ReactContextBaseJavaModule implements Life
}
}
/**
* Prompt the device user to update play services
*/
@ReactMethod
public void resolutionForPlayServices() {
int status = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(getReactApplicationContext());
ConnectionResult connectionResult = new ConnectionResult(status);
if (!connectionResult.isSuccess() && connectionResult.hasResolution()) {
Activity activity = getCurrentActivity();
if (activity != null) {
try {
connectionResult.startResolutionForResult(activity, status);
} catch (IntentSender.SendIntentException error) {
Log.d(TAG, "resolutionForPlayServices", error);
}
}
}
}
/**
* Prompt the device user to update play services
*/
@ -122,32 +145,16 @@ public class RNFirebaseModule extends ReactContextBaseJavaModule implements Life
}
}
@Override
public void onHostResume() {
// WritableMap params = Arguments.createMap();
// params.putBoolean("isForeground", true);
// Utils.sendEvent(getReactApplicationContext(), "RNFirebaseAppState", params);
}
@Override
public void onHostPause() {
// WritableMap params = Arguments.createMap();
// params.putBoolean("isForeground", false);
// Utils.sendEvent(getReactApplicationContext(), "RNFirebaseAppState", params);
}
@Override
public void onHostDestroy() {
}
@Override
public Map<String, Object> getConstants() {
FirebaseApp firebaseApp;
Map<String, Object> constants = new HashMap<>();
List<FirebaseApp> firebaseAppList = FirebaseApp.getApps(getReactApplicationContext());
List<Map<String, Object>> appMapsList = new ArrayList<Map<String, Object>>();
Map<String, Object> constants = new HashMap<>();
List<Map<String, Object>> appMapsList = new ArrayList<>();
List<FirebaseApp> firebaseAppList = FirebaseApp.getApps(getReactApplicationContext());
// TODO no way to get client id currently from app options - firebase sdk issue
for (FirebaseApp app : firebaseAppList) {
String appName = app.getName();
FirebaseOptions appOptions = app.getOptions();
@ -156,16 +163,16 @@ public class RNFirebaseModule extends ReactContextBaseJavaModule implements Life
appProps.put("name", appName);
appProps.put("apiKey", appOptions.getApiKey());
appProps.put("appId", appOptions.getApplicationId());
appProps.put("projectId", appOptions.getProjectId());
appProps.put("databaseURL", appOptions.getDatabaseUrl());
appProps.put("messagingSenderId", appOptions.getGcmSenderId());
appProps.put("projectId", appOptions.getProjectId());
appProps.put("storageBucket", appOptions.getStorageBucket());
// TODO no way to get client id currently from app options - firebase sdk issue
appMapsList.add(appProps);
}
constants.put("apps", appMapsList);
constants.put("googleApiAvailability", getPlayServicesStatus());
constants.put("playServicesAvailability", getPlayServicesStatus());
return constants;
}
}

View File

@ -15,13 +15,6 @@ import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.GeoPoint;
import com.google.firebase.firestore.QuerySnapshot;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@ -154,8 +147,34 @@ public class FirestoreSerialize {
WritableArray writableArray = Arguments.createArray();
for (Object item : array) {
WritableMap typeMap = buildTypeMap(item);
writableArray.pushMap(typeMap);
if (item == null) {
writableArray.pushNull();
continue;
}
Class itemClass = item.getClass();
if (itemClass == Boolean.class) {
writableArray.pushBoolean((Boolean) item);
} else if (itemClass == Integer.class) {
writableArray.pushDouble(((Integer) item).doubleValue());
} else if (itemClass == Long.class) {
writableArray.pushDouble(((Long) item).doubleValue());
} else if (itemClass == Double.class) {
writableArray.pushDouble((Double) item);
} else if (itemClass == Float.class) {
writableArray.pushDouble(((Float) item).doubleValue());
} else if (itemClass == String.class) {
writableArray.pushString(item.toString());
} else if (Map.class.isAssignableFrom(itemClass)) {
writableArray.pushMap((objectMapToWritable((Map<String, Object>) item)));
} else if (List.class.isAssignableFrom(itemClass)) {
List<Object> list = (List<Object>) item;
Object[] listAsArray = list.toArray(new Object[list.size()]);
writableArray.pushArray(objectArrayToWritable(listAsArray));
} else {
throw new RuntimeException("Cannot convert object of type " + itemClass);
}
}
return writableArray;
@ -178,8 +197,9 @@ public class FirestoreSerialize {
typeMap.putString("type", "boolean");
typeMap.putBoolean("value", (Boolean) value);
} else if (valueClass == Integer.class) {
typeMap.putString("type", "number");
typeMap.putDouble("value", ((Integer) value).doubleValue());
map.putDouble(key, ((Integer) value).doubleValue());
} else if (valueClass == Long.class) {
map.putDouble(key, ((Long) value).doubleValue());
} else if (valueClass == Double.class) {
typeMap.putString("type", "number");
typeMap.putDouble("value", (Double) value);
@ -187,16 +207,10 @@ public class FirestoreSerialize {
typeMap.putString("type", "number");
typeMap.putDouble("value", ((Float) value).doubleValue());
} else if (valueClass == String.class) {
typeMap.putString("type", "string");
typeMap.putString("value", value.toString());
} else if (valueClass == Map.class || valueClass == HashMap.class) {
typeMap.putString("type", "object");
typeMap.putMap("value", (objectMapToWritable((Map<String, Object>) value)));
} else if (valueClass == Arrays.class) {
typeMap.putString("type", "array");
typeMap.putArray("value", objectArrayToWritable((Object[]) value));
} else if (valueClass == List.class || valueClass == ArrayList.class) {
typeMap.putString("type", "array");
map.putString(key, value.toString());
} else if (Map.class.isAssignableFrom(valueClass)) {
map.putMap(key, (objectMapToWritable((Map<String, Object>) value)));
} else if (List.class.isAssignableFrom(valueClass)) {
List<Object> list = (List<Object>) value;
Object[] array = list.toArray(new Object[list.size()]);
typeMap.putArray("value", objectArrayToWritable(array));
@ -213,6 +227,7 @@ public class FirestoreSerialize {
typeMap.putString("type", "date");
typeMap.putString("value", DATE_FORMAT.format((Date) value));
} else {
// TODO: Changed to log an error rather than crash - is this correct?
Log.e(TAG, "buildTypeMap", new RuntimeException("Cannot convert object of type " + valueClass));
typeMap.putString("type", "null");
typeMap.putNull("value");

View File

@ -1,6 +1,10 @@
# Android Installation
## 1) Setup google-services.json
## 1) Link RNFirebase
Run `react-native link react-native-firebase`
## 2) Setup google-services.json
Download the `google-services.json` file provided by Firebase in the _Add Firebase to Android_ platform menu in your Firebase configuration console. This file should be downloaded to `YOUR_PROJECT/android/app/google-services.json`.
Next you'll have to add the google-services gradle plugin in order to parse it.
@ -23,28 +27,19 @@ In your app build.gradle file, add the gradle plugin at the VERY BOTTOM of the f
apply plugin: 'com.google.gms.google-services'
```
## 2) Link RNFirebase
## 3) Setup Firebase
RNFirebase is split into separate modules to allow you to only include the Firebase functionality that you need in your application.
First add the project path to `android/settings.gradle`:
```groovy
include ':react-native-firebase'
project(':react-native-firebase').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-firebase/android')
```
Now you need to include RNFirebase and the required Firebase dependencies in our `android/app/build.gradle` so that they are compiled as part of React Native. In the `dependencies` listing, add the appropriate `compile` lines:
Now you need to the required Firebase dependencies in our `android/app/build.gradle` so that they are compiled as part of React Native. In the `dependencies` listing, add the appropriate `compile` lines:
```groovy
dependencies {
// RNFirebase required dependencies
// This should be added already
compile(project(':react-native-firebase')) {
transitive = false
}
compile "com.google.firebase:firebase-core:11.4.2"
// If you are receiving Google Play API availability issues, add the following dependency
// RNFirebase required dependencies
compile "com.google.firebase:firebase-core:11.4.2"
compile "com.google.android.gms:play-services-base:11.4.2"
// RNFirebase optional dependencies
@ -60,7 +55,7 @@ dependencies {
}
```
Google Play services from 11.4.2 onwards require their dependencies to be downloaded from Google's Maven respository so add the
Google Play services from 11.2.0 onwards require their dependencies to be downloaded from Google's Maven respository so add the
required reference to the repositories section of the *project* level build.gradle
`android/build.gradle`
@ -83,13 +78,17 @@ allprojects {
}
```
## 4) Install RNFirebase modules
RNFirebase is split into separate modules to allow you to only include the Firebase functionality that you need in your application.
To install `react-native-firebase` in your project, you'll need to import the packages you need from `io.invertase.firebase` in your project's `android/app/src/main/java/com/[app name]/MainApplication.java` and list them as packages for ReactNative in the `getPackages()` function:
```java
package com.youcompany.application;
// ...
// Required package
import io.invertase.firebase.RNFirebasePackage; // <-- Add this line
import io.invertase.firebase.RNFirebasePackage; // <-- This should be added already
// Optional packages - add as appropriate
import io.invertase.firebase.admob.RNFirebaseAdMobPackage; //Firebase AdMob
import io.invertase.firebase.analytics.RNFirebaseAnalyticsPackage; // Firebase Analytics
@ -109,7 +108,7 @@ public class MainApplication extends Application implements ReactApplication {
protected List<ReactPackage> getPackages() {
return Arrays.<ReactPackage>asList(
new MainReactPackage(),
new RNFirebasePackage(), // <-- Add this line
new RNFirebasePackage(), // <-- This should be added already
// Add these packages as appropriate
new RNFirebaseAdMobPackage(),
new RNFirebaseAnalyticsPackage(),
@ -128,7 +127,7 @@ public class MainApplication extends Application implements ReactApplication {
}
```
## 3) Cloud Messaging (optional)
## 5) Cloud Messaging (optional)
If you plan on using [Firebase Cloud Messaging](https://firebase.google.com/docs/cloud-messaging/), add the following to `android/app/src/main/AndroidManifest.xml`.
@ -179,7 +178,7 @@ If you would like to schedule local notifications then you also need to add the
</receiver>
```
## 4) Performance Monitoring (optional)
## 6) Performance Monitoring (optional)
If you'd like to take advantage of Firebase's [Performance Monitoring](https://firebase.google.com/docs/perf-mon/), the following additions
to your project setup are required:

View File

@ -2,10 +2,23 @@
Please note that there is a known issue when using Cocoapods with the `use_frameworks!` enabled. This is explained [here](https://github.com/invertase/react-native-firebase/issues/252#issuecomment-316340974). Unfortunately we don't currently have a workaround, but are engaging with Firebase directly to try and resolve the problem.
## 1) Setup GoogleService-Info.plist
## 1) Link RNFirebase
Run `react-native link react-native-firebase`
## 2) Setup GoogleService-Info.plist
Setup the `GoogleService-Info.plist` file by following the instructions and adding it to the root of your project at `ios/[YOUR APP NAME]/GoogleService-Info.plist` [here](https://firebase.google.com/docs/ios/setup#add_firebase_to_your_app).
### 1.1) Initialisation
Adding the file into the directory doesn't automatically add the file to the iOS project. You need to then manually add it by doing the following:
- 2.1. Open `<project root>/ios/'project name'.xcworkspace` file via XCode
- 2.1.1. If you've not got a `.xcworkspace` file yet then you'll need to come back to these steps after setting up your pods + pod install (step 3 on this page)
- 2.2. Right click on your project
- 2.3. Click "Add files to 'project name'"
- 2.4. Select the .plist file you copied into your project
- 2.5. Click OK
### 2.1) Initialisation
Make sure you've added the following to the top of your `ios/[YOUR APP NAME]]/AppDelegate.m` file:
`#import <Firebase.h>`
@ -14,11 +27,11 @@ and this to the `didFinishLaunchingWithOptions:(NSDictionary *)launchOptions` me
`[FIRApp configure];`
## 2) Setup RNFirebase
## 3) Setup Firebase Pods
Unfortunately, due to the fact that Firebase is much easier to setup using Cocoapods, *we do not recommend* `react-native link` as it is not customisable enough for our needs and we have had numerous problems reported.
Firebase recommends using Cocoapods to install the Firebase SDK.
### 2.0) If you don't already have Cocoapods set up
### 3.0) If you don't already have Cocoapods set up
Follow the instructions to install Cocoapods and create your Podfile [here](https://firebase.google.com/docs/ios/setup#add_the_sdk).
**NOTE: The Podfile needs to be initialised in the `ios` directory of your project. Make sure to update cocoapods libs first by running `pod update`**
@ -50,18 +63,17 @@ Follow the instructions to install Cocoapods and create your Podfile [here](http
- Uncomment the `# platform :ios, '9.0'` line by removing the `#` character
- Change the version as required
### 2.1) Check the Podfile platform version
### 3.1) Check the Podfile platform version
We recommend using a minimum platform version of at least 9.0 for your application to ensure that the correct version of the Firebase libraries are used. To do this, you need to uncomment or make sure the following line is present at the top of your `Podfile`:
`platform :ios, '9.0'`
### 2.2) Add the required pods
### 3.2) Add the required pods
Simply add the following to your `Podfile` either at the top level, or within the main project target:
```ruby
# Required by RNFirebase
pod 'Firebase/Core'
pod 'RNFirebase', :path => '../node_modules/react-native-firebase'
# [OPTIONAL PODS] - comment out pods for firebase products you won't be using.
pod 'Firebase/AdMob'
@ -75,27 +87,6 @@ pod 'Firebase/RemoteConfig'
pod 'Firebase/Storage'
```
If you do not already have React and Yoga installed as pods, then add Yoga and React to your `Podfile` as follows:
```ruby
pod "Yoga", :path => "../node_modules/react-native/ReactCommon/yoga"
pod 'React', :path => '../node_modules/react-native', :subspecs => [
'BatchedBridge', # Required For React Native 0.45.0+
'Core',
# Add any other subspecs you want to use in your project
]
#Also add this at the very bottom of your Podfile
post_install do |installer|
installer.pods_project.targets.each do |target|
if target.name == "React"
target.remove_from_project
end
end
end
```
Run `pod install`.
**NOTE: You need to use the `ios/[YOUR APP NAME].xcworkspace` instead of the `ios/[YOUR APP NAME].xcproj` file from now on.**
@ -106,24 +97,24 @@ Run `pod install`.
**Resolution**
- Run `npm install --save react-native-firebase` from the root of your project
## 3) Cloud Messaging (optional)
## 4) Cloud Messaging (optional)
If you plan on using [Firebase Cloud Messaging](https://firebase.google.com/docs/cloud-messaging/) then, you need to:
**NOTE: FCM does not work on the iOS simulator, you must test is using a real device. This is a restriction enforced by Apple for some unknown reason.**
### 3.1) Set up certificates
### 4.1) Set up certificates
Follow the instructions at https://firebase.google.com/docs/cloud-messaging/ios/certs
### 3.2) Enable capabilities
### 4.2) Enable capabilities
In Xcode, enable the following capabilities:
1) Push Notifications
2) Background modes > Remote notifications
### 3.3) Update `AppDelegate.h`
### 4.3) Update `AppDelegate.h`
Add the following import:
@ -133,7 +124,7 @@ Change the interface descriptor to:
`@interface AppDelegate : UIResponder <UIApplicationDelegate,UNUserNotificationCenterDelegate>`
### 3.4) Update `AppDelegate.m`
### 4.4) Update `AppDelegate.m`
Add the following import:
@ -172,7 +163,7 @@ didReceiveNotificationResponse:(UNNotificationResponse *)response
}
```
### 3.5) Debugging
### 4.5) Debugging
If you're having problems with messages not being received, check out the following blog post for help:

View File

@ -1,7 +1,7 @@
import { NativeModules } from 'react-native';
import INTERNALS from './internals';
import { isObject } from './utils';
import { isObject, isAndroid } from './utils';
import AdMob, { statics as AdMobStatics } from './modules/admob';
import Auth, { statics as AuthStatics } from './modules/auth';
@ -13,6 +13,7 @@ import Storage, { statics as StorageStatics } from './modules/storage';
import Database, { statics as DatabaseStatics } from './modules/database';
import Messaging, { statics as MessagingStatics } from './modules/messaging';
import Firestore, { statics as FirestoreStatics } from './modules/firestore';
import Utils, { statics as UtilsStatics } from './modules/utils';
const FirebaseCoreModule = NativeModules.RNFirebase;
@ -37,6 +38,7 @@ export default class FirebaseApp {
this.messaging = this._staticsOrModuleInstance(MessagingStatics, Messaging);
this.perf = this._staticsOrModuleInstance({}, Performance);
this.storage = this._staticsOrModuleInstance(StorageStatics, Storage);
this.utils = this._staticsOrModuleInstance(UtilsStatics, Utils);
this._extendedProps = {};
}
@ -150,6 +152,11 @@ export default class FirebaseApp {
const getInstance = () => {
const _name = `_${InstanceClass._NAMESPACE}`;
if (isAndroid && InstanceClass._NAMESPACE !== Utils._NAMESPACE && !INTERNALS.FLAGS.checkedPlayServices) {
INTERNALS.FLAGS.checkedPlayServices = true;
this.utils().checkPlayServicesAvailability();
}
if (!this._namespaces[_name]) {
this._namespaces[_name] = new InstanceClass(this);
}

View File

@ -4,11 +4,9 @@
*/
import { NativeModules, NativeEventEmitter } from 'react-native';
import { isObject, isString } from './utils';
import INTERNALS from './internals';
import PACKAGE from './../package.json';
import FirebaseApp from './firebase-app';
import { isObject, isString, isAndroid } from './utils';
// module imports
import AdMob, { statics as AdMobStatics } from './modules/admob';
@ -21,6 +19,7 @@ import Storage, { statics as StorageStatics } from './modules/storage';
import Database, { statics as DatabaseStatics } from './modules/database';
import Messaging, { statics as MessagingStatics } from './modules/messaging';
import Firestore, { statics as FirestoreStatics } from './modules/firestore';
import Utils, { statics as UtilsStatics } from './modules/utils';
const FirebaseCoreModule = NativeModules.RNFirebase;
@ -33,13 +32,7 @@ class FirebaseCore {
throw (new Error(INTERNALS.STRINGS.ERROR_MISSING_CORE));
}
for (let i = 0, len = FirebaseCoreModule.apps.length; i < len; i++) {
const app = FirebaseCoreModule.apps[i];
const options = Object.assign({}, app);
delete options.name;
INTERNALS.APPS[app.name] = new FirebaseApp(app.name, options);
INTERNALS.APPS[app.name]._initializeApp(true);
}
this._initializeNativeApps();
// modules
this.admob = this._appNamespaceOrStatics(AdMobStatics, AdMob);
@ -52,6 +45,21 @@ class FirebaseCore {
this.messaging = this._appNamespaceOrStatics(MessagingStatics, Messaging);
this.perf = this._appNamespaceOrStatics(DatabaseStatics, Performance);
this.storage = this._appNamespaceOrStatics(StorageStatics, Storage);
this.utils = this._appNamespaceOrStatics(UtilsStatics, Utils);
}
/**
* Bootstraps all native app instances that were discovered on boot
* @private
*/
_initializeNativeApps() {
for (let i = 0, len = FirebaseCoreModule.apps.length; i < len; i++) {
const app = FirebaseCoreModule.apps[i];
const options = Object.assign({}, app);
delete options.name;
INTERNALS.APPS[app.name] = new FirebaseApp(app.name, options);
INTERNALS.APPS[app.name]._initializeApp(true);
}
}
/**
@ -139,42 +147,6 @@ class FirebaseCore {
return Object.values(INTERNALS.APPS);
}
/**
* The current RNFirebase SDK version.
*/
get SDK_VERSION() {
return PACKAGE.version;
}
/**
* The platform specific default app name
*/
get DEFAULT_APP_NAME() {
return INTERNALS.STRINGS.DEFAULT_APP_NAME;
}
/**
* Returns props from the android GoogleApiAvailability sdk
* @android
* @return {RNFirebase.GoogleApiAvailabilityType|{isAvailable: boolean, status: number}}
*/
get googleApiAvailability(): GoogleApiAvailabilityType {
return FirebaseCoreModule.googleApiAvailability || { isAvailable: true, status: 0 };
}
/*
* CONFIG METHODS
*/
/**
* Set the global logging level for all logs.
*
* @param booleanOrDebugString
*/
setLogLevel(booleanOrDebugString) {
INTERNALS.OPTIONS.logLevel = booleanOrDebugString;
Log.setLevel(booleanOrDebugString);
}
/*
* INTERNALS
*/
@ -207,7 +179,6 @@ class FirebaseCore {
/**
*
* @param namespace
* @param statics
* @param InstanceClass
* @return {function(FirebaseApp=)}
@ -215,8 +186,10 @@ class FirebaseCore {
*/
_appNamespaceOrStatics(statics = {}, InstanceClass): Function {
const namespace = InstanceClass._NAMESPACE;
const getNamespace = (app?: FirebaseApp) => {
let _app = app;
// throw an error if it's not a valid app instance
if (_app && !(_app instanceof FirebaseApp)) throw new Error(INTERNALS.STRINGS.ERROR_NOT_APP(namespace));
@ -229,6 +202,7 @@ class FirebaseCore {
Object.assign(getNamespace, statics, {
nativeModuleExists: !!NativeModules[InstanceClass._NATIVE_MODULE],
});
return getNamespace;
}

View File

@ -35,6 +35,7 @@ declare type GoogleApiAvailabilityType = {
status: number,
isAvailable: boolean,
isUserResolvableError?: boolean,
hasResolution?: boolean,
error?: string
};

View File

@ -22,10 +22,43 @@ const GRADLE_DEPS = {
admob: 'ads',
};
const PLAY_SERVICES_CODES = {
1: {
code: 'SERVICE_MISSING',
message: 'Google Play services is missing on this device.',
},
2: {
code: 'SERVICE_VERSION_UPDATE_REQUIRED',
message: 'The installed version of Google Play services on this device is out of date.',
},
3: {
code: 'SERVICE_DISABLED',
message: 'The installed version of Google Play services has been disabled on this device.',
},
9: {
code: 'SERVICE_INVALID',
message: 'The version of the Google Play services installed on this device is not authentic.',
},
18: {
code: 'SERVICE_UPDATING',
message: 'Google Play services is currently being updated on this device.',
},
19: {
code: 'SERVICE_MISSING_PERMISSION',
message: 'Google Play service doesn\'t have one or more required permissions.',
},
};
export default {
// default options
OPTIONS: {
logLevel: 'warn',
errorOnMissingPlayServices: true,
promptOnMissingPlayServices: true,
},
FLAGS: {
checkedPlayServices: false,
},
// track all initialized firebase apps
@ -141,15 +174,15 @@ export default {
/**
* @return {string}
*/
ERROR_UNSUPPORTED_CLASS_METHOD(classname, method) {
return `${classname}.${method}() is unsupported by the native Firebase SDKs.`;
ERROR_UNSUPPORTED_CLASS_METHOD(className, method) {
return `${className}.${method}() is unsupported by the native Firebase SDKs.`;
},
/**
* @return {string}
*/
ERROR_UNSUPPORTED_CLASS_PROPERTY(classname, property) {
return `${classname}.${property} is unsupported by the native Firebase SDKs.`;
ERROR_UNSUPPORTED_CLASS_PROPERTY(className, property) {
return `${className}.${property} is unsupported by the native Firebase SDKs.`;
},
/**
@ -159,6 +192,32 @@ export default {
return `firebase.${module._NAMESPACE}().${method}() is unsupported by the native Firebase SDKs.`;
},
/**
* @return {string}
*/
ERROR_PLAY_SERVICES(statusCode) {
const knownError = PLAY_SERVICES_CODES[statusCode];
let start = 'Google Play Services is required to run firebase services on android but a valid installation was not found on this device.';
if (statusCode === 2) {
start = 'Google Play Services is out of date and may cause some firebase services like authentication to hang when used. It is recommended that you update it.';
}
// eslint-disable-next-line prefer-template
return `${start}\r\n\r\n` +
'-------------------------\r\n' +
(knownError ?
`${knownError.code}: ${knownError.message} (code ${statusCode})` :
`A specific play store availability reason reason was not available (unknown code: ${statusCode || null})`
) +
'\r\n-------------------------' +
'\r\n\r\n' +
'For more information on how to resolve this issue, configure Play Services checks or for guides on how to validate Play Services on your users devices see the link below:' +
'\r\n\r\nhttp://invertase.link/play-services';
},
DEFAULT_APP_NAME,
},

131
lib/modules/utils/index.js Normal file
View File

@ -0,0 +1,131 @@
// @flow
import { NativeModules } from 'react-native';
// import { version as ReactVersion } from 'react';
// import ReactNativeVersion from 'react-native/Libraries/Core/ReactNativeVersion';
import INTERNALS from './../../internals';
import { isIOS } from './../../utils';
import PACKAGE from './../../../package.json';
const FirebaseCoreModule = NativeModules.RNFirebase;
export default class RNFirebaseUtils {
static _NAMESPACE = 'utils';
static _NATIVE_DISABLED = true;
static _NATIVE_MODULE = 'RNFirebaseUtils';
/**
*
*/
checkPlayServicesAvailability() {
if (isIOS) return null;
const code = this.playServicesAvailability.code;
if (!this.playServicesAvailability.isAvailable) {
if (INTERNALS.OPTIONS.promptOnMissingPlayServices && this.playServicesAvailability.isUserResolvableError) {
this.promptForPlayServices();
} else {
const error = INTERNALS.STRINGS.ERROR_PLAY_SERVICES(code);
if (INTERNALS.OPTIONS.errorOnMissingPlayServices) {
if (code === 2) console.warn(error); // only warn if it exists but may need an update
else throw new Error(error);
} else {
console.warn(error);
}
}
}
return null;
}
promptForPlayServices() {
if (isIOS) return null;
return FirebaseCoreModule.promptForPlayServices();
}
resolutionForPlayServices() {
if (isIOS) return null;
return FirebaseCoreModule.resolutionForPlayServices();
}
makePlayServicesAvailable() {
if (isIOS) return null;
return FirebaseCoreModule.makePlayServicesAvailable();
}
get sharedEventEmitter(): Object {
return INTERNALS.SharedEventEmitter;
}
/**
* Set the global logging level for all logs.
*
* @param booleanOrDebugString
*/
set logLevel(booleanOrDebugString) {
INTERNALS.OPTIONS.logLevel = booleanOrDebugString;
}
/**
* Returns an array of all current database registrations id strings
*/
get databaseRegistrations(): Array<string> {
return Object.keys(INTERNALS.SyncTree._reverseLookup);
}
/**
* Call with a registration id string to get the details off this reg
*/
get getDatabaseRegistrationDetails(): Function {
return INTERNALS.SyncTree.getRegistration.bind(INTERNALS.SyncTree);
}
/**
* Accepts an array or a single string of registration ids.
* This will remove the refs on both the js and native sides and their listeners.
* @return {function(this:T)}
*/
get removeDatabaseRegistration(): Function {
return INTERNALS.SyncTree.removeListenersForRegistrations.bind(INTERNALS.SyncTree);
}
/**
* Returns props from the android GoogleApiAvailability sdk
* @android
* @return {RNFirebase.GoogleApiAvailabilityType|{isAvailable: boolean, status: number}}
*/
get playServicesAvailability(): GoogleApiAvailabilityType {
return FirebaseCoreModule.playServicesAvailability || { isAvailable: true, status: 0 };
}
/**
* Enable/Disable throwing an error or warning on detecting a play services problem
* @android
* @param bool
*/
set errorOnMissingPlayServices(bool: Boolean) {
INTERNALS.OPTIONS.errorOnMissingPlayServices = bool;
}
/**
* Enable/Disable automatic prompting of the play services update dialog
* @android
* @param bool
*/
set promptOnMissingPlayServices(bool: Boolean) {
INTERNALS.OPTIONS.promptOnMissingPlayServices = bool;
}
}
export const statics = {
DEFAULT_APP_NAME: INTERNALS.STRINGS.DEFAULT_APP_NAME,
// VERSIONS: {
// react: ReactVersion,
// 'react-native': Object.values(ReactNativeVersion.version).slice(0, 3).join('.'),
// 'react-native-firebase': PACKAGE.version,
// },
};

2
package-lock.json generated
View File

@ -1,6 +1,6 @@
{
"name": "react-native-firebase",
"version": "3.0.0-alpha.5",
"version": "3.0.2",
"lockfileVersion": 1,
"requires": true,
"dependencies": {

View File

@ -1,6 +1,6 @@
{
"name": "react-native-firebase",
"version": "3.0.0",
"version": "3.0.2",
"author": "Invertase <contact@invertase.io> (http://invertase.io)",
"description": "A well tested, feature rich Firebase implementation for React Native, supporting iOS & Android. Individual module support for Admob, Analytics, Auth, Crash Reporting, Cloud Firestore, Database, Messaging (FCM), Remote Config, Storage and Performance.",
"main": "index",

View File

@ -12,6 +12,7 @@ import io.invertase.firebase.crash.RNFirebaseCrashPackage;
import io.invertase.firebase.database.RNFirebaseDatabasePackage;
import io.invertase.firebase.firestore.RNFirebaseFirestorePackage;
import io.invertase.firebase.messaging.RNFirebaseMessagingPackage;
import io.invertase.firebase.perf.RNFirebasePerformancePackage;
import io.invertase.firebase.storage.RNFirebaseStoragePackage;
import com.oblador.vectoricons.VectorIconsPackage;
import com.facebook.react.ReactNativeHost;
@ -44,7 +45,7 @@ public class MainApplication extends Application implements ReactApplication {
new RNFirebaseDatabasePackage(),
new RNFirebaseFirestorePackage(),
new RNFirebaseMessagingPackage(),
// new RNFirebasePerformancePackage(),
new RNFirebasePerformancePackage(),
new RNFirebaseStoragePackage()
);
}

View File

@ -48,13 +48,14 @@ function coreTests({ describe, it }) {
it('it should provide an array of apps', () => {
should.equal(!!RNFirebase.apps.length, true);
should.equal(RNFirebase.apps[0]._name, RNFirebase.DEFAULT_APP_NAME);
should.equal(RNFirebase.apps[0]._name, RNFirebase.utils.DEFAULT_APP_NAME);
should.equal(RNFirebase.apps[0].name, '[DEFAULT]');
return Promise.resolve();
});
// todo move to UTILS module tests
it('it should provide the sdk version', () => {
should.equal(!!RNFirebase.SDK_VERSION.length, true);
should.equal(!!RNFirebase.utils.VERSIONS['react-native-firebase'].length, true);
return Promise.resolve();
});