From 5728fa76bcc5fff9a5da6814f3ca43f60ecc42bc Mon Sep 17 00:00:00 2001 From: Omer Levy Date: Mon, 4 Sep 2017 18:35:21 +0300 Subject: [PATCH 1/3] [android] add short link suffix support --- .../firebase/links/RNFirebaseLinks.java | 101 ++++++++++-------- 1 file changed, 56 insertions(+), 45 deletions(-) diff --git a/android/src/main/java/io/invertase/firebase/links/RNFirebaseLinks.java b/android/src/main/java/io/invertase/firebase/links/RNFirebaseLinks.java index 3cdef8f2..ab00df36 100644 --- a/android/src/main/java/io/invertase/firebase/links/RNFirebaseLinks.java +++ b/android/src/main/java/io/invertase/firebase/links/RNFirebaseLinks.java @@ -51,47 +51,49 @@ public class RNFirebaseLinks extends ReactContextBaseJavaModule implements Activ Activity activity = getCurrentActivity(); if (activity == null) { return; + } + + FirebaseDynamicLinks.getInstance() + .getDynamicLink(activity.getIntent()) + .addOnSuccessListener(activity, new OnSuccessListener() { + @Override + public void onSuccess(PendingDynamicLinkData pendingDynamicLinkData) { + // Get deep link from result (may be null if no link is found) + if (pendingDynamicLinkData != null) { + Uri deepLinkUri = pendingDynamicLinkData.getLink(); + String deepLink = deepLinkUri.toString(); + // TODO: Validate that this is called when opening from a deep link + if (initialLink == null) { + initialLink = deepLink; + } + Utils.sendEvent(getReactApplicationContext(), "dynamic_link_received", deepLink); + } + } + }) + .addOnFailureListener(activity, new OnFailureListener() { + @Override + public void onFailure(@NonNull Exception e) { + Log.w(TAG, "getDynamicLink:onFailure", e); + } + }); } - FirebaseDynamicLinks.getInstance() - .getDynamicLink(activity.getIntent()) - .addOnSuccessListener(activity, new OnSuccessListener() { - @Override - public void onSuccess(PendingDynamicLinkData pendingDynamicLinkData) { - // Get deep link from result (may be null if no link is found) - if (pendingDynamicLinkData != null) { - Uri deepLinkUri = pendingDynamicLinkData.getLink(); - String deepLink = deepLinkUri.toString(); - // TODO: Validate that this is called when opening from a deep link - if (initialLink == null) { - initialLink = deepLink; - } - Utils.sendEvent(getReactApplicationContext(), "dynamic_link_received", deepLink); - } - } - }) - .addOnFailureListener(activity, new OnFailureListener() { - @Override - public void onFailure(@NonNull Exception e) { - Log.w(TAG, "getDynamicLink:onFailure", e); - } - }); - } + @Override + public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent data) { + // Not required for this module + } - @Override - public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent data) { - // Not required for this module - } - - @Override - public void onNewIntent(Intent intent) { - // TODO: Do I need to re-register the links handler for each new intent? - } + @Override + public void onNewIntent(Intent intent) { + // TODO: Do I need to re-register the links handler for each new intent? + } @ReactMethod public void createDynamicLink(final ReadableMap parameters, final Promise promise) { try { - DynamicLink.Builder builder = setDynamicLinkBuilderFromMap(parameters); + Map m = Utils.recursivelyDeconstructReadableMap(parameters); + + DynamicLink.Builder builder = setDynamicLinkBuilderFromMap(m); Uri link = builder.buildDynamicLink().getUri(); Log.d(TAG, "created dynamic link: " + link.toString()); @@ -106,8 +108,11 @@ public class RNFirebaseLinks extends ReactContextBaseJavaModule implements Activ @ReactMethod public void createShortDynamicLink(final ReadableMap parameters, final Promise promise) { try { - DynamicLink.Builder builder = setDynamicLinkBuilderFromMap(parameters); - Task shortLinkTask = builder.buildShortDynamicLink() + Map m = Utils.recursivelyDeconstructReadableMap(parameters); + + DynamicLink.Builder builder = setDynamicLinkBuilderFromMap(m); + + Task shortLinkTask = getShortDynamicLinkTask(builder, m) .addOnCompleteListener(new OnCompleteListener() { @Override public void onComplete(@NonNull Task task) { @@ -128,18 +133,24 @@ public class RNFirebaseLinks extends ReactContextBaseJavaModule implements Activ } } - /** - * Converts a RN ReadableMap into a set DynamicLink.Builder instance - * - * @param parameters - * @return - */ - private DynamicLink.Builder setDynamicLinkBuilderFromMap(ReadableMap parameters) { + private Task getShortDynamicLinkTask(final DynamicLink.Builder builder ,final Map m) { + Map suffixParameters = (Map) m.get("suffix"); + if (suffixParameters != null) { + String option = (String) suffixParameters.get("option"); + if (option.equals("SHORT")) { + return builder.buildShortDynamicLink(ShortDynamicLink.Suffix.SHORT); + } + else if (option.equals("UNGUESSABLE")) { + return builder.buildShortDynamicLink(ShortDynamicLink.Suffix.UNGUESSABLE); + } + } + return builder.buildShortDynamicLink(); + } + + private DynamicLink.Builder setDynamicLinkBuilderFromMap(final Map m) { DynamicLink.Builder parametersBuilder = FirebaseDynamicLinks.getInstance().createDynamicLink(); try { - Map m = Utils.recursivelyDeconstructReadableMap(parameters); - parametersBuilder.setLink(Uri.parse((String)m.get("link"))); parametersBuilder.setDynamicLinkDomain((String)m.get("dynamicLinkDomain")); From d4a1304beae9644590a9978a086fb3ca8ce4b48d Mon Sep 17 00:00:00 2001 From: Omer Levy Date: Sat, 9 Sep 2017 21:49:45 +0300 Subject: [PATCH 2/3] temporary disable link registration, methods rename, undo prettify in lib/firebase.js --- .../firebase/links/RNFirebaseLinks.java | 224 ++++++------------ ios/RNFirebase/links/RNFirebaseLinks.m | 10 +- lib/firebase.js | 179 ++++++-------- 3 files changed, 160 insertions(+), 253 deletions(-) diff --git a/android/src/main/java/io/invertase/firebase/links/RNFirebaseLinks.java b/android/src/main/java/io/invertase/firebase/links/RNFirebaseLinks.java index ab00df36..ca9e62b5 100644 --- a/android/src/main/java/io/invertase/firebase/links/RNFirebaseLinks.java +++ b/android/src/main/java/io/invertase/firebase/links/RNFirebaseLinks.java @@ -33,8 +33,8 @@ public class RNFirebaseLinks extends ReactContextBaseJavaModule implements Activ public RNFirebaseLinks(ReactApplicationContext reactContext) { super(reactContext); - getReactApplicationContext().addActivityEventListener(this); - registerLinksHandler(); + //getReactApplicationContext().addActivityEventListener(this); + //registerLinksHandler(); } @Override @@ -51,55 +51,54 @@ public class RNFirebaseLinks extends ReactContextBaseJavaModule implements Activ Activity activity = getCurrentActivity(); if (activity == null) { return; - } + } - FirebaseDynamicLinks.getInstance() - .getDynamicLink(activity.getIntent()) - .addOnSuccessListener(activity, new OnSuccessListener() { - @Override - public void onSuccess(PendingDynamicLinkData pendingDynamicLinkData) { - // Get deep link from result (may be null if no link is found) - if (pendingDynamicLinkData != null) { - Uri deepLinkUri = pendingDynamicLinkData.getLink(); - String deepLink = deepLinkUri.toString(); - // TODO: Validate that this is called when opening from a deep link - if (initialLink == null) { - initialLink = deepLink; - } - Utils.sendEvent(getReactApplicationContext(), "dynamic_link_received", deepLink); + FirebaseDynamicLinks.getInstance() + .getDynamicLink(activity.getIntent()) + .addOnSuccessListener(activity, new OnSuccessListener() { + @Override + public void onSuccess(PendingDynamicLinkData pendingDynamicLinkData) { + // Get deep link from result (may be null if no link is found) + if (pendingDynamicLinkData != null) { + Uri deepLinkUri = pendingDynamicLinkData.getLink(); + String deepLink = deepLinkUri.toString(); + // TODO: Validate that this is called when opening from a deep link + if (initialLink == null) { + initialLink = deepLink; } + Utils.sendEvent(getReactApplicationContext(), "dynamic_link_received", deepLink); } - }) - .addOnFailureListener(activity, new OnFailureListener() { - @Override - public void onFailure(@NonNull Exception e) { - Log.w(TAG, "getDynamicLink:onFailure", e); - } - }); - } + } + }) + .addOnFailureListener(activity, new OnFailureListener() { + @Override + public void onFailure(@NonNull Exception e) { + Log.w(TAG, "getDynamicLink:onFailure", e); + } + }); + } - @Override - public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent data) { - // Not required for this module - } + @Override + public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent data) { + // Not required for this module + } - @Override - public void onNewIntent(Intent intent) { - // TODO: Do I need to re-register the links handler for each new intent? - } + @Override + public void onNewIntent(Intent intent) { + // TODO: Do I need to re-register the links handler for each new intent? + } @ReactMethod public void createDynamicLink(final ReadableMap parameters, final Promise promise) { - try { - Map m = Utils.recursivelyDeconstructReadableMap(parameters); + try { + Map m = Utils.recursivelyDeconstructReadableMap(parameters); - DynamicLink.Builder builder = setDynamicLinkBuilderFromMap(m); - Uri link = builder.buildDynamicLink().getUri(); + DynamicLink.Builder builder = getDynamicLinkBuilderFromMap(m); + Uri link = builder.buildDynamicLink().getUri(); - Log.d(TAG, "created dynamic link: " + link.toString()); - promise.resolve(link.toString()); - } - catch(Exception ex) { + Log.d(TAG, "created dynamic link: " + link.toString()); + promise.resolve(link.toString()); + } catch (Exception ex) { Log.e(TAG, "create dynamic link failure " + ex.getMessage()); promise.reject("links/failure", ex.getMessage(), ex); } @@ -107,58 +106,54 @@ public class RNFirebaseLinks extends ReactContextBaseJavaModule implements Activ @ReactMethod public void createShortDynamicLink(final ReadableMap parameters, final Promise promise) { - try { - Map m = Utils.recursivelyDeconstructReadableMap(parameters); + try { + Map m = Utils.recursivelyDeconstructReadableMap(parameters); - DynamicLink.Builder builder = setDynamicLinkBuilderFromMap(m); + DynamicLink.Builder builder = getDynamicLinkBuilderFromMap(m); - Task shortLinkTask = getShortDynamicLinkTask(builder, m) - .addOnCompleteListener(new OnCompleteListener() { - @Override - public void onComplete(@NonNull Task task) { - if (task.isSuccessful()) { - Uri shortLink = task.getResult().getShortLink(); - Log.d(TAG, "created short dynamic link: " + shortLink.toString()); - promise.resolve(shortLink.toString()); - } else { - Log.e(TAG, "create shot dynamic link failure " + task.getException().getMessage()); - promise.reject("links/failure", task.getException().getMessage(), task.getException()); - } + Task shortLinkTask = getShortDynamicLinkTask(builder, m) + .addOnCompleteListener(new OnCompleteListener() { + @Override + public void onComplete(@NonNull Task task) { + if (task.isSuccessful()) { + Uri shortLink = task.getResult().getShortLink(); + Log.d(TAG, "created short dynamic link: " + shortLink.toString()); + promise.resolve(shortLink.toString()); + } else { + Log.e(TAG, "create short dynamic link failure " + task.getException().getMessage()); + promise.reject("links/failure", task.getException().getMessage(), task.getException()); } - }); - } - catch(Exception ex) { + } + }); + } catch (Exception ex) { Log.e(TAG, "create short dynamic link failure " + ex.getMessage()); promise.reject("links/failure", ex.getMessage(), ex); } } - private Task getShortDynamicLinkTask(final DynamicLink.Builder builder ,final Map m) { + private Task getShortDynamicLinkTask(final DynamicLink.Builder builder, final Map m) { Map suffixParameters = (Map) m.get("suffix"); if (suffixParameters != null) { String option = (String) suffixParameters.get("option"); - if (option.equals("SHORT")) { + if ("SHORT".equals(option)) { return builder.buildShortDynamicLink(ShortDynamicLink.Suffix.SHORT); - } - else if (option.equals("UNGUESSABLE")) { + } else if ("UNGUESSABLE".equals(option)) { return builder.buildShortDynamicLink(ShortDynamicLink.Suffix.UNGUESSABLE); } } return builder.buildShortDynamicLink(); } - private DynamicLink.Builder setDynamicLinkBuilderFromMap(final Map m) { + private DynamicLink.Builder getDynamicLinkBuilderFromMap(final Map m) { DynamicLink.Builder parametersBuilder = FirebaseDynamicLinks.getInstance().createDynamicLink(); try { - parametersBuilder.setLink(Uri.parse((String)m.get("link"))); - parametersBuilder.setDynamicLinkDomain((String)m.get("dynamicLinkDomain")); + parametersBuilder.setLink(Uri.parse((String) m.get("link"))); + parametersBuilder.setDynamicLinkDomain((String) m.get("dynamicLinkDomain")); setAndroidParameters(m, parametersBuilder); setIosParameters(m, parametersBuilder); - //setNavigationInfoParameters(m, parametersBuilder); setSocialMetaTagParameters(m, parametersBuilder); - setAnalyticsParameters(m, parametersBuilder); } catch (Exception e) { Log.e(TAG, "error while building parameters " + e.getMessage()); @@ -172,14 +167,14 @@ public class RNFirebaseLinks extends ReactContextBaseJavaModule implements Activ if (androidParameters != null) { DynamicLink.AndroidParameters.Builder androidParametersBuilder = androidParameters.containsKey("androidPackageName") ? - new DynamicLink.AndroidParameters.Builder((String)androidParameters.get("androidPackageName")) : - new DynamicLink.AndroidParameters.Builder(); + new DynamicLink.AndroidParameters.Builder((String) androidParameters.get("androidPackageName")) : + new DynamicLink.AndroidParameters.Builder(); if (androidParameters.containsKey("androidFallbackLink")) { - androidParametersBuilder.setFallbackUrl(Uri.parse((String)androidParameters.get("androidFallbackLink"))); + androidParametersBuilder.setFallbackUrl(Uri.parse((String) androidParameters.get("androidFallbackLink"))); } if (androidParameters.containsKey("androidMinPackageVersionCode")) { - androidParametersBuilder.setMinimumVersion(((Double)androidParameters.get("androidMinPackageVersionCode")).intValue()); + androidParametersBuilder.setMinimumVersion(((Double) androidParameters.get("androidMinPackageVersionCode")).intValue()); } parametersBuilder.setAndroidParameters(androidParametersBuilder.build()); } @@ -189,42 +184,29 @@ public class RNFirebaseLinks extends ReactContextBaseJavaModule implements Activ Map iosParameters = (Map) m.get("iosInfo"); //TODO: see what happens if bundleId is missing if (iosParameters != null && iosParameters.containsKey("iosBundleId")) { - DynamicLink.IosParameters.Builder iosParametersBuilder = new DynamicLink.IosParameters.Builder((String)iosParameters.get("iosBundleId")); + DynamicLink.IosParameters.Builder iosParametersBuilder = new DynamicLink.IosParameters.Builder((String) iosParameters.get("iosBundleId")); if (iosParameters.containsKey("iosAppStoreId")) { - iosParametersBuilder.setAppStoreId((String)iosParameters.get("iosAppStoreId")); + iosParametersBuilder.setAppStoreId((String) iosParameters.get("iosAppStoreId")); } if (iosParameters.containsKey("iosCustomScheme")) { - iosParametersBuilder.setCustomScheme((String)iosParameters.get("iosCustomScheme")); + iosParametersBuilder.setCustomScheme((String) iosParameters.get("iosCustomScheme")); } if (iosParameters.containsKey("iosFallbackLink")) { - iosParametersBuilder.setFallbackUrl(Uri.parse((String)iosParameters.get("iosFallbackLink"))); + iosParametersBuilder.setFallbackUrl(Uri.parse((String) iosParameters.get("iosFallbackLink"))); } if (iosParameters.containsKey("iosIpadBundleId")) { - iosParametersBuilder.setIpadBundleId((String)iosParameters.get("iosIpadBundleId")); + iosParametersBuilder.setIpadBundleId((String) iosParameters.get("iosIpadBundleId")); } if (iosParameters.containsKey("iosIpadFallbackLink")) { - iosParametersBuilder.setIpadFallbackUrl(Uri.parse((String)iosParameters.get("iosIpadFallbackLink"))); + iosParametersBuilder.setIpadFallbackUrl(Uri.parse((String) iosParameters.get("iosIpadFallbackLink"))); } if (iosParameters.containsKey("iosMinPackageVersionCode")) { - iosParametersBuilder.setMinimumVersion((String)iosParameters.get("iosMinPackageVersionCode")); + iosParametersBuilder.setMinimumVersion((String) iosParameters.get("iosMinPackageVersionCode")); } parametersBuilder.setIosParameters(iosParametersBuilder.build()); } } - // private void setNavigationInfoParameters(final Map m, final DynamicLink.Builder parametersBuilder) { - // Map navigationInfoParameters = (Map) m.get("navigationInfo"); - // if (navigationInfoParameters != null) { - // DynamicLink.NavigationInfoParameters.Builder navigationInfoParametersBuilder = - // new DynamicLink.NavigationInfoParameters.Builder(); - // - // if (navigationInfoParameters.containsKey("enableForcedRedirect")) { - // navigationInfoParametersBuilder.setForcedRedirectEnabled((boolean)navigationInfoParameters.get("enableForcedRedirect")); - // } - // parametersBuilder.setNavigationInfoParameters(navigationInfoParametersBuilder.build()); - // } - // } - private void setSocialMetaTagParameters(final Map m, final DynamicLink.Builder parametersBuilder) { Map socialMetaTagParameters = (Map) m.get("socialMetaTagInfo"); if (socialMetaTagParameters != null) { @@ -232,67 +214,15 @@ public class RNFirebaseLinks extends ReactContextBaseJavaModule implements Activ new DynamicLink.SocialMetaTagParameters.Builder(); if (socialMetaTagParameters.containsKey("socialDescription")) { - socialMetaTagParametersBuilder.setDescription((String)socialMetaTagParameters.get("socialDescription")); + socialMetaTagParametersBuilder.setDescription((String) socialMetaTagParameters.get("socialDescription")); } if (socialMetaTagParameters.containsKey("socialImageLink")) { - socialMetaTagParametersBuilder.setImageUrl(Uri.parse((String)socialMetaTagParameters.get("socialImageLink"))); + socialMetaTagParametersBuilder.setImageUrl(Uri.parse((String) socialMetaTagParameters.get("socialImageLink"))); } if (socialMetaTagParameters.containsKey("socialTitle")) { - socialMetaTagParametersBuilder.setTitle((String)socialMetaTagParameters.get("socialTitle")); + socialMetaTagParametersBuilder.setTitle((String) socialMetaTagParameters.get("socialTitle")); } parametersBuilder.setSocialMetaTagParameters(socialMetaTagParametersBuilder.build()); } } - - private void setAnalyticsParameters (final Map m, final DynamicLink.Builder parametersBuilder) { - Map analyticsParameters = (Map) m.get("analyticsInfo"); - if (analyticsParameters != null) { - setGoogleAnalyticsParameters(analyticsParameters, parametersBuilder); - setItunesConnectAnalyticsParameters(analyticsParameters, parametersBuilder); - } - } - - private void setGoogleAnalyticsParameters(final Map m, final DynamicLink.Builder parametersBuilder) { - Map googleAnalyticsParameters = (Map) m.get("googlePlayAnalytics"); - if (googleAnalyticsParameters != null) { - DynamicLink.GoogleAnalyticsParameters.Builder googleAnalyticsParametersBuilder = - new DynamicLink.GoogleAnalyticsParameters.Builder(); - - if (googleAnalyticsParameters.containsKey("utmCampaign")) { - googleAnalyticsParametersBuilder.setCampaign((String)googleAnalyticsParameters.get("utmCampaign")); - } - if (googleAnalyticsParameters.containsKey("utmContent")) { - googleAnalyticsParametersBuilder.setContent((String)googleAnalyticsParameters.get("utmContent")); - } - if (googleAnalyticsParameters.containsKey("utmMedium")) { - googleAnalyticsParametersBuilder.setMedium((String)googleAnalyticsParameters.get("utmMedium")); - } - if (googleAnalyticsParameters.containsKey("utmSource")) { - googleAnalyticsParametersBuilder.setSource((String)googleAnalyticsParameters.get("utmSource")); - } - if (googleAnalyticsParameters.containsKey("utmTerm")) { - googleAnalyticsParametersBuilder.setTerm((String)googleAnalyticsParameters.get("utmTerm")); - } - parametersBuilder.setGoogleAnalyticsParameters(googleAnalyticsParametersBuilder.build()); - } - } - - private void setItunesConnectAnalyticsParameters(final Map m, final DynamicLink.Builder parametersBuilder) { - Map itunesConnectAnalyticsParameters = (Map) m.get("itunesConnectAnalytics"); - if (itunesConnectAnalyticsParameters != null) { - DynamicLink.ItunesConnectAnalyticsParameters.Builder itunesConnectAnalyticsParametersBuilder = - new DynamicLink.ItunesConnectAnalyticsParameters.Builder(); - - if (itunesConnectAnalyticsParameters.containsKey("at")) { - itunesConnectAnalyticsParametersBuilder.setAffiliateToken((String)itunesConnectAnalyticsParameters.get("at")); - } - if (itunesConnectAnalyticsParameters.containsKey("ct")) { - itunesConnectAnalyticsParametersBuilder.setCampaignToken((String)itunesConnectAnalyticsParameters.get("ct")); - } - if (itunesConnectAnalyticsParameters.containsKey("pt")) { - itunesConnectAnalyticsParametersBuilder.setProviderToken((String)itunesConnectAnalyticsParameters.get("pt")); - } - parametersBuilder.setItunesConnectAnalyticsParameters(itunesConnectAnalyticsParametersBuilder.build()); - } - } } diff --git a/ios/RNFirebase/links/RNFirebaseLinks.m b/ios/RNFirebase/links/RNFirebaseLinks.m index 4c11d90d..091f47f9 100644 --- a/ios/RNFirebase/links/RNFirebaseLinks.m +++ b/ios/RNFirebase/links/RNFirebaseLinks.m @@ -7,8 +7,8 @@ RCT_EXPORT_MODULE(); RCT_EXPORT_METHOD(createDynamicLink: (NSDictionary *) metadata resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject) { - FIRDynamicLinkComponents *components = [self setDynamicLinkBuilderFromMap:metadata]; - + FIRDynamicLinkComponents *components = [self getDynamicLinkComponentsFromMetadata:metadata]; + if (components == nil) { reject(@"links/failure", @"error", nil); } else { @@ -19,8 +19,8 @@ RCT_EXPORT_METHOD(createDynamicLink: (NSDictionary *) metadata resolver:(RCTProm } RCT_EXPORT_METHOD(createShortDynamicLink: (NSDictionary *) metadata resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject) { - FIRDynamicLinkComponents *components = [self setDynamicLinkBuilderFromMap:metadata]; - + FIRDynamicLinkComponents *components = [self getDynamicLinkComponentsFromMetadata:metadata]; + [components shortenWithCompletion:^(NSURL *_Nullable shortURL, NSArray *_Nullable warnings, NSError *_Nullable error) { @@ -35,7 +35,7 @@ RCT_EXPORT_METHOD(createShortDynamicLink: (NSDictionary *) metadata resolver:(RC } -- (FIRDynamicLinkComponents *)setDynamicLinkBuilderFromMap:(NSDictionary *)metadata { +- (FIRDynamicLinkComponents *)getDynamicLinkComponentsFromMetadata:(NSDictionary *)metadata { NSURL *link = [NSURL URLWithString:metadata[@"link"]]; FIRDynamicLinkComponents *components = [FIRDynamicLinkComponents componentsWithLink:link domain:metadata[@"dynamicLinkDomain"]]; diff --git a/lib/firebase.js b/lib/firebase.js index ab781828..1f3d3e66 100644 --- a/lib/firebase.js +++ b/lib/firebase.js @@ -2,121 +2,106 @@ * @providesModule Firebase * @flow */ -import { NativeModules } from 'react-native' +import { NativeModules } from 'react-native'; -import Log from './utils/log' -import { isObject } from './utils' +import Log from './utils/log'; +import { isObject } from './utils'; // modules -import Auth, { statics as AuthStatics } from './modules/auth' -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 Analytics from './modules/analytics' -import Crash from './modules/crash' -import RemoteConfig from './modules/config' -import Performance from './modules/perf' -import AdMob, { statics as AdMobStatics } from './modules/admob' -import Links, { statics as LinksStatics } from './modules/links' +import Auth, { statics as AuthStatics } from './modules/auth'; +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 Analytics from './modules/analytics'; +import Crash from './modules/crash'; +import RemoteConfig from './modules/config'; +import Performance from './modules/perf'; +import AdMob, { statics as AdMobStatics } from './modules/admob'; +import Links, { statics as LinksStatics } from './modules/links'; -const instances: Object = { default: null } -const FirebaseModule = NativeModules.RNFirebase +const instances: Object = { default: null }; +const FirebaseModule = NativeModules.RNFirebase; /** * @class Firebase */ export default class Firebase { - _log: ?Object - _auth: ?Object - _store: ?Object - _storage: ?Object - _database: ?Object - _presence: ?Object - _analytics: ?Object - _constants: ?Object - _messaging: ?Object - _config: ?Object - _crash: ?Object - _perf: ?Object - _admob: ?Object - _links: ?Object + _log: ?Object; + _auth: ?Object; + _store: ?Object; + _storage: ?Object; + _database: ?Object; + _presence: ?Object; + _analytics: ?Object; + _constants: ?Object; + _messaging: ?Object; + _config: ?Object; + _crash: ?Object; + _perf: ?Object; + _admob: ?Object; + _links: ?Object; - auth: Function - crash: Function - storage: Function - database: Function - analytics: Function - messaging: Function - config: Function - perf: Function - admob: Function - links: Function + auth: Function; + crash: Function; + storage: Function; + database: Function; + analytics: Function; + messaging: Function; + config: Function; + perf: Function; + admob: Function; + links: Function; - eventHandlers: Object - debug: boolean + eventHandlers: Object; + debug: boolean; options: { errorOnMissingPlayServices: boolean, debug?: boolean, - persistence?: boolean, - } + persistence?: boolean + }; /** * * @param options */ constructor(options: Object = {}) { - this.eventHandlers = {} - this.debug = options.debug || false - this.options = Object.assign( - { errorOnMissingPlayServices: true, promptOnMissingPlayServices: true }, - options - ) + this.eventHandlers = {}; + this.debug = options.debug || false; + this.options = Object.assign({ errorOnMissingPlayServices: true, promptOnMissingPlayServices: true }, options); if (this.debug) { - Log.enable(this.debug) + Log.enable(this.debug); } - this._log = new Log('firebase') + this._log = new Log('firebase'); if (!this.googleApiAvailability.isAvailable) { - if ( - this.options.promptOnMissingPlayServices && - this.googleApiAvailability.isUserResolvableError - ) { - FirebaseModule.promptPlayServices() + if (this.options.promptOnMissingPlayServices && this.googleApiAvailability.isUserResolvableError) { + FirebaseModule.promptPlayServices(); } else { - const error = `Google Play Services is required to run this application but no valid installation was found (Code ${this - .googleApiAvailability.status}).` + const error = `Google Play Services is required to run this application but no valid installation was found (Code ${this.googleApiAvailability.status}).`; if (this.options.errorOnMissingPlayServices) { - throw new Error(error) + throw new Error(error); } else { - console.warn(error) + console.warn(error); } } } - this.auth = this._staticsOrInstance('auth', AuthStatics, Auth) - this.storage = this._staticsOrInstance('storage', StorageStatics, Storage) - this.database = this._staticsOrInstance( - 'database', - DatabaseStatics, - Database - ) - this.messaging = this._staticsOrInstance( - 'messaging', - MessagingStatics, - Messaging - ) - this.analytics = this._staticsOrInstance('analytics', {}, Analytics) - this.crash = this._staticsOrInstance('crash', {}, Crash) - this.config = this._staticsOrInstance('config', {}, RemoteConfig) - this.perf = this._staticsOrInstance('perf', {}, Performance) - this.admob = this._staticsOrInstance('admob', AdMobStatics, AdMob) - this.links = this._staticsOrInstance('links', LinksStatics, Links) + this.auth = this._staticsOrInstance('auth', AuthStatics, Auth); + this.storage = this._staticsOrInstance('storage', StorageStatics, Storage); + this.database = this._staticsOrInstance('database', DatabaseStatics, Database); + this.messaging = this._staticsOrInstance('messaging', MessagingStatics, Messaging); + this.analytics = this._staticsOrInstance('analytics', {}, Analytics); + this.crash = this._staticsOrInstance('crash', {}, Crash); + this.config = this._staticsOrInstance('config', {}, RemoteConfig); + this.perf = this._staticsOrInstance('perf', {}, Performance); + this.admob = this._staticsOrInstance('admob', AdMobStatics, AdMob); + this.links = this._staticsOrInstance('links', LinksStatics, Links); // init auth to start listeners if (NativeModules.RNFirebaseAuth) { - this.auth() + this.auth(); } } @@ -128,29 +113,23 @@ export default class Firebase { */ static initializeApp(options: Object = {}, name: string = 'default') { if (!isObject(options)) { - throw new Error( - 'Firebase.initializeApp(options <- requires a configuration object' - ) + throw new Error('Firebase.initializeApp(options <- requires a configuration object'); } if (typeof name !== 'string') { - throw new Error( - 'Firebase.initializeApp(options, name <- requires a string value' - ) + throw new Error('Firebase.initializeApp(options, name <- requires a string value'); } if (name !== 'default') { - throw new Error( - 'RNFirebase currently only supports one instance of firebase - the default one.' - ) + throw new Error('RNFirebase currently only supports one instance of firebase - the default one.'); } - if (!instances[name]) instances[name] = new Firebase(options) - return instances[name] + if (!instances[name]) instances[name] = new Firebase(options); + return instances[name]; } get apps(): Array { - return Object.keys(instances) + return Object.keys(instances); } /** @@ -159,16 +138,14 @@ export default class Firebase { */ get googleApiAvailability(): GoogleApiAvailabilityType { // if not available then return a fake object for ios - saves doing platform specific logic. - return ( - FirebaseModule.googleApiAvailability || { isAvailable: true, status: 0 } - ) + return FirebaseModule.googleApiAvailability || { isAvailable: true, status: 0 }; } /** * Logger */ get log(): Log { - return this._log + return this._log; } /** @@ -181,19 +158,19 @@ export default class Firebase { */ _staticsOrInstance(name, statics, InstanceClass): Function { const getInstance = () => { - const internalPropName = `_${name}` + const internalPropName = `_${name}`; // $FlowFixMe if (!this[internalPropName]) { // $FlowFixMe - this[internalPropName] = new InstanceClass(this) + this[internalPropName] = new InstanceClass(this); } // $FlowFixMe - return this[internalPropName] - } + return this[internalPropName]; + }; - Object.assign(getInstance, statics || {}) - return getInstance + Object.assign(getInstance, statics || {}); + return getInstance; } } From 79d18e95e0840f67f3212b1d47bfde80fc88f401 Mon Sep 17 00:00:00 2001 From: Omer Levy Date: Mon, 25 Sep 2017 12:19:21 +0300 Subject: [PATCH 3/3] [android] receive dynamic links support --- .../firebase/links/RNFirebaseLinks.java | 25 +++++++++++++------ 1 file changed, 18 insertions(+), 7 deletions(-) diff --git a/android/src/main/java/io/invertase/firebase/links/RNFirebaseLinks.java b/android/src/main/java/io/invertase/firebase/links/RNFirebaseLinks.java index ca9e62b5..2dd69ce0 100644 --- a/android/src/main/java/io/invertase/firebase/links/RNFirebaseLinks.java +++ b/android/src/main/java/io/invertase/firebase/links/RNFirebaseLinks.java @@ -9,6 +9,7 @@ import android.util.Log; import java.util.Map; import com.facebook.react.bridge.ActivityEventListener; +import com.facebook.react.bridge.LifecycleEventListener; import com.facebook.react.bridge.Promise; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactContextBaseJavaModule; @@ -27,14 +28,14 @@ import com.google.android.gms.tasks.OnFailureListener; import io.invertase.firebase.Utils; -public class RNFirebaseLinks extends ReactContextBaseJavaModule implements ActivityEventListener { +public class RNFirebaseLinks extends ReactContextBaseJavaModule implements ActivityEventListener ,LifecycleEventListener { private final static String TAG = RNFirebaseLinks.class.getCanonicalName(); private String initialLink = null; public RNFirebaseLinks(ReactApplicationContext reactContext) { super(reactContext); - //getReactApplicationContext().addActivityEventListener(this); - //registerLinksHandler(); + getReactApplicationContext().addActivityEventListener(this); + getReactApplicationContext().addLifecycleEventListener(this); } @Override @@ -52,7 +53,6 @@ public class RNFirebaseLinks extends ReactContextBaseJavaModule implements Activ if (activity == null) { return; } - FirebaseDynamicLinks.getInstance() .getDynamicLink(activity.getIntent()) .addOnSuccessListener(activity, new OnSuccessListener() { @@ -62,10 +62,10 @@ public class RNFirebaseLinks extends ReactContextBaseJavaModule implements Activ if (pendingDynamicLinkData != null) { Uri deepLinkUri = pendingDynamicLinkData.getLink(); String deepLink = deepLinkUri.toString(); - // TODO: Validate that this is called when opening from a deep link if (initialLink == null) { initialLink = deepLink; } + Log.d(TAG, "sending a dynamic_link_received event!"); Utils.sendEvent(getReactApplicationContext(), "dynamic_link_received", deepLink); } } @@ -84,8 +84,19 @@ public class RNFirebaseLinks extends ReactContextBaseJavaModule implements Activ } @Override - public void onNewIntent(Intent intent) { - // TODO: Do I need to re-register the links handler for each new intent? + public void onNewIntent(Intent intent) {} + + @Override + public void onHostResume() { + registerLinksHandler(); + } + + @Override + public void onHostPause() {} + + @Override + public void onHostDestroy() { + initialLink = null; } @ReactMethod