diff --git a/.github/workflows/cpp-packaging.yml b/.github/workflows/cpp-packaging.yml index 13db3f4219..45e1228657 100644 --- a/.github/workflows/cpp-packaging.yml +++ b/.github/workflows/cpp-packaging.yml @@ -433,6 +433,8 @@ jobs: run: | cd out-sdk find .. -type f -print > src_file_list.txt + # Remove intermediate build files (.o and .obj) files to save space. + find . -type f -name '*.o' -or -name '*.obj' -print0 | xargs -0 rm -f -- tar -czhf ../firebase-cpp-sdk-${{ env.SDK_NAME }}-build.tgz . - name: Print built libraries @@ -782,6 +784,7 @@ jobs: - name: Use GitHub API to start workflow shell: bash run: | + pip install -r scripts/gha/requirements.txt if [[ -z ${USE_EXPANDED_MATRIX} ]]; then USE_EXPANDED_MATRIX=0 fi diff --git a/.github/workflows/integration_tests.yml b/.github/workflows/integration_tests.yml index 78f4676b9e..eaaf4441f4 100644 --- a/.github/workflows/integration_tests.yml +++ b/.github/workflows/integration_tests.yml @@ -829,7 +829,7 @@ jobs: npm install -g firebase-tools firebase emulators:start --only firestore --project demo-example & - name: Run Android integration tests on Emulator locally - timeout-minutes: 60 + timeout-minutes: 90 if: steps.get-device-type.outputs.device_type == 'virtual' run: | python scripts/gha/test_simulator.py --testapp_dir testapps \ diff --git a/admob/src/include/firebase/admob/banner_view.h b/admob/src/include/firebase/admob/banner_view.h index f5b46039d9..1711f4ff20 100644 --- a/admob/src/include/firebase/admob/banner_view.h +++ b/admob/src/include/firebase/admob/banner_view.h @@ -99,21 +99,21 @@ class BannerView : public AdView { /// /// param[in] listener A listener object which will be invoked when lifecycle /// events occur on this AdView. - void SetAdListener(AdListener *listener) override; + void SetAdListener(AdListener* listener) override; /// Sets a listener to be invoked when the Ad's bounding box /// changes size or location. /// /// param[in] listener A listener object which will be invoked when the ad /// changes size, shape, or position. - void SetBoundingBoxListener(AdViewBoundingBoxListener *listener) override; + void SetBoundingBoxListener(AdViewBoundingBoxListener* listener) override; /// Sets a listener to be invoked when this ad is estimated to have earned /// money. /// /// param[in] A listener object to be invoked when a paid event occurs on the /// ad. - void SetPaidEventListener(PaidEventListener *listener) override; + void SetPaidEventListener(PaidEventListener* listener) override; /// 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. diff --git a/admob/src/include/firebase/admob/rewarded_ad.h b/admob/src/include/firebase/admob/rewarded_ad.h index dde6f38085..9632cd36a6 100644 --- a/admob/src/include/firebase/admob/rewarded_ad.h +++ b/admob/src/include/firebase/admob/rewarded_ad.h @@ -137,7 +137,7 @@ class RewardedAd { /// ServerSideVerificationOptions object containing custom data and a user /// Id. void SetServerSideVerificationOptions( - const ServerSideVerificationOptions &serverSideVerificationOptions); + const ServerSideVerificationOptions& serverSideVerificationOptions); private: // An internal, platform-specific implementation object that this class uses diff --git a/admob/src_java/com/google/firebase/admob/internal/cpp/AdMobInitializationHelper.java b/admob/src_java/com/google/firebase/admob/internal/cpp/AdMobInitializationHelper.java index c1024ce7c5..c500c48527 100644 --- a/admob/src_java/com/google/firebase/admob/internal/cpp/AdMobInitializationHelper.java +++ b/admob/src_java/com/google/firebase/admob/internal/cpp/AdMobInitializationHelper.java @@ -24,7 +24,7 @@ /** * Helper class for initializing the AdMob SDK. */ -public final class AdMobInitializationHelper { +public final class AdMobInitializationHelper { public static void initializeAdMob(Context context) { MobileAds.initialize(context, new OnInitializationCompleteListener() { @Override @@ -32,7 +32,8 @@ public void onInitializationComplete(InitializationStatus initializationStatus) initializationCompleteCallback(initializationStatus); } }); - } - - public static native void initializationCompleteCallback(InitializationStatus initializationStatus); + } + + public static native void initializationCompleteCallback( + InitializationStatus initializationStatus); } diff --git a/admob/src_java/com/google/firebase/admob/internal/cpp/AdRequestHelper.java b/admob/src_java/com/google/firebase/admob/internal/cpp/AdRequestHelper.java index 4fe9faa3cc..94ca85024f 100644 --- a/admob/src_java/com/google/firebase/admob/internal/cpp/AdRequestHelper.java +++ b/admob/src_java/com/google/firebase/admob/internal/cpp/AdRequestHelper.java @@ -25,7 +25,6 @@ * into their (typically more complicated) Java equivalents. */ public class AdRequestHelper { - public AdRequestHelper() {} /** diff --git a/admob/src_java/com/google/firebase/admob/internal/cpp/BannerViewHelper.java b/admob/src_java/com/google/firebase/admob/internal/cpp/BannerViewHelper.java index e1ec117c49..1ce5ab87b1 100644 --- a/admob/src_java/com/google/firebase/admob/internal/cpp/BannerViewHelper.java +++ b/admob/src_java/com/google/firebase/admob/internal/cpp/BannerViewHelper.java @@ -20,23 +20,20 @@ import android.graphics.drawable.ColorDrawable; import android.os.Handler; import android.os.Looper; +import android.util.Log; import android.view.Gravity; import android.view.View; import android.view.ViewGroup.LayoutParams; import android.view.ViewTreeObserver; import android.widget.PopupWindow; - import com.google.android.gms.ads.AdListener; import com.google.android.gms.ads.AdRequest; import com.google.android.gms.ads.AdValue; import com.google.android.gms.ads.AdView; import com.google.android.gms.ads.LoadAdError; import com.google.android.gms.ads.OnPaidEventListener; - import java.util.concurrent.atomic.AtomicBoolean; -import android.util.Log; - /** * Helper class to make interactions between the AdMob C++ wrapper and Java AdView objects cleaner. * It's designed to wrap and adapt a single instance of AdView, translate calls coming from C++ into @@ -44,7 +41,6 @@ * game engine-friendly state machine polling. */ public class BannerViewHelper implements ViewTreeObserver.OnPreDrawListener { - // It's possible to attempt to show a popup when an activity doesn't have focus. This value // controls the number of times the BannerViewHelper object checks for activity window focus // before timing out. Assuming 10ms per retry this value attempts to retry for 2 minutes before @@ -146,50 +142,47 @@ public void destroy(final long callbackDataPtr, final boolean destructor_invocat // If the Activity isn't initialized, or already Destroyed, then there's // nothing to destroy. if (mActivity != null) { - mActivity.runOnUiThread( - new Runnable() { - @Override - public void run() { - // Stop any attempts to show the popup window. - synchronized (mPopUpLock) { - mPopUpRunnable = null; - } + mActivity.runOnUiThread(new Runnable() { + @Override + public void run() { + // Stop any attempts to show the popup window. + synchronized (mPopUpLock) { + mPopUpRunnable = null; + } - if (mAdView != null) { - mAdView.setAdListener(null); - mAdView.setOnPaidEventListener(null); - mAdView.destroy(); - mAdView = null; - } + if (mAdView != null) { + mAdView.setAdListener(null); + mAdView.setOnPaidEventListener(null); + mAdView.destroy(); + mAdView = null; + } - synchronized (mPopUpLock) { - if (mPopUp != null) { - mPopUp.dismiss(); - mPopUp = null; - } - } - synchronized (mBannerViewLock) { - if (destructor_invocation == false) { - notifyBoundingBoxChanged(mBannerViewInternalPtr); - } - mBannerViewInternalPtr = CPP_NULLPTR; - } - mActivity = null; - - // BannerView's C++ destructor does not pass a future - // to callback and complete, since that would cause the destructor - // to block. - if (callbackDataPtr != CPP_NULLPTR) { - completeBannerViewFutureCallback(callbackDataPtr, - ConstantsHelper.CALLBACK_ERROR_NONE, - ConstantsHelper.CALLBACK_ERROR_MESSAGE_NONE); - } + synchronized (mPopUpLock) { + if (mPopUp != null) { + mPopUp.dismiss(); + mPopUp = null; } - }); + } + synchronized (mBannerViewLock) { + if (destructor_invocation == false) { + notifyBoundingBoxChanged(mBannerViewInternalPtr); + } + mBannerViewInternalPtr = CPP_NULLPTR; + } + mActivity = null; + + // BannerView's C++ destructor does not pass a future + // to callback and complete, since that would cause the destructor + // to block. + if (callbackDataPtr != CPP_NULLPTR) { + completeBannerViewFutureCallback(callbackDataPtr, ConstantsHelper.CALLBACK_ERROR_NONE, + ConstantsHelper.CALLBACK_ERROR_MESSAGE_NONE); + } + } + }); } else { if (callbackDataPtr != CPP_NULLPTR) { - completeBannerViewFutureCallback(callbackDataPtr, - ConstantsHelper.CALLBACK_ERROR_NONE, + completeBannerViewFutureCallback(callbackDataPtr, ConstantsHelper.CALLBACK_ERROR_NONE, ConstantsHelper.CALLBACK_ERROR_MESSAGE_NONE); } } @@ -205,8 +198,7 @@ public void loadAd(long callbackDataPtr, final AdRequest request) { synchronized (mBannerViewLock) { if (mLoadAdCallbackDataPtr != CPP_NULLPTR) { - completeBannerViewLoadAdInternalError( - callbackDataPtr, + completeBannerViewLoadAdInternalError(callbackDataPtr, ConstantsHelper.CALLBACK_ERROR_LOAD_IN_PROGRESS, ConstantsHelper.CALLBACK_ERROR_MESSAGE_LOAD_IN_PROGRESS); return; @@ -216,8 +208,7 @@ public void loadAd(long callbackDataPtr, final AdRequest request) { if (mAdView == null) { synchronized (mBannerViewLock) { - completeBannerViewLoadAdInternalError( - mLoadAdCallbackDataPtr, + completeBannerViewLoadAdInternalError(mLoadAdCallbackDataPtr, ConstantsHelper.CALLBACK_ERROR_UNINITIALIZED, ConstantsHelper.CALLBACK_ERROR_MESSAGE_UNINITIALIZED); mLoadAdCallbackDataPtr = CPP_NULLPTR; @@ -275,8 +266,7 @@ public void pause(final long callbackDataPtr) { } else if (mAdView != null) { mAdView.pause(); } - completeBannerViewFutureCallback(callbackDataPtr, - ConstantsHelper.CALLBACK_ERROR_NONE, + completeBannerViewFutureCallback(callbackDataPtr, ConstantsHelper.CALLBACK_ERROR_NONE, ConstantsHelper.CALLBACK_ERROR_MESSAGE_NONE); } @@ -290,8 +280,7 @@ public void resume(final long callbackDataPtr) { mAdView.resume(); } - completeBannerViewFutureCallback(callbackDataPtr, - ConstantsHelper.CALLBACK_ERROR_NONE, + completeBannerViewFutureCallback(callbackDataPtr, ConstantsHelper.CALLBACK_ERROR_NONE, ConstantsHelper.CALLBACK_ERROR_MESSAGE_NONE); } @@ -355,7 +344,7 @@ public int[] getBoundingBox() { } } } - return new int[]{width, height, x, y}; + return new int[] {width, height, x, y}; } } @@ -397,94 +386,91 @@ private boolean updatePopUpLocation(final long callbackDataPtr) { synchronized (mPopUpLock) { if (mPopUp != null) { - mActivity.runOnUiThread( - new Runnable() { - @Override - public void run() { - synchronized (mPopUpLock) { - // Any change in visibility or position results in the dismissal of the popup (if - // one is being displayed) and creation of a fresh one. - mPopUp.dismiss(); - mPopUp = null; - } - } - }); + mActivity.runOnUiThread(new Runnable() { + @Override + public void run() { + synchronized (mPopUpLock) { + // Any change in visibility or position results in the dismissal of the popup (if + // one is being displayed) and creation of a fresh one. + mPopUp.dismiss(); + mPopUp = null; + } + } + }); } mPopUpShowRetryCount = 0; - mPopUpRunnable = - new Runnable() { - @Override - public void run() { - int errorCode = ConstantsHelper.CALLBACK_ERROR_NONE; - String errorMessage = ConstantsHelper.CALLBACK_ERROR_MESSAGE_NONE; - // If the Activity's window doesn't currently have focus it's not - // possible to display the popup window. Poll the focus after a delay of 10ms and try - // to show the popup again. - if (!mActivity.hasWindowFocus()) { - synchronized (mPopUpLock) { - if (mPopUpRunnable == null) { - errorCode = ConstantsHelper.CALLBACK_ERROR_UNINITIALIZED; - errorMessage = ConstantsHelper.CALLBACK_ERROR_MESSAGE_UNINITIALIZED; - } else { - if (mPopUpShowRetryCount < POPUP_SHOW_RETRY_COUNT) { - mPopUpShowRetryCount++; - new Handler().postDelayed(mPopUpRunnable, 10); - return; - } - errorCode = ConstantsHelper.CALLBACK_ERROR_NO_WINDOW_TOKEN; - errorMessage = ConstantsHelper.CALLBACK_ERROR_MESSAGE_NO_WINDOW_TOKEN; - } - } - } - - if (mAdView == null) { + mPopUpRunnable = new Runnable() { + @Override + public void run() { + int errorCode = ConstantsHelper.CALLBACK_ERROR_NONE; + String errorMessage = ConstantsHelper.CALLBACK_ERROR_MESSAGE_NONE; + // If the Activity's window doesn't currently have focus it's not + // possible to display the popup window. Poll the focus after a delay of 10ms and try + // to show the popup again. + if (!mActivity.hasWindowFocus()) { + synchronized (mPopUpLock) { + if (mPopUpRunnable == null) { errorCode = ConstantsHelper.CALLBACK_ERROR_UNINITIALIZED; errorMessage = ConstantsHelper.CALLBACK_ERROR_MESSAGE_UNINITIALIZED; - } - - if (errorCode != ConstantsHelper.CALLBACK_ERROR_NONE) { - completeBannerViewFutureCallback(callbackDataPtr, errorCode, errorMessage); - return; - } else if (mPopUp == null) { - mPopUp = - new PopupWindow(mAdView, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); - mPopUp.setBackgroundDrawable(new ColorDrawable(0xFF000000)); // Black - mAdView.getViewTreeObserver().addOnPreDrawListener(BannerViewHelper.this); - - if (mShouldUseXYForPosition) { - mPopUp.showAtLocation(root, Gravity.NO_GRAVITY, mDesiredX, mDesiredY); - } else { - switch (mDesiredPosition) { - case ConstantsHelper.AD_VIEW_POSITION_TOP: - mPopUp.showAtLocation(root, Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, 0); - break; - case ConstantsHelper.AD_VIEW_POSITION_BOTTOM: - mPopUp.showAtLocation(root, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0); - break; - case ConstantsHelper.AD_VIEW_POSITION_TOP_LEFT: - mPopUp.showAtLocation(root, Gravity.TOP | Gravity.LEFT, 0, 0); - break; - case ConstantsHelper.AD_VIEW_POSITION_TOP_RIGHT: - mPopUp.showAtLocation(root, Gravity.TOP | Gravity.RIGHT, 0, 0); - break; - case ConstantsHelper.AD_VIEW_POSITION_BOTTOM_LEFT: - mPopUp.showAtLocation(root, Gravity.BOTTOM | Gravity.LEFT, 0, 0); - break; - case ConstantsHelper.AD_VIEW_POSITION_BOTTOM_RIGHT: - mPopUp.showAtLocation(root, Gravity.BOTTOM | Gravity.RIGHT, 0, 0); - break; - default: - mPopUp.showAtLocation(root, Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, 0); - break; - } + } else { + if (mPopUpShowRetryCount < POPUP_SHOW_RETRY_COUNT) { + mPopUpShowRetryCount++; + new Handler().postDelayed(mPopUpRunnable, 10); + return; } + errorCode = ConstantsHelper.CALLBACK_ERROR_NO_WINDOW_TOKEN; + errorMessage = ConstantsHelper.CALLBACK_ERROR_MESSAGE_NO_WINDOW_TOKEN; } + } + } - completeBannerViewFutureCallback(callbackDataPtr, errorCode, errorMessage); - mNotifyBoundingBoxListenerOnNextDraw.set(true); + if (mAdView == null) { + errorCode = ConstantsHelper.CALLBACK_ERROR_UNINITIALIZED; + errorMessage = ConstantsHelper.CALLBACK_ERROR_MESSAGE_UNINITIALIZED; + } + + if (errorCode != ConstantsHelper.CALLBACK_ERROR_NONE) { + completeBannerViewFutureCallback(callbackDataPtr, errorCode, errorMessage); + return; + } else if (mPopUp == null) { + mPopUp = new PopupWindow(mAdView, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); + mPopUp.setBackgroundDrawable(new ColorDrawable(0xFF000000)); // Black + mAdView.getViewTreeObserver().addOnPreDrawListener(BannerViewHelper.this); + + if (mShouldUseXYForPosition) { + mPopUp.showAtLocation(root, Gravity.NO_GRAVITY, mDesiredX, mDesiredY); + } else { + switch (mDesiredPosition) { + case ConstantsHelper.AD_VIEW_POSITION_TOP: + mPopUp.showAtLocation(root, Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, 0); + break; + case ConstantsHelper.AD_VIEW_POSITION_BOTTOM: + mPopUp.showAtLocation(root, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0); + break; + case ConstantsHelper.AD_VIEW_POSITION_TOP_LEFT: + mPopUp.showAtLocation(root, Gravity.TOP | Gravity.LEFT, 0, 0); + break; + case ConstantsHelper.AD_VIEW_POSITION_TOP_RIGHT: + mPopUp.showAtLocation(root, Gravity.TOP | Gravity.RIGHT, 0, 0); + break; + case ConstantsHelper.AD_VIEW_POSITION_BOTTOM_LEFT: + mPopUp.showAtLocation(root, Gravity.BOTTOM | Gravity.LEFT, 0, 0); + break; + case ConstantsHelper.AD_VIEW_POSITION_BOTTOM_RIGHT: + mPopUp.showAtLocation(root, Gravity.BOTTOM | Gravity.RIGHT, 0, 0); + break; + default: + mPopUp.showAtLocation(root, Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, 0); + break; + } } - }; + } + + completeBannerViewFutureCallback(callbackDataPtr, errorCode, errorMessage); + mNotifyBoundingBoxListenerOnNextDraw.set(true); + } + }; } // TODO(b/31391149): This delay is a workaround for b/31391149, and should be removed once @@ -521,7 +507,8 @@ public void onAdClosed() { public void onAdFailedToLoad(LoadAdError loadAdError) { synchronized (mBannerViewLock) { if (mLoadAdCallbackDataPtr != CPP_NULLPTR) { - completeBannerViewLoadAdError(mLoadAdCallbackDataPtr, loadAdError, loadAdError.getCode(), loadAdError.getMessage()); + completeBannerViewLoadAdError( + mLoadAdCallbackDataPtr, loadAdError, loadAdError.getCode(), loadAdError.getMessage()); mLoadAdCallbackDataPtr = CPP_NULLPTR; } } @@ -571,8 +558,8 @@ public void onAdOpened() { public void onPaidEvent(AdValue value) { synchronized (mBannerViewLock) { if (mBannerViewInternalPtr != CPP_NULLPTR) { - notifyPaidEvent(mBannerViewInternalPtr, value.getCurrencyCode(), - value.getPrecisionType(), value.getValueMicros()); + notifyPaidEvent(mBannerViewInternalPtr, value.getCurrencyCode(), value.getPrecisionType(), + value.getValueMicros()); } } } @@ -654,6 +641,6 @@ public static native void completeBannerViewLoadAdInternalError( /** * Native callback to notify the C++ wrapper that a paid event has occurred. */ - public static native void notifyPaidEvent(long nativeInternalPtr, String currencyCode, - int precisionType, long valueMicros); + public static native void notifyPaidEvent( + long nativeInternalPtr, String currencyCode, int precisionType, long valueMicros); } diff --git a/admob/src_java/com/google/firebase/admob/internal/cpp/ConstantsHelper.java b/admob/src_java/com/google/firebase/admob/internal/cpp/ConstantsHelper.java index 5c0f121eb6..d2b355bb1a 100644 --- a/admob/src_java/com/google/firebase/admob/internal/cpp/ConstantsHelper.java +++ b/admob/src_java/com/google/firebase/admob/internal/cpp/ConstantsHelper.java @@ -20,7 +20,6 @@ * Helper class containing constants that are shared across the various AdMob ad formats. */ public final class ConstantsHelper { - /** * Error codes used in completing futures. These match the AdMobError enumeration in the C++ API. */ diff --git a/admob/src_java/com/google/firebase/admob/internal/cpp/InterstitialAdHelper.java b/admob/src_java/com/google/firebase/admob/internal/cpp/InterstitialAdHelper.java index 4624254c3f..315539c799 100644 --- a/admob/src_java/com/google/firebase/admob/internal/cpp/InterstitialAdHelper.java +++ b/admob/src_java/com/google/firebase/admob/internal/cpp/InterstitialAdHelper.java @@ -17,7 +17,7 @@ package com.google.firebase.admob.internal.cpp; import android.app.Activity; - +import android.util.Log; import com.google.android.gms.ads.AdError; import com.google.android.gms.ads.AdRequest; import com.google.android.gms.ads.AdValue; @@ -27,15 +27,12 @@ import com.google.android.gms.ads.interstitial.InterstitialAd; import com.google.android.gms.ads.interstitial.InterstitialAdLoadCallback; -import android.util.Log; - /** * Helper class to make interactions between the AdMob C++ wrapper and Java {@link InterstitialAd} * objects cleaner. It's designed to wrap and adapt a single instance of {@link InterstitialAd}, * translate calls coming from C++ into their (typically more complicated) Java equivalents. */ public class InterstitialAdHelper { - // C++ nullptr for use with the callbacks. private static final long CPP_NULLPTR = 0; @@ -82,30 +79,28 @@ public InterstitialAdHelper(long interstitialAdInternalPtr) { public void initialize(final long callbackDataPtr, Activity activity) { mActivity = activity; - mActivity.runOnUiThread( - new Runnable() { - @Override - public void run() { - int errorCode; - String errorMessage; - if (mInterstitial == null) { - try { - errorCode = ConstantsHelper.CALLBACK_ERROR_NONE; - errorMessage = ConstantsHelper.CALLBACK_ERROR_MESSAGE_NONE; - } catch (IllegalStateException e) { - mInterstitial = null; - // This exception can be thrown if the ad unit ID was already set. - errorCode = ConstantsHelper.CALLBACK_ERROR_ALREADY_INITIALIZED; - errorMessage = ConstantsHelper.CALLBACK_ERROR_MESSAGE_ALREADY_INITIALIZED; - } - } else { - errorCode = ConstantsHelper.CALLBACK_ERROR_ALREADY_INITIALIZED; - errorMessage = ConstantsHelper.CALLBACK_ERROR_MESSAGE_ALREADY_INITIALIZED; - - } - completeInterstitialAdFutureCallback(callbackDataPtr, errorCode, errorMessage); + mActivity.runOnUiThread(new Runnable() { + @Override + public void run() { + int errorCode; + String errorMessage; + if (mInterstitial == null) { + try { + errorCode = ConstantsHelper.CALLBACK_ERROR_NONE; + errorMessage = ConstantsHelper.CALLBACK_ERROR_MESSAGE_NONE; + } catch (IllegalStateException e) { + mInterstitial = null; + // This exception can be thrown if the ad unit ID was already set. + errorCode = ConstantsHelper.CALLBACK_ERROR_ALREADY_INITIALIZED; + errorMessage = ConstantsHelper.CALLBACK_ERROR_MESSAGE_ALREADY_INITIALIZED; } - }); + } else { + errorCode = ConstantsHelper.CALLBACK_ERROR_ALREADY_INITIALIZED; + errorMessage = ConstantsHelper.CALLBACK_ERROR_MESSAGE_ALREADY_INITIALIZED; + } + completeInterstitialAdFutureCallback(callbackDataPtr, errorCode, errorMessage); + } + }); } /** @@ -121,19 +116,18 @@ public void disconnect() { return; } - mActivity.runOnUiThread( - new Runnable() { - @Override - public void run() { - synchronized (mInterstitialLock) { - if (mInterstitial != null) { - mInterstitial.setFullScreenContentCallback(null); - mInterstitial.setOnPaidEventListener(null); - mInterstitial = null; - } - } + mActivity.runOnUiThread(new Runnable() { + @Override + public void run() { + synchronized (mInterstitialLock) { + if (mInterstitial != null) { + mInterstitial.setFullScreenContentCallback(null); + mInterstitial.setOnPaidEventListener(null); + mInterstitial = null; } - }); + } + } + }); } /** @@ -145,8 +139,7 @@ public void loadAd(long callbackDataPtr, String adUnitId, final AdRequest reques } synchronized (mInterstitialLock) { if (mLoadAdCallbackDataPtr != CPP_NULLPTR) { - completeInterstitialLoadAdInternalError( - callbackDataPtr, + completeInterstitialLoadAdInternalError(callbackDataPtr, ConstantsHelper.CALLBACK_ERROR_LOAD_IN_PROGRESS, ConstantsHelper.CALLBACK_ERROR_MESSAGE_LOAD_IN_PROGRESS); return; @@ -156,66 +149,61 @@ public void loadAd(long callbackDataPtr, String adUnitId, final AdRequest reques mAdUnitId = adUnitId; - mActivity.runOnUiThread( - new Runnable() { - @Override - public void run() { - if (mActivity == null) { - synchronized (mInterstitialLock) { - completeInterstitialLoadAdInternalError( - mLoadAdCallbackDataPtr, - ConstantsHelper.CALLBACK_ERROR_UNINITIALIZED, - ConstantsHelper.CALLBACK_ERROR_MESSAGE_UNINITIALIZED); - mLoadAdCallbackDataPtr = CPP_NULLPTR; - } - } else { - try { - InterstitialAd.load(mActivity, mAdUnitId, request, new InterstitialAdListener()); - } catch (IllegalStateException e) { - synchronized (mInterstitialLock) { - completeInterstitialLoadAdInternalError( - mLoadAdCallbackDataPtr, - ConstantsHelper.CALLBACK_ERROR_UNINITIALIZED, - ConstantsHelper.CALLBACK_ERROR_MESSAGE_UNINITIALIZED); - mLoadAdCallbackDataPtr = CPP_NULLPTR; - } - } + mActivity.runOnUiThread(new Runnable() { + @Override + public void run() { + if (mActivity == null) { + synchronized (mInterstitialLock) { + completeInterstitialLoadAdInternalError(mLoadAdCallbackDataPtr, + ConstantsHelper.CALLBACK_ERROR_UNINITIALIZED, + ConstantsHelper.CALLBACK_ERROR_MESSAGE_UNINITIALIZED); + mLoadAdCallbackDataPtr = CPP_NULLPTR; + } + } else { + try { + InterstitialAd.load(mActivity, mAdUnitId, request, new InterstitialAdListener()); + } catch (IllegalStateException e) { + synchronized (mInterstitialLock) { + completeInterstitialLoadAdInternalError(mLoadAdCallbackDataPtr, + ConstantsHelper.CALLBACK_ERROR_UNINITIALIZED, + ConstantsHelper.CALLBACK_ERROR_MESSAGE_UNINITIALIZED); + mLoadAdCallbackDataPtr = CPP_NULLPTR; } } - }); + } + } + }); } /** * Shows a previously loaded ad. */ public void show(final long callbackDataPtr) { - mActivity.runOnUiThread( - new Runnable() { - @Override - public void run() { - synchronized (mInterstitialLock) { - int errorCode; - String errorMessage; - if (mAdUnitId == null) { - errorCode = ConstantsHelper.CALLBACK_ERROR_UNINITIALIZED; - errorMessage = ConstantsHelper.CALLBACK_ERROR_MESSAGE_UNINITIALIZED; - } else if (mInterstitial == null) { - errorCode = ConstantsHelper.CALLBACK_ERROR_LOAD_IN_PROGRESS; - errorMessage = ConstantsHelper.CALLBACK_ERROR_MESSAGE_LOAD_IN_PROGRESS; - } else { - errorCode = ConstantsHelper.CALLBACK_ERROR_NONE; - errorMessage = ConstantsHelper.CALLBACK_ERROR_MESSAGE_NONE; - mInterstitial.show(mActivity); - } - completeInterstitialAdFutureCallback(callbackDataPtr, errorCode, errorMessage); - } + mActivity.runOnUiThread(new Runnable() { + @Override + public void run() { + synchronized (mInterstitialLock) { + int errorCode; + String errorMessage; + if (mAdUnitId == null) { + errorCode = ConstantsHelper.CALLBACK_ERROR_UNINITIALIZED; + errorMessage = ConstantsHelper.CALLBACK_ERROR_MESSAGE_UNINITIALIZED; + } else if (mInterstitial == null) { + errorCode = ConstantsHelper.CALLBACK_ERROR_LOAD_IN_PROGRESS; + errorMessage = ConstantsHelper.CALLBACK_ERROR_MESSAGE_LOAD_IN_PROGRESS; + } else { + errorCode = ConstantsHelper.CALLBACK_ERROR_NONE; + errorMessage = ConstantsHelper.CALLBACK_ERROR_MESSAGE_NONE; + mInterstitial.show(mActivity); } - }); + completeInterstitialAdFutureCallback(callbackDataPtr, errorCode, errorMessage); + } + } + }); } private class InterstitialAdFullScreenContentListener extends FullScreenContentCallback implements OnPaidEventListener { - @Override public void onAdClicked() { synchronized (mInterstitialLock) { @@ -275,8 +263,7 @@ public void onAdFailedToLoad(LoadAdError loadAdError) { synchronized (mInterstitialLock) { if (mLoadAdCallbackDataPtr != CPP_NULLPTR) { completeInterstitialLoadAdError( - mLoadAdCallbackDataPtr, loadAdError, loadAdError.getCode(), - loadAdError.getMessage()); + mLoadAdCallbackDataPtr, loadAdError, loadAdError.getCode(), loadAdError.getMessage()); mLoadAdCallbackDataPtr = CPP_NULLPTR; } } @@ -286,7 +273,8 @@ public void onAdFailedToLoad(LoadAdError loadAdError) { public void onAdLoaded(InterstitialAd ad) { synchronized (mInterstitialLock) { mInterstitial = ad; - InterstitialAdFullScreenContentListener listener = new InterstitialAdFullScreenContentListener(); + InterstitialAdFullScreenContentListener listener = + new InterstitialAdFullScreenContentListener(); mInterstitial.setFullScreenContentCallback(listener); mInterstitial.setOnPaidEventListener(listener); if (mLoadAdCallbackDataPtr != CPP_NULLPTR) { @@ -330,13 +318,13 @@ public static native void completeInterstitialLoadAdInternalError( public static native void notifyAdDismissedFullScreenContentEvent(long nativeInternalPtr); - public static native void notifyAdFailedToShowFullScreenContentEvent(long nativeInternalPtr, - AdError adError); + public static native void notifyAdFailedToShowFullScreenContentEvent( + long nativeInternalPtr, AdError adError); public static native void notifyAdImpressionEvent(long nativeInternalPtr); public static native void notifyAdShowedFullScreenContentEvent(long nativeInternalPtr); - public static native void notifyPaidEvent(long nativeInternalPtr, String currencyCode, - int precisionType, long valueMicros); + public static native void notifyPaidEvent( + long nativeInternalPtr, String currencyCode, int precisionType, long valueMicros); } diff --git a/admob/src_java/com/google/firebase/admob/internal/cpp/RewardedAdHelper.java b/admob/src_java/com/google/firebase/admob/internal/cpp/RewardedAdHelper.java index a162adc97d..2a57579ec6 100644 --- a/admob/src_java/com/google/firebase/admob/internal/cpp/RewardedAdHelper.java +++ b/admob/src_java/com/google/firebase/admob/internal/cpp/RewardedAdHelper.java @@ -17,7 +17,7 @@ package com.google.firebase.admob.internal.cpp; import android.app.Activity; - +import android.util.Log; import com.google.android.gms.ads.AdError; import com.google.android.gms.ads.AdRequest; import com.google.android.gms.ads.AdValue; @@ -25,12 +25,10 @@ import com.google.android.gms.ads.LoadAdError; import com.google.android.gms.ads.OnPaidEventListener; import com.google.android.gms.ads.OnUserEarnedRewardListener; -import com.google.android.gms.ads.rewarded.ServerSideVerificationOptions; +import com.google.android.gms.ads.rewarded.RewardItem; import com.google.android.gms.ads.rewarded.RewardedAd; import com.google.android.gms.ads.rewarded.RewardedAdLoadCallback; -import com.google.android.gms.ads.rewarded.RewardItem; - -import android.util.Log; +import com.google.android.gms.ads.rewarded.ServerSideVerificationOptions; /** * Helper class to make interactions between the AdMob C++ wrapper and Java {@link RewardedAd} @@ -38,7 +36,6 @@ * translate calls coming from C++ into their (typically more complicated) Java equivalents. */ public class RewardedAdHelper { - // C++ nullptr for use with the callbacks. private static final long CPP_NULLPTR = 0; @@ -74,8 +71,7 @@ public RewardedAdHelper(long rewardedAdInternalPtr) { mRewardedLock = new Object(); // Test the callbacks and fail quickly if something's wrong. - completeRewardedAdFutureCallback( - CPP_NULLPTR, 0, ConstantsHelper.CALLBACK_ERROR_MESSAGE_NONE); + completeRewardedAdFutureCallback(CPP_NULLPTR, 0, ConstantsHelper.CALLBACK_ERROR_MESSAGE_NONE); } /** @@ -85,31 +81,30 @@ public RewardedAdHelper(long rewardedAdInternalPtr) { public void initialize(final long callbackDataPtr, Activity activity) { mActivity = activity; - mActivity.runOnUiThread( - new Runnable() { - @Override - public void run() { - int errorCode; - String errorMessage; - synchronized (mRewardedLock) { - if (mRewarded == null) { - try { - errorCode = ConstantsHelper.CALLBACK_ERROR_NONE; - errorMessage = ConstantsHelper.CALLBACK_ERROR_MESSAGE_NONE; - } catch (IllegalStateException e) { - mRewarded = null; - // This exception can be thrown if the ad unit ID was already set. - errorCode = ConstantsHelper.CALLBACK_ERROR_ALREADY_INITIALIZED; - errorMessage = ConstantsHelper.CALLBACK_ERROR_MESSAGE_ALREADY_INITIALIZED; - } - } else { - errorCode = ConstantsHelper.CALLBACK_ERROR_ALREADY_INITIALIZED; - errorMessage = ConstantsHelper.CALLBACK_ERROR_MESSAGE_ALREADY_INITIALIZED; - } - completeRewardedAdFutureCallback(callbackDataPtr, errorCode, errorMessage); + mActivity.runOnUiThread(new Runnable() { + @Override + public void run() { + int errorCode; + String errorMessage; + synchronized (mRewardedLock) { + if (mRewarded == null) { + try { + errorCode = ConstantsHelper.CALLBACK_ERROR_NONE; + errorMessage = ConstantsHelper.CALLBACK_ERROR_MESSAGE_NONE; + } catch (IllegalStateException e) { + mRewarded = null; + // This exception can be thrown if the ad unit ID was already set. + errorCode = ConstantsHelper.CALLBACK_ERROR_ALREADY_INITIALIZED; + errorMessage = ConstantsHelper.CALLBACK_ERROR_MESSAGE_ALREADY_INITIALIZED; } + } else { + errorCode = ConstantsHelper.CALLBACK_ERROR_ALREADY_INITIALIZED; + errorMessage = ConstantsHelper.CALLBACK_ERROR_MESSAGE_ALREADY_INITIALIZED; } - }); + completeRewardedAdFutureCallback(callbackDataPtr, errorCode, errorMessage); + } + } + }); } /** @@ -125,19 +120,18 @@ public void disconnect() { return; } - mActivity.runOnUiThread( - new Runnable() { - @Override - public void run() { - synchronized (mRewardedLock) { - if (mRewarded != null) { - mRewarded.setFullScreenContentCallback(null); - mRewarded.setOnPaidEventListener(null); - mRewarded = null; - } - } + mActivity.runOnUiThread(new Runnable() { + @Override + public void run() { + synchronized (mRewardedLock) { + if (mRewarded != null) { + mRewarded.setFullScreenContentCallback(null); + mRewarded.setOnPaidEventListener(null); + mRewarded = null; } - }); + } + } + }); } /** @@ -149,8 +143,7 @@ public void loadAd(long callbackDataPtr, String adUnitId, final AdRequest reques } synchronized (mRewardedLock) { if (mLoadAdCallbackDataPtr != CPP_NULLPTR) { - completeRewardedLoadAdInternalError( - callbackDataPtr, + completeRewardedLoadAdInternalError(callbackDataPtr, ConstantsHelper.CALLBACK_ERROR_LOAD_IN_PROGRESS, ConstantsHelper.CALLBACK_ERROR_MESSAGE_LOAD_IN_PROGRESS); return; @@ -160,79 +153,72 @@ public void loadAd(long callbackDataPtr, String adUnitId, final AdRequest reques mAdUnitId = adUnitId; - mActivity.runOnUiThread( - new Runnable() { - @Override - public void run() { - synchronized (mRewardedLock) { - if (mActivity == null) { - completeRewardedLoadAdInternalError( - mLoadAdCallbackDataPtr, + mActivity.runOnUiThread(new Runnable() { + @Override + public void run() { + synchronized (mRewardedLock) { + if (mActivity == null) { + completeRewardedLoadAdInternalError(mLoadAdCallbackDataPtr, ConstantsHelper.CALLBACK_ERROR_UNINITIALIZED, ConstantsHelper.CALLBACK_ERROR_MESSAGE_UNINITIALIZED); - mLoadAdCallbackDataPtr = CPP_NULLPTR; - } - else { - try { - RewardedAd.load(mActivity, mAdUnitId, request, new RewardedAdListener()); - } catch (IllegalStateException e) { - completeRewardedLoadAdInternalError( - mLoadAdCallbackDataPtr, + mLoadAdCallbackDataPtr = CPP_NULLPTR; + } else { + try { + RewardedAd.load(mActivity, mAdUnitId, request, new RewardedAdListener()); + } catch (IllegalStateException e) { + completeRewardedLoadAdInternalError(mLoadAdCallbackDataPtr, ConstantsHelper.CALLBACK_ERROR_UNINITIALIZED, ConstantsHelper.CALLBACK_ERROR_MESSAGE_UNINITIALIZED); - mLoadAdCallbackDataPtr = CPP_NULLPTR; - } + mLoadAdCallbackDataPtr = CPP_NULLPTR; } } } - }); + } + }); } /** * Shows a previously loaded ad. */ public void show(final long callbackDataPtr, final String verificationCustomData, - final String verificationUserId) { - mActivity.runOnUiThread( - new Runnable() { - @Override - public void run() { - synchronized (mRewardedLock) { - int errorCode; - String errorMessage; - if (mAdUnitId == null) { - errorCode = ConstantsHelper.CALLBACK_ERROR_UNINITIALIZED; - errorMessage = ConstantsHelper.CALLBACK_ERROR_MESSAGE_UNINITIALIZED; - } else if (mRewarded == null) { - errorCode = ConstantsHelper.CALLBACK_ERROR_LOAD_IN_PROGRESS; - errorMessage = ConstantsHelper.CALLBACK_ERROR_MESSAGE_LOAD_IN_PROGRESS; - } else { - errorCode = ConstantsHelper.CALLBACK_ERROR_NONE; - errorMessage = ConstantsHelper.CALLBACK_ERROR_MESSAGE_NONE; - if (!verificationCustomData.isEmpty() || !verificationUserId.isEmpty()) { - ServerSideVerificationOptions options = - new ServerSideVerificationOptions.Builder() - .setCustomData(verificationCustomData) - .setUserId(verificationUserId).build(); - mRewarded.setServerSideVerificationOptions(options); - } - mRewarded.show( - mActivity, - new UserEarnedRewardListener()); - } - completeRewardedAdFutureCallback(callbackDataPtr, errorCode, errorMessage); + final String verificationUserId) { + mActivity.runOnUiThread(new Runnable() { + @Override + public void run() { + synchronized (mRewardedLock) { + int errorCode; + String errorMessage; + if (mAdUnitId == null) { + errorCode = ConstantsHelper.CALLBACK_ERROR_UNINITIALIZED; + errorMessage = ConstantsHelper.CALLBACK_ERROR_MESSAGE_UNINITIALIZED; + } else if (mRewarded == null) { + errorCode = ConstantsHelper.CALLBACK_ERROR_LOAD_IN_PROGRESS; + errorMessage = ConstantsHelper.CALLBACK_ERROR_MESSAGE_LOAD_IN_PROGRESS; + } else { + errorCode = ConstantsHelper.CALLBACK_ERROR_NONE; + errorMessage = ConstantsHelper.CALLBACK_ERROR_MESSAGE_NONE; + if (!verificationCustomData.isEmpty() || !verificationUserId.isEmpty()) { + ServerSideVerificationOptions options = new ServerSideVerificationOptions.Builder() + .setCustomData(verificationCustomData) + .setUserId(verificationUserId) + .build(); + mRewarded.setServerSideVerificationOptions(options); } + mRewarded.show(mActivity, new UserEarnedRewardListener()); } - }); + completeRewardedAdFutureCallback(callbackDataPtr, errorCode, errorMessage); + } + } + }); } - private class UserEarnedRewardListener - implements OnUserEarnedRewardListener { + private class UserEarnedRewardListener implements OnUserEarnedRewardListener { @Override public void onUserEarnedReward(RewardItem rewardItem) { synchronized (mRewardedLock) { if (mRewardedAdInternalPtr != CPP_NULLPTR) { - notifyUserEarnedRewardEvent(mRewardedAdInternalPtr, rewardItem.getType(), rewardItem.getAmount()); + notifyUserEarnedRewardEvent( + mRewardedAdInternalPtr, rewardItem.getType(), rewardItem.getAmount()); } } } @@ -288,8 +274,8 @@ public void onAdShowedFullScreenContent() { public void onPaidEvent(AdValue value) { synchronized (mRewardedLock) { if (mRewardedAdInternalPtr != CPP_NULLPTR) { - notifyPaidEvent(mRewardedAdInternalPtr, value.getCurrencyCode(), - value.getPrecisionType(), value.getValueMicros()); + notifyPaidEvent(mRewardedAdInternalPtr, value.getCurrencyCode(), value.getPrecisionType(), + value.getValueMicros()); } } } @@ -301,8 +287,7 @@ public void onAdFailedToLoad(LoadAdError loadAdError) { synchronized (mRewardedLock) { if (mLoadAdCallbackDataPtr != CPP_NULLPTR) { completeRewardedLoadAdError( - mLoadAdCallbackDataPtr, loadAdError, loadAdError.getCode(), - loadAdError.getMessage()); + mLoadAdCallbackDataPtr, loadAdError, loadAdError.getCode(), loadAdError.getMessage()); mLoadAdCallbackDataPtr = CPP_NULLPTR; } } @@ -359,13 +344,13 @@ public static native void notifyUserEarnedRewardEvent( public static native void notifyAdDismissedFullScreenContentEvent(long nativeInternalPtr); - public static native void notifyAdFailedToShowFullScreenContentEvent(long nativeInternalPtr, - AdError adError); + public static native void notifyAdFailedToShowFullScreenContentEvent( + long nativeInternalPtr, AdError adError); public static native void notifyAdImpressionEvent(long nativeInternalPtr); public static native void notifyAdShowedFullScreenContentEvent(long nativeInternalPtr); - public static native void notifyPaidEvent(long nativeInternalPtr, String currencyCode, - int precisionType, long valueMicros); + public static native void notifyPaidEvent( + long nativeInternalPtr, String currencyCode, int precisionType, long valueMicros); } diff --git a/admob/tools/ios/testapp/testapp/ViewController.mm b/admob/tools/ios/testapp/testapp/ViewController.mm index fe9446ac0b..f2cf791b66 100644 --- a/admob/tools/ios/testapp/testapp/ViewController.mm +++ b/admob/tools/ios/testapp/testapp/ViewController.mm @@ -52,7 +52,7 @@ - (void)setUpGL { // Set up the UITapGestureRecognizer for the GLKView. UITapGestureRecognizer *tapRecognizer = - [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)]; + [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)]; tapRecognizer.numberOfTapsRequired = 1; [self.view addGestureRecognizer:tapRecognizer]; } @@ -123,7 +123,7 @@ - (void)handleTap:(UITapGestureRecognizer *)recognizer { #pragma mark - Log Message // Log a message that can be viewed in the console. -int LogMessage(const char* format, ...) { +int LogMessage(const char *format, ...) { va_list list; int rc = 0; va_start(list, format); diff --git a/admob/tools/ios/testapp/testapp/main.m b/admob/tools/ios/testapp/testapp/main.m index 35f5ab1db6..a6b3b3ebd4 100644 --- a/admob/tools/ios/testapp/testapp/main.m +++ b/admob/tools/ios/testapp/testapp/main.m @@ -3,9 +3,8 @@ #import #import "AppDelegate.h" -int main(int argc, char * argv[]) { +int main(int argc, char* argv[]) { @autoreleasepool { - return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class])); + return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class])); } - } diff --git a/analytics/src/analytics_ios.mm b/analytics/src/analytics_ios.mm index fac7514acc..dd36d1987f 100644 --- a/analytics/src/analytics_ios.mm +++ b/analytics/src/analytics_ios.mm @@ -21,12 +21,12 @@ #include "analytics/src/include/firebase/analytics.h" #include "analytics/src/analytics_common.h" -#include "app/src/include/firebase/version.h" #include "app/src/assert.h" +#include "app/src/include/firebase/version.h" #include "app/src/log.h" #include "app/src/mutex.h" -#include "app/src/time.h" #include "app/src/thread.h" +#include "app/src/time.h" #include "app/src/util.h" #include "app/src/util_ios.h" @@ -41,6 +41,7 @@ kResetStateRequested, kResetStateRetry, }; + public: // Initialize the class. AnalyticsDataResetter() : reset_state_(kResetStateNone), reset_timestamp_(0) {} @@ -114,7 +115,7 @@ uint64_t GetResetTimeElapsedMilliseconds() const { static const double kMillisecondsPerSecond = 1000.0; static Mutex g_mutex; // NOLINT static bool g_initialized = false; -static AnalyticsDataResetter *g_resetter = nullptr; +static AnalyticsDataResetter* g_resetter = nullptr; // Initialize the API. void Initialize(const ::firebase::App& app) { @@ -213,10 +214,9 @@ void LogEvent(const char* name, const Parameter* parameters, size_t number_of_pa [parameters_dict setObject:[NSNumber numberWithLongLong:0] forKey:parameter_name]; } else { // Vector or Map were passed in. - LogError( - "LogEvent(%s): %s is not a valid parameter value type. " - "Container types are not allowed. No event was logged.", - parameter.name, Variant::TypeName(parameter.value.type())); + LogError("LogEvent(%s): %s is not a valid parameter value type. " + "Container types are not allowed. No event was logged.", + parameter.name, Variant::TypeName(parameter.value.type())); } } [FIRAnalytics logEventWithName:@(name) parameters:parameters_dict]; @@ -253,25 +253,26 @@ void ResetAnalyticsData() { MutexLock lock(g_mutex); FIREBASE_ASSERT_RETURN(Future(), internal::IsInitialized()); auto* api = internal::FutureData::Get()->api(); - const auto future_handle = api->SafeAlloc( - internal::kAnalyticsFnGetAnalyticsInstanceId); + const auto future_handle = + api->SafeAlloc(internal::kAnalyticsFnGetAnalyticsInstanceId); static int kPollTimeMs = 100; - Thread get_id_thread([](SafeFutureHandle* handle) { - for ( ; ; ) { - { - MutexLock lock(g_mutex); - if (!internal::IsInitialized()) break; - std::string instance_id = g_resetter->GetInstanceId(); - if (!instance_id.empty()) { - internal::FutureData::Get()->api()->CompleteWithResult( - *handle, 0, "", instance_id); - break; + Thread get_id_thread( + [](SafeFutureHandle* handle) { + for (;;) { + { + MutexLock lock(g_mutex); + if (!internal::IsInitialized()) break; + std::string instance_id = g_resetter->GetInstanceId(); + if (!instance_id.empty()) { + internal::FutureData::Get()->api()->CompleteWithResult(*handle, 0, "", instance_id); + break; + } } + firebase::internal::Sleep(kPollTimeMs); } - firebase::internal::Sleep(kPollTimeMs); - } - delete handle; - }, new SafeFutureHandle(future_handle)); + delete handle; + }, + new SafeFutureHandle(future_handle)); get_id_thread.Detach(); return Future(api, future_handle.get()); } @@ -280,8 +281,7 @@ Thread get_id_thread([](SafeFutureHandle* handle) { MutexLock lock(g_mutex); FIREBASE_ASSERT_RETURN(Future(), internal::IsInitialized()); return static_cast&>( - internal::FutureData::Get()->api()->LastResult( - internal::kAnalyticsFnGetAnalyticsInstanceId)); + internal::FutureData::Get()->api()->LastResult(internal::kAnalyticsFnGetAnalyticsInstanceId)); } } // namespace measurement diff --git a/analytics/src_java/fake/com/google/firebase/analytics/FirebaseAnalytics.java b/analytics/src_java/fake/com/google/firebase/analytics/FirebaseAnalytics.java index 5e212db71e..8be63c473d 100644 --- a/analytics/src_java/fake/com/google/firebase/analytics/FirebaseAnalytics.java +++ b/analytics/src_java/fake/com/google/firebase/analytics/FirebaseAnalytics.java @@ -22,14 +22,12 @@ import com.google.android.gms.tasks.Task; import com.google.firebase.testing.cppsdk.FakeReporter; import com.google.firebase.testing.cppsdk.TickerAndroid; - import java.util.TreeSet; /** * Fake for FirebaseAnalytics. */ public final class FirebaseAnalytics { - public static FirebaseAnalytics getInstance(Context context) { FakeReporter.addReport("FirebaseAnalytics.getInstance"); return new FirebaseAnalytics(); @@ -43,8 +41,8 @@ public Task getAppInstanceId() { } public void setAnalyticsCollectionEnabled(boolean enabled) { - FakeReporter.addReport("FirebaseAnalytics.setAnalyticsCollectionEnabled", - Boolean.toString(enabled)); + FakeReporter.addReport( + "FirebaseAnalytics.setAnalyticsCollectionEnabled", Boolean.toString(enabled)); } public void logEvent(String name, Bundle params) { @@ -73,13 +71,12 @@ public void setUserId(String userId) { } public void setMinimumSessionDuration(long milliseconds) { - FakeReporter.addReport("FirebaseAnalytics.setMinimumSessionDuration", - Long.toString(milliseconds)); + FakeReporter.addReport( + "FirebaseAnalytics.setMinimumSessionDuration", Long.toString(milliseconds)); } public void setSessionTimeoutDuration(long milliseconds) { - FakeReporter.addReport("FirebaseAnalytics.setSessionTimeoutDuration", - Long.toString(milliseconds)); + FakeReporter.addReport( + "FirebaseAnalytics.setSessionTimeoutDuration", Long.toString(milliseconds)); } - } diff --git a/app/src/app_ios.mm b/app/src/app_ios.mm index 11e50d4332..e2c649482d 100644 --- a/app/src/app_ios.mm +++ b/app/src/app_ios.mm @@ -19,10 +19,10 @@ #include #include -#include "app/src/include/firebase/version.h" #include "app/src/app_common.h" #include "app/src/app_ios.h" #include "app/src/assert.h" +#include "app/src/include/firebase/version.h" #include "app/src/log.h" #include "app/src/mutex.h" #include "app/src/util.h" @@ -37,11 +37,10 @@ @interface FIRApp () + (BOOL)isDefaultAppConfigured; // Internal method (should be part of the public API *soon*) that allows registration of a library // at the specified version which is added to the firebaseUserAgent string. -+ (void)registerLibrary:(NSString *)library - withVersion:(NSString *)version; ++ (void)registerLibrary:(NSString*)library withVersion:(NSString*)version; // Use the private method firebaseUserAgent to get propagate the set of register libraries into // the C++ SDK. -+ (NSString *)firebaseUserAgent; ++ (NSString*)firebaseUserAgent; @end namespace firebase { @@ -51,8 +50,7 @@ + (NSString *)firebaseUserAgent; namespace { // Copy values of FIROptions into AppOptions. -static void PlatformOptionsToAppOptions(FIROptions* platform_options, - AppOptions* app_options) { +static void PlatformOptionsToAppOptions(FIROptions* platform_options, AppOptions* app_options) { if (!strlen(app_options->app_id())) { const char* value = platform_options.googleAppID.UTF8String; if (value) app_options->set_app_id(value); @@ -93,8 +91,7 @@ static void PlatformOptionsToAppOptions(FIROptions* platform_options, // Copy AppOptions into a FIROptions instance. static FIROptions* AppOptionsToPlatformOptions(const AppOptions& app_options) { - FIROptions* platform_options = [[FIROptions alloc] initWithGoogleAppID:@"" - GCMSenderID:@""]; + FIROptions* platform_options = [[FIROptions alloc] initWithGoogleAppID:@"" GCMSenderID:@""]; if (strlen(app_options.app_id())) { platform_options.googleAppID = @(app_options.app_id()); } @@ -130,8 +127,8 @@ static void PlatformOptionsToAppOptions(FIROptions* platform_options, // Silence iOS SDKs warnings about FIRApp instances being missing. LogLevel log_level = GetLogLevel(); SetLogLevel(kLogLevelAssert); - FIRApp *platform_app = app_common::IsDefaultAppName(name) ? - [FIRApp defaultApp] : [FIRApp appNamed:@(name)]; + FIRApp* platform_app = + app_common::IsDefaultAppName(name) ? [FIRApp defaultApp] : [FIRApp appNamed:@(name)]; SetLogLevel(log_level); return platform_app; } @@ -175,8 +172,7 @@ static void PlatformOptionsToAppOptions(FIROptions* platform_options, } // Create or get a iOS SDK FIRApp instance. -static FIRApp* CreateOrGetPlatformApp(const AppOptions& options, - const char* name) { +static FIRApp* CreateOrGetPlatformApp(const AppOptions& options, const char* name) { FIRApp* platform_app = GetPlatformAppByName(name); if (platform_app) { // If a FIRApp exists, make sure it has the requested options. @@ -185,17 +181,19 @@ static void PlatformOptionsToAppOptions(FIROptions* platform_options, if (options != existing_options) { LogWarning("Existing instance of App %s found and options do not match " "the requested options. Deleting %s to attempt recreation " - "with requested options.", name, name); + "with requested options.", + name, name); dispatch_semaphore_t block_semaphore = dispatch_semaphore_create(0); [platform_app deleteApp:^(BOOL /*success*/) { - // NOTE: The delete will always succeed if the app previously existed. - dispatch_semaphore_signal(block_semaphore); - }]; + // NOTE: The delete will always succeed if the app previously existed. + dispatch_semaphore_signal(block_semaphore); + }]; dispatch_semaphore_wait(block_semaphore, DISPATCH_TIME_FOREVER); platform_app = nil; } } - return platform_app ? platform_app : CreatePlatformApp(options, name);; + return platform_app ? platform_app : CreatePlatformApp(options, name); + ; } } // namespace @@ -215,7 +213,8 @@ static void PlatformOptionsToAppOptions(FIROptions* platform_options, } else { LogError("Failed to read Firebase options from the app's resources (%s). " "Either make sure GoogleService-Info.plist is included in your build or specify " - "options explicitly.", util::NSStringToString(error_message).c_str()); + "options explicitly.", + util::NSStringToString(error_message).c_str()); } return app_options; } @@ -263,11 +262,9 @@ static void PlatformOptionsToAppOptions(FIROptions* platform_options, util::NSStringToString([FIRApp firebaseUserAgent]).c_str()); } -const char* App::GetUserAgent() { - return app_common::GetUserAgent(); -} +const char* App::GetUserAgent() { return app_common::GetUserAgent(); } -void App::SetDefaultConfigPath(const char* path) { } +void App::SetDefaultConfigPath(const char* path) {} void App::SetDataCollectionDefaultEnabled(bool enabled) { GetPlatformApp().dataCollectionDefaultEnabled = (enabled ? YES : NO); @@ -277,8 +274,6 @@ static void PlatformOptionsToAppOptions(FIROptions* platform_options, return GetPlatformApp().isDataCollectionDefaultEnabled ? true : false; } -FIRApp* App::GetPlatformApp() const { - return internal_->get(); -} +FIRApp* App::GetPlatformApp() const { return internal_->get(); } } // namespace firebase diff --git a/app/src/callback.h b/app/src/callback.h index 2f4f555f2d..3666e9f9e3 100644 --- a/app/src/callback.h +++ b/app/src/callback.h @@ -24,7 +24,6 @@ #include #endif - /// @cond FIREBASE_APP_INTERNAL /// This file is intended for use with the C# interfaces, to allow registration diff --git a/app/src/filesystem_apple.mm b/app/src/filesystem_apple.mm index 71082d102a..5e1727aff6 100644 --- a/app/src/filesystem_apple.mm +++ b/app/src/filesystem_apple.mm @@ -53,11 +53,11 @@ bool Mkdir(const std::string& path, std::string* out_error) { } #if TARGET_OS_IOS || TARGET_OS_OSX - NSArray* directories = NSSearchPathForDirectoriesInDomains( - NSApplicationSupportDirectory, NSUserDomainMask, YES); + NSArray* directories = + NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES); #elif TARGET_OS_TV - NSArray* directories = NSSearchPathForDirectoriesInDomains( - NSCachesDirectory, NSUserDomainMask, YES); + NSArray* directories = + NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES); #else #error "Don't know where to store documents on this platform." #endif diff --git a/app/src/include/firebase/app.h b/app/src/include/firebase/app.h index 29c502e2f2..1758703391 100644 --- a/app/src/include/firebase/app.h +++ b/app/src/include/firebase/app.h @@ -51,8 +51,8 @@ class AppInternal; } // namespace internal #if FIREBASE_PLATFORM_ANDROID && defined(__GLIBCXX__) -#warning "Firebase support for gnustl is deprecated and will be removed in \ - the next major release. Please use libc++ instead." +#warning \ + "Firebase support for gnustl is deprecated and will be removed in the next major release. Please use libc++ instead." #endif /// @brief Reports whether a Firebase module initialized successfully. @@ -720,24 +720,25 @@ class App { /// @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 // FIREBASE_PLATFORM_ANDROID, FIREBASE_PLATFORM_IOS, + // FIREBASE_PLATFORM_TVOS #endif // INTERNAL_EXPERIMENTAL private: /// Construct the object. - App() : + App() + : #if FIREBASE_PLATFORM_ANDROID || defined(DOXYGEN) - activity_(nullptr), + activity_(nullptr), #endif - internal_(nullptr) { + internal_(nullptr) { Initialize(); #ifdef FIREBASE_LINUX_BUILD_CONFIG_STRING - CheckCompilerString(FIREBASE_LINUX_BUILD_CONFIG_STRING); + CheckCompilerString(FIREBASE_LINUX_BUILD_CONFIG_STRING); #endif // FIREBASE_LINUX_BUILD_CONFIG_STRING } - /// Initialize internal implementation void Initialize(); diff --git a/app/src/include/firebase/future.h b/app/src/include/firebase/future.h index 15c42d5352..3f63b3e079 100644 --- a/app/src/include/firebase/future.h +++ b/app/src/include/firebase/future.h @@ -20,6 +20,7 @@ #include #include +#include #include #include "firebase/internal/common.h" @@ -309,6 +310,7 @@ class FutureBase { /// Returns true if the two Futures reference the same result. bool operator==(const FutureBase& rhs) const { + std::lock_guard lock(mutex_); return api_ == rhs.api_ && handle_ == rhs.handle_; } @@ -317,12 +319,17 @@ class FutureBase { #if defined(INTERNAL_EXPERIMENTAL) /// Returns the API-specific handle. Should only be called by the API. - const FutureHandle& GetHandle() const { return handle_; } + FutureHandle GetHandle() const { + std::lock_guard lock(mutex_); + return handle_; + } #endif // defined(INTERNAL_EXPERIMENTAL) protected: /// @cond FIREBASE_APP_INTERNAL + mutable std::mutex mutex_; + /// Backpointer to the issuing API class. /// Set to nullptr when Future is invalidated. detail::FutureApiInterface* api_; diff --git a/app/src/include/firebase/internal/future_impl.h b/app/src/include/firebase/internal/future_impl.h index 5e4d0a74a0..86bad3e8d2 100644 --- a/app/src/include/firebase/internal/future_impl.h +++ b/app/src/include/firebase/internal/future_impl.h @@ -27,7 +27,6 @@ #include #endif // defined(FIREBASE_USE_MOVE_OPERATORS) - namespace firebase { class ReferenceCountedFutureImpl; @@ -207,17 +206,30 @@ inline FutureBase::FutureBase(const FutureBase& rhs) : api_(NULL) // NOLINT { // NOLINT *this = rhs; - detail::RegisterForCleanup(api_, this); } inline FutureBase& FutureBase::operator=(const FutureBase& rhs) { Release(); - api_ = rhs.api_; - handle_ = rhs.handle_; - if (api_ != NULL) { // NOLINT - api_->ReferenceFuture(handle_); + + detail::FutureApiInterface* new_api; + FutureHandle new_handle; + { + std::lock_guard lock(rhs.mutex_); + new_api = rhs.api_; + new_handle = rhs.handle_; } - detail::RegisterForCleanup(api_, this); + + { + std::lock_guard lock(mutex_); + api_ = new_api; + handle_ = new_handle; + + if (api_ != NULL) { // NOLINT + api_->ReferenceFuture(handle_); + } + detail::RegisterForCleanup(api_, this); + } + return *this; } @@ -225,23 +237,32 @@ inline FutureBase& FutureBase::operator=(const FutureBase& rhs) { inline FutureBase::FutureBase(FutureBase&& rhs) noexcept : api_(NULL) // NOLINT { - detail::UnregisterForCleanup(rhs.api_, &rhs); *this = std::move(rhs); - detail::RegisterForCleanup(api_, this); } inline FutureBase& FutureBase::operator=(FutureBase&& rhs) noexcept { Release(); - detail::UnregisterForCleanup(rhs.api_, &rhs); - api_ = rhs.api_; - handle_ = rhs.handle_; - rhs.api_ = NULL; // NOLINT + + detail::FutureApiInterface* new_api; + FutureHandle new_handle; + { + std::lock_guard lock(rhs.mutex_); + detail::UnregisterForCleanup(rhs.api_, &rhs); + new_api = rhs.api_; + new_handle = rhs.handle_; + rhs.api_ = NULL; // NOLINT + } + + std::lock_guard lock(mutex_); + api_ = new_api; + handle_ = new_handle; detail::RegisterForCleanup(api_, this); return *this; } #endif // defined(FIREBASE_USE_MOVE_OPERATORS) inline void FutureBase::Release() { + std::lock_guard lock(mutex_); if (api_ != NULL) { // NOLINT detail::UnregisterForCleanup(api_, this); api_->ReleaseFuture(handle_); @@ -250,25 +271,30 @@ inline void FutureBase::Release() { } inline FutureStatus FutureBase::status() const { + std::lock_guard lock(mutex_); return api_ == NULL ? // NOLINT kFutureStatusInvalid : api_->GetFutureStatus(handle_); } inline int FutureBase::error() const { + std::lock_guard lock(mutex_); return api_ == NULL ? -1 : api_->GetFutureError(handle_); // NOLINT } inline const char* FutureBase::error_message() const { + std::lock_guard lock(mutex_); return api_ == NULL ? NULL : api_->GetFutureErrorMessage(handle_); // NOLINT } inline const void* FutureBase::result_void() const { + std::lock_guard lock(mutex_); return api_ == NULL ? NULL : api_->GetFutureResult(handle_); // NOLINT } inline void FutureBase::OnCompletion(CompletionCallback callback, void* user_data) const { + std::lock_guard lock(mutex_); if (api_ != NULL) { // NOLINT api_->AddCompletionCallback(handle_, callback, user_data, nullptr, /*clear_existing_callbacks=*/true); @@ -278,6 +304,7 @@ inline void FutureBase::OnCompletion(CompletionCallback callback, #if defined(INTERNAL_EXPERIMENTAL) inline FutureBase::CompletionCallbackHandle FutureBase::AddOnCompletion( CompletionCallback callback, void* user_data) const { + std::lock_guard lock(mutex_); if (api_ != NULL) { // NOLINT return api_->AddCompletionCallback(handle_, callback, user_data, nullptr, /*clear_existing_callbacks=*/false); @@ -287,6 +314,7 @@ inline FutureBase::CompletionCallbackHandle FutureBase::AddOnCompletion( inline void FutureBase::RemoveOnCompletion( CompletionCallbackHandle completion_handle) const { + std::lock_guard lock(mutex_); if (api_ != NULL) { // NOLINT api_->RemoveCompletionCallback(handle_, completion_handle); } @@ -296,6 +324,7 @@ inline void FutureBase::RemoveOnCompletion( #if defined(FIREBASE_USE_STD_FUNCTION) inline void FutureBase::OnCompletion( std::function callback) const { + std::lock_guard lock(mutex_); if (api_ != NULL) { // NOLINT api_->AddCompletionCallbackLambda(handle_, callback, /*clear_existing_callbacks=*/true); @@ -305,6 +334,7 @@ inline void FutureBase::OnCompletion( #if defined(INTERNAL_EXPERIMENTAL) inline FutureBase::CompletionCallbackHandle FutureBase::AddOnCompletion( std::function callback) const { + std::lock_guard lock(mutex_); if (api_ != NULL) { // NOLINT return api_->AddCompletionCallbackLambda( handle_, callback, diff --git a/app/src/log_ios.mm b/app/src/log_ios.mm index 0c31d549ad..ddeef37b6e 100644 --- a/app/src/log_ios.mm +++ b/app/src/log_ios.mm @@ -31,14 +31,14 @@ // Maps C++ to iOS SDK log levels. static const FIRLoggerLevel kCppToIOSLogLevel[] = { - FIRLoggerLevelDebug, // kLogLevelVerbose = 0, - // Mapping C++ debug to Obj-C info is intentional. - // Info messages are intended to be shown only for debugging scenarios. - FIRLoggerLevelInfo, // kLogLevelDebug, - FIRLoggerLevelNotice, // kLogLevelInfo, - FIRLoggerLevelWarning, // kLogLevelWarning, - FIRLoggerLevelError, // kLogLevelError, - FIRLoggerLevelError, // kLogLevelAssert, + FIRLoggerLevelDebug, // kLogLevelVerbose = 0, + // Mapping C++ debug to Obj-C info is intentional. + // Info messages are intended to be shown only for debugging scenarios. + FIRLoggerLevelInfo, // kLogLevelDebug, + FIRLoggerLevelNotice, // kLogLevelInfo, + FIRLoggerLevelWarning, // kLogLevelWarning, + FIRLoggerLevelError, // kLogLevelError, + FIRLoggerLevelError, // kLogLevelAssert, }; // Initialize the logging system. @@ -46,8 +46,8 @@ void LogInitialize() { static bool read_log_level_from_plist = false; if (read_log_level_from_plist) return; read_log_level_from_plist = true; - NSNumber* log_level_number = (NSNumber*)( - [[NSBundle mainBundle] objectForInfoDictionaryKey:kLogLevelInfoPlistKey]); + NSNumber* log_level_number = + (NSNumber*)([[NSBundle mainBundle] objectForInfoDictionaryKey:kLogLevelInfoPlistKey]); if (log_level_number) { int log_level_value = log_level_number.intValue; if (log_level_value >= kLogLevelVerbose && log_level_value <= kLogLevelAssert) { diff --git a/app/src/reference_counted_future_impl.h b/app/src/reference_counted_future_impl.h index 0517f6c084..6e4e06043f 100644 --- a/app/src/reference_counted_future_impl.h +++ b/app/src/reference_counted_future_impl.h @@ -22,12 +22,10 @@ #include #include "app/src/cleanup_notifier.h" +#include "app/src/include/firebase/future.h" #include "app/src/include/firebase/internal/common.h" #include "app/src/mutex.h" - -#include "app/src/include/firebase/future.h" - namespace firebase { // FutureBackingData holds the important data for each Future. These are held by diff --git a/app/src/secure/user_secure_darwin_internal.mm b/app/src/secure/user_secure_darwin_internal.mm index 873047addb..c5fe84ed5d 100644 --- a/app/src/secure/user_secure_darwin_internal.mm +++ b/app/src/secure/user_secure_darwin_internal.mm @@ -172,9 +172,7 @@ DeleteData(app_name.c_str(), "DeleteUserData"); } -void UserSecureDarwinInternal::DeleteAllData() { - DeleteData(nullptr, "DeleteAllData"); -} +void UserSecureDarwinInternal::DeleteAllData() { DeleteData(nullptr, "DeleteAllData"); } } // namespace secure } // namespace app diff --git a/app/src/util_ios.h b/app/src/util_ios.h index 70baf1db89..f059e3953a 100644 --- a/app/src/util_ios.h +++ b/app/src/util_ios.h @@ -120,7 +120,7 @@ class ObjCPointer { public: \ class_name() {} \ explicit class_name( \ - const firebase::util::ObjCPointer& obj) \ + const firebase::util::ObjCPointer &obj) \ : firebase::util::ObjCPointer(obj) {} \ explicit class_name(objc_type_name *_Nullable objc_object) \ : firebase::util::ObjCPointer(objc_object) {} \ diff --git a/app/src/util_ios.mm b/app/src/util_ios.mm index afb6d7c354..8be02dd709 100644 --- a/app/src/util_ios.mm +++ b/app/src/util_ios.mm @@ -58,8 +58,7 @@ - (void)application:(UIApplication *)application } - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo - fetchCompletionHandler: - (void (^)(UIBackgroundFetchResult result))handler { + fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))handler { } #if defined(__IPHONE_12_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_12_0 - (BOOL)application:(UIApplication *)application @@ -74,7 +73,7 @@ - (BOOL)application:(UIApplication *)application restorationHandler:(void (^)(NSArray *))restorationHandler { return NO; } -#endif // defined(__IPHONE_12_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_12_0 +#endif // defined(__IPHONE_12_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_12_0 @end namespace firebase { @@ -102,8 +101,11 @@ void ForEachAppDelegateClass(void (^block)(Class)) { } } if (!blacklisted) { - ::firebase::LogDebug("Firebase: Found UIApplicationDelegate class %s", - class_name); + if (GetLogLevel() <= kLogLevelDebug) { + // Call NSLog directly because we may be in a +load method, + // and C++ classes may not be constructed yet. + NSLog(@"Firebase: Found UIApplicationDelegate class %s", class_name); + } block(clazz); } } @@ -111,8 +113,7 @@ void ForEachAppDelegateClass(void (^block)(Class)) { free(classes); } -NSDictionary *StringMapToNSDictionary( - const std::map &string_map) { +NSDictionary *StringMapToNSDictionary(const std::map &string_map) { NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init]; for (auto &kv : string_map) { dictionary[[NSString stringWithUTF8String:kv.first.c_str()]] = @@ -121,8 +122,7 @@ void ForEachAppDelegateClass(void (^block)(Class)) { return dictionary; } -NSDictionary *CharArrayMapToNSDictionary( - const std::map &string_map) { +NSDictionary *CharArrayMapToNSDictionary(const std::map &string_map) { NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init]; for (auto &kv : string_map) { dictionary[[NSString stringWithUTF8String:kv.first]] = @@ -143,17 +143,14 @@ void ForEachAppDelegateClass(void (^block)(Class)) { return std::string(static_cast(data.bytes), data.length); } -NSString *StringToNSString(const std::string &str) { - return CStringToNSString(str.c_str()); -} +NSString *StringToNSString(const std::string &str) { return CStringToNSString(str.c_str()); } NSString *CStringToNSString(const char *c_str) { return [NSString stringWithCString:c_str encoding:NSUTF8StringEncoding]; } std::string NSStringToString(NSString *str) { - return str ? std::string([str cStringUsingEncoding:NSUTF8StringEncoding]) : - std::string(); + return str ? std::string([str cStringUsingEncoding:NSUTF8StringEncoding]) : std::string(); } NSMutableArray *StringVectorToNSMutableArray(const std::vector &vector) { @@ -184,32 +181,29 @@ void NSArrayOfNSStringToVectorOfString(NSArray* array, std::vector* return array; } -NSMutableDictionary* StdMapToNSMutableDictionary( - const std::map& map) { - NSMutableDictionary* dictionary = - [[NSMutableDictionary alloc] initWithCapacity:map.size()]; - for (auto& pair : map) { - [dictionary setObject:VariantToId(pair.second) - forKey:VariantToId(pair.first)]; +NSMutableDictionary *StdMapToNSMutableDictionary(const std::map &map) { + NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] initWithCapacity:map.size()]; + for (auto &pair : map) { + [dictionary setObject:VariantToId(pair.second) forKey:VariantToId(pair.first)]; } return dictionary; } -void NSArrayToStdVector(NSArray *array, std::vector* vector) { +void NSArrayToStdVector(NSArray *array, std::vector *vector) { vector->reserve(array.count); for (id object in array) { vector->push_back(IdToVariant(object)); } } -void NSDictionaryToStdMap(NSDictionary *dictionary, std::map* map) { +void NSDictionaryToStdMap(NSDictionary *dictionary, std::map *map) { for (id key in dictionary) { id value = [dictionary objectForKey:key]; map->insert(std::make_pair(IdToVariant(key), IdToVariant(value))); } } -id VariantToId(const Variant& variant) { +id VariantToId(const Variant &variant) { switch (variant.type()) { case Variant::kTypeNull: { return [NSNull null]; @@ -242,22 +236,18 @@ id VariantToId(const Variant& variant) { static bool IdIsBoolean(id value) { if ([value isKindOfClass:[NSNumber class]]) { - const char* type = [value objCType]; - return strcmp(type, @encode(BOOL)) == 0 || - strcmp(type, @encode(signed char)) == 0; + const char *type = [value objCType]; + return strcmp(type, @encode(BOOL)) == 0 || strcmp(type, @encode(signed char)) == 0; } return false; } static bool IdIsInteger(id value) { if ([value isKindOfClass:[NSNumber class]]) { - const char* type = [value objCType]; - return strcmp(type, @encode(int)) == 0 || - strcmp(type, @encode(short)) == 0 || - strcmp(type, @encode(long)) == 0 || - strcmp(type, @encode(long long)) == 0 || - strcmp(type, @encode(unsigned char)) == 0 || - strcmp(type, @encode(unsigned int)) == 0 || + const char *type = [value objCType]; + return strcmp(type, @encode(int)) == 0 || strcmp(type, @encode(short)) == 0 || + strcmp(type, @encode(long)) == 0 || strcmp(type, @encode(long long)) == 0 || + strcmp(type, @encode(unsigned char)) == 0 || strcmp(type, @encode(unsigned int)) == 0 || strcmp(type, @encode(unsigned short)) == 0 || strcmp(type, @encode(unsigned long)) == 0 || strcmp(type, @encode(unsigned long long)) == 0; @@ -267,9 +257,8 @@ static bool IdIsInteger(id value) { static bool IdIsFloatingPoint(id value) { if ([value isKindOfClass:[NSNumber class]]) { - const char* type = [value objCType]; - return strcmp(type, @encode(float)) == 0 || - strcmp(type, @encode(double)) == 0; + const char *type = [value objCType]; + return strcmp(type, @encode(float)) == 0 || strcmp(type, @encode(double)) == 0; } return false; } @@ -318,15 +307,13 @@ void DispatchAsyncSafeMainQueue(void (^block)(void)) { } } -void RunOnMainThread(void (*function_ptr)(void *function_data), - void *function_data) { +void RunOnMainThread(void (*function_ptr)(void *function_data), void *function_data) { dispatch_async(dispatch_get_main_queue(), ^{ function_ptr(function_data); }); } -void RunOnBackgroundThread(void (*function_ptr)(void *function_data), - void *function_data) { +void RunOnBackgroundThread(void (*function_ptr)(void *function_data), void *function_data) { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ function_ptr(function_data); }); @@ -361,12 +348,14 @@ void RunOnBackgroundThread(void (*function_ptr)(void *function_data), // Get the type encoding of the selector from a type_encoding_class (which is a class which // implements a stub for the method). - const char *type_encoding = method_getTypeEncoding( - class_getInstanceMethod(type_encoding_class, name)); + const char *type_encoding = + method_getTypeEncoding(class_getInstanceMethod(type_encoding_class, name)); FIREBASE_ASSERT(type_encoding); NSString *new_method_name_nsstring = nil; - ::firebase::LogDebug("Registering method for %s selector %s", class_name, selector_name); + if (GetLogLevel() <= kLogLevelDebug) { + NSLog(@"Registering method for %s selector %s", class_name, selector_name); + } if (original_method_implementation) { // Try adding a method with randomized prefix on the name. int retry = kRandomNameGenerationRetries; @@ -381,27 +370,32 @@ void RunOnBackgroundThread(void (*function_ptr)(void *function_data), } const char *new_method_name = new_method_name_nsstring.UTF8String; if (retry == 0) { - LogError("Failed to add method %s on class %s as the %s method already exists on the class. " - "To resolve this issue, change the name of the method %s on the class %s.", - new_method_name, class_name, new_method_name, new_method_name, class_name); + NSLog(@"Failed to add method %s on class %s as the %s method already exists on the class. To " + @"resolve this issue, change the name of the method %s on the class %s.", + new_method_name, class_name, new_method_name, new_method_name, class_name); return; } method_setImplementation(method, imp); // Save the selector name that points at the original method implementation. SetMethod(name, new_method_name_nsstring); - ::firebase::LogDebug("Registered method for %s selector %s (original method %s 0x%08x)", - class_name, selector_name, new_method_name, - static_cast(reinterpret_cast( - original_method_implementation))); + if (GetLogLevel() <= kLogLevelDebug) { + NSLog(@"Registered method for %s selector %s (original method %s 0x%08x)", class_name, + selector_name, new_method_name, + static_cast(reinterpret_cast(original_method_implementation))); + } } else if (add_method) { - ::firebase::LogDebug("Adding method for %s selector %s", class_name, selector_name); + if (GetLogLevel() <= kLogLevelDebug) { + NSLog(@"Adding method for %s selector %s", class_name, selector_name); + } // The class doesn't implement the selector so simply install our method implementation. if (!class_addMethod(clazz, name, imp, type_encoding)) { - LogError("Failed to add new method %s on class %s.", selector_name, class_name); + NSLog(@"Failed to add new method %s on class %s.", selector_name, class_name); } } else { - ::firebase::LogDebug("Method implementation for %s selector %s not found, ignoring.", - class_name, selector_name); + if (GetLogLevel() <= kLogLevelDebug) { + NSLog(@"Method implementation for %s selector %s not found, ignoring.", class_name, + selector_name); + } } } @@ -431,10 +425,10 @@ void RunOnBackgroundThread(void (*function_ptr)(void *function_data), const char *selector_implementation_name = selector_implementation_name_nsstring.UTF8String; SEL selector_implementation = NSSelectorFromString(selector_implementation_name_nsstring); search_class = clazz; - for ( ; search_class; search_class = class_getSuperclass(search_class)) { + for (; search_class; search_class = class_getSuperclass(search_class)) { const char *search_class_name = class_getName(search_class); - firebase::LogDebug("Searching for selector %s (%s) on class %s", - selector_name, selector_implementation_name, search_class_name); + firebase::LogDebug("Searching for selector %s (%s) on class %s", selector_name, + selector_implementation_name, search_class_name); Method method = class_getInstanceMethod(search_class, selector_implementation); method_implementation = method ? method_getImplementation(method) : nil; if (method_implementation) break; @@ -442,8 +436,8 @@ void RunOnBackgroundThread(void (*function_ptr)(void *function_data), if (method_implementation) break; } if (!method_implementation) { - firebase::LogDebug("Class %s does not respond to selector %s (%s)", class_name, - selector_name, selector_implementation_name_nsstring.UTF8String); + firebase::LogDebug("Class %s does not respond to selector %s (%s)", class_name, selector_name, + selector_implementation_name_nsstring.UTF8String); return nil; } firebase::LogDebug("Found %s (%s, 0x%08x) on class %s (%s)", selector_name, @@ -483,8 +477,8 @@ void RunOnBackgroundThread(void (*function_ptr)(void *function_data), while (retry--) { // Cache the old method implementation in a new method so that we can lookup the original // implementation from the instance of the class. - NSString *random_selector_name = [[NSString alloc] initWithFormat:@"FIRA%x%@", arc4random(), - selector_name]; + NSString *random_selector_name = + [[NSString alloc] initWithFormat:@"FIRA%x%@", arc4random(), selector_name]; if (!implementation_selector_names[random_selector_name]) { return random_selector_name; } diff --git a/app/src/uuid_ios_darwin.mm b/app/src/uuid_ios_darwin.mm index 52d3475693..5c3ecf12df 100644 --- a/app/src/uuid_ios_darwin.mm +++ b/app/src/uuid_ios_darwin.mm @@ -28,4 +28,3 @@ } // namespace internal } // namespace firebase - diff --git a/app/src_java/com/google/firebase/app/internal/cpp/GoogleApiAvailabilityHelper.java b/app/src_java/com/google/firebase/app/internal/cpp/GoogleApiAvailabilityHelper.java index 9db5f66b57..b5b13e533b 100644 --- a/app/src_java/com/google/firebase/app/internal/cpp/GoogleApiAvailabilityHelper.java +++ b/app/src_java/com/google/firebase/app/internal/cpp/GoogleApiAvailabilityHelper.java @@ -16,7 +16,6 @@ package com.google.firebase.app.internal.cpp; - import android.app.Activity; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GoogleApiAvailability; @@ -79,29 +78,25 @@ public static boolean makeGooglePlayServicesAvailable(Activity activity) { if (task == null) { return false; } - task.addOnSuccessListener( - new OnSuccessListener() { - @Override - public void onSuccess(Void result) { - GoogleApiAvailabilityHelper.onComplete(SUCCESS, "Success"); - } - }); - task.addOnFailureListener( - new OnFailureListener() { - @Override - public void onFailure(Exception exception) { - GoogleApiAvailabilityHelper.onComplete( - FAILURE_COULD_NOT_UPDATE, - "Couldn't make Google Play services available: " + exception.getMessage()); - } - }); - task.addOnCanceledListener( - new OnCanceledListener() { - @Override - public void onCanceled() { - GoogleApiAvailabilityHelper.onComplete(FAILURE_CANCELED, "User canceled the update"); - } - }); + task.addOnSuccessListener(new OnSuccessListener() { + @Override + public void onSuccess(Void result) { + GoogleApiAvailabilityHelper.onComplete(SUCCESS, "Success"); + } + }); + task.addOnFailureListener(new OnFailureListener() { + @Override + public void onFailure(Exception exception) { + GoogleApiAvailabilityHelper.onComplete(FAILURE_COULD_NOT_UPDATE, + "Couldn't make Google Play services available: " + exception.getMessage()); + } + }); + task.addOnCanceledListener(new OnCanceledListener() { + @Override + public void onCanceled() { + GoogleApiAvailabilityHelper.onComplete(FAILURE_CANCELED, "User canceled the update"); + } + }); return true; } } diff --git a/app/src_java/com/google/firebase/app/internal/cpp/JniResultCallback.java b/app/src_java/com/google/firebase/app/internal/cpp/JniResultCallback.java index f3b2a79a0d..954957e50d 100644 --- a/app/src_java/com/google/firebase/app/internal/cpp/JniResultCallback.java +++ b/app/src_java/com/google/firebase/app/internal/cpp/JniResultCallback.java @@ -156,11 +156,6 @@ public void onCompletion( } /** This function is implemented in the App C++ library (util_android.cc). */ - private native void nativeOnResult( - Object result, - boolean success, - boolean cancelled, - String statusString, - long callbackFn, - long callbackData); + private native void nativeOnResult(Object result, boolean success, boolean cancelled, + String statusString, long callbackFn, long callbackData); } diff --git a/app/src_java/com/google/firebase/app/internal/cpp/Log.java b/app/src_java/com/google/firebase/app/internal/cpp/Log.java index 3aed09bdd6..d2b80d3219 100644 --- a/app/src_java/com/google/firebase/app/internal/cpp/Log.java +++ b/app/src_java/com/google/firebase/app/internal/cpp/Log.java @@ -75,7 +75,6 @@ public static int e(String tag, String msg) { * See android.util.Log.wtf(). */ public static int wtf(String tag, String msg) { - safeNativeLog(android.util.Log.ERROR, tag, msg); return 0; } @@ -125,9 +124,9 @@ private void safeNativeLogInternal(int level, String tag, String msg) { nativeLog(level, tag, msg); } catch (UnsatisfiedLinkError e) { nativeLogAvailable = false; - android.util.Log.w( - TAG, String.format("nativeLog not registered, falling back to android.util.Log (%s)", - e.toString())); + android.util.Log.w(TAG, + String.format( + "nativeLog not registered, falling back to android.util.Log (%s)", e.toString())); } } if (!nativeLogAvailable) { diff --git a/app/src_java/com/google/firebase/dynamiclinks/internal/cpp/DynamicLinksNativeWrapper.java b/app/src_java/com/google/firebase/dynamiclinks/internal/cpp/DynamicLinksNativeWrapper.java index fd07cffa95..e774ac6672 100644 --- a/app/src_java/com/google/firebase/dynamiclinks/internal/cpp/DynamicLinksNativeWrapper.java +++ b/app/src_java/com/google/firebase/dynamiclinks/internal/cpp/DynamicLinksNativeWrapper.java @@ -42,11 +42,10 @@ public class DynamicLinksNativeWrapper { // Message that describes the failure to find a native method and a potential resolution. private static final String NATIVE_METHOD_MISSING_MESSAGE = "Native method not found, unable to send %s message to the application. " - + "Make sure Firebase was not shut down while a Dynamic Links fetch operation " - + "was in progress. (%s)"; + + "Make sure Firebase was not shut down while a Dynamic Links fetch operation " + + "was in progress. (%s)"; public DynamicLinksNativeWrapper(long nativePtr, Activity incomingActivity) { - nativeInternalPtr = nativePtr; // Call our JNI function (passing in 0 as the nativeInternalPtr) so we can verify that // they are all hooked up properly. @@ -69,40 +68,36 @@ public void discardNativePointer() { // Fetch Dynamic Links - this function is called from JNI to trigger checking for dynamic links. public boolean fetchDynamicLink() { try { - activity.runOnUiThread( - new Runnable() { - @Override - public void run() { - 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) - Uri deepLink = null; - String deepLinkString = null; - if (pendingDynamicLinkData != null) { - deepLink = pendingDynamicLinkData.getLink(); - if (deepLink != null) { - deepLinkString = deepLink.toString(); - } - } - safeReceivedDynamicLinkCallback(nativeInternalPtr, deepLinkString, 0, ""); - } - }) - .addOnFailureListener( - activity, - new OnFailureListener() { - @Override - public void onFailure(Exception e) { - safeReceivedDynamicLinkCallback( - nativeInternalPtr, "", Activity.RESULT_CANCELED, e.toString()); + activity.runOnUiThread(new Runnable() { + @Override + public void run() { + 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) + Uri deepLink = null; + String deepLinkString = null; + if (pendingDynamicLinkData != null) { + deepLink = pendingDynamicLinkData.getLink(); + if (deepLink != null) { + deepLinkString = deepLink.toString(); } - }); - } - }); + } + safeReceivedDynamicLinkCallback(nativeInternalPtr, deepLinkString, 0, ""); + } + }) + .addOnFailureListener(activity, new OnFailureListener() { + @Override + public void onFailure(Exception e) { + safeReceivedDynamicLinkCallback( + nativeInternalPtr, "", Activity.RESULT_CANCELED, e.toString()); + } + }); + } + }); return true; } catch (Exception e) { // Failed to start fetching invites. The client code will handle this when we return false.. @@ -115,10 +110,8 @@ public static void safeReceivedDynamicLinkCallback( try { receivedDynamicLinkCallback(nativeInternalPtr, deepLinkUrl, resultCode, errorString); } catch (UnsatisfiedLinkError e) { - String missingDetails = - String.format( - "received url=%s (code=%d, message=%s)", - String.valueOf(deepLinkUrl), resultCode, errorString); + String missingDetails = String.format("received url=%s (code=%d, message=%s)", + String.valueOf(deepLinkUrl), resultCode, errorString); Log.e(TAG, String.format(NATIVE_METHOD_MISSING_MESSAGE, missingDetails, e.toString())); } } diff --git a/app/src_java/fake/com/google/android/gms/common/GoogleApiAvailability.java b/app/src_java/fake/com/google/android/gms/common/GoogleApiAvailability.java index 9bdfa3ab52..430afb32a0 100644 --- a/app/src_java/fake/com/google/android/gms/common/GoogleApiAvailability.java +++ b/app/src_java/fake/com/google/android/gms/common/GoogleApiAvailability.java @@ -22,7 +22,6 @@ /** Fake gms/common/GoogleApiAvailability.java for unit testing. */ public final class GoogleApiAvailability { - private static final GoogleApiAvailability INSTANCE = new GoogleApiAvailability(); public static GoogleApiAvailability getInstance() { diff --git a/app/src_java/fake/com/google/firebase/FirebaseException.java b/app/src_java/fake/com/google/firebase/FirebaseException.java index 8d430cd072..0d509df859 100644 --- a/app/src_java/fake/com/google/firebase/FirebaseException.java +++ b/app/src_java/fake/com/google/firebase/FirebaseException.java @@ -18,7 +18,6 @@ /** Fake FirebaseException */ public class FirebaseException extends Exception { - public FirebaseException(String message) { super(message); } diff --git a/app/src_java/fake/com/google/firebase/FirebaseOptions.java b/app/src_java/fake/com/google/firebase/FirebaseOptions.java index 7559eee97f..10c252d4b0 100644 --- a/app/src_java/fake/com/google/firebase/FirebaseOptions.java +++ b/app/src_java/fake/com/google/firebase/FirebaseOptions.java @@ -97,14 +97,13 @@ private FirebaseOptions(Builder builder) { } public static FirebaseOptions fromResource(Context context) { - return new FirebaseOptions( - new Builder() - .setApiKey("fake api key from resource") - .setDatabaseUrl("fake database url from resource") - .setApplicationId("fake app id from resource") - .setGcmSenderId("fake messaging sender id from resource") - .setStorageBucket("fake storage bucket from resource") - .setProjectId("fake project id from resource")); + return new FirebaseOptions(new Builder() + .setApiKey("fake api key from resource") + .setDatabaseUrl("fake database url from resource") + .setApplicationId("fake app id from resource") + .setGcmSenderId("fake messaging sender id from resource") + .setStorageBucket("fake storage bucket from resource") + .setProjectId("fake project id from resource")); } public String getApiKey() { diff --git a/app/src_java/fake/com/google/firebase/app/internal/cpp/CppThreadDispatcher.java b/app/src_java/fake/com/google/firebase/app/internal/cpp/CppThreadDispatcher.java index 9837ef421a..44a07f625c 100644 --- a/app/src_java/fake/com/google/firebase/app/internal/cpp/CppThreadDispatcher.java +++ b/app/src_java/fake/com/google/firebase/app/internal/cpp/CppThreadDispatcher.java @@ -22,17 +22,17 @@ /** Runs a native C++ function on an alternate thread. */ public class CppThreadDispatcher { - private static final ExecutorService executor = Executors.newSingleThreadExecutor( - Executors.defaultThreadFactory()); + private static final ExecutorService executor = + Executors.newSingleThreadExecutor(Executors.defaultThreadFactory()); /** Runs a C++ function on the main thread using the executor. */ public static void runOnMainThread(Activity activity, final CppThreadDispatcherContext context) { Object unused = executor.submit(new Runnable() { - @Override - public void run() { - context.execute(); - } - }); + @Override + public void run() { + context.execute(); + } + }); } /** Runs a C++ function on a new Java background thread. */ diff --git a/app/src_java/fake/com/google/firebase/app/internal/cpp/GoogleApiAvailabilityHelper.java b/app/src_java/fake/com/google/firebase/app/internal/cpp/GoogleApiAvailabilityHelper.java index ee34b2e859..0e491fafcf 100644 --- a/app/src_java/fake/com/google/firebase/app/internal/cpp/GoogleApiAvailabilityHelper.java +++ b/app/src_java/fake/com/google/firebase/app/internal/cpp/GoogleApiAvailabilityHelper.java @@ -33,16 +33,15 @@ public static boolean makeGooglePlayServicesAvailable(Activity activity) { final ConfigRow row = ConfigAndroid.get("GoogleApiAvailabilityHelper.makeGooglePlayServicesAvailable"); if (row != null) { - TickerAndroid.register( - new TickerObserver() { - @Override - public void elapse() { - if (TickerAndroid.now() == row.futureint().ticker()) { - int resultCode = row.futureint().value(); - onCompleteNative(resultCode, "result code is " + resultCode); - } - } - }); + TickerAndroid.register(new TickerObserver() { + @Override + public void elapse() { + if (TickerAndroid.now() == row.futureint().ticker()) { + int resultCode = row.futureint().value(); + onCompleteNative(resultCode, "result code is " + resultCode); + } + } + }); return row.futurebool().value() == FutureBoolResult.True; } diff --git a/app/src_java/fake/com/google/firebase/app/internal/cpp/JniResultCallback.java b/app/src_java/fake/com/google/firebase/app/internal/cpp/JniResultCallback.java index 0be47b678f..dff647cd83 100644 --- a/app/src_java/fake/com/google/firebase/app/internal/cpp/JniResultCallback.java +++ b/app/src_java/fake/com/google/firebase/app/internal/cpp/JniResultCallback.java @@ -27,7 +27,8 @@ private interface Callback { public void register(); public void disconnect(); - }; + } + ; private long callbackFn; private long callbackData; @@ -86,18 +87,12 @@ public void cancel() { private void onCompletion( Object result, boolean success, boolean cancelled, String statusMessage) { if (callbackHandler != null) { - nativeOnResult( - result, success, cancelled, statusMessage, callbackFn, callbackData); + nativeOnResult(result, success, cancelled, statusMessage, callbackFn, callbackData); callbackHandler.disconnect(); callbackHandler = null; } } - private native void nativeOnResult( - Object result, - boolean success, - boolean cancelled, - String statusString, - long callbackFn, - long callbackData); + private native void nativeOnResult(Object result, boolean success, boolean cancelled, + String statusString, long callbackFn, long callbackData); } diff --git a/app/tests/util_ios_test.mm b/app/tests/util_ios_test.mm index b9c231f8bc..9d866e2417 100644 --- a/app/tests/util_ios_test.mm +++ b/app/tests/util_ios_test.mm @@ -34,7 +34,7 @@ - (void)testConstructAndGet { NSStringPointer pointer; XCTAssertEqual(cpp.get(), nil); XCTAssertEqual(handle.get(), nil); - XCTAssertEqual(pointer.get(), nil); + XCTAssertEqual(pointer.get(), nil); } - (void)testConstructWithObjectAndGet { @@ -45,12 +45,12 @@ - (void)testConstructWithObjectAndGet { NSStringHandle from_base_type(cpp); XCTAssertEqual(cpp.get(), nsstring); XCTAssertEqual(handle.get(), nsstring); - XCTAssertEqual(pointer.get(), nsstring); + XCTAssertEqual(pointer.get(), nsstring); XCTAssertEqual(from_base_type.get(), nsstring); } - (void)testRelease { - NSString *nsstring = @"hello"; + NSString* nsstring = @"hello"; NSStringCpp cpp(nsstring); XCTAssertEqual(cpp.get(), nsstring); cpp.release(); @@ -297,14 +297,12 @@ - (void)testVector { { // NSArray containing an NSArray and an NSDictionary to an std::vector // holding an std::vector and std::map - id array = @[ @[ @1, @2, @3 ], @{ @4 : @5, @6 : @7, @8 : @9 } ]; + id array = @[ @[ @1, @2, @3 ], @{@4 : @5, @6 : @7, @8 : @9} ]; std::vector vector_element{1, 2, 3}; - std::map map_element{ - std::make_pair(Variant(4), Variant(5)), - std::make_pair(Variant(6), Variant(7)), - std::make_pair(Variant(8), Variant(9))}; - std::vector expected{Variant(vector_element), - Variant(map_element)}; + std::map map_element{std::make_pair(Variant(4), Variant(5)), + std::make_pair(Variant(6), Variant(7)), + std::make_pair(Variant(8), Variant(9))}; + std::vector expected{Variant(vector_element), Variant(map_element)}; Variant variant = IdToVariant(array); XCTAssertTrue(variant.is_vector()); XCTAssertTrue(variant.vector() == expected); @@ -323,18 +321,10 @@ - (void)testMap { { // Check that a NSDictionary of strings to numbers maps to a std::map of // string variants to number variants. - id dictionary = @{ - @"test1" : @1, - @"test2" : @2, - @"test3" : @3, - @"test4" : @4, - @"test5" : @5 - }; + id dictionary = @{@"test1" : @1, @"test2" : @2, @"test3" : @3, @"test4" : @4, @"test5" : @5}; std::map expected{ - std::make_pair(Variant("test1"), Variant(1)), - std::make_pair(Variant("test2"), Variant(2)), - std::make_pair(Variant("test3"), Variant(3)), - std::make_pair(Variant("test4"), Variant(4)), + std::make_pair(Variant("test1"), Variant(1)), std::make_pair(Variant("test2"), Variant(2)), + std::make_pair(Variant("test3"), Variant(3)), std::make_pair(Variant("test4"), Variant(4)), std::make_pair(Variant("test5"), Variant(5))}; Variant variant = IdToVariant(dictionary); XCTAssertTrue(variant.is_map()); @@ -343,11 +333,10 @@ - (void)testMap { { // Check that a NSDictionary of various types maps to a std::map of variants // holding various types. - id dictionary = @{ @20 : @"Different types", @6.28 : @10, @"Blah" : @3.14 }; - std::map expected{ - std::make_pair(Variant(20), Variant("Different types")), - std::make_pair(Variant(6.28), Variant(10)), - std::make_pair(Variant("Blah"), Variant(3.14))}; + id dictionary = @{@20 : @"Different types", @6.28 : @10, @"Blah" : @3.14}; + std::map expected{std::make_pair(Variant(20), Variant("Different types")), + std::make_pair(Variant(6.28), Variant(10)), + std::make_pair(Variant("Blah"), Variant(3.14))}; Variant variant = IdToVariant(dictionary); XCTAssertTrue(variant.is_map()); XCTAssertTrue(variant.map() == expected); @@ -355,12 +344,11 @@ - (void)testMap { { // Check that a NSDictionary of NSArray-to-NSDictionary maps to an std::map // of vector-to-map - id dictionary = @{ @[ @1, @2, @3 ] : @{@4 : @5, @6 : @7, @8 : @9} }; + id dictionary = @{@[ @1, @2, @3 ] : @{@4 : @5, @6 : @7, @8 : @9}}; std::vector vector_element{1, 2, 3}; - std::map map_element{ - std::make_pair(Variant(4), Variant(5)), - std::make_pair(Variant(6), Variant(7)), - std::make_pair(Variant(8), Variant(9))}; + std::map map_element{std::make_pair(Variant(4), Variant(5)), + std::make_pair(Variant(6), Variant(7)), + std::make_pair(Variant(8), Variant(9))}; std::map expected{ std::make_pair(Variant(vector_element), Variant(map_element))}; Variant variant = IdToVariant(dictionary); @@ -550,8 +538,7 @@ - (void)testVector { } { // std::vector of static and mutable strings to NSArray of NSStrings. - std::vector vector{"This", std::string("is"), "a", - std::string("test.")}; + std::vector vector{"This", std::string("is"), "a", std::string("test.")}; id expected = @[ @"This", @"is", @"a", @"test." ]; Variant variant(vector); id array = VariantToId(variant); @@ -571,12 +558,11 @@ - (void)testVector { // std::vector containing a vector and map to an NSArray containing an // NSArray and an NSDictionary. std::vector vector_element{1, 2, 3}; - std::map map_element{ - std::make_pair(Variant(4), Variant(5)), - std::make_pair(Variant(6), Variant(7)), - std::make_pair(Variant(8), Variant(9))}; + std::map map_element{std::make_pair(Variant(4), Variant(5)), + std::make_pair(Variant(6), Variant(7)), + std::make_pair(Variant(8), Variant(9))}; std::vector vector{Variant(vector_element), Variant(map_element)}; - id expected = @[ @[ @1, @2, @3 ], @{ @4 : @5, @6 : @7, @8 : @9 } ]; + id expected = @[ @[ @1, @2, @3 ], @{@4 : @5, @6 : @7, @8 : @9} ]; Variant variant(vector); id array = VariantToId(variant); XCTAssertTrue([array isKindOfClass:[NSArray class]]); @@ -599,18 +585,10 @@ - (void)testMap { // Check that an std::map of strings to numbers maps to an NSDictionary of // NSString to NSNumbers. std::map map{ - std::make_pair(Variant("test1"), Variant(1)), - std::make_pair(Variant("test2"), Variant(2)), - std::make_pair(Variant("test3"), Variant(3)), - std::make_pair(Variant("test4"), Variant(4)), + std::make_pair(Variant("test1"), Variant(1)), std::make_pair(Variant("test2"), Variant(2)), + std::make_pair(Variant("test3"), Variant(3)), std::make_pair(Variant("test4"), Variant(4)), std::make_pair(Variant("test5"), Variant(5))}; - id expected = @{ - @"test1" : @1, - @"test2" : @2, - @"test3" : @3, - @"test4" : @4, - @"test5" : @5 - }; + id expected = @{@"test1" : @1, @"test2" : @2, @"test3" : @3, @"test4" : @4, @"test5" : @5}; Variant variant(map); id dictionary = VariantToId(variant); XCTAssertTrue([dictionary isKindOfClass:[NSDictionary class]]); @@ -621,9 +599,8 @@ - (void)testMap { // various types. std::map map{ std::make_pair(Variant(20), Variant(std::string("Different types"))), - std::make_pair(Variant(6.28), Variant(10)), - std::make_pair(Variant("Blah"), Variant(3.14))}; - id expected = @{ @20 : @"Different types", @6.28 : @10, @"Blah" : @3.14 }; + std::make_pair(Variant(6.28), Variant(10)), std::make_pair(Variant("Blah"), Variant(3.14))}; + id expected = @{@20 : @"Different types", @6.28 : @10, @"Blah" : @3.14}; Variant variant(map); id dictionary = VariantToId(variant); XCTAssertTrue([dictionary isKindOfClass:[NSDictionary class]]); @@ -633,13 +610,11 @@ - (void)testMap { // Check that an std::map of vector-to-map maps to a NSDictionary of // NSArray-to-NSDictionary std::vector vector_element{1, 2, 3}; - std::map map_element{ - std::make_pair(Variant(4), Variant(5)), - std::make_pair(Variant(6), Variant(7)), - std::make_pair(Variant(8), Variant(9))}; - std::map map{ - std::make_pair(Variant(vector_element), Variant(map_element))}; - id expected = @{ @[ @1, @2, @3 ] : @{@4 : @5, @6 : @7, @8 : @9} }; + std::map map_element{std::make_pair(Variant(4), Variant(5)), + std::make_pair(Variant(6), Variant(7)), + std::make_pair(Variant(8), Variant(9))}; + std::map map{std::make_pair(Variant(vector_element), Variant(map_element))}; + id expected = @{@[ @1, @2, @3 ] : @{@4 : @5, @6 : @7, @8 : @9}}; Variant variant(map); id dictionary = VariantToId(variant); XCTAssertTrue([dictionary isKindOfClass:[NSDictionary class]]); diff --git a/auth/src/desktop/user_view.h b/auth/src/desktop/user_view.h index 2c3b2305bc..20f28d685c 100644 --- a/auth/src/desktop/user_view.h +++ b/auth/src/desktop/user_view.h @@ -17,6 +17,7 @@ #include #include + #include "app/src/assert.h" #include "app/src/mutex.h" #include "auth/src/common.h" diff --git a/auth/src/include/firebase/auth.h b/auth/src/include/firebase/auth.h index e307dd0e01..77d46da3cd 100644 --- a/auth/src/include/firebase/auth.h +++ b/auth/src/include/firebase/auth.h @@ -20,9 +20,9 @@ #include #include "firebase/app.h" +#include "firebase/auth/user.h" #include "firebase/future.h" #include "firebase/internal/common.h" -#include "firebase/auth/user.h" #if !defined(DOXYGEN) #ifndef SWIG diff --git a/auth/src/include/firebase/auth/user.h b/auth/src/include/firebase/auth/user.h index 8460ebedd6..32e92de5e8 100644 --- a/auth/src/include/firebase/auth/user.h +++ b/auth/src/include/firebase/auth/user.h @@ -20,11 +20,11 @@ #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" -#include "firebase/auth/credential.h" -#include "firebase/auth/types.h" namespace firebase { namespace auth { diff --git a/auth/src/ios/auth_ios.mm b/auth/src/ios/auth_ios.mm index 17b8236829..b641245e05 100644 --- a/auth/src/ios/auth_ios.mm +++ b/auth/src/ios/auth_ios.mm @@ -17,8 +17,8 @@ #import "FIRAdditionalUserInfo.h" #import "FIRAuthDataResult.h" #import "FIRAuthErrors.h" -#import "FIROptions.h" #import "FIROAuthCredential.h" +#import "FIROptions.h" #include "app/src/app_ios.h" #include "app/src/assert.h" @@ -126,12 +126,10 @@ @implementation FIRCPPAuthListenerHandle public: // Construct a Credential given a preexisting FIRAuthCredential wrapped by a // FIRAuthCredentialPointer. - static Credential GetCredential(FIRAuthCredentialPointer* impl) { - return Credential(impl); - } + static Credential GetCredential(FIRAuthCredentialPointer *impl) { return Credential(impl); } }; -template +template struct ListenerHandleHolder { explicit ListenerHandleHolder(T handle) : handle(handle) {} T handle; @@ -150,7 +148,7 @@ explicit ListenerHandleHolder(T handle) : handle(handle) {} } // Grab the user value from the iOS API and remember it locally. -void UpdateCurrentUser(AuthData* auth_data) { +void UpdateCurrentUser(AuthData *auth_data) { MutexLock lock(auth_data->future_impl.mutex()); FIRUser *user = [AuthImpl(auth_data) currentUser]; SetUserImpl(auth_data, user); @@ -158,36 +156,31 @@ void UpdateCurrentUser(AuthData* auth_data) { // Platform-specific method to initialize AuthData. void Auth::InitPlatformAuth(AuthData *auth_data) { - FIRCPPAuthListenerHandle* listener_cpp_handle = - [[FIRCPPAuthListenerHandle alloc] init]; + FIRCPPAuthListenerHandle *listener_cpp_handle = [[FIRCPPAuthListenerHandle alloc] init]; listener_cpp_handle.authData = auth_data; - reinterpret_cast(auth_data->auth_impl)->listener_handle = listener_cpp_handle; + reinterpret_cast(auth_data->auth_impl)->listener_handle = listener_cpp_handle; // Register a listening block that will notify all the C++ listeners on // auth state change. - FIRAuthStateDidChangeListenerHandle listener_handle = - [AuthImpl(auth_data) - addAuthStateDidChangeListener:^(FIRAuth * _Nonnull __strong, - FIRUser * _Nullable __strong) { - @synchronized (listener_cpp_handle) { - AuthData* data = listener_cpp_handle.authData; - if (data) { - UpdateCurrentUser(data); - NotifyAuthStateListeners(data); - } - } - }]; - FIRIDTokenDidChangeListenerHandle id_token_listener_handle = - [AuthImpl(auth_data) - addIDTokenDidChangeListener:^(FIRAuth * _Nonnull __strong, - FIRUser * _Nullable __strong) { - @synchronized (listener_cpp_handle) { - AuthData* data = listener_cpp_handle.authData; - if (data) { - UpdateCurrentUser(data); - NotifyIdTokenListeners(data); - } - } - }]; + FIRAuthStateDidChangeListenerHandle listener_handle = [AuthImpl(auth_data) + addAuthStateDidChangeListener:^(FIRAuth *_Nonnull __strong, FIRUser *_Nullable __strong) { + @synchronized(listener_cpp_handle) { + AuthData *data = listener_cpp_handle.authData; + if (data) { + UpdateCurrentUser(data); + NotifyAuthStateListeners(data); + } + } + }]; + FIRIDTokenDidChangeListenerHandle id_token_listener_handle = [AuthImpl(auth_data) + addIDTokenDidChangeListener:^(FIRAuth *_Nonnull __strong, FIRUser *_Nullable __strong) { + @synchronized(listener_cpp_handle) { + AuthData *data = listener_cpp_handle.authData; + if (data) { + UpdateCurrentUser(data); + NotifyIdTokenListeners(data); + } + } + }]; auth_data->listener_impl = new ListenerHandleHolder(listener_handle); @@ -203,23 +196,22 @@ void UpdateCurrentUser(AuthData* auth_data) { // Platform-specific method to destroy the wrapped Auth class. void Auth::DestroyPlatformAuth(AuthData *auth_data) { // Remove references from listener blocks. - AuthDataIos* auth_data_ios = reinterpret_cast(auth_data->auth_impl); + AuthDataIos *auth_data_ios = reinterpret_cast(auth_data->auth_impl); FIRCPPAuthListenerHandle *listener_cpp_handle = auth_data_ios->listener_handle.get(); - @synchronized (listener_cpp_handle) { + @synchronized(listener_cpp_handle) { listener_cpp_handle.authData = nullptr; } // Unregister the listeners. - ListenerHandleHolder* handle_holder = - reinterpret_cast< - ListenerHandleHolder*>(auth_data->listener_impl); + ListenerHandleHolder *handle_holder = + reinterpret_cast *>( + auth_data->listener_impl); [AuthImpl(auth_data) removeAuthStateDidChangeListener:handle_holder->handle]; delete handle_holder; auth_data->listener_impl = nullptr; - ListenerHandleHolder* id_token_listener_handle_holder = - reinterpret_cast< - ListenerHandleHolder*>( - auth_data->id_token_listener_impl); + ListenerHandleHolder *id_token_listener_handle_holder = + reinterpret_cast *>( + auth_data->id_token_listener_impl); [AuthImpl(auth_data) removeIDTokenDidChangeListener:id_token_listener_handle_holder->handle]; delete id_token_listener_handle_holder; auth_data->id_token_listener_impl = nullptr; @@ -239,21 +231,21 @@ void UpdateCurrentUser(AuthData* auth_data) { const auto handle = futures.SafeAlloc(kAuthFn_FetchProvidersForEmail, initial_data); - [AuthImpl(auth_data_) - fetchSignInMethodsForEmail:@(email) - completion:^(NSArray *_Nullable providers, - NSError *_Nullable error) { - futures.Complete( - handle, AuthErrorFromNSError(error), - [error.localizedDescription UTF8String], - [providers](FetchProvidersResult* data) { - // Copy data to our result format. - data->providers.resize(providers.count); - for (size_t i = 0; i < providers.count; ++i) { - data->providers[i] = util::StringFromNSString(providers[i]); - } - }); - }]; + [AuthImpl(auth_data_) fetchSignInMethodsForEmail:@(email) + completion:^(NSArray *_Nullable providers, + NSError *_Nullable error) { + futures.Complete( + handle, AuthErrorFromNSError(error), + [error.localizedDescription UTF8String], + [providers](FetchProvidersResult *data) { + // Copy data to our result format. + data->providers.resize(providers.count); + for (size_t i = 0; i < providers.count; ++i) { + data->providers[i] = + util::StringFromNSString(providers[i]); + } + }); + }]; return MakeFuture(&futures, handle); } @@ -272,7 +264,7 @@ void UpdateCurrentUser(AuthData* auth_data) { return user; } -static User* AssignUser(FIRUser *_Nullable user, AuthData *auth_data) { +static User *AssignUser(FIRUser *_Nullable user, AuthData *auth_data) { // Update our pointer to the iOS user that we're wrapping. MutexLock lock(auth_data->future_impl.mutex()); if (user) { @@ -318,14 +310,13 @@ AuthError AuthErrorFromNSError(NSError *_Nullable error) { } void SignInCallback(FIRUser *_Nullable user, NSError *_Nullable error, - SafeFutureHandle handle, AuthData *auth_data) { - User* result = AssignUser(user, auth_data); + SafeFutureHandle handle, AuthData *auth_data) { + User *result = AssignUser(user, auth_data); // Finish off the asynchronous call so that the caller can read it. ReferenceCountedFutureImpl &futures = auth_data->future_impl; futures.CompleteWithResult(handle, AuthErrorFromNSError(error), - util::NSStringToString(error.localizedDescription).c_str(), - result); + util::NSStringToString(error.localizedDescription).c_str(), result); } void SignInResultWithProviderCallback( @@ -340,7 +331,7 @@ void SignInResultWithProviderCallback( void SignInResultCallback(FIRAuthDataResult *_Nullable auth_result, NSError *_Nullable error, SafeFutureHandle handle, AuthData *auth_data) { - User* user = AssignUser(auth_result.user, auth_data); + User *user = AssignUser(auth_result.user, auth_data); SignInResult result; result.user = user; @@ -356,7 +347,7 @@ void SignInResultCallback(FIRAuthDataResult *_Nullable auth_result, NSError *_Nu if (error.userInfo[FIRAuthErrorUserInfoUpdatedCredentialKey] != nullptr) { result.info.updated_credential = ServiceUpdatedCredentialProvider::GetCredential( new FIRAuthCredentialPointer(error.userInfo[FIRAuthErrorUserInfoUpdatedCredentialKey])); - } + } } ReferenceCountedFutureImpl &futures = auth_data->future_impl; @@ -390,22 +381,21 @@ void SignInResultCallback(FIRAuthDataResult *_Nullable auth_result, NSError *_Nu return MakeFuture(&futures, handle); } -Future Auth::SignInAndRetrieveDataWithCredential( - const Credential& credential) { +Future Auth::SignInAndRetrieveDataWithCredential(const Credential &credential) { ReferenceCountedFutureImpl &futures = auth_data_->future_impl; const auto handle = futures.SafeAlloc(kAuthFn_SignInAndRetrieveDataWithCredential, SignInResult()); - [AuthImpl(auth_data_) signInWithCredential:CredentialFromImpl(credential.impl_) - completion:^(FIRAuthDataResult *_Nullable auth_result, - NSError *_Nullable error) { - SignInResultCallback(auth_result, error, handle, auth_data_); - }]; + [AuthImpl(auth_data_) + signInWithCredential:CredentialFromImpl(credential.impl_) + completion:^(FIRAuthDataResult *_Nullable auth_result, NSError *_Nullable error) { + SignInResultCallback(auth_result, error, handle, auth_data_); + }]; return MakeFuture(&futures, handle); } -Future Auth::SignInWithProvider(FederatedAuthProvider* provider) { +Future Auth::SignInWithProvider(FederatedAuthProvider *provider) { FIREBASE_ASSERT_RETURN(Future(), provider); return provider->SignIn(auth_data_); } @@ -442,8 +432,7 @@ void SignInResultCallback(FIRAuthDataResult *_Nullable auth_result, NSError *_Nu Future Auth::CreateUserWithEmailAndPassword(const char *email, const char *password) { ReferenceCountedFutureImpl &futures = auth_data_->future_impl; - const auto handle = - futures.SafeAlloc(kAuthFn_CreateUserWithEmailAndPassword, nullptr); + const auto handle = futures.SafeAlloc(kAuthFn_CreateUserWithEmailAndPassword, nullptr); if (!email || strlen(email) == 0) { futures.Complete(handle, kAuthErrorMissingEmail, "Empty email is not allowed."); } else if (!password || strlen(password) == 0) { @@ -472,17 +461,16 @@ void SignInResultCallback(FIRAuthDataResult *_Nullable auth_result, NSError *_Nu [AuthImpl(auth_data_) sendPasswordResetWithEmail:@(email) completion:^(NSError *_Nullable error) { - futures.Complete( - handle, AuthErrorFromNSError(error), - [error.localizedDescription UTF8String]); - }]; + futures.Complete(handle, AuthErrorFromNSError(error), + [error.localizedDescription UTF8String]); + }]; return MakeFuture(&futures, handle); } // Remap iOS SDK errors reported by the UIDelegate. While these errors seem like // user interaction errors, they are actually caused by bad provider ids. -NSError* RemapBadProviderIDErrors(NSError* _Nonnull error) { +NSError *RemapBadProviderIDErrors(NSError *_Nonnull error) { if (error.code == FIRAuthErrorCodeWebSignInUserInteractionFailure && [error.domain isEqualToString:@"FIRAuthErrorDomain"]) { return [[NSError alloc] initWithDomain:error.domain diff --git a/auth/src/ios/common_ios.h b/auth/src/ios/common_ios.h index 66469392ea..d6d471e811 100644 --- a/auth/src/ios/common_ios.h +++ b/auth/src/ios/common_ios.h @@ -37,8 +37,7 @@ namespace firebase { namespace auth { // No static_assert available without C++11, unfortunately. -#define AUTH_STATIC_ASSERT(x) \ - typedef char AUTH_STATIC_ASSERT_FAILED[(x) ? 1 : -1] +#define AUTH_STATIC_ASSERT(x) typedef char AUTH_STATIC_ASSERT_FAILED[(x) ? 1 : -1] OBJ_C_PTR_WRAPPER(FIRAuth); OBJ_C_PTR_WRAPPER(FIRAuthCredential); @@ -53,13 +52,11 @@ struct AuthDataIos { /// Convert from the platform-independent void* to the Obj-C FIRUser pointer. static inline FIRUser *_Nullable UserImpl(AuthData *_Nonnull auth_data) { - return FIRUserPointer::SafeGet( - static_cast(auth_data->user_impl)); + return FIRUserPointer::SafeGet(static_cast(auth_data->user_impl)); } /// Release the platform-dependent FIRUser object. -static inline void SetUserImpl(AuthData *_Nonnull auth_data, - FIRUser *_Nullable user) { +static inline void SetUserImpl(AuthData *_Nonnull auth_data, FIRUser *_Nullable user) { MutexLock lock(auth_data->future_impl.mutex()); // Delete existing pointer to FIRUser. @@ -81,8 +78,7 @@ static inline FIRAuth *_Nonnull AuthImpl(AuthData *_Nonnull auth_data) { /// Convert from the void* credential implementation pointer into the Obj-C /// FIRAuthCredential pointer. -static inline FIRAuthCredential *_Nonnull CredentialFromImpl( - void *_Nonnull impl) { +static inline FIRAuthCredential *_Nonnull CredentialFromImpl(void *_Nonnull impl) { return static_cast(impl)->get(); } @@ -91,29 +87,26 @@ AuthError AuthErrorFromNSError(NSError *_Nullable error); /// Common code for all API calls that return a User*. /// Initialize `auth_data->current_user` and complete the `future`. void SignInCallback(FIRUser *_Nullable user, NSError *_Nullable error, - SafeFutureHandle handle, - AuthData *_Nonnull auth_data); + SafeFutureHandle handle, AuthData *_Nonnull auth_data); /// Common code for all API calls that return a SignInResult. /// Initialize `auth_data->current_user` and complete the `future`. -void SignInResultCallback(FIRAuthDataResult *_Nullable auth_result, - NSError *_Nullable error, - SafeFutureHandle handle, - AuthData *_Nonnull auth_data); +void SignInResultCallback(FIRAuthDataResult *_Nullable auth_result, NSError *_Nullable error, + SafeFutureHandle handle, AuthData *_Nonnull auth_data); /// Common code for all FederatedOAuth API calls which return a SignInResult and /// must hold a reference to a FIROAuthProvider so that the provider is not /// deallocated by the Objective-C environment. Directly invokes /// SignInResultCallback(). -void SignInResultWithProviderCallback( - FIRAuthDataResult* _Nullable auth_result, NSError* _Nullable error, - SafeFutureHandle handle, AuthData *_Nonnull auth_data, - const FIROAuthProvider *_Nonnull ios_auth_provider); +void SignInResultWithProviderCallback(FIRAuthDataResult *_Nullable auth_result, + NSError *_Nullable error, + SafeFutureHandle handle, + AuthData *_Nonnull auth_data, + const FIROAuthProvider *_Nonnull ios_auth_provider); /// Remap iOS SDK errors reported by the UIDelegate. While these errors seem /// like user interaction errors, they are actually caused by bad provider ids. -NSError* RemapBadProviderIDErrors(NSError* _Nonnull error); - +NSError *RemapBadProviderIDErrors(NSError *_Nonnull error); } // namespace auth } // namespace firebase diff --git a/auth/src/ios/credential_ios.mm b/auth/src/ios/credential_ios.mm index aeb899a0e4..5c271f907c 100644 --- a/auth/src/ios/credential_ios.mm +++ b/auth/src/ios/credential_ios.mm @@ -32,7 +32,7 @@ // PhoneAuth is not supported on non-iOS Apple platforms (eg: tvOS). // We are using stub implementation for these platforms (just like on desktop). #import "FIRPhoneAuthProvider.h" -#endif //FIREBASE_PLATFORM_IOS +#endif // FIREBASE_PLATFORM_IOS #import "FIRTwitterAuthProvider.h" @@ -41,7 +41,7 @@ // @ref VerifyPhoneNumber. It exists for as long as one of those two lives. We use Objective-C // for reference counting. @interface PhoneListenerDataObjC : NSObject { -@public + @public // Back-pointer to the PhoneAuthProvider::Listener, or nullptr if it has been deleted. // This lets the VerifyPhoneNumber block know when its Listener has been deleted so it should // become a no-op. @@ -53,7 +53,7 @@ @interface PhoneListenerDataObjC : NSObject { @end @implementation PhoneListenerDataObjC @end -#endif //FIREBASE_PLATFORM_IOS +#endif // FIREBASE_PLATFORM_IOS namespace firebase { namespace auth { @@ -90,14 +90,14 @@ @implementation PhoneListenerDataObjC bool Credential::is_valid() const { return CredentialFromImpl(impl_) != NULL; } std::string Credential::provider() const { - return impl_ == nullptr ? std::string("") : - util::StringFromNSString(CredentialFromImpl(impl_).provider); + return impl_ == nullptr ? std::string("") + : util::StringFromNSString(CredentialFromImpl(impl_).provider); } // static Credential EmailAuthProvider::GetCredential(const char* email, const char* password) { FIREBASE_ASSERT_RETURN(Credential(), email && password); - FIRAuthCredential *credential = [FIREmailAuthProvider credentialWithEmail:@(email) + FIRAuthCredential* credential = [FIREmailAuthProvider credentialWithEmail:@(email) password:@(password)]; return Credential(new FIRAuthCredentialPointer(credential)); } @@ -105,7 +105,7 @@ @implementation PhoneListenerDataObjC // static Credential FacebookAuthProvider::GetCredential(const char* access_token) { FIREBASE_ASSERT_RETURN(Credential(), access_token); - FIRAuthCredential *credential = + FIRAuthCredential* credential = [FIRFacebookAuthProvider credentialWithAccessToken:@(access_token)]; return Credential(new FIRAuthCredentialPointer(credential)); } @@ -113,7 +113,7 @@ @implementation PhoneListenerDataObjC // static Credential GitHubAuthProvider::GetCredential(const char* token) { FIREBASE_ASSERT_RETURN(Credential(), token); - FIRAuthCredential *credential = [FIRGitHubAuthProvider credentialWithToken:@(token)]; + FIRAuthCredential* credential = [FIRGitHubAuthProvider credentialWithToken:@(token)]; return Credential(new FIRAuthCredentialPointer(credential)); } @@ -121,8 +121,8 @@ @implementation PhoneListenerDataObjC Credential GoogleAuthProvider::GetCredential(const char* id_token, const char* access_token) { NSString* ns_id_token = id_token ? @(id_token) : nil; NSString* ns_access_token = access_token ? @(access_token) : nil; - FIRAuthCredential* credential = - [FIRGoogleAuthProvider credentialWithIDToken:ns_id_token accessToken:ns_access_token]; + FIRAuthCredential* credential = [FIRGoogleAuthProvider credentialWithIDToken:ns_id_token + accessToken:ns_access_token]; return Credential(new FIRAuthCredentialPointer(credential)); } @@ -137,14 +137,14 @@ @implementation PhoneListenerDataObjC // static Credential TwitterAuthProvider::GetCredential(const char* token, const char* secret) { FIREBASE_ASSERT_RETURN(Credential(), token && secret); - FIRAuthCredential *credential = [FIRTwitterAuthProvider credentialWithToken:@(token) + FIRAuthCredential* credential = [FIRTwitterAuthProvider credentialWithToken:@(token) secret:@(secret)]; return Credential(new FIRAuthCredentialPointer(credential)); } // static -Credential OAuthProvider::GetCredential( - const char* provider_id, const char* id_token, const char* access_token) { +Credential OAuthProvider::GetCredential(const char* provider_id, const char* id_token, + const char* access_token) { FIREBASE_ASSERT_RETURN(Credential(), provider_id && id_token && access_token); FIRAuthCredential* credential = (FIRAuthCredential*)[FIROAuthProvider credentialWithProviderID:@(provider_id) @@ -154,10 +154,8 @@ @implementation PhoneListenerDataObjC } // static -Credential OAuthProvider::GetCredential(const char* provider_id, - const char* id_token, - const char* raw_nonce, - const char* access_token) { +Credential OAuthProvider::GetCredential(const char* provider_id, const char* id_token, + const char* raw_nonce, const char* access_token) { FIREBASE_ASSERT_RETURN(Credential(), provider_id && id_token && raw_nonce); NSString* access_token_string = @@ -182,12 +180,12 @@ @implementation PhoneListenerDataObjC checking whether the APP that consuming our SDK has linked GameKit.framework. If not, will complete with kAuthErrorInvalidCredential error. **/ - GKLocalPlayer *_Nullable optionalLocalPlayer = [[NSClassFromString(@"GKLocalPlayer") alloc] init]; + GKLocalPlayer* _Nullable optionalLocalPlayer = [[NSClassFromString(@"GKLocalPlayer") alloc] init]; // Early-out if GameKit is not linked if (!optionalLocalPlayer) { future_api->Complete(handle, kAuthErrorInvalidCredential, - "GameCenter authentication is unavailable - missing GameKit capability."); + "GameCenter authentication is unavailable - missing GameKit capability."); return MakeFuture(future_api, handle); } @@ -195,14 +193,14 @@ @implementation PhoneListenerDataObjC NSError* _Nullable error) { Credential result(new FIRAuthCredentialPointer(credential)); future_api->CompleteWithResult(handle, AuthErrorFromNSError(error), - util::NSStringToString(error.localizedDescription).c_str(), - result); + util::NSStringToString(error.localizedDescription).c_str(), + result); }]; return MakeFuture(future_api, handle); } - // static +// static Future GameCenterAuthProvider::GetCredentialLastResult() { auto future_api = GetCredentialFutureImpl(); FIREBASE_ASSERT(future_api != nullptr); @@ -211,7 +209,6 @@ @implementation PhoneListenerDataObjC return static_cast&>(last_result); } - // static bool GameCenterAuthProvider::IsPlayerAuthenticated() { /** @@ -220,28 +217,31 @@ @implementation PhoneListenerDataObjC checking whether the APP that consuming our SDK has linked GameKit.framework. If not, early out. **/ - GKLocalPlayer *_Nullable optionalLocalPlayer = [[NSClassFromString(@"GKLocalPlayer") alloc] init]; + GKLocalPlayer* _Nullable optionalLocalPlayer = [[NSClassFromString(@"GKLocalPlayer") alloc] init]; // If the GameKit Framework isn't linked - early out. if (!optionalLocalPlayer) { return false; } - __weak GKLocalPlayer *localPlayer = [[optionalLocalPlayer class] localPlayer]; + __weak GKLocalPlayer* localPlayer = [[optionalLocalPlayer class] localPlayer]; return localPlayer.isAuthenticated; } // We skip the implementation of ForceResendingTokenData since it is not needed. // The ForceResendingToken class for iOS is empty. -PhoneAuthProvider::ForceResendingToken::ForceResendingToken() - : data_(nullptr) {} +PhoneAuthProvider::ForceResendingToken::ForceResendingToken() : data_(nullptr) {} PhoneAuthProvider::ForceResendingToken::~ForceResendingToken() {} -PhoneAuthProvider::ForceResendingToken::ForceResendingToken( - const ForceResendingToken&) : data_(nullptr) {} -PhoneAuthProvider::ForceResendingToken& PhoneAuthProvider::ForceResendingToken:: -operator=(const ForceResendingToken&) { return *this; } -bool PhoneAuthProvider::ForceResendingToken::operator==( - const ForceResendingToken&) const { return true; } -bool PhoneAuthProvider::ForceResendingToken::operator!=( - const ForceResendingToken&) const { return false; } +PhoneAuthProvider::ForceResendingToken::ForceResendingToken(const ForceResendingToken&) + : data_(nullptr) {} +PhoneAuthProvider::ForceResendingToken& PhoneAuthProvider::ForceResendingToken::operator=( + const ForceResendingToken&) { + return *this; +} +bool PhoneAuthProvider::ForceResendingToken::operator==(const ForceResendingToken&) const { + return true; +} +bool PhoneAuthProvider::ForceResendingToken::operator!=(const ForceResendingToken&) const { + return false; +} #if FIREBASE_PLATFORM_IOS // This implementation of PhoneListenerData is specific to iOS. @@ -255,10 +255,10 @@ @implementation PhoneListenerDataObjC data_->objc = [[PhoneListenerDataObjC alloc] init]; data_->objc->active_listener = this; } -#else // non-iOS Apple platforms (eg: tvOS) +#else // non-iOS Apple platforms (eg: tvOS) // Stub for tvOS and other non-iOS apple platforms. PhoneAuthProvider::Listener::Listener() : data_(nullptr) {} -#endif // FIREBASE_PLATFORM_IOS +#endif // FIREBASE_PLATFORM_IOS #if FIREBASE_PLATFORM_IOS PhoneAuthProvider::Listener::~Listener() { @@ -271,9 +271,9 @@ @implementation PhoneListenerDataObjC data_->objc = nil; delete data_; } -#else // non-iOS Apple platforms (eg: tvOS) +#else // non-iOS Apple platforms (eg: tvOS) PhoneAuthProvider::Listener::~Listener() {} -#endif // FIREBASE_PLATFORM_IOS +#endif // FIREBASE_PLATFORM_IOS #if FIREBASE_PLATFORM_IOS // This implementation of PhoneAuthProviderData is specific to iOS. @@ -285,42 +285,43 @@ explicit PhoneAuthProviderData(FIRPhoneAuthProvider* objc_provider) // The wrapped provider in Objective-C. FIRPhoneAuthProvider* objc_provider; }; -#endif // FIREBASE_PLATFORM_IOS +#endif // FIREBASE_PLATFORM_IOS PhoneAuthProvider::PhoneAuthProvider() : data_(nullptr) {} #if FIREBASE_PLATFORM_IOS PhoneAuthProvider::~PhoneAuthProvider() { delete data_; } -#else // non-iOS Apple platforms (eg: tvOS) +#else // non-iOS Apple platforms (eg: tvOS) PhoneAuthProvider::~PhoneAuthProvider() {} -#endif // FIREBASE_PLATFORM_IOS +#endif // FIREBASE_PLATFORM_IOS #if FIREBASE_PLATFORM_IOS -void PhoneAuthProvider::VerifyPhoneNumber( - const char* phone_number, uint32_t /*auto_verify_time_out_ms*/, - const ForceResendingToken* /*force_resending_token*/, Listener* listener) { +void PhoneAuthProvider::VerifyPhoneNumber(const char* phone_number, + uint32_t /*auto_verify_time_out_ms*/, + const ForceResendingToken* /*force_resending_token*/, + Listener* listener) { FIREBASE_ASSERT_RETURN_VOID(listener != nullptr); const PhoneAuthProvider::ForceResendingToken invalid_resending_token; PhoneListenerDataObjC* objc_listener_data = listener->data_->objc; - [data_->objc_provider verifyPhoneNumber:@(phone_number) - UIDelegate:nil - completion:^(NSString *_Nullable verificationID, - NSError *_Nullable error) { - MutexLock lock(objc_listener_data->listener_mutex); - - // If the listener has been deleted before this callback, do nothing. - if (objc_listener_data->active_listener == nullptr) return; - - // Call OnVerificationFailed() or OnCodeSent() as appropriate. - if (verificationID == nullptr) { - listener->OnVerificationFailed( - util::StringFromNSString(error.localizedDescription)); - } else { - listener->OnCodeSent(util::StringFromNSString(verificationID), - invalid_resending_token); - } - }]; + [data_->objc_provider + verifyPhoneNumber:@(phone_number) + UIDelegate:nil + completion:^(NSString* _Nullable verificationID, NSError* _Nullable error) { + MutexLock lock(objc_listener_data->listener_mutex); + + // If the listener has been deleted before this callback, do nothing. + if (objc_listener_data->active_listener == nullptr) return; + + // Call OnVerificationFailed() or OnCodeSent() as appropriate. + if (verificationID == nullptr) { + listener->OnVerificationFailed( + util::StringFromNSString(error.localizedDescription)); + } else { + listener->OnCodeSent(util::StringFromNSString(verificationID), + invalid_resending_token); + } + }]; // Only call the callback when protected by the mutex. { @@ -330,10 +331,11 @@ explicit PhoneAuthProviderData(FIRPhoneAuthProvider* objc_provider) } } } -#else // non-iOS Apple platforms (eg: tvOS) -void PhoneAuthProvider::VerifyPhoneNumber( - const char* /*phone_number*/, uint32_t /*auto_verify_time_out_ms*/, - const ForceResendingToken* force_resending_token, Listener* listener) { +#else // non-iOS Apple platforms (eg: tvOS) +void PhoneAuthProvider::VerifyPhoneNumber(const char* /*phone_number*/, + uint32_t /*auto_verify_time_out_ms*/, + const ForceResendingToken* force_resending_token, + Listener* listener) { FIREBASE_ASSERT_RETURN_VOID(listener != nullptr); // Mock the tokens by sending a new one whenever it's unspecified. @@ -345,26 +347,27 @@ explicit PhoneAuthProviderData(FIRPhoneAuthProvider* objc_provider) listener->OnCodeAutoRetrievalTimeOut(kMockVerificationId); listener->OnCodeSent(kMockVerificationId, token); } -#endif // FIREBASE_PLATFORM_IOS +#endif // FIREBASE_PLATFORM_IOS #if FIREBASE_PLATFORM_IOS Credential PhoneAuthProvider::GetCredential(const char* verification_id, const char* verification_code) { FIREBASE_ASSERT_RETURN(Credential(), verification_id && verification_code); - FIRPhoneAuthCredential *credential = + FIRPhoneAuthCredential* credential = [data_->objc_provider credentialWithVerificationID:@(verification_id) verificationCode:@(verification_code)]; return Credential(new FIRAuthCredentialPointer((FIRAuthCredential*)credential)); } -#else // non-iOS Apple platforms (eg: tvOS) +#else // non-iOS Apple platforms (eg: tvOS) Credential PhoneAuthProvider::GetCredential(const char* verification_id, const char* verification_code) { - FIREBASE_ASSERT_MESSAGE_RETURN(Credential(nullptr), false, - "Phone Auth is not supported on non iOS Apple platforms (eg:tvOS)."); + FIREBASE_ASSERT_MESSAGE_RETURN( + Credential(nullptr), false, + "Phone Auth is not supported on non iOS Apple platforms (eg:tvOS)."); return Credential(nullptr); } -#endif // FIREBASE_PLATFORM_IOS +#endif // FIREBASE_PLATFORM_IOS #if FIREBASE_PLATFORM_IOS // static @@ -379,21 +382,21 @@ explicit PhoneAuthProviderData(FIRPhoneAuthProvider* objc_provider) } return provider; } -#else // non-iOS Apple platforms (eg: tvOS) +#else // non-iOS Apple platforms (eg: tvOS) // static PhoneAuthProvider& PhoneAuthProvider::GetInstance(Auth* auth) { return auth->auth_data_->phone_auth_provider; } -#endif // FIREBASE_PLATFORM_IOS +#endif // FIREBASE_PLATFORM_IOS // FederatedAuthHandlers -FederatedOAuthProvider::FederatedOAuthProvider() { } +FederatedOAuthProvider::FederatedOAuthProvider() {} FederatedOAuthProvider::FederatedOAuthProvider(const FederatedOAuthProviderData& provider_data) { provider_data_ = provider_data; } -FederatedOAuthProvider::~FederatedOAuthProvider() { } +FederatedOAuthProvider::~FederatedOAuthProvider() {} void FederatedOAuthProvider::SetProviderData(const FederatedOAuthProviderData& provider_data) { provider_data_ = provider_data; @@ -450,9 +453,8 @@ void ReauthenticateWithProviderGetCredentialCallback(FIRAuthCredential* _Nullabl Future FederatedOAuthProvider::SignIn(AuthData* auth_data) { assert(auth_data); - ReferenceCountedFutureImpl &futures = auth_data->future_impl; - const auto handle = - futures.SafeAlloc(kAuthFn_SignInWithProvider, SignInResult()); + ReferenceCountedFutureImpl& futures = auth_data->future_impl; + const auto handle = futures.SafeAlloc(kAuthFn_SignInWithProvider, SignInResult()); FIROAuthProvider* ios_provider = (FIROAuthProvider*)[FIROAuthProvider providerWithProviderID:@(provider_data_.provider_id.c_str()) auth:AuthImpl(auth_data)]; @@ -470,17 +472,16 @@ void ReauthenticateWithProviderGetCredentialCallback(FIRAuthCredential* _Nullabl } else { Future future = MakeFuture(&futures, handle); futures.CompleteWithResult(handle, kAuthErrorFailure, "Internal error constructing provider.", - SignInResult()); + SignInResult()); return future; } } Future FederatedOAuthProvider::Link(AuthData* auth_data) { assert(auth_data); - ReferenceCountedFutureImpl &futures = auth_data->future_impl; - auto handle = - futures.SafeAlloc(kUserFn_LinkWithProvider, SignInResult()); - #if FIREBASE_PLATFORM_IOS + ReferenceCountedFutureImpl& futures = auth_data->future_impl; + auto handle = futures.SafeAlloc(kUserFn_LinkWithProvider, SignInResult()); +#if FIREBASE_PLATFORM_IOS FIROAuthProvider* ios_provider = (FIROAuthProvider*)[FIROAuthProvider providerWithProviderID:@(provider_data_.provider_id.c_str()) auth:AuthImpl(auth_data)]; @@ -489,13 +490,12 @@ void ReauthenticateWithProviderGetCredentialCallback(FIRAuthCredential* _Nullabl ios_provider.scopes = util::StringVectorToNSMutableArray(provider_data_.scopes); // TODO(b/138788092) invoke FIRUser linkWithProvider instead, once that method is added to the // iOS SDK. - [ios_provider - getCredentialWithUIDelegate:nullptr - completion:^(FIRAuthCredential* _Nullable credential, - NSError* _Nullable error) { - LinkWithProviderGetCredentialCallback( - credential, error, handle, auth_data, ios_provider); - }]; + [ios_provider getCredentialWithUIDelegate:nullptr + completion:^(FIRAuthCredential* _Nullable credential, + NSError* _Nullable error) { + LinkWithProviderGetCredentialCallback( + credential, error, handle, auth_data, ios_provider); + }]; return MakeFuture(&futures, handle); } else { Future future = MakeFuture(&futures, handle); @@ -504,20 +504,18 @@ void ReauthenticateWithProviderGetCredentialCallback(FIRAuthCredential* _Nullabl return future; } - #else // non-iOS Apple platforms (eg: tvOS) +#else // non-iOS Apple platforms (eg: tvOS) Future future = MakeFuture(&futures, handle); futures.Complete(handle, kAuthErrorApiNotAvailable, - "OAuth provider linking is not supported on non-iOS Apple platforms."); - #endif // FIREBASE_PLATFORM_IOS - + "OAuth provider linking is not supported on non-iOS Apple platforms."); +#endif // FIREBASE_PLATFORM_IOS } Future FederatedOAuthProvider::Reauthenticate(AuthData* auth_data) { assert(auth_data); - ReferenceCountedFutureImpl &futures = auth_data->future_impl; - auto handle = - futures.SafeAlloc(kUserFn_LinkWithProvider, SignInResult()); - #if FIREBASE_PLATFORM_IOS + ReferenceCountedFutureImpl& futures = auth_data->future_impl; + auto handle = futures.SafeAlloc(kUserFn_LinkWithProvider, SignInResult()); +#if FIREBASE_PLATFORM_IOS FIROAuthProvider* ios_provider = (FIROAuthProvider*)[FIROAuthProvider providerWithProviderID:@(provider_data_.provider_id.c_str()) auth:AuthImpl(auth_data)]; @@ -526,13 +524,12 @@ void ReauthenticateWithProviderGetCredentialCallback(FIRAuthCredential* _Nullabl ios_provider.scopes = util::StringVectorToNSMutableArray(provider_data_.scopes); // TODO(b/138788092) invoke FIRUser:reuthenticateWithProvider instead, once that method is added // to the iOS SDK. - [ios_provider - getCredentialWithUIDelegate:nullptr - completion:^(FIRAuthCredential* _Nullable credential, - NSError* _Nullable error) { - ReauthenticateWithProviderGetCredentialCallback( - credential, error, handle, auth_data, ios_provider); - }]; + [ios_provider getCredentialWithUIDelegate:nullptr + completion:^(FIRAuthCredential* _Nullable credential, + NSError* _Nullable error) { + ReauthenticateWithProviderGetCredentialCallback( + credential, error, handle, auth_data, ios_provider); + }]; return MakeFuture(&futures, handle); } else { Future future = MakeFuture(&futures, handle); @@ -541,11 +538,11 @@ void ReauthenticateWithProviderGetCredentialCallback(FIRAuthCredential* _Nullabl return future; } - #else // non-iOS Apple platforms (eg: tvOS) +#else // non-iOS Apple platforms (eg: tvOS) Future future = MakeFuture(&futures, handle); futures.Complete(handle, kAuthErrorApiNotAvailable, - "OAuth reauthentication is not supported on non-iOS Apple platforms."); - #endif // FIREBASE_PLATFORM_IOS + "OAuth reauthentication is not supported on non-iOS Apple platforms."); +#endif // FIREBASE_PLATFORM_IOS } } // namespace auth diff --git a/auth/src/ios/user_ios.mm b/auth/src/ios/user_ios.mm index ccbe470199..e4c3817440 100644 --- a/auth/src/ios/user_ios.mm +++ b/auth/src/ios/user_ios.mm @@ -33,33 +33,19 @@ public: explicit IOSWrappedUserInfo(id user_info) : user_info_(user_info) {} - virtual ~IOSWrappedUserInfo() { - user_info_ = nil; - } + virtual ~IOSWrappedUserInfo() { user_info_ = nil; } - virtual std::string uid() const { - return StringFromNSString(user_info_.uid); - } + virtual std::string uid() const { return StringFromNSString(user_info_.uid); } - virtual std::string email() const { - return StringFromNSString(user_info_.email); - } + virtual std::string email() const { return StringFromNSString(user_info_.email); } - virtual std::string display_name() const { - return StringFromNSString(user_info_.displayName); - } + virtual std::string display_name() const { return StringFromNSString(user_info_.displayName); } - virtual std::string phone_number() const { - return StringFromNSString(user_info_.phoneNumber); - } + virtual std::string phone_number() const { return StringFromNSString(user_info_.phoneNumber); } - virtual std::string photo_url() const { - return StringFromNSUrl(user_info_.photoURL); - } + virtual std::string photo_url() const { return StringFromNSUrl(user_info_.photoURL); } - virtual std::string provider_id() const { - return StringFromNSString(user_info_.providerID); - } + virtual std::string provider_id() const { return StringFromNSString(user_info_.providerID); } private: /// Pointer to the main class. @@ -78,21 +64,21 @@ explicit IOSWrappedUserInfo(id user_info) : user_info_(user_info) { if (!ValidUser(auth_data_)) { return Future(); } - ReferenceCountedFutureImpl& futures = auth_data_->future_impl; + ReferenceCountedFutureImpl &futures = auth_data_->future_impl; const auto handle = futures.SafeAlloc(kUserFn_GetToken); [UserImpl(auth_data_) getIDTokenForcingRefresh:force_refresh completion:^(NSString *_Nullable token, NSError *_Nullable error) { - futures.Complete( - handle, AuthErrorFromNSError(error), - [error.localizedDescription UTF8String], [token](std::string* data) { - data->assign(token == nullptr ? "" : [token UTF8String]); - }); - }]; + futures.Complete(handle, AuthErrorFromNSError(error), + [error.localizedDescription UTF8String], + [token](std::string *data) { + data->assign(token == nullptr ? "" : [token UTF8String]); + }); + }]; return MakeFuture(&futures, handle); } -const std::vector& User::provider_data() const { +const std::vector &User::provider_data() const { ClearUserInfos(auth_data_); if (ValidUser(auth_data_)) { @@ -113,13 +99,13 @@ explicit IOSWrappedUserInfo(id user_info) : user_info_(user_info) { if (!ValidUser(auth_data_)) { return Future(); } - ReferenceCountedFutureImpl& futures = auth_data_->future_impl; + ReferenceCountedFutureImpl &futures = auth_data_->future_impl; const auto handle = futures.SafeAlloc(kUserFn_UpdateEmail); [UserImpl(auth_data_) updateEmail:@(email) completion:^(NSError *_Nullable error) { - futures.Complete(handle, AuthErrorFromNSError(error), - [error.localizedDescription UTF8String]); - }]; + futures.Complete(handle, AuthErrorFromNSError(error), + [error.localizedDescription UTF8String]); + }]; return MakeFuture(&futures, handle); } @@ -127,22 +113,21 @@ explicit IOSWrappedUserInfo(id user_info) : user_info_(user_info) { if (!ValidUser(auth_data_)) { return Future(); } - ReferenceCountedFutureImpl& futures = auth_data_->future_impl; + ReferenceCountedFutureImpl &futures = auth_data_->future_impl; const auto handle = futures.SafeAlloc(kUserFn_UpdatePassword); - [UserImpl(auth_data_) - updatePassword:@(password) - completion:^(NSError *_Nullable error) { - futures.Complete(handle, AuthErrorFromNSError(error), - [error.localizedDescription UTF8String]); - }]; + [UserImpl(auth_data_) updatePassword:@(password) + completion:^(NSError *_Nullable error) { + futures.Complete(handle, AuthErrorFromNSError(error), + [error.localizedDescription UTF8String]); + }]; return MakeFuture(&futures, handle); } -Future User::UpdateUserProfile(const UserProfile& profile) { +Future User::UpdateUserProfile(const UserProfile &profile) { if (!ValidUser(auth_data_)) { return Future(); } - ReferenceCountedFutureImpl& futures = auth_data_->future_impl; + ReferenceCountedFutureImpl &futures = auth_data_->future_impl; const auto handle = futures.SafeAlloc(kUserFn_UpdateUserProfile); // Create and populate the change request. FIRUserProfileChangeRequest *request = [UserImpl(auth_data_) profileChangeRequest]; @@ -151,15 +136,15 @@ explicit IOSWrappedUserInfo(id user_info) : user_info_(user_info) { } if (profile.photo_url != nullptr) { NSString *photo_url_string = @(profile.photo_url); - request.photoURL = [NSURL URLWithString:[photo_url_string - stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]; + request.photoURL = + [NSURL URLWithString:[photo_url_string + stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]; } // Execute the change request. [request commitChangesWithCompletion:^(NSError *_Nullable error) { - futures.Complete(handle, AuthErrorFromNSError(error), - [error.localizedDescription UTF8String]); - }]; + futures.Complete(handle, AuthErrorFromNSError(error), [error.localizedDescription UTF8String]); + }]; return MakeFuture(&futures, handle); } @@ -167,21 +152,20 @@ explicit IOSWrappedUserInfo(id user_info) : user_info_(user_info) { if (!ValidUser(auth_data_)) { return Future(); } - ReferenceCountedFutureImpl& futures = auth_data_->future_impl; + ReferenceCountedFutureImpl &futures = auth_data_->future_impl; const auto handle = futures.SafeAlloc(kUserFn_SendEmailVerification); [UserImpl(auth_data_) sendEmailVerificationWithCompletion:^(NSError *_Nullable error) { - futures.Complete(handle, AuthErrorFromNSError(error), - [error.localizedDescription UTF8String]); + futures.Complete(handle, AuthErrorFromNSError(error), [error.localizedDescription UTF8String]); }]; return MakeFuture(&futures, handle); } -Future User::LinkWithCredential(const Credential &credential) { +Future User::LinkWithCredential(const Credential &credential) { if (!ValidUser(auth_data_)) { - return Future(); + return Future(); } - ReferenceCountedFutureImpl& futures = auth_data_->future_impl; - const auto handle = futures.SafeAlloc(kUserFn_LinkWithCredential); + ReferenceCountedFutureImpl &futures = auth_data_->future_impl; + const auto handle = futures.SafeAlloc(kUserFn_LinkWithCredential); [UserImpl(auth_data_) linkWithCredential:CredentialFromImpl(credential.impl_) completion:^(FIRAuthDataResult *_Nullable auth_result, NSError *_Nullable error) { @@ -194,61 +178,59 @@ explicit IOSWrappedUserInfo(id user_info) : user_info_(user_info) { if (!ValidUser(auth_data_)) { return Future(); } - ReferenceCountedFutureImpl& futures = auth_data_->future_impl; + ReferenceCountedFutureImpl &futures = auth_data_->future_impl; const auto handle = auth_data_->future_impl.SafeAlloc( - kUserFn_LinkAndRetrieveDataWithCredential, SignInResult()); + kUserFn_LinkAndRetrieveDataWithCredential, SignInResult()); [UserImpl(auth_data_) linkWithCredential:CredentialFromImpl(credential.impl_) - completion:^(FIRAuthDataResult *_Nullable auth_result, - NSError *_Nullable error) { - SignInResultCallback(auth_result, error, handle, auth_data_); - }]; + completion:^(FIRAuthDataResult *_Nullable auth_result, NSError *_Nullable error) { + SignInResultCallback(auth_result, error, handle, auth_data_); + }]; return MakeFuture(&futures, handle); } -Future User::LinkWithProvider(FederatedAuthProvider* provider) const { +Future User::LinkWithProvider(FederatedAuthProvider *provider) const { FIREBASE_ASSERT_RETURN(Future(), provider); return provider->Link(auth_data_); } -Future User::Unlink(const char *provider) { +Future User::Unlink(const char *provider) { if (!ValidUser(auth_data_)) { - return Future(); + return Future(); } - ReferenceCountedFutureImpl& futures = auth_data_->future_impl; - const auto handle = futures.SafeAlloc(kUserFn_Unlink); - [UserImpl(auth_data_) - unlinkFromProvider:@(provider) - completion:^(FIRUser *_Nullable user, NSError *_Nullable error) { - SignInCallback(user, error, handle, auth_data_); - }]; + ReferenceCountedFutureImpl &futures = auth_data_->future_impl; + const auto handle = futures.SafeAlloc(kUserFn_Unlink); + [UserImpl(auth_data_) unlinkFromProvider:@(provider) + completion:^(FIRUser *_Nullable user, NSError *_Nullable error) { + SignInCallback(user, error, handle, auth_data_); + }]; return MakeFuture(&futures, handle); } -Future User::UpdatePhoneNumberCredential(const Credential& credential) { +Future User::UpdatePhoneNumberCredential(const Credential &credential) { if (!ValidUser(auth_data_)) { - return Future(); + return Future(); } - ReferenceCountedFutureImpl& futures = auth_data_->future_impl; - const auto handle = futures.SafeAlloc(kUserFn_UpdatePhoneNumberCredential); + ReferenceCountedFutureImpl &futures = auth_data_->future_impl; + const auto handle = futures.SafeAlloc(kUserFn_UpdatePhoneNumberCredential); - #if FIREBASE_PLATFORM_IOS +#if FIREBASE_PLATFORM_IOS FIRAuthCredential *objc_credential = CredentialFromImpl(credential.impl_); if ([objc_credential isKindOfClass:[FIRPhoneAuthCredential class]]) { [UserImpl(auth_data_) - updatePhoneNumberCredential:(FIRPhoneAuthCredential*)objc_credential - completion:^(NSError *_Nullable error) { - futures.Complete(handle, AuthErrorFromNSError(error), - [error.localizedDescription UTF8String]); - }]; + updatePhoneNumberCredential:(FIRPhoneAuthCredential *)objc_credential + completion:^(NSError *_Nullable error) { + futures.Complete(handle, AuthErrorFromNSError(error), + [error.localizedDescription UTF8String]); + }]; } else { futures.Complete(handle, kAuthErrorInvalidCredential, kInvalidCredentialMessage); } - #else // non iOS Apple platforms (eg: tvOS). +#else // non iOS Apple platforms (eg: tvOS). futures.Complete(handle, kAuthErrorApiNotAvailable, "Phone Auth is not supported on non-iOS apple platforms."); - #endif // FIREBASE_PLATFORM_IOS +#endif // FIREBASE_PLATFORM_IOS return MakeFuture(&futures, handle); } @@ -257,21 +239,20 @@ explicit IOSWrappedUserInfo(id user_info) : user_info_(user_info) { if (!ValidUser(auth_data_)) { return Future(); } - ReferenceCountedFutureImpl& futures = auth_data_->future_impl; + ReferenceCountedFutureImpl &futures = auth_data_->future_impl; const auto handle = futures.SafeAlloc(kUserFn_Reload); [UserImpl(auth_data_) reloadWithCompletion:^(NSError *_Nullable error) { - futures.Complete(handle, AuthErrorFromNSError(error), - [error.localizedDescription UTF8String]); + futures.Complete(handle, AuthErrorFromNSError(error), [error.localizedDescription UTF8String]); }]; return MakeFuture(&futures, handle); } -Future User::Reauthenticate(const Credential& credential) { +Future User::Reauthenticate(const Credential &credential) { if (!ValidUser(auth_data_)) { return Future(); } - ReferenceCountedFutureImpl& futures = auth_data_->future_impl; + ReferenceCountedFutureImpl &futures = auth_data_->future_impl; const auto handle = futures.SafeAlloc(kUserFn_Reauthenticate); [UserImpl(auth_data_) @@ -284,11 +265,11 @@ explicit IOSWrappedUserInfo(id user_info) : user_info_(user_info) { return MakeFuture(&futures, handle); } -Future User::ReauthenticateAndRetrieveData(const Credential& credential) { +Future User::ReauthenticateAndRetrieveData(const Credential &credential) { if (!ValidUser(auth_data_)) { return Future(); } - ReferenceCountedFutureImpl& futures = auth_data_->future_impl; + ReferenceCountedFutureImpl &futures = auth_data_->future_impl; const auto handle = auth_data_->future_impl.SafeAlloc( kUserFn_ReauthenticateAndRetrieveData, SignInResult()); @@ -296,12 +277,12 @@ explicit IOSWrappedUserInfo(id user_info) : user_info_(user_info) { reauthenticateWithCredential:CredentialFromImpl(credential.impl_) completion:^(FIRAuthDataResult *_Nullable auth_result, NSError *_Nullable error) { - SignInResultCallback(auth_result, error, handle, auth_data_); - }]; + SignInResultCallback(auth_result, error, handle, auth_data_); + }]; return MakeFuture(&futures, handle); } -Future User::ReauthenticateWithProvider(FederatedAuthProvider* provider) const { +Future User::ReauthenticateWithProvider(FederatedAuthProvider *provider) const { FIREBASE_ASSERT_RETURN(Future(), provider); return provider->Reauthenticate(auth_data_); } @@ -310,7 +291,7 @@ explicit IOSWrappedUserInfo(id user_info) : user_info_(user_info) { if (!ValidUser(auth_data_)) { return Future(); } - ReferenceCountedFutureImpl& futures = auth_data_->future_impl; + ReferenceCountedFutureImpl &futures = auth_data_->future_impl; const auto handle = futures.SafeAlloc(kUserFn_Delete); [UserImpl(auth_data_) deleteWithCompletion:^(NSError *_Nullable error) { diff --git a/auth/src_java/com/google/firebase/auth/internal/cpp/AuthCommon.java b/auth/src_java/com/google/firebase/auth/internal/cpp/AuthCommon.java index 9d1f64364e..37c2500c10 100644 --- a/auth/src_java/com/google/firebase/auth/internal/cpp/AuthCommon.java +++ b/auth/src_java/com/google/firebase/auth/internal/cpp/AuthCommon.java @@ -31,8 +31,10 @@ public static void safeRunNativeMethod(Runnable runnable) { try { runnable.run(); } catch (UnsatisfiedLinkError e) { - Log.e(TAG, String.format("Failed to execute native method, perhaps Auth shut down " - + "prematurely? (%s)", e.toString())); + Log.e(TAG, + String.format("Failed to execute native method, perhaps Auth shut down " + + "prematurely? (%s)", + e.toString())); } } } diff --git a/auth/src_java/com/google/firebase/auth/internal/cpp/JniAuthPhoneListener.java b/auth/src_java/com/google/firebase/auth/internal/cpp/JniAuthPhoneListener.java index ed2e3513f6..700f9b81c6 100644 --- a/auth/src_java/com/google/firebase/auth/internal/cpp/JniAuthPhoneListener.java +++ b/auth/src_java/com/google/firebase/auth/internal/cpp/JniAuthPhoneListener.java @@ -52,11 +52,11 @@ public void onVerificationCompleted(final PhoneAuthCredential credential) { synchronized (lock) { if (cListener != CPP_NULLPTR) { AuthCommon.safeRunNativeMethod(new Runnable() { - @Override - public void run() { - nativeOnVerificationCompleted(cListener, credential); - } - }); + @Override + public void run() { + nativeOnVerificationCompleted(cListener, credential); + } + }); } } } @@ -66,11 +66,11 @@ public void onVerificationFailed(final FirebaseException exception) { synchronized (lock) { if (cListener != CPP_NULLPTR) { AuthCommon.safeRunNativeMethod(new Runnable() { - @Override - public void run() { - nativeOnVerificationFailed(cListener, exception.getMessage()); - } - }); + @Override + public void run() { + nativeOnVerificationFailed(cListener, exception.getMessage()); + } + }); } } } @@ -80,11 +80,11 @@ public void onCodeSent(final String verificationId, final ForceResendingToken to synchronized (lock) { if (cListener != CPP_NULLPTR) { AuthCommon.safeRunNativeMethod(new Runnable() { - @Override - public void run() { - nativeOnCodeSent(cListener, verificationId, token); - } - }); + @Override + public void run() { + nativeOnCodeSent(cListener, verificationId, token); + } + }); } } } @@ -94,11 +94,11 @@ public void onCodeAutoRetrievalTimeOut(final String verificationId) { synchronized (lock) { if (cListener != CPP_NULLPTR) { AuthCommon.safeRunNativeMethod(new Runnable() { - @Override - public void run() { - nativeOnCodeAutoRetrievalTimeOut(cListener, verificationId); - } - }); + @Override + public void run() { + nativeOnCodeAutoRetrievalTimeOut(cListener, verificationId); + } + }); } } } @@ -106,10 +106,9 @@ public void run() { /** * This function is implemented in the Auth C++ library (credential_android.cc). */ - private native void nativeOnVerificationCompleted(long cListener, - PhoneAuthCredential credential); + private native void nativeOnVerificationCompleted(long cListener, PhoneAuthCredential credential); private native void nativeOnVerificationFailed(long cListener, String exceptionMessage); - private native void nativeOnCodeSent(long cListener, String verificationId, - ForceResendingToken forceResendingToken); + private native void nativeOnCodeSent( + long cListener, String verificationId, ForceResendingToken forceResendingToken); private native void nativeOnCodeAutoRetrievalTimeOut(long cListener, String verificationId); } diff --git a/auth/src_java/com/google/firebase/auth/internal/cpp/JniAuthStateListener.java b/auth/src_java/com/google/firebase/auth/internal/cpp/JniAuthStateListener.java index 6ee02bc183..6c354d6260 100644 --- a/auth/src_java/com/google/firebase/auth/internal/cpp/JniAuthStateListener.java +++ b/auth/src_java/com/google/firebase/auth/internal/cpp/JniAuthStateListener.java @@ -22,7 +22,6 @@ * Implements AuthStateListener by redirecting calls into C++. */ public class JniAuthStateListener implements FirebaseAuth.AuthStateListener { - /** * Lock that controls access to authData. */ @@ -54,15 +53,15 @@ public void disconnect() { @Override public void onAuthStateChanged(FirebaseAuth auth) { AuthCommon.safeRunNativeMethod(new Runnable() { - @Override - public void run() { - synchronized (lock) { - if (cppAuthData != 0) { - nativeOnAuthStateChanged(cppAuthData); - } + @Override + public void run() { + synchronized (lock) { + if (cppAuthData != 0) { + nativeOnAuthStateChanged(cppAuthData); } } - }); + } + }); } /** diff --git a/auth/src_java/com/google/firebase/auth/internal/cpp/JniIdTokenListener.java b/auth/src_java/com/google/firebase/auth/internal/cpp/JniIdTokenListener.java index 5abad2fb46..07da7ccbce 100644 --- a/auth/src_java/com/google/firebase/auth/internal/cpp/JniIdTokenListener.java +++ b/auth/src_java/com/google/firebase/auth/internal/cpp/JniIdTokenListener.java @@ -22,7 +22,6 @@ * Implements IdTokenListener by redirecting calls into C++. */ public class JniIdTokenListener implements FirebaseAuth.IdTokenListener { - /** * Lock that controls access to authData. */ @@ -54,15 +53,15 @@ public void disconnect() { @Override public void onIdTokenChanged(FirebaseAuth auth) { AuthCommon.safeRunNativeMethod(new Runnable() { - @Override - public void run() { - synchronized (lock) { - if (cppAuthData != 0) { - nativeOnIdTokenChanged(cppAuthData); - } + @Override + public void run() { + synchronized (lock) { + if (cppAuthData != 0) { + nativeOnIdTokenChanged(cppAuthData); } } - }); + } + }); } /** diff --git a/auth/src_java/fake/com/google/firebase/FirebaseApiNotAvailableException.java b/auth/src_java/fake/com/google/firebase/FirebaseApiNotAvailableException.java index 263e3035e2..d480463fb0 100644 --- a/auth/src_java/fake/com/google/firebase/FirebaseApiNotAvailableException.java +++ b/auth/src_java/fake/com/google/firebase/FirebaseApiNotAvailableException.java @@ -18,7 +18,6 @@ /** Fake FirebaseApiNotAvailableException */ public class FirebaseApiNotAvailableException extends FirebaseException { - public FirebaseApiNotAvailableException(String message) { super(message); } diff --git a/auth/src_java/fake/com/google/firebase/FirebaseNetworkException.java b/auth/src_java/fake/com/google/firebase/FirebaseNetworkException.java index 80571d4871..eda0365450 100644 --- a/auth/src_java/fake/com/google/firebase/FirebaseNetworkException.java +++ b/auth/src_java/fake/com/google/firebase/FirebaseNetworkException.java @@ -18,7 +18,6 @@ /** Fake FirebaseNetworkException */ public class FirebaseNetworkException extends FirebaseException { - public FirebaseNetworkException(String message) { super(message); } diff --git a/auth/src_java/fake/com/google/firebase/FirebaseTooManyRequestsException.java b/auth/src_java/fake/com/google/firebase/FirebaseTooManyRequestsException.java index 339c566a92..ef4aa8a84d 100644 --- a/auth/src_java/fake/com/google/firebase/FirebaseTooManyRequestsException.java +++ b/auth/src_java/fake/com/google/firebase/FirebaseTooManyRequestsException.java @@ -18,7 +18,6 @@ /** Fake FirebaseTooManyRequestsException */ public class FirebaseTooManyRequestsException extends FirebaseException { - public FirebaseTooManyRequestsException(String message) { super(message); } diff --git a/auth/src_java/fake/com/google/firebase/auth/AdditionalUserInfo.java b/auth/src_java/fake/com/google/firebase/auth/AdditionalUserInfo.java index c4eaeb29cf..4761c2c135 100644 --- a/auth/src_java/fake/com/google/firebase/auth/AdditionalUserInfo.java +++ b/auth/src_java/fake/com/google/firebase/auth/AdditionalUserInfo.java @@ -20,7 +20,6 @@ /** Fake AdditionalUserInfo */ public final class AdditionalUserInfo { - public String getProviderId() { return "fake provider id"; } diff --git a/auth/src_java/fake/com/google/firebase/auth/AuthCredential.java b/auth/src_java/fake/com/google/firebase/auth/AuthCredential.java index 8022311410..e52aa30f31 100644 --- a/auth/src_java/fake/com/google/firebase/auth/AuthCredential.java +++ b/auth/src_java/fake/com/google/firebase/auth/AuthCredential.java @@ -20,8 +20,10 @@ public final class AuthCredential { private String provider; - /** C++ code does not rely on any constructor. This is solely for fake to specify provider and - * does not map to a constructor in the real AuthCredential. */ + /** + * C++ code does not rely on any constructor. This is solely for fake to specify provider and + * does not map to a constructor in the real AuthCredential. + */ AuthCredential(String provider) { this.provider = provider; } diff --git a/auth/src_java/fake/com/google/firebase/auth/AuthResult.java b/auth/src_java/fake/com/google/firebase/auth/AuthResult.java index fa3bf9fa92..3d5c6da4af 100644 --- a/auth/src_java/fake/com/google/firebase/auth/AuthResult.java +++ b/auth/src_java/fake/com/google/firebase/auth/AuthResult.java @@ -18,7 +18,6 @@ /** Fake AuthResult */ public final class AuthResult { - FirebaseUser getUser() { return new FirebaseUser(); } diff --git a/auth/src_java/fake/com/google/firebase/auth/EmailAuthProvider.java b/auth/src_java/fake/com/google/firebase/auth/EmailAuthProvider.java index c785cfb7aa..96171dcb49 100644 --- a/auth/src_java/fake/com/google/firebase/auth/EmailAuthProvider.java +++ b/auth/src_java/fake/com/google/firebase/auth/EmailAuthProvider.java @@ -18,7 +18,6 @@ /** Fake EmailAuthProvider */ public final class EmailAuthProvider { - public static AuthCredential getCredential(String email, String password) { return new AuthCredential("password"); } diff --git a/auth/src_java/fake/com/google/firebase/auth/FacebookAuthProvider.java b/auth/src_java/fake/com/google/firebase/auth/FacebookAuthProvider.java index ee9997561b..1973bc4e22 100644 --- a/auth/src_java/fake/com/google/firebase/auth/FacebookAuthProvider.java +++ b/auth/src_java/fake/com/google/firebase/auth/FacebookAuthProvider.java @@ -18,7 +18,6 @@ /** Fake FacebookAuthProvider */ public final class FacebookAuthProvider { - public static AuthCredential getCredential(String accessToken) { return new AuthCredential("facebook.com"); } diff --git a/auth/src_java/fake/com/google/firebase/auth/FirebaseAuth.java b/auth/src_java/fake/com/google/firebase/auth/FirebaseAuth.java index 6a02beeea3..3dabb3aa90 100644 --- a/auth/src_java/fake/com/google/firebase/auth/FirebaseAuth.java +++ b/auth/src_java/fake/com/google/firebase/auth/FirebaseAuth.java @@ -106,15 +106,13 @@ private void randomDelayThread() { public void addAuthStateListener(final AuthStateListener listener) { authStateListeners.add(listener); - new Thread( - new Runnable() { - @Override - public void run() { - randomDelayThread(); - listener.onAuthStateChanged(FirebaseAuth.this); - } - }) - .start(); + new Thread(new Runnable() { + @Override + public void run() { + randomDelayThread(); + listener.onAuthStateChanged(FirebaseAuth.this); + } + }).start(); } public void removeAuthStateListener(AuthStateListener listener) { @@ -123,15 +121,13 @@ public void removeAuthStateListener(AuthStateListener listener) { public void addIdTokenListener(final IdTokenListener listener) { idTokenListeners.add(listener); - new Thread( - new Runnable() { - @Override - public void run() { - randomDelayThread(); - listener.onIdTokenChanged(FirebaseAuth.this); - } - }) - .start(); + new Thread(new Runnable() { + @Override + public void run() { + randomDelayThread(); + listener.onIdTokenChanged(FirebaseAuth.this); + } + }).start(); } public void removeIdTokenListener(IdTokenListener listener) { @@ -152,7 +148,7 @@ public String getLanguageCode() { /** Sets the user-facing language code to be the default app language. */ public void useAppLanguage() { - languageCode = "en-US"; + languageCode = "en-US"; } public Task fetchSignInMethodsForEmail(String email) { diff --git a/auth/src_java/fake/com/google/firebase/auth/FirebaseAuthActionCodeException.java b/auth/src_java/fake/com/google/firebase/auth/FirebaseAuthActionCodeException.java index 30cc2e5398..fc9251d0c7 100644 --- a/auth/src_java/fake/com/google/firebase/auth/FirebaseAuthActionCodeException.java +++ b/auth/src_java/fake/com/google/firebase/auth/FirebaseAuthActionCodeException.java @@ -18,7 +18,6 @@ /** Fake FirebaseAuthActionCodeException */ public class FirebaseAuthActionCodeException extends FirebaseAuthException { - public FirebaseAuthActionCodeException(String code, String message) { super(code, message); } diff --git a/auth/src_java/fake/com/google/firebase/auth/FirebaseAuthEmailException.java b/auth/src_java/fake/com/google/firebase/auth/FirebaseAuthEmailException.java index e1d46ad849..f2cf1aa54c 100644 --- a/auth/src_java/fake/com/google/firebase/auth/FirebaseAuthEmailException.java +++ b/auth/src_java/fake/com/google/firebase/auth/FirebaseAuthEmailException.java @@ -18,7 +18,6 @@ /** Fake FirebaseAuthEmailException */ public class FirebaseAuthEmailException extends FirebaseAuthException { - public FirebaseAuthEmailException(String code, String message) { super(code, message); } diff --git a/auth/src_java/fake/com/google/firebase/auth/FirebaseAuthException.java b/auth/src_java/fake/com/google/firebase/auth/FirebaseAuthException.java index f519095c5a..12850e1916 100644 --- a/auth/src_java/fake/com/google/firebase/auth/FirebaseAuthException.java +++ b/auth/src_java/fake/com/google/firebase/auth/FirebaseAuthException.java @@ -20,7 +20,6 @@ /** Fake FirebaseAuthException */ public class FirebaseAuthException extends FirebaseException { - public FirebaseAuthException(String code, String message) { super(message); code_ = code; diff --git a/auth/src_java/fake/com/google/firebase/auth/FirebaseAuthInvalidCredentialsException.java b/auth/src_java/fake/com/google/firebase/auth/FirebaseAuthInvalidCredentialsException.java index 8e37cda351..75f5a611d3 100644 --- a/auth/src_java/fake/com/google/firebase/auth/FirebaseAuthInvalidCredentialsException.java +++ b/auth/src_java/fake/com/google/firebase/auth/FirebaseAuthInvalidCredentialsException.java @@ -18,7 +18,6 @@ /** Fake FirebaseAuthInvalidCredentialsException */ public class FirebaseAuthInvalidCredentialsException extends FirebaseAuthException { - public FirebaseAuthInvalidCredentialsException(String code, String message) { super(code, message); } diff --git a/auth/src_java/fake/com/google/firebase/auth/FirebaseAuthInvalidUserException.java b/auth/src_java/fake/com/google/firebase/auth/FirebaseAuthInvalidUserException.java index 30566fa193..b3d298603b 100644 --- a/auth/src_java/fake/com/google/firebase/auth/FirebaseAuthInvalidUserException.java +++ b/auth/src_java/fake/com/google/firebase/auth/FirebaseAuthInvalidUserException.java @@ -18,7 +18,6 @@ /** Fake FirebaseAuthInvalidUserException */ public final class FirebaseAuthInvalidUserException extends FirebaseAuthException { - public FirebaseAuthInvalidUserException(String code, String message) { super(code, message); } diff --git a/auth/src_java/fake/com/google/firebase/auth/FirebaseAuthRecentLoginRequiredException.java b/auth/src_java/fake/com/google/firebase/auth/FirebaseAuthRecentLoginRequiredException.java index e1a7cecd13..36b47b7821 100644 --- a/auth/src_java/fake/com/google/firebase/auth/FirebaseAuthRecentLoginRequiredException.java +++ b/auth/src_java/fake/com/google/firebase/auth/FirebaseAuthRecentLoginRequiredException.java @@ -18,7 +18,6 @@ /** Fake FirebaseAuthRecentLoginRequiredException */ public class FirebaseAuthRecentLoginRequiredException extends FirebaseAuthException { - public FirebaseAuthRecentLoginRequiredException(String code, String message) { super(code, message); } diff --git a/auth/src_java/fake/com/google/firebase/auth/FirebaseAuthUserCollisionException.java b/auth/src_java/fake/com/google/firebase/auth/FirebaseAuthUserCollisionException.java index 63e94ce39d..0e0b1df30d 100644 --- a/auth/src_java/fake/com/google/firebase/auth/FirebaseAuthUserCollisionException.java +++ b/auth/src_java/fake/com/google/firebase/auth/FirebaseAuthUserCollisionException.java @@ -18,7 +18,6 @@ /** Fake FirebaseAuthUserCollisionException */ public class FirebaseAuthUserCollisionException extends FirebaseAuthException { - public FirebaseAuthUserCollisionException(String code, String message) { super(code, message); } diff --git a/auth/src_java/fake/com/google/firebase/auth/FirebaseAuthWeakPasswordException.java b/auth/src_java/fake/com/google/firebase/auth/FirebaseAuthWeakPasswordException.java index acfb84ebc5..4f31f28efe 100644 --- a/auth/src_java/fake/com/google/firebase/auth/FirebaseAuthWeakPasswordException.java +++ b/auth/src_java/fake/com/google/firebase/auth/FirebaseAuthWeakPasswordException.java @@ -18,7 +18,6 @@ /** Fake FirebaseAuthWeakPasswordException */ public class FirebaseAuthWeakPasswordException extends FirebaseAuthInvalidCredentialsException { - public FirebaseAuthWeakPasswordException(String code, String message) { super(code, message); } diff --git a/auth/src_java/fake/com/google/firebase/auth/FirebaseAuthWebException.java b/auth/src_java/fake/com/google/firebase/auth/FirebaseAuthWebException.java index 8260a51a76..94f12e68b0 100644 --- a/auth/src_java/fake/com/google/firebase/auth/FirebaseAuthWebException.java +++ b/auth/src_java/fake/com/google/firebase/auth/FirebaseAuthWebException.java @@ -18,7 +18,6 @@ /** Fake FirebaseAuthWebException */ public class FirebaseAuthWebException extends FirebaseAuthException { - public FirebaseAuthWebException(String code, String message) { super(code, message); } diff --git a/auth/src_java/fake/com/google/firebase/auth/FirebaseUser.java b/auth/src_java/fake/com/google/firebase/auth/FirebaseUser.java index 753371f789..94dcc3a997 100644 --- a/auth/src_java/fake/com/google/firebase/auth/FirebaseUser.java +++ b/auth/src_java/fake/com/google/firebase/auth/FirebaseUser.java @@ -46,13 +46,12 @@ public Task updateEmail(String email) { ConfigRow row = ConfigAndroid.get(configKey); if (!row.futuregeneric().throwexception()) { - result.addListener( - new FakeListener() { - @Override - public void onSuccess(Void res) { - FirebaseUser.this.email = email; - } - }); + result.addListener(new FakeListener() { + @Override + public void onSuccess(Void res) { + FirebaseUser.this.email = email; + } + }); } TickerAndroid.register(result); @@ -181,7 +180,6 @@ public Task startActivityForReauthenticateWithProvider( return result; } - public Task delete() { Task result = Task.forResult("FirebaseUser.delete", null); TickerAndroid.register(result); diff --git a/auth/src_java/fake/com/google/firebase/auth/FirebaseUserMetadata.java b/auth/src_java/fake/com/google/firebase/auth/FirebaseUserMetadata.java index 6f214cad5b..2ada88e1f0 100644 --- a/auth/src_java/fake/com/google/firebase/auth/FirebaseUserMetadata.java +++ b/auth/src_java/fake/com/google/firebase/auth/FirebaseUserMetadata.java @@ -18,7 +18,6 @@ /** Holds the user metadata for the current {@link FirebaseUser} */ public class FirebaseUserMetadata { - /** Fake timestamp returned that's non-zero. */ public long getLastSignInTimestamp() { return 1; diff --git a/auth/src_java/fake/com/google/firebase/auth/GetTokenResult.java b/auth/src_java/fake/com/google/firebase/auth/GetTokenResult.java index b925fc7627..2afac9255f 100644 --- a/auth/src_java/fake/com/google/firebase/auth/GetTokenResult.java +++ b/auth/src_java/fake/com/google/firebase/auth/GetTokenResult.java @@ -18,7 +18,6 @@ /** Fake GetTokenResult */ public final class GetTokenResult { - public String getToken() { return "a fake token"; } diff --git a/auth/src_java/fake/com/google/firebase/auth/GithubAuthProvider.java b/auth/src_java/fake/com/google/firebase/auth/GithubAuthProvider.java index 8f08b9df4c..58d1b6c422 100644 --- a/auth/src_java/fake/com/google/firebase/auth/GithubAuthProvider.java +++ b/auth/src_java/fake/com/google/firebase/auth/GithubAuthProvider.java @@ -18,7 +18,6 @@ /** Fake GithubAuthProvider */ public final class GithubAuthProvider { - public static AuthCredential getCredential(String accessToken) { return new AuthCredential("github.com"); } diff --git a/auth/src_java/fake/com/google/firebase/auth/GoogleAuthProvider.java b/auth/src_java/fake/com/google/firebase/auth/GoogleAuthProvider.java index ad9b327934..9bf9d20011 100644 --- a/auth/src_java/fake/com/google/firebase/auth/GoogleAuthProvider.java +++ b/auth/src_java/fake/com/google/firebase/auth/GoogleAuthProvider.java @@ -18,7 +18,6 @@ /** Fake GoogleAuthProvider */ public final class GoogleAuthProvider { - public static AuthCredential getCredential(String idToken, String accessToken) { return new AuthCredential("google.com"); } diff --git a/auth/src_java/fake/com/google/firebase/auth/OAuthProvider.java b/auth/src_java/fake/com/google/firebase/auth/OAuthProvider.java index 32867a4aca..b14d85326f 100644 --- a/auth/src_java/fake/com/google/firebase/auth/OAuthProvider.java +++ b/auth/src_java/fake/com/google/firebase/auth/OAuthProvider.java @@ -21,7 +21,6 @@ /** Fake FakeOAuthProvider */ public final class OAuthProvider extends FederatedAuthProvider { - public static AuthCredential getCredential( String providerId, String idToken, String accessToken) { return new AuthCredential(providerId); @@ -37,7 +36,6 @@ public static OAuthProvider.Builder newBuilder(String providerId, FirebaseAuth f /** Class used to create instances of {@link OAuthProvider}. */ public static class Builder { - /* Fake constructor */ private Builder() {} @@ -91,7 +89,6 @@ public static CredentialBuilder newCredentialBuilder(String providerId) { /** Builder class to initialize {@link AuthCredential}'s. */ public static class CredentialBuilder { - private final String providerId; /** diff --git a/auth/src_java/fake/com/google/firebase/auth/PhoneAuthProvider.java b/auth/src_java/fake/com/google/firebase/auth/PhoneAuthProvider.java index 84b10a73a9..9f89725282 100644 --- a/auth/src_java/fake/com/google/firebase/auth/PhoneAuthProvider.java +++ b/auth/src_java/fake/com/google/firebase/auth/PhoneAuthProvider.java @@ -22,7 +22,6 @@ /** Fake PhoneAuthProvider */ public class PhoneAuthProvider { - /** Fake OnVerificationStateChangedCallbacks */ public abstract static class OnVerificationStateChangedCallbacks { public abstract void onVerificationCompleted(PhoneAuthCredential credential); @@ -41,16 +40,10 @@ public static PhoneAuthProvider getInstance(FirebaseAuth firebaseAuth) { return null; } - public static PhoneAuthCredential getCredential( - String verificationId, String smsCode) { + public static PhoneAuthCredential getCredential(String verificationId, String smsCode) { return null; } - public void verifyPhoneNumber( - String phoneNumber, - long timeout, - TimeUnit unit, - Activity activity, - OnVerificationStateChangedCallbacks callbacks, - ForceResendingToken forceResendingToken) {} + public void verifyPhoneNumber(String phoneNumber, long timeout, TimeUnit unit, Activity activity, + OnVerificationStateChangedCallbacks callbacks, ForceResendingToken forceResendingToken) {} } diff --git a/auth/src_java/fake/com/google/firebase/auth/PlayGamesAuthProvider.java b/auth/src_java/fake/com/google/firebase/auth/PlayGamesAuthProvider.java index b5da4c3cf2..4ba6a0b54b 100644 --- a/auth/src_java/fake/com/google/firebase/auth/PlayGamesAuthProvider.java +++ b/auth/src_java/fake/com/google/firebase/auth/PlayGamesAuthProvider.java @@ -16,9 +16,8 @@ package com.google.firebase.auth; -/** Fake PlayGamesAuthProvider */ +/** Fake PlayGamesAuthProvider */ class PlayGamesAuthProvider { - public static AuthCredential getCredential(String authCode) { return new AuthCredential("playgames.google.com"); } diff --git a/auth/src_java/fake/com/google/firebase/auth/SignInMethodQueryResult.java b/auth/src_java/fake/com/google/firebase/auth/SignInMethodQueryResult.java index d0ba463a8f..1828098932 100644 --- a/auth/src_java/fake/com/google/firebase/auth/SignInMethodQueryResult.java +++ b/auth/src_java/fake/com/google/firebase/auth/SignInMethodQueryResult.java @@ -20,7 +20,6 @@ /** Fake SignInMethodQueryResult */ public final class SignInMethodQueryResult { - List getSignInMethods() { return null; } diff --git a/auth/src_java/fake/com/google/firebase/auth/TwitterAuthProvider.java b/auth/src_java/fake/com/google/firebase/auth/TwitterAuthProvider.java index c3358e7c20..34afac07bb 100644 --- a/auth/src_java/fake/com/google/firebase/auth/TwitterAuthProvider.java +++ b/auth/src_java/fake/com/google/firebase/auth/TwitterAuthProvider.java @@ -18,7 +18,6 @@ /** Fake TwitterAuthProvider */ public final class TwitterAuthProvider { - public static AuthCredential getCredential(String token, String secret) { return new AuthCredential("twitter.com"); } diff --git a/auth/src_java/fake/com/google/firebase/auth/UserProfileChangeRequest.java b/auth/src_java/fake/com/google/firebase/auth/UserProfileChangeRequest.java index dfab7c05b0..4afe8fce1d 100644 --- a/auth/src_java/fake/com/google/firebase/auth/UserProfileChangeRequest.java +++ b/auth/src_java/fake/com/google/firebase/auth/UserProfileChangeRequest.java @@ -20,7 +20,6 @@ /** Fake UserProfileChangeRequest$Builder */ public final class UserProfileChangeRequest { - /** Builder */ public static class Builder { public Builder setDisplayName(String displayName) { diff --git a/database/src/include/firebase/database/database_reference.h b/database/src/include/firebase/database/database_reference.h index f403dc24d8..3e746541a1 100644 --- a/database/src/include/firebase/database/database_reference.h +++ b/database/src/include/firebase/database/database_reference.h @@ -17,12 +17,13 @@ #include #include -#include "firebase/future.h" -#include "firebase/internal/common.h" -#include "firebase/variant.h" + #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 { diff --git a/database/src/include/firebase/database/query.h b/database/src/include/firebase/database/query.h index 8611f4d147..861bdd505a 100644 --- a/database/src/include/firebase/database/query.h +++ b/database/src/include/firebase/database/query.h @@ -16,9 +16,10 @@ #define FIREBASE_DATABASE_SRC_INCLUDE_FIREBASE_DATABASE_QUERY_H_ #include + +#include "firebase/database/listener.h" #include "firebase/future.h" #include "firebase/internal/common.h" -#include "firebase/database/listener.h" namespace firebase { namespace database { diff --git a/database/src_java/com/google/firebase/database/internal/cpp/CppTransactionHandler.java b/database/src_java/com/google/firebase/database/internal/cpp/CppTransactionHandler.java index aadf0d5dee..56025c8df1 100644 --- a/database/src_java/com/google/firebase/database/internal/cpp/CppTransactionHandler.java +++ b/database/src_java/com/google/firebase/database/internal/cpp/CppTransactionHandler.java @@ -74,10 +74,6 @@ private static native MutableData nativeDoTransaction( long databaseObject, long transactionObject, MutableData currentData); /** This native function is implemented in the Firebase Database C++ library (util_android.cc). */ - private static native void nativeOnComplete( - long databaseObject, - long transactionObject, - DatabaseError error, - boolean committed, - DataSnapshot currentData); + private static native void nativeOnComplete(long databaseObject, long transactionObject, + DatabaseError error, boolean committed, DataSnapshot currentData); } diff --git a/dynamic_links/src/dynamic_links_ios.mm b/dynamic_links/src/dynamic_links_ios.mm index b86b861b2b..5e707fcfa7 100644 --- a/dynamic_links/src/dynamic_links_ios.mm +++ b/dynamic_links/src/dynamic_links_ios.mm @@ -64,42 +64,42 @@ void Terminate() { // Encode a URL from a C string. If this fails, nil is returned. static NSURL* EncodeUrlFromString(const char* url_string) { // Try encoding without escaping as the URL may already be escaped correctly. - NSURL*url = [NSURL URLWithString:@(url_string)]; + NSURL* url = [NSURL URLWithString:@(url_string)]; if (url) return url; // If encoding without escaping fails, try again with percent encoding. - return [NSURL URLWithString:[@(url_string) - stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]; + return [NSURL + URLWithString:[@(url_string) stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]; } // Add a warning to the list of warnings regarding failure to encode the specified // URL. -static void AddUrlEncodingWarning( - std::vector* warnings, const char* url, const char* field_description) { - warnings->push_back(std::string("Failed to encode URL for ") + - std::string(field_description) + ", URL: " + url); +static void AddUrlEncodingWarning(std::vector* warnings, const char* url, + const char* field_description) { + warnings->push_back(std::string("Failed to encode URL for ") + std::string(field_description) + + ", URL: " + url); } // Set a URL field of an iOS dynamic link components object from a C++ structure string field. #define FIR_DYNAMIC_LINK_PARAMS_SET_URL(fir_params_object, field, cpp_params_object, cpp_field, \ - field_description, generated_link_warnings) \ - { \ - if ((cpp_params_object)->cpp_field) { \ - NSURL* ns_url = EncodeUrlFromString((cpp_params_object)->cpp_field); \ - if (ns_url) { \ - (fir_params_object).field = ns_url; \ - } else { \ - AddUrlEncodingWarning(generated_link_warnings, (cpp_params_object)->cpp_field, \ - field_description); \ - } \ - } \ + field_description, generated_link_warnings) \ + { \ + if ((cpp_params_object)->cpp_field) { \ + NSURL* ns_url = EncodeUrlFromString((cpp_params_object)->cpp_field); \ + if (ns_url) { \ + (fir_params_object).field = ns_url; \ + } else { \ + AddUrlEncodingWarning(generated_link_warnings, (cpp_params_object)->cpp_field, \ + field_description); \ + } \ + } \ } // Set a string field of an iOS dynamic link components object from a C++ structure string field. #define FIR_DYNAMIC_LINK_PARAMS_SET_STRING(fir_params_object, field, cpp_params_object, cpp_field) \ - { \ - if ((cpp_params_object)->cpp_field) { \ - (fir_params_object).field = @((cpp_params_object)->cpp_field); \ - } \ + { \ + if ((cpp_params_object)->cpp_field) { \ + (fir_params_object).field = @((cpp_params_object)->cpp_field); \ + } \ } // Construct FIRDynamicLinkComponents and populate GeneratedDynamicLink from DynamicLinkComponents. @@ -111,11 +111,10 @@ static void AddUrlEncodingWarning( return nil; } if (!components.domain_uri_prefix || !*components.domain_uri_prefix) { - generated_link->error = - std::string("Domain URI Prefix ") + kMissingFieldPostfix; + generated_link->error = std::string("Domain URI Prefix ") + kMissingFieldPostfix; return nil; } - NSURL *link_url = EncodeUrlFromString(components.link); + NSURL* link_url = EncodeUrlFromString(components.link); if (!link_url) { generated_link->error = kUrlEncodingError; return nil; @@ -172,8 +171,8 @@ static void AddUrlEncodingWarning( auto* cpp_params = components.android_parameters; if (cpp_params) { if (!cpp_params->package_name) { - generated_link->error = std::string("Android parameters package name ") + - kMissingFieldPostfix; + generated_link->error = + std::string("Android parameters package name ") + kMissingFieldPostfix; return nil; } FIRDynamicLinkAndroidParameters* fir_params = @@ -232,75 +231,68 @@ GeneratedDynamicLink GetLongLink(const DynamicLinkComponents& components) { } // Generate a short link from a long dynamic link. -static Future GetShortLink(NSURL *long_link_url, +static Future GetShortLink(NSURL* long_link_url, const GeneratedDynamicLink& generated_link, const DynamicLinkOptions& dynamic_link_options) { - FIREBASE_ASSERT_RETURN(Future(), - internal::IsInitialized()); + FIREBASE_ASSERT_RETURN(Future(), internal::IsInitialized()); ReferenceCountedFutureImpl* api = FutureData::Get()->api(); const SafeFutureHandle handle = api->SafeAlloc(kDynamicLinksFnGetShortLink); if (long_link_url) { GeneratedDynamicLink* output_generated_link = new GeneratedDynamicLink(); *output_generated_link = generated_link; - [FIRDynamicLinkComponents shortenURL:long_link_url - options:ToFIRDynamicLinkComponentsOptions(dynamic_link_options) - completion:^(NSURL * _Nullable shortURL, - NSArray * _Nullable warnings, - NSError * _Nullable error) { - int error_code = kErrorCodeSuccess; - if (error) { - error_code = error.code ? static_cast(error.code) : kErrorCodeFailed; - output_generated_link->error = util::NSStringToString(error.localizedDescription); - } else { - if (warnings) { - for (NSString* warning in warnings) { - output_generated_link->warnings.push_back(warning.UTF8String); - } - } - if (shortURL) { - output_generated_link->url = util::NSStringToString(shortURL.absoluteString); + [FIRDynamicLinkComponents + shortenURL:long_link_url + options:ToFIRDynamicLinkComponentsOptions(dynamic_link_options) + completion:^(NSURL* _Nullable shortURL, NSArray* _Nullable warnings, + NSError* _Nullable error) { + int error_code = kErrorCodeSuccess; + if (error) { + error_code = error.code ? static_cast(error.code) : kErrorCodeFailed; + output_generated_link->error = util::NSStringToString(error.localizedDescription); } else { - error_code = kErrorCodeFailed; - output_generated_link->error = std::string("Failed to shorten link ") + - output_generated_link->url; + if (warnings) { + for (NSString* warning in warnings) { + output_generated_link->warnings.push_back(warning.UTF8String); + } + } + if (shortURL) { + output_generated_link->url = util::NSStringToString(shortURL.absoluteString); + } else { + error_code = kErrorCodeFailed; + output_generated_link->error = + std::string("Failed to shorten link ") + output_generated_link->url; + } } - } - FutureData::Get()->api()->CompleteWithResult( - handle, error_code, output_generated_link->error.c_str(), *output_generated_link); - delete output_generated_link; - }]; + FutureData::Get()->api()->CompleteWithResult( + handle, error_code, output_generated_link->error.c_str(), *output_generated_link); + delete output_generated_link; + }]; } else { - api->CompleteWithResult(handle, kErrorCodeFailed, generated_link.error.c_str(), - generated_link); + api->CompleteWithResult(handle, kErrorCodeFailed, generated_link.error.c_str(), generated_link); } return MakeFuture(api, handle); } -Future GetShortLink( - const DynamicLinkComponents& components, - const DynamicLinkOptions& dynamic_link_options) { - FIREBASE_ASSERT_RETURN(Future(), - internal::IsInitialized()); +Future GetShortLink(const DynamicLinkComponents& components, + const DynamicLinkOptions& dynamic_link_options) { + FIREBASE_ASSERT_RETURN(Future(), internal::IsInitialized()); GeneratedDynamicLink generated_link; - FIRDynamicLinkComponents* fir_components = GetFIRComponentsAndGeneratedLink(components, - &generated_link); + FIRDynamicLinkComponents* fir_components = + GetFIRComponentsAndGeneratedLink(components, &generated_link); return GetShortLink(fir_components ? fir_components.url : nil, generated_link, dynamic_link_options); } -Future GetShortLink( - const DynamicLinkComponents& components) { +Future GetShortLink(const DynamicLinkComponents& components) { return GetShortLink(components, DynamicLinkOptions()); } -Future GetShortLink( - const char* long_dynamic_link, - const DynamicLinkOptions& dynamic_link_options) { - FIREBASE_ASSERT_RETURN(Future(), - internal::IsInitialized()); +Future GetShortLink(const char* long_dynamic_link, + const DynamicLinkOptions& dynamic_link_options) { + FIREBASE_ASSERT_RETURN(Future(), internal::IsInitialized()); GeneratedDynamicLink generated_link; - NSURL *link_url = EncodeUrlFromString(long_dynamic_link); + NSURL* link_url = EncodeUrlFromString(long_dynamic_link); if (!link_url) generated_link.error = kUrlEncodingError; return GetShortLink(link_url, generated_link, dynamic_link_options); } @@ -310,8 +302,7 @@ GeneratedDynamicLink GetLongLink(const DynamicLinkComponents& components) { } Future GetShortLinkLastResult() { - FIREBASE_ASSERT_RETURN(Future(), - internal::IsInitialized()); + FIREBASE_ASSERT_RETURN(Future(), internal::IsInitialized()); ReferenceCountedFutureImpl* api = FutureData::Get()->api(); return static_cast&>( api->LastResult(kDynamicLinksFnGetShortLink)); diff --git a/firestore/src/common/settings_apple.mm b/firestore/src/common/settings_apple.mm index 7a1deb2a4d..57856d16fc 100644 --- a/firestore/src/common/settings_apple.mm +++ b/firestore/src/common/settings_apple.mm @@ -18,8 +18,8 @@ #include -#include "absl/memory/memory.h" #include "Firestore/core/src/util/executor_libdispatch.h" +#include "absl/memory/memory.h" namespace firebase { namespace firestore { @@ -35,7 +35,8 @@ Settings::Settings() : host_(kDefaultHost), - executor_(Executor::CreateSerial("com.google.firebase.firestore.callback")) {} + executor_( + Executor::CreateSerial("com.google.firebase.firestore.callback")) {} std::unique_ptr Settings::CreateExecutor() const { return absl::make_unique(dispatch_queue()); @@ -45,7 +46,8 @@ if (!executor_) { return dispatch_get_main_queue(); } - auto* executor_libdispatch = static_cast(executor_.get()); + auto* executor_libdispatch = + static_cast(executor_.get()); return executor_libdispatch->dispatch_queue(); } diff --git a/firestore/src/main/create_credentials_provider_ios.mm b/firestore/src/main/create_credentials_provider_ios.mm index 7e50f6f489..c8eee6e0c3 100644 --- a/firestore/src/main/create_credentials_provider_ios.mm +++ b/firestore/src/main/create_credentials_provider_ios.mm @@ -16,12 +16,12 @@ #include "firestore/src/main/create_credentials_provider.h" -#import "FirebaseCoreInternal.h" #import "FIRAuthInterop.h" +#import "FirebaseCoreInternal.h" -#include "app/src/include/firebase/app.h" -#include "absl/memory/memory.h" #include "Firestore/core/src/credentials/firebase_auth_credentials_provider_apple.h" +#include "absl/memory/memory.h" +#include "app/src/include/firebase/app.h" namespace firebase { namespace firestore { diff --git a/firestore/src/main/create_firebase_metadata_provider_ios.mm b/firestore/src/main/create_firebase_metadata_provider_ios.mm index 904bf406e3..1161bcb836 100644 --- a/firestore/src/main/create_firebase_metadata_provider_ios.mm +++ b/firestore/src/main/create_firebase_metadata_provider_ios.mm @@ -16,9 +16,9 @@ #include "firestore/src/main/create_firebase_metadata_provider.h" -#include "app/src/include/firebase/app.h" #include "Firestore/core/src/remote/firebase_metadata_provider_apple.h" #include "absl/memory/memory.h" +#include "app/src/include/firebase/app.h" namespace firebase { namespace firestore { @@ -26,7 +26,8 @@ using remote::FirebaseMetadataProvider; using remote::FirebaseMetadataProviderApple; -std::unique_ptr CreateFirebaseMetadataProvider(App& app) { +std::unique_ptr CreateFirebaseMetadataProvider( + App& app) { return absl::make_unique(app.GetPlatformApp()); } diff --git a/firestore/src/main/credentials_provider_desktop.cc b/firestore/src/main/credentials_provider_desktop.cc index 0929b9932f..8182c34497 100644 --- a/firestore/src/main/credentials_provider_desktop.cc +++ b/firestore/src/main/credentials_provider_desktop.cc @@ -188,11 +188,6 @@ void FirebaseCppCredentialsProvider::GetToken( } } -void FirebaseCppCredentialsProvider::InvalidateToken() { - std::lock_guard lock(contents_->mutex); - force_refresh_token_ = true; -} - void FirebaseCppCredentialsProvider::AddAuthStateListener() { App& app = contents_->app; auto callback = reinterpret_cast(OnAuthStateChanged); @@ -234,8 +229,8 @@ void FirebaseCppCredentialsProvider::RequestToken( // can fail if there is a token change while the request is outstanding. int expected_generation = contents_->token_generation; - bool force_refresh = force_refresh_token_; - force_refresh_token_ = false; + bool force_refresh = force_refresh_; + force_refresh_ = false; auto future = GetAuthTokenAsync(contents_->app, force_refresh); std::weak_ptr weak_contents(contents_); diff --git a/firestore/src/main/credentials_provider_desktop.h b/firestore/src/main/credentials_provider_desktop.h index 24b434cf36..aed23b3c81 100644 --- a/firestore/src/main/credentials_provider_desktop.h +++ b/firestore/src/main/credentials_provider_desktop.h @@ -59,7 +59,6 @@ class FirebaseCppCredentialsProvider void GetToken( firestore::credentials::TokenListener listener) override; - void InvalidateToken() override; private: void AddAuthStateListener(); @@ -109,14 +108,6 @@ class FirebaseCppCredentialsProvider int token_generation = 0; }; std::shared_ptr contents_; - - // Affects the next `GetToken` request; if `true`, the token will be refreshed - // even if it hasn't expired yet. - bool force_refresh_token_ = false; - - // Provided by the user code; may be an empty function. - firestore::credentials::CredentialChangeListener - change_listener_; }; } // namespace firestore diff --git a/firestore/src_java/com/google/firebase/firestore/internal/cpp/DocumentEventListener.java b/firestore/src_java/com/google/firebase/firestore/internal/cpp/DocumentEventListener.java index 85eb3e8358..e72595d96b 100644 --- a/firestore/src_java/com/google/firebase/firestore/internal/cpp/DocumentEventListener.java +++ b/firestore/src_java/com/google/firebase/firestore/internal/cpp/DocumentEventListener.java @@ -23,44 +23,47 @@ /** * Implements Firestore {@code - * firebase::firestore::EventListener} by redirecting calls - * into the C++ equivalent. + * firebase::firestore::EventListener} by + * redirecting calls into the C++ equivalent. */ -public class DocumentEventListener extends CppEventListener - implements EventListener { +public class DocumentEventListener + extends CppEventListener implements EventListener { /** - * Constructs a DocumentEventListener. Ownership of the underlying EventListener can be - * transferred when creating the {@code ListenerRegistration}. If the ListenerRegistration owns - * the EventListener, it will de-allocate the EventListener in its destructor. + * Constructs a DocumentEventListener. Ownership of the underlying + * EventListener can be transferred when creating the {@code + * ListenerRegistration}. If the ListenerRegistration owns the EventListener, + * it will de-allocate the EventListener in its destructor. * - *

Passing in 0 is considered a null pointer and will result in {@code onEvent} becoming a - * no-op. + *

Passing in 0 is considered a null pointer and will result in {@code + * onEvent} becoming a no-op. * - * @param cppFirestoreObject Pointer to a {@code firebase::firestore::Firestore}. + * @param cppFirestoreObject Pointer to a {@code + * firebase::firestore::Firestore}. * @param cppListenerObject Pointer to a {@code * firebase::firestore::EventListener}. */ - public DocumentEventListener(long cppFirestoreObject, long cppListenerObject) { + public DocumentEventListener( + long cppFirestoreObject, long cppListenerObject) { super(cppFirestoreObject, cppListenerObject); } @Override - public synchronized void onEvent( - @Nullable DocumentSnapshot value, @Nullable FirebaseFirestoreException error) { - nativeOnEvent(cppFirestoreObject, cppListenerObject, value, error); + public synchronized void onEvent(@Nullable DocumentSnapshot value, + @Nullable FirebaseFirestoreException error) { + nativeOnEvent(cppFirestoreObject, cppListenerObject, value, error); } /** * Interprets the {@code listenerObject} as a {@code - * firebase::firestore::EventListener} and invokes the listener's {@code - * OnEvent} method with the {@code error} and {@code DocumentSnapshot} created by interpreting the + * firebase::firestore::EventListener} and invokes the + * listener's {@code OnEvent} method with the {@code error} and {@code + * DocumentSnapshot} created by interpreting the * {@code firestoreObject} as a {@code firebase::firestore::Firestore}. * *

This native method is implemented in the Firestore C++ library {@code * event_listener_android.cc}. */ - private static native void nativeOnEvent( - long firestoreObject, + private static native void nativeOnEvent(long firestoreObject, long listenerObject, @Nullable Object value, @Nullable FirebaseFirestoreException error); diff --git a/firestore/src_java/com/google/firebase/firestore/internal/cpp/Dummy.java b/firestore/src_java/com/google/firebase/firestore/internal/cpp/Dummy.java index 4a4b69e52c..a42a85692e 100644 --- a/firestore/src_java/com/google/firebase/firestore/internal/cpp/Dummy.java +++ b/firestore/src_java/com/google/firebase/firestore/internal/cpp/Dummy.java @@ -17,7 +17,8 @@ package com.google.firebase.firestore.internal.cpp; /** - * Place-holder dummy Java class for Firestore C++ Android clients. This is currently being used to - * prevent Tricorder errors since we do not have desktop support yet. + * Place-holder dummy Java class for Firestore C++ Android clients. This is + * currently being used to prevent Tricorder errors since we do not have desktop + * support yet. */ public class Dummy {} diff --git a/firestore/src_java/com/google/firebase/firestore/internal/cpp/FirestoreTasks.java b/firestore/src_java/com/google/firebase/firestore/internal/cpp/FirestoreTasks.java index 2d44804737..856c9e4120 100644 --- a/firestore/src_java/com/google/firebase/firestore/internal/cpp/FirestoreTasks.java +++ b/firestore/src_java/com/google/firebase/firestore/internal/cpp/FirestoreTasks.java @@ -28,56 +28,61 @@ * Helper methods for working with {@link Task} objects from C++. */ public final class FirestoreTasks { - - private FirestoreTasks() { - } + private FirestoreTasks() {} /** - * Takes a {@link Task} and returns a new Task, whose result will be the same as the incoming Task, - * if the result is not null, otherwise fails the returned Task with given error message. + * Takes a {@link Task} and returns a new Task, whose result will be the same + * as the incoming Task, if the result is not null, otherwise fails the + * returned Task with given error message. */ - public static Task failTaskWhenResultIsNull(Task task, final String message) { - Continuation continuation = - new Continuation() { - @Override - public T then(Task task) throws Exception { - T result = task.getResult(); - if (result == null) { - throw new FirebaseFirestoreException(message, FirebaseFirestoreException.Code.NOT_FOUND); - } - return result; + public static Task failTaskWhenResultIsNull( + Task task, final String message) { + Continuation continuation = new Continuation() { + @Override + public T then(Task task) throws Exception { + T result = task.getResult(); + if (result == null) { + throw new FirebaseFirestoreException( + message, FirebaseFirestoreException.Code.NOT_FOUND); } - }; + return result; + } + }; return task.continueWith(continuation); } /** * Blocks the calling thread until the given {@link Task} has completed. * - *

This method is identical to {@link com.google.android.gms.tasks.Tasks#await} except that it - * does not throw an exception if invoked from the main thread. Since it is technically - * possible to wait for a {@link Task} from any thread in C++, throwing is undesirable if called - * from the main thread. + *

This method is identical to {@link + * com.google.android.gms.tasks.Tasks#await} except that it does not + * throw an exception if invoked from the main thread. Since it is technically + * possible to wait for a {@link Task} from any thread in C++, throwing is + * undesirable if called from the main thread. * - *

The result of the given {@link Task} (i.e. success or failure) is not considered by this - * method; whenever the task completes, either successfully or unsuccessfully, this method will - * return. + *

The result of the given {@link Task} (i.e. success or failure) is not + * considered by this method; whenever the task completes, either successfully + * or unsuccessfully, this method will return. * * @param task The task whose completion to await. - * @throws InterruptedException if waiting for the task to complete is interrupted. + * @throws InterruptedException if waiting for the task to complete is + * interrupted. */ - public static void awaitCompletion(Task task) throws InterruptedException { + public static void awaitCompletion(Task task) + throws InterruptedException { CountDownLatch countDownLatch = new CountDownLatch(1); ExecutorService executor = Executors.newSingleThreadExecutor(); try { - task.addOnCompleteListener(executor, new CountDownOnCompleteListener(countDownLatch)); + task.addOnCompleteListener( + executor, new CountDownOnCompleteListener(countDownLatch)); countDownLatch.await(); } finally { executor.shutdown(); } } - private static final class CountDownOnCompleteListener implements OnCompleteListener { + private static final class CountDownOnCompleteListener + implements OnCompleteListener { private final CountDownLatch countDownLatch; CountDownOnCompleteListener(CountDownLatch countDownLatch) { diff --git a/firestore/src_java/com/google/firebase/firestore/internal/cpp/JniRunnable.java b/firestore/src_java/com/google/firebase/firestore/internal/cpp/JniRunnable.java index d27ba170c1..30e519f386 100644 --- a/firestore/src_java/com/google/firebase/firestore/internal/cpp/JniRunnable.java +++ b/firestore/src_java/com/google/firebase/firestore/internal/cpp/JniRunnable.java @@ -23,7 +23,6 @@ /** A {@link Runnable} whose {@link #run} method calls a native function. */ public final class JniRunnable implements Runnable { - private final Object lock = new Object(); private long data; @@ -37,7 +36,7 @@ public JniRunnable(long data) { if (data == 0) { throw new IllegalArgumentException( "data==0 is forbidden because 0 is reserved to indicate that we are detached from the" - + " C++ function"); + + " C++ function"); } this.data = data; } @@ -45,15 +44,16 @@ public JniRunnable(long data) { /** * Invokes the C++ function encapsulated by this object. * - *

If {@link #detach} has been invoked then this method does nothing and returns as if - * successful. + *

If {@link #detach} has been invoked then this method does nothing and + * returns as if successful. */ @Override public void run() { - // NOTE: Because of the `synchronized` block below, the native function will not be called - // concurrently. If concurrent invocations are desired, then this class can be modified with a - // more complicated synchronization mechanism. - // e.g. https://gist.github.com/dconeybe/2d95fbc75f88de58a49804df5c55157b + // NOTE: Because of the `synchronized` block below, the native function will + // not be called concurrently. If concurrent invocations are desired, then + // this class can be modified with a more complicated synchronization + // mechanism. e.g. + // https://gist.github.com/dconeybe/2d95fbc75f88de58a49804df5c55157b synchronized (lock) { if (data == 0) { return; @@ -65,15 +65,16 @@ public void run() { /** * Releases the reference to native data. * - *

After this method returns, all future invocations of {@link #run} will do nothing and return - * as if successful. + *

After this method returns, all future invocations of {@link #run} will + * do nothing and return as if successful. * - *

This method blocks until all invocations of the native function called from {@link #run} - * complete; therefore, when this method returns it is safe to delete any data that would be - * referenced by the native function. + *

This method blocks until all invocations of the native function called + * from {@link #run} complete; therefore, when this method returns it is safe + * to delete any data that would be referenced by the native function. * - *

This method may be safely invoked multiple times. Subsequent invocations have no side - * effects but will still block while there are active invocations of the native function. + *

This method may be safely invoked multiple times. Subsequent invocations + * have no side effects but will still block while there are active + * invocations of the native function. */ public void detach() { synchronized (lock) { @@ -84,10 +85,12 @@ public void detach() { /** * Invokes {@link #run} on the main event thread. * - *

If the calling thread is the main event thread then {@link #run} is called synchronously. + *

If the calling thread is the main event thread then {@link #run} is + * called synchronously. * - * @return A {@link Task} that will complete after {@link #run} returns; if {@link #run} throws an - * exception, then that exception will be set as the exception of the task. + * @return A {@link Task} that will complete after {@link #run} returns; if + * {@link #run} throws an exception, then that exception will be set as + * the exception of the task. */ Task runOnMainThread() { TaskRunnable runnable = new TaskRunnable(); @@ -98,7 +101,8 @@ Task runOnMainThread() { Handler handler = new Handler(mainLooper); boolean postSucceeded = handler.post(runnable); if (!postSucceeded) { - runnable.setException(new RuntimeException("Handler.post() returned false")); + runnable.setException( + new RuntimeException("Handler.post() returned false")); } } return runnable.getTask(); @@ -107,8 +111,9 @@ Task runOnMainThread() { /** * Invokes {@link #run} on a newly-created thread. * - * @return A {@link Task} that will complete after {@link #run} returns; if {@link #run} throws an - * exception, then that exception will be set as the exception of the task. + * @return A {@link Task} that will complete after {@link #run} returns; if + * {@link #run} throws an exception, then that exception will be set as + * the exception of the task. */ Task runOnNewThread() { TaskRunnable runnable = new TaskRunnable(); @@ -119,14 +124,15 @@ Task runOnNewThread() { /** * Invokes the encapsulated C++ function. * - * @param data The data that was specified to the constructor, or {@code 0} if {@link #detach} has - * been called, in which case the native function should do nothing and return immediately. + * @param data The data that was specified to the constructor, or {@code 0} if + * {@link #detach} has been called, in which case the native function + * should do nothing and return immediately. */ private static native void nativeRun(long data); private final class TaskRunnable implements Runnable { - - private final TaskCompletionSource taskCompletionSource = new TaskCompletionSource<>(); + private final TaskCompletionSource taskCompletionSource = + new TaskCompletionSource<>(); @Override public void run() { diff --git a/firestore/src_java/com/google/firebase/firestore/internal/cpp/LoadBundleProgressListener.java b/firestore/src_java/com/google/firebase/firestore/internal/cpp/LoadBundleProgressListener.java index a16b4a6be0..af5c28a7b9 100644 --- a/firestore/src_java/com/google/firebase/firestore/internal/cpp/LoadBundleProgressListener.java +++ b/firestore/src_java/com/google/firebase/firestore/internal/cpp/LoadBundleProgressListener.java @@ -18,47 +18,48 @@ import androidx.annotation.Nullable; import com.google.firebase.firestore.EventListener; +import com.google.firebase.firestore.FirebaseFirestoreException; import com.google.firebase.firestore.LoadBundleTaskProgress; import com.google.firebase.firestore.OnProgressListener; -import com.google.firebase.firestore.FirebaseFirestoreException; /** * Implements Firestore {@code - * firebase::firestore::EventListener} by redirecting calls - * into the C++ equivalent. + * firebase::firestore::EventListener} + * by redirecting calls into the C++ equivalent. */ public class LoadBundleProgressListener extends CppEventListener implements OnProgressListener { /** * Constructs a ProgressEventListener. * - *

Passing in 0 is considered a null pointer and will result in {@code onEvent} becoming a - * no-op. + *

Passing in 0 is considered a null pointer and will result in {@code + * onEvent} becoming a no-op. * - * @param cppFirestoreObject Pointer to a {@code firebase::firestore::Firestore}. + * @param cppFirestoreObject Pointer to a {@code + * firebase::firestore::Firestore}. * @param cppListenerObject Pointer to a {@code * firebase::firestore::EventListener}. */ - public LoadBundleProgressListener(long cppFirestoreObject, long cppListenerObject) { + public LoadBundleProgressListener( + long cppFirestoreObject, long cppListenerObject) { super(cppFirestoreObject, cppListenerObject); } @Override public synchronized void onProgress( @Nullable LoadBundleTaskProgress progress) { - nativeOnProgress(cppFirestoreObject, cppListenerObject, progress); + nativeOnProgress(cppFirestoreObject, cppListenerObject, progress); } /** * Interprets the {@code listenerObject} as a {@code - * firebase::firestore::EventListener} and invokes the listener's {@code - * OnEvent} method with {@code value} interpreted as (@code LoadBundleTaskProgress). + * firebase::firestore::EventListener} and invokes the + * listener's {@code OnEvent} method with {@code value} interpreted as (@code + * LoadBundleTaskProgress). * *

This native method is implemented in the Firestore C++ library {@code * event_listener_android.cc}. */ private static native void nativeOnProgress( - long firestoreObject, - long listenerObject, - @Nullable Object value); + long firestoreObject, long listenerObject, @Nullable Object value); } diff --git a/firestore/src_java/com/google/firebase/firestore/internal/cpp/QueryEventListener.java b/firestore/src_java/com/google/firebase/firestore/internal/cpp/QueryEventListener.java index f812d8f9c5..83306b8799 100644 --- a/firestore/src_java/com/google/firebase/firestore/internal/cpp/QueryEventListener.java +++ b/firestore/src_java/com/google/firebase/firestore/internal/cpp/QueryEventListener.java @@ -23,19 +23,22 @@ /** * Implements Firestore {@code - * firebase::firestore::EventListener} by redirecting calls into - * the C++ equivalent. + * firebase::firestore::EventListener} by + * redirecting calls into the C++ equivalent. */ -public class QueryEventListener extends CppEventListener implements EventListener { +public class QueryEventListener + extends CppEventListener implements EventListener { /** - * Constructs a QueryEventListener. Ownership of the underlying EventListener can be transferred - * when creating the {@code ListenerRegistration}. If the ListenerRegistration owns the - * EventListener, it will de-allocate the EventListener in its destructor. + * Constructs a QueryEventListener. Ownership of the underlying EventListener + * can be transferred when creating the {@code ListenerRegistration}. If the + * ListenerRegistration owns the EventListener, it will de-allocate the + * EventListener in its destructor. * - *

Passing in 0 is considered a null pointer and will result in {@code onEvent} becoming a - * no-op. + *

Passing in 0 is considered a null pointer and will result in {@code + * onEvent} becoming a no-op. * - * @param cppFirestoreObject Pointer to a {@code firebase::firestore::Firestore}. + * @param cppFirestoreObject Pointer to a {@code + * firebase::firestore::Firestore}. * @param cppListenerObject Pointer to a {@code * firebase::firestore::EventListener}. */ @@ -44,22 +47,22 @@ public QueryEventListener(long cppFirestoreObject, long cppListenerObject) { } @Override - public synchronized void onEvent( - @Nullable QuerySnapshot value, @Nullable FirebaseFirestoreException error) { - nativeOnEvent(cppFirestoreObject, cppListenerObject, value, error); + public synchronized void onEvent(@Nullable QuerySnapshot value, + @Nullable FirebaseFirestoreException error) { + nativeOnEvent(cppFirestoreObject, cppListenerObject, value, error); } /** * Interprets the {@code listenerObject} as a {@code - * firebase::firestore::EventListener} and invokes the listener's {@code OnEvent} - * method with the {@code error} and {@code QuerySnapshot} created by interpreting the {@code - * firestoreObject} as a {@code firebase::firestore::Firestore}. + * firebase::firestore::EventListener} and invokes the + * listener's {@code OnEvent} method with the {@code error} and {@code + * QuerySnapshot} created by interpreting the {@code firestoreObject} as a + * {@code firebase::firestore::Firestore}. * *

This native method is implemented in the Firestore C++ library {@code * event_listener_android.cc}. */ - private static native void nativeOnEvent( - long firestoreObject, + private static native void nativeOnEvent(long firestoreObject, long listenerObject, @Nullable Object value, @Nullable FirebaseFirestoreException error); diff --git a/firestore/src_java/com/google/firebase/firestore/internal/cpp/SilentRejectionSingleThreadExecutor.java b/firestore/src_java/com/google/firebase/firestore/internal/cpp/SilentRejectionSingleThreadExecutor.java index 2fdf02a376..5a0fffe684 100644 --- a/firestore/src_java/com/google/firebase/firestore/internal/cpp/SilentRejectionSingleThreadExecutor.java +++ b/firestore/src_java/com/google/firebase/firestore/internal/cpp/SilentRejectionSingleThreadExecutor.java @@ -22,19 +22,22 @@ import java.util.concurrent.RejectedExecutionException; /** - * Simple {@code Executor} implementation wraps around a single threaded executor and swallows + * Simple {@code Executor} implementation wraps around a single threaded + * executor and swallows * {@code RejectedExecutionException} when executing commands. * - *

During shutdown, the C++ API must be able to prevent user callbacks from running after the - * Firestore object has been disposed. To do so, it shuts down its executors, accepting that new - * callbacks may be rejected, and if there is work already scheduled, they will not be executed. + *

During shutdown, the C++ API must be able to prevent user callbacks from + * running after the Firestore object has been disposed. To do so, it shuts down + * its executors, accepting that new callbacks may be rejected, and if there is + * work already scheduled, they will not be executed. * * This class catches and discards the {@code RejectedExecutionException} - * that is thrown by the underlying Java executor after shutdown, bridging the gap between C++ - * expectations and the Java implementation. + * that is thrown by the underlying Java executor after shutdown, bridging the + * gap between C++ expectations and the Java implementation. */ public final class SilentRejectionSingleThreadExecutor implements Executor { - private final ExecutorService internalExecutor = Executors.newSingleThreadExecutor(); + private final ExecutorService internalExecutor = + Executors.newSingleThreadExecutor(); @Override public void execute(Runnable command) { diff --git a/firestore/src_java/com/google/firebase/firestore/internal/cpp/TransactionFunction.java b/firestore/src_java/com/google/firebase/firestore/internal/cpp/TransactionFunction.java index 7ac8966dff..0c23f7371e 100644 --- a/firestore/src_java/com/google/firebase/firestore/internal/cpp/TransactionFunction.java +++ b/firestore/src_java/com/google/firebase/firestore/internal/cpp/TransactionFunction.java @@ -22,21 +22,25 @@ import com.google.firebase.firestore.Transaction; /** - * Implements Firestore TransactionFunction by redirecting calls into C++. This shares the same - * logic as a listener but there is difference. A listener implements onEvent() while Transaction - * Function implements apply(). + * Implements Firestore TransactionFunction by redirecting calls into C++. This + * shares the same logic as a listener but there is difference. A listener + * implements onEvent() while Transaction Function implements apply(). */ -public class TransactionFunction extends CppEventListener implements Transaction.Function { +public class TransactionFunction + extends CppEventListener implements Transaction.Function { /** Construct a TransactionFunction. Parameters are C++ pointers. */ - public TransactionFunction(long cppFirestoreObject, long cppTransactionFunctionObject) { + public TransactionFunction( + long cppFirestoreObject, long cppTransactionFunctionObject) { super(cppFirestoreObject, cppTransactionFunctionObject); } @Override - public Object apply(Transaction transaction) throws FirebaseFirestoreException { + public Object apply(Transaction transaction) + throws FirebaseFirestoreException { if (cppFirestoreObject != 0 && cppListenerObject != 0) { try { - Exception exception = nativeApply(cppFirestoreObject, cppListenerObject, transaction); + Exception exception = + nativeApply(cppFirestoreObject, cppListenerObject, transaction); if (exception != null) { throw exception; } @@ -54,8 +58,12 @@ public Object apply(Transaction transaction) throws FirebaseFirestoreException { return null; } - /** This native function is implemented in the Firestore C++ library (transaction_android.cc). */ + /** + * This native function is implemented in the Firestore C++ library + * (transaction_android.cc). + */ @Nullable - private static native Exception nativeApply( - long firestoreObject, long transactionFunctionObject, Transaction transaction); + private static native Exception nativeApply(long firestoreObject, + long transactionFunctionObject, + Transaction transaction); } diff --git a/firestore/src_java/com/google/firebase/firestore/internal/cpp/VoidEventListener.java b/firestore/src_java/com/google/firebase/firestore/internal/cpp/VoidEventListener.java index ec2bfada9c..29078e4934 100644 --- a/firestore/src_java/com/google/firebase/firestore/internal/cpp/VoidEventListener.java +++ b/firestore/src_java/com/google/firebase/firestore/internal/cpp/VoidEventListener.java @@ -18,18 +18,21 @@ /** * An implementation of {@code Runnable} that delegates to a {@code - * firebase::firestore::EventListener}. This is useful for getting callbacks from Java APIs - * that cannot fail, like addSnapshotsInSyncListener. + * firebase::firestore::EventListener}. This is useful for getting + * callbacks from Java APIs that cannot fail, like addSnapshotsInSyncListener. */ public class VoidEventListener extends CppEventListener implements Runnable { /** - * Constructs a VoidEventListener. Ownership of the underlying EventListener can be transferred - * when creating the {@code ListenerRegistration}. If the ListenerRegistration owns the - * EventListener, it will de-allocate the EventListener in its destructor. + * Constructs a VoidEventListener. Ownership of the underlying EventListener + * can be transferred when creating the {@code ListenerRegistration}. If the + * ListenerRegistration owns the EventListener, it will de-allocate the + * EventListener in its destructor. * - *

Passing in 0 is considered a null pointer and will result in {@code run} becoming a no-op. + *

Passing in 0 is considered a null pointer and will result in {@code run} + * becoming a no-op. * - * @param cppListenerObject Pointer to a {@code firebase::firestore::EventListener}. + * @param cppListenerObject Pointer to a {@code + * firebase::firestore::EventListener}. */ public VoidEventListener(long cppListenerObject) { super(0, cppListenerObject); @@ -41,9 +44,10 @@ public void run() { } /** - * Interprets the {@code listenerObject} as a {@code firebase::firestore::EventListener} and - * invokes the listener's {@code OnEvent} method with {@code Error::kOk}. The EventListener will - * never be passed anything other than Ok because VoidEventListener can only be used in + * Interprets the {@code listenerObject} as a {@code + * firebase::firestore::EventListener} and invokes the listener's {@code + * OnEvent} method with {@code Error::kOk}. The EventListener will never be + * passed anything other than Ok because VoidEventListener can only be used in * circumstances where the callback can't fail. * *

This native method is implemented in the Firestore C++ library {@code diff --git a/functions/src/include/firebase/functions/callable_result.h b/functions/src/include/firebase/functions/callable_result.h index 84cf870df1..5186377ae8 100644 --- a/functions/src/include/firebase/functions/callable_result.h +++ b/functions/src/include/firebase/functions/callable_result.h @@ -15,8 +15,8 @@ #ifndef FIREBASE_FUNCTIONS_SRC_INCLUDE_FIREBASE_FUNCTIONS_CALLABLE_RESULT_H_ #define FIREBASE_FUNCTIONS_SRC_INCLUDE_FIREBASE_FUNCTIONS_CALLABLE_RESULT_H_ -#include "firebase/variant.h" #include "firebase/functions/common.h" +#include "firebase/variant.h" namespace firebase { namespace functions { diff --git a/functions/src/include/firebase/functions/common.h b/functions/src/include/firebase/functions/common.h index aa4b864dab..133fe14aa4 100644 --- a/functions/src/include/firebase/functions/common.h +++ b/functions/src/include/firebase/functions/common.h @@ -25,7 +25,7 @@ namespace functions { /// https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto enum Error { #ifdef INTERNAL_EXPERIMENTAL - // LINT.IfChange +// LINT.IfChange #endif // INTERNAL_EXPERIMENTAL // Not an error; returned on success @@ -182,7 +182,7 @@ enum Error { kErrorDataLoss = 15, #ifdef INTERNAL_EXPERIMENTAL - // LINT.ThenChange(//depot_firebase_cpp/functions/client/cpp/src/ios/\ +// LINT.ThenChange(//depot_firebase_cpp/functions/client/cpp/src/ios/\ // callable_reference_ios.mm) #endif // INTERNAL_EXPERIMENTAL }; diff --git a/installations/src_java/fake/com/google/firebase/installations/FirebaseInstallations.java b/installations/src_java/fake/com/google/firebase/installations/FirebaseInstallations.java index 0953547218..1ff8762a15 100644 --- a/installations/src_java/fake/com/google/firebase/installations/FirebaseInstallations.java +++ b/installations/src_java/fake/com/google/firebase/installations/FirebaseInstallations.java @@ -21,7 +21,6 @@ /** Mock FirebaseInstallations. */ public class FirebaseInstallations { - private static final String FN_GET_ID = "FirebaseInstallations.getId"; private static final String FN_GEI_TOKEN = "FirebaseInstallations.getToken"; private static final String FN_DELETE = "FirebaseInstallations.delete"; diff --git a/installations/src_java/fake/com/google/firebase/installations/InstallationTokenResult.java b/installations/src_java/fake/com/google/firebase/installations/InstallationTokenResult.java index 67ddd19621..7ae6933611 100644 --- a/installations/src_java/fake/com/google/firebase/installations/InstallationTokenResult.java +++ b/installations/src_java/fake/com/google/firebase/installations/InstallationTokenResult.java @@ -16,7 +16,6 @@ /** Mock InstallationTokenResult */ public class InstallationTokenResult { - private InstallationTokenResult() {} public static synchronized InstallationTokenResult getInstance() { diff --git a/messaging/samples/src/java/com/google/firebase/messaging/cpp/samples/MyActivity.java b/messaging/samples/src/java/com/google/firebase/messaging/cpp/samples/MyActivity.java index 6a97c0ad3f..8bc173fae6 100644 --- a/messaging/samples/src/java/com/google/firebase/messaging/cpp/samples/MyActivity.java +++ b/messaging/samples/src/java/com/google/firebase/messaging/cpp/samples/MyActivity.java @@ -23,7 +23,6 @@ import android.app.Activity; import android.content.Intent; import android.util.Log; - // [START messaging_on_new_intent] import com.google.firebase.messaging.MessageForwardingService; diff --git a/messaging/samples/src/java/com/google/firebase/messaging/cpp/samples/MyListenerService.java b/messaging/samples/src/java/com/google/firebase/messaging/cpp/samples/MyListenerService.java index af9063eced..e65270532a 100644 --- a/messaging/samples/src/java/com/google/firebase/messaging/cpp/samples/MyListenerService.java +++ b/messaging/samples/src/java/com/google/firebase/messaging/cpp/samples/MyListenerService.java @@ -22,12 +22,11 @@ import android.util.Log; import com.google.firebase.messaging.RemoteMessage; - // [START messaging_extend_listener_service] import com.google.firebase.messaging.cpp.ListenerService; class MyListenerService extends ListenerService { -// [END messaging_extend_listener_service] + // [END messaging_extend_listener_service] private static final String TAG = "MyListenerService"; // [START messaging_on_message_received_override] diff --git a/messaging/src/android/cpp/messaging.cc b/messaging/src/android/cpp/messaging.cc index 8f5d257bec..047c4e8591 100644 --- a/messaging/src/android/cpp/messaging.cc +++ b/messaging/src/android/cpp/messaging.cc @@ -630,6 +630,8 @@ InitResult Initialize(const ::firebase::App& app, Listener* listener, pthread_create(&g_poll_thread, nullptr, MessageProcessingThread, nullptr); FIREBASE_ASSERT(result == 0); + FutureData::Create(); + if (g_registration_token_request_state != kRegistrationTokenRequestStateNone) { // Calling this again, now that we're initialized. @@ -647,8 +649,6 @@ InitResult Initialize(const ::firebase::App& app, Listener* listener, kDeliveryMetricsExportToBigQueryEnable); } - FutureData::Create(); - // Supposedly App creation also creates a registration token, but this seems // to happen before the C++ listeners are able to capture it. // So this may seem redundant but at least both are respecting the same flag @@ -677,6 +677,7 @@ void Terminate() { } internal::UnregisterTerminateOnDefaultAppDestroy(); JNIEnv* env = g_app->GetJNIEnv(); + util::CancelCallbacks(env, kApiIdentifier); // Dereference the app. { MutexLock lock(g_app_mutex); diff --git a/messaging/src/android/java/com/google/firebase/messaging/JobIds.java b/messaging/src/android/java/com/google/firebase/messaging/JobIds.java index 9cfca6fb1e..cff5f7f9e0 100644 --- a/messaging/src/android/java/com/google/firebase/messaging/JobIds.java +++ b/messaging/src/android/java/com/google/firebase/messaging/JobIds.java @@ -16,7 +16,6 @@ /** Unique ids for JobIntentServices. */ public final class JobIds { - private JobIds() {} public static final int MESSAGE_FORWARDING_SERVICE = 1000; diff --git a/messaging/src/android/java/com/google/firebase/messaging/MessageForwardingService.java b/messaging/src/android/java/com/google/firebase/messaging/MessageForwardingService.java index a5b35f30a2..81d4b32bfc 100644 --- a/messaging/src/android/java/com/google/firebase/messaging/MessageForwardingService.java +++ b/messaging/src/android/java/com/google/firebase/messaging/MessageForwardingService.java @@ -30,9 +30,9 @@ public class MessageForwardingService extends JobIntentService { public static final String ACTION_REMOTE_INTENT = "com.google.android.c2dm.intent.RECEIVE"; /** - * Convenience wrapper over enqueueWork to either directly start the service (when running on - * pre-O platforms) or enqueue work for it as a job (when running on Android O and later). - */ + * Convenience wrapper over enqueueWork to either directly start the service (when running on + * pre-O platforms) or enqueue work for it as a job (when running on Android O and later). + */ public static void enqueueWork(Context context, Intent intent) { enqueueWork(context, MessageForwardingService.class, JobIds.MESSAGE_FORWARDING_SERVICE, intent); } @@ -46,14 +46,11 @@ protected void onHandleWork(Intent intent) { // TODO(b/79994182): see go/objecttostring-lsc @SuppressWarnings("ObjectToString") static void handleIntent(Context context, Intent intent, MessageWriter messageWriter) { - DebugLogging.log( - TAG, + DebugLogging.log(TAG, "onHandleIntent " - + (intent == null - ? "null intent" - : (intent.getAction() == null ? "(null)" : intent.getAction()))); - if (intent != null - && intent.getAction() != null + + (intent == null ? "null intent" + : (intent.getAction() == null ? "(null)" : intent.getAction()))); + if (intent != null && intent.getAction() != null && intent.getAction().equals(ACTION_REMOTE_INTENT)) { Bundle extras = intent.getExtras(); DebugLogging.log(TAG, "extras: " + (extras == null ? "(null)" : extras.toString())); diff --git a/messaging/src/android/java/com/google/firebase/messaging/cpp/ListenerService.java b/messaging/src/android/java/com/google/firebase/messaging/cpp/ListenerService.java index 5dfe5cda43..243af4a3b0 100644 --- a/messaging/src/android/java/com/google/firebase/messaging/cpp/ListenerService.java +++ b/messaging/src/android/java/com/google/firebase/messaging/cpp/ListenerService.java @@ -22,7 +22,6 @@ * OnMessage function. */ public class ListenerService extends FirebaseMessagingService { - // TODO(amablue): Add an IfChange/ThenChange block around this, and the other copy of these // variables in com.google.firebase.messaging.RemoteMessageBuilder. public static final String MESSAGE_TYPE_DELETED = "deleted_messages"; @@ -61,8 +60,7 @@ public void onMessageSent(String messageId) { @Override public void onSendError(String messageId, Exception exception) { - DebugLogging.log( - TAG, + DebugLogging.log(TAG, String.format("onSendError messageId=%s exception=%s", messageId, exception.toString())); messageWriter.writeMessageEventToInternalStorage( this, messageId, MESSAGE_TYPE_SEND_ERROR, exception.toString()); diff --git a/messaging/src/android/java/com/google/firebase/messaging/cpp/MessageWriter.java b/messaging/src/android/java/com/google/firebase/messaging/cpp/MessageWriter.java index 937b89b3fb..bb7a4c437e 100644 --- a/messaging/src/android/java/com/google/firebase/messaging/cpp/MessageWriter.java +++ b/messaging/src/android/java/com/google/firebase/messaging/cpp/MessageWriter.java @@ -64,53 +64,20 @@ public void writeMessage( linkUri = notification.getLink(); } String link = (linkUri != null) ? linkUri.toString() : null; - DebugLogging.log( - TAG, - String.format( - "onMessageReceived from=%s message_id=%s, data=%s, notification=%s", - from, - messageId, - (data == null ? "(null)" : data.toString()), + DebugLogging.log(TAG, + String.format("onMessageReceived from=%s message_id=%s, data=%s, notification=%s", from, + messageId, (data == null ? "(null)" : data.toString()), (notification == null ? "(null)" : notification.toString()))); - writeMessageToInternalStorage( - context, - from, - to, - messageId, - messageType, - null, - data, - rawData, - notification, - notificationOpened, - link, - collapseKey, - priority, - originalPriority, - sentTime, + writeMessageToInternalStorage(context, from, to, messageId, messageType, null, data, rawData, + notification, notificationOpened, link, collapseKey, priority, originalPriority, sentTime, timeToLive); } /** Writes an event associated with a message to internal storage. */ void writeMessageEventToInternalStorage( Context context, String messageId, String messageType, String error) { - writeMessageToInternalStorage( - context, - null, - null, - messageId, - messageType, - null, - null, - null, - null, - false, - null, - null, - 0, - 0, - 0, - 0); + writeMessageToInternalStorage(context, null, null, messageId, messageType, null, null, null, + null, false, null, null, 0, 0, 0, 0); } /** @@ -122,40 +89,13 @@ void writeMessageEventToInternalStorage( * whenever it gets around to it. */ @SuppressWarnings("CatchAndPrintStackTrace") - void writeMessageToInternalStorage( - Context context, - String from, - String to, - String messageId, - String messageType, - String error, - Map data, - byte[] rawData, - Notification notification, - boolean notificationOpened, - String link, - String collapseKey, - int priority, - int originalPriority, - long sentTime, - int timeToLive) { - byte[] buffer = - generateMessageByteBuffer( - from, - to, - messageId, - messageType, - error, - data, - rawData, - notification, - notificationOpened, - link, - collapseKey, - priority, - originalPriority, - sentTime, - timeToLive); + void writeMessageToInternalStorage(Context context, String from, String to, String messageId, + String messageType, String error, Map data, byte[] rawData, + Notification notification, boolean notificationOpened, String link, String collapseKey, + int priority, int originalPriority, long sentTime, int timeToLive) { + byte[] buffer = generateMessageByteBuffer(from, to, messageId, messageType, error, data, + rawData, notification, notificationOpened, link, collapseKey, priority, originalPriority, + sentTime, timeToLive); ByteBuffer sizeBuffer = ByteBuffer.allocate(4); // Write out the buffer length into the first four bytes. sizeBuffer.order(ByteOrder.LITTLE_ENDIAN); @@ -202,22 +142,10 @@ private static String priorityToString(int priority) { } } - private static byte[] generateMessageByteBuffer( - String from, - String to, - String messageId, - String messageType, - String error, - Map data, - byte[] rawData, - Notification notification, - boolean notificationOpened, - String link, - String collapseKey, - int priority, - int originalPriority, - long sentTime, - int timeToLive) { + private static byte[] generateMessageByteBuffer(String from, String to, String messageId, + String messageType, String error, Map data, byte[] rawData, + Notification notification, boolean notificationOpened, String link, String collapseKey, + int priority, int originalPriority, long sentTime, int timeToLive) { FlatBufferBuilder builder = new FlatBufferBuilder(0); int fromOffset = builder.createString(emptyIfNull(from)); int toOffset = builder.createString(emptyIfNull(to)); diff --git a/messaging/src/android/java/com/google/firebase/messaging/cpp/RegistrationIntentService.java b/messaging/src/android/java/com/google/firebase/messaging/cpp/RegistrationIntentService.java index d296000c02..912ff38f4a 100644 --- a/messaging/src/android/java/com/google/firebase/messaging/cpp/RegistrationIntentService.java +++ b/messaging/src/android/java/com/google/firebase/messaging/cpp/RegistrationIntentService.java @@ -18,10 +18,10 @@ import android.content.Intent; import android.util.Log; import androidx.annotation.NonNull; +import androidx.core.app.JobIntentService; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.messaging.FirebaseMessaging; -import androidx.core.app.JobIntentService; import com.google.flatbuffers.FlatBufferBuilder; import java.io.FileOutputStream; import java.nio.ByteBuffer; @@ -39,24 +39,24 @@ public class RegistrationIntentService extends JobIntentService { @Override protected void onHandleWork(Intent intent) { final Context context = this; - FirebaseMessaging.getInstance().getToken() - .addOnCompleteListener(new OnCompleteListener() { - @Override - public void onComplete(@NonNull Task task) { - if (!task.isSuccessful()) { - Log.w(TAG, "Fetching FCM registration token failed", task.getException()); - return; - } + FirebaseMessaging.getInstance().getToken().addOnCompleteListener( + new OnCompleteListener() { + @Override + public void onComplete(@NonNull Task task) { + if (!task.isSuccessful()) { + Log.w(TAG, "Fetching FCM registration token failed", task.getException()); + return; + } - // Get new FCM registration token - String token = task.getResult(); + // Get new FCM registration token + String token = task.getResult(); - DebugLogging.log(TAG, String.format("onHandleWork token=%s", token)); - if (token != null) { - writeTokenToInternalStorage(context, token); + DebugLogging.log(TAG, String.format("onHandleWork token=%s", token)); + if (token != null) { + writeTokenToInternalStorage(context, token); + } } - } - }); + }); } /** Write token to internal storage so it can be accessed by the C++ layer. */ diff --git a/messaging/src/android/javatests/com/google/firebase/messaging/MessageForwardingServiceTest.java b/messaging/src/android/javatests/com/google/firebase/messaging/MessageForwardingServiceTest.java index 05e86e6466..765857bd6b 100644 --- a/messaging/src/android/javatests/com/google/firebase/messaging/MessageForwardingServiceTest.java +++ b/messaging/src/android/javatests/com/google/firebase/messaging/MessageForwardingServiceTest.java @@ -33,7 +33,6 @@ @RunWith(GoogleRobolectricTestRunner.class) public final class MessageForwardingServiceTest { - @Mock private Context context; @Mock private MessageWriter messageWriter; diff --git a/messaging/src/android/javatests/com/google/firebase/messaging/RemoteMessageUtil.java b/messaging/src/android/javatests/com/google/firebase/messaging/RemoteMessageUtil.java index 64ce0ad5c2..55033e6f67 100644 --- a/messaging/src/android/javatests/com/google/firebase/messaging/RemoteMessageUtil.java +++ b/messaging/src/android/javatests/com/google/firebase/messaging/RemoteMessageUtil.java @@ -18,7 +18,6 @@ /** */ public class RemoteMessageUtil { - private RemoteMessageUtil() {} // Utility class. public static RemoteMessage remoteMessage(Bundle bundle) { diff --git a/messaging/src/android/javatests/com/google/firebase/messaging/cpp/ListenerServiceTest.java b/messaging/src/android/javatests/com/google/firebase/messaging/cpp/ListenerServiceTest.java index ff7db3b4ed..4fc47a7691 100644 --- a/messaging/src/android/javatests/com/google/firebase/messaging/cpp/ListenerServiceTest.java +++ b/messaging/src/android/javatests/com/google/firebase/messaging/cpp/ListenerServiceTest.java @@ -32,7 +32,6 @@ @RunWith(GoogleRobolectricTestRunner.class) public final class ListenerServiceTest { - @Mock private MessageWriter messageWriter; private ListenerService listenerService; @@ -47,11 +46,8 @@ public void setUp() { public void testOnDeletedMessages() throws Exception { listenerService.onDeletedMessages(); verify(messageWriter) - .writeMessageEventToInternalStorage( - eq(listenerService), - (String) isNull(), - eq(ListenerService.MESSAGE_TYPE_DELETED), - (String) isNull()); + .writeMessageEventToInternalStorage(eq(listenerService), (String) isNull(), + eq(ListenerService.MESSAGE_TYPE_DELETED), (String) isNull()); } @Test @@ -65,11 +61,8 @@ public void testOnMessageReceived() { public void testOnMessageSent() { listenerService.onMessageSent("message_id"); verify(messageWriter) - .writeMessageEventToInternalStorage( - eq(listenerService), - eq("message_id"), - eq(ListenerService.MESSAGE_TYPE_SEND_EVENT), - (String) isNull()); + .writeMessageEventToInternalStorage(eq(listenerService), eq("message_id"), + eq(ListenerService.MESSAGE_TYPE_SEND_EVENT), (String) isNull()); } @Test @@ -77,9 +70,7 @@ public void testOnSendError() { listenerService.onSendError( "message_id", RemoteMessageUtil.sendException("service_not_available")); verify(messageWriter) - .writeMessageEventToInternalStorage( - eq(listenerService), - eq("message_id"), + .writeMessageEventToInternalStorage(eq(listenerService), eq("message_id"), eq(ListenerService.MESSAGE_TYPE_SEND_ERROR), eq("com.google.firebase.messaging.SendException: service_not_available")); } diff --git a/messaging/src/android/javatests/com/google/firebase/messaging/cpp/MessageWriterTest.java b/messaging/src/android/javatests/com/google/firebase/messaging/cpp/MessageWriterTest.java index 7621a0b0be..4c33f27744 100644 --- a/messaging/src/android/javatests/com/google/firebase/messaging/cpp/MessageWriterTest.java +++ b/messaging/src/android/javatests/com/google/firebase/messaging/cpp/MessageWriterTest.java @@ -40,7 +40,6 @@ @RunWith(GoogleRobolectricTestRunner.class) public final class MessageWriterTest { - private static final Path STORAGE_FILE_PATH = Paths.get("/tmp/" + MessageWriter.STORAGE_FILE); @Mock private Context context; @@ -71,7 +70,7 @@ public void testMessageWriter() throws Exception { RemoteMessage message = RemoteMessageUtil.remoteMessage(bundle); messageWriter.writeMessage(context, message, false, null); ByteBuffer byteBuffer = ByteBuffer.wrap(readStorageFile()).order(ByteOrder.LITTLE_ENDIAN); - byteBuffer.getInt(); // Discard size. + byteBuffer.getInt(); // Discard size. SerializedEvent event = SerializedEvent.getRootAsSerializedEvent(byteBuffer); SerializedMessage result = (SerializedMessage) event.event(new SerializedMessage()); assertThat(result.from()).isEqualTo("my_from"); diff --git a/messaging/src/ios/messaging.mm b/messaging/src/ios/messaging.mm index 934438faa4..fcf9f7cffe 100644 --- a/messaging/src/ios/messaging.mm +++ b/messaging/src/ios/messaging.mm @@ -869,7 +869,8 @@ void SetTokenRegistrationOnInitEnabled(bool enable) { // http://www.opensource.apple.com/source/objc4/objc4-274/runtime/objc-runtime.m) @implementation UIApplication (FIRFCM) + (void)load { - ::firebase::LogInfo("FCM: Loading UIApplication FIRFCM category"); + // C++ constructors may not be called yet so call NSLog rather than LogInfo. + NSLog(@"FCM: Loading UIApplication FIRFCM category"); ::firebase::util::ForEachAppDelegateClass(^(Class clazz) { FirebaseMessagingHookAppDelegate(clazz); }); diff --git a/messaging/src_java/fake/com/google/firebase/messaging/FirebaseMessaging.java b/messaging/src_java/fake/com/google/firebase/messaging/FirebaseMessaging.java index e4f91e7ef2..d3099ae6d0 100644 --- a/messaging/src_java/fake/com/google/firebase/messaging/FirebaseMessaging.java +++ b/messaging/src_java/fake/com/google/firebase/messaging/FirebaseMessaging.java @@ -24,7 +24,6 @@ * Fake FirebaseMessaging class. */ public class FirebaseMessaging { - private static final String FN_GET_TOKEN = "FirebaseMessaging.getToken"; private static final String FN_DELETE_TOKEN = "FirebaseMessaging.deleteToken"; diff --git a/messaging/src_java/fake/com/google/firebase/messaging/RemoteMessage.java b/messaging/src_java/fake/com/google/firebase/messaging/RemoteMessage.java index b65cd5e9b5..5abb8d3b2e 100644 --- a/messaging/src_java/fake/com/google/firebase/messaging/RemoteMessage.java +++ b/messaging/src_java/fake/com/google/firebase/messaging/RemoteMessage.java @@ -20,7 +20,6 @@ * Fake RemoteMessage class. */ public class RemoteMessage { - public final String from; public final String to; public final Map data; @@ -40,7 +39,6 @@ private RemoteMessage( * Fake Builder class. */ public static class Builder { - private final String to; private Map data; private Integer ttl; diff --git a/messaging/src_java/fake/com/google/firebase/messaging/cpp/RegistrationIntentService.java b/messaging/src_java/fake/com/google/firebase/messaging/cpp/RegistrationIntentService.java index d7a7efc6ae..ed2f8afcb2 100644 --- a/messaging/src_java/fake/com/google/firebase/messaging/cpp/RegistrationIntentService.java +++ b/messaging/src_java/fake/com/google/firebase/messaging/cpp/RegistrationIntentService.java @@ -17,5 +17,4 @@ /** * Fake RegistrationIntentService class. */ -public class RegistrationIntentService { -} +public class RegistrationIntentService {} diff --git a/messaging/tests/ios/messaging_test_util.mm b/messaging/tests/ios/messaging_test_util.mm index 106381b769..9e4004b5d8 100644 --- a/messaging/tests/ios/messaging_test_util.mm +++ b/messaging/tests/ios/messaging_test_util.mm @@ -44,14 +44,11 @@ // Dual purpose body text or data dictionary. static NSString *const kAlert = @"alert"; - void InitializeMessagingTest() {} -void TerminateMessagingTest() { - [FIRMessaging messaging].FCMToken = nil; -} +void TerminateMessagingTest() { [FIRMessaging messaging].FCMToken = nil; } -void OnTokenReceived(const char* tokenstr) { +void OnTokenReceived(const char *tokenstr) { [FIRMessaging messaging].FCMToken = @(tokenstr); [[FIRMessaging messaging].delegate messaging:[FIRMessaging messaging] didReceiveRegistrationToken:@(tokenstr)]; @@ -62,8 +59,8 @@ void SleepMessagingTest(double seconds) { [[NSRunLoop mainRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:seconds]]; } -void OnMessageReceived(const Message& message) { - NSMutableDictionary* userData = [NSMutableDictionary dictionary]; +void OnMessageReceived(const Message &message) { + NSMutableDictionary *userData = [NSMutableDictionary dictionary]; userData[kMessageID] = @(message.message_id.c_str()); userData[kTo] = @(message.to.c_str()); userData[kFrom] = @(message.from.c_str()); @@ -73,15 +70,15 @@ void OnMessageReceived(const Message& message) { userData[kTimeToLive] = @(message.time_to_live); userData[kError] = @(message.error.c_str()); userData[kErrorDescription] = @(message.error_description.c_str()); - for (const auto& entry : message.data) { + for (const auto &entry : message.data) { userData[@(entry.first.c_str())] = @(entry.second.c_str()); } if (message.notification) { - NSMutableDictionary* alert = [NSMutableDictionary dictionary]; + NSMutableDictionary *alert = [NSMutableDictionary dictionary]; alert[kTitle] = @(message.notification->title.c_str()); alert[kBody] = @(message.notification->body.c_str()); - NSMutableDictionary* aps = [NSMutableDictionary dictionary]; + NSMutableDictionary *aps = [NSMutableDictionary dictionary]; aps[kSound] = @(message.notification->sound.c_str()); aps[kBadge] = @(message.notification->badge.c_str()); aps[kAlert] = alert; @@ -91,9 +88,9 @@ void OnMessageReceived(const Message& message) { didReceiveRemoteNotification:userData]; } -void OnMessageSent(const char* message_id) {} +void OnMessageSent(const char *message_id) {} -void OnMessageSentError(const char* message_id, const char* error) {} +void OnMessageSentError(const char *message_id, const char *error) {} } // namespace messaging } // namespace firebase diff --git a/performance/src_java/fake/com/google/firebase/perf/FirebasePerformance.java b/performance/src_java/fake/com/google/firebase/perf/FirebasePerformance.java index d5c25b384b..70fd28a70d 100644 --- a/performance/src_java/fake/com/google/firebase/perf/FirebasePerformance.java +++ b/performance/src_java/fake/com/google/firebase/perf/FirebasePerformance.java @@ -13,17 +13,8 @@ public class FirebasePerformance { private static boolean performanceCollectionEnabled = true; /** Valid HttpMethods for manual network APIs */ - @StringDef({ - HttpMethod.GET, - HttpMethod.PUT, - HttpMethod.POST, - HttpMethod.DELETE, - HttpMethod.HEAD, - HttpMethod.PATCH, - HttpMethod.OPTIONS, - HttpMethod.TRACE, - HttpMethod.CONNECT - }) + @StringDef({HttpMethod.GET, HttpMethod.PUT, HttpMethod.POST, HttpMethod.DELETE, HttpMethod.HEAD, + HttpMethod.PATCH, HttpMethod.OPTIONS, HttpMethod.TRACE, HttpMethod.CONNECT}) @Retention(RetentionPolicy.SOURCE) public @interface HttpMethod { String GET = "GET"; diff --git a/performance/src_java/fake/com/google/firebase/perf/FirebasePerformanceAttributable.java b/performance/src_java/fake/com/google/firebase/perf/FirebasePerformanceAttributable.java index fc38e5f714..e157804bb5 100644 --- a/performance/src_java/fake/com/google/firebase/perf/FirebasePerformanceAttributable.java +++ b/performance/src_java/fake/com/google/firebase/perf/FirebasePerformanceAttributable.java @@ -6,7 +6,6 @@ /** Attribute functions needed for Traces and HttpMetrics */ public interface FirebasePerformanceAttributable { - /** Maximum allowed number of attributes allowed in a trace. */ int MAX_TRACE_CUSTOM_ATTRIBUTES = 5; /** Maximum allowed length of the Key of the {@link Trace} attribute */ @@ -35,8 +34,7 @@ public interface FirebasePerformanceAttributable { * @param attribute name of the attribute to fetch the value for * @return The value of the attribute if it exists or null otherwise. */ - @Nullable - String getAttribute(String attribute); + @Nullable String getAttribute(String attribute); /** * Removes the attribute from the list of attributes. diff --git a/performance/src_java/fake/com/google/firebase/perf/metrics/HttpMetric.java b/performance/src_java/fake/com/google/firebase/perf/metrics/HttpMetric.java index 18b305224d..2350eb3518 100644 --- a/performance/src_java/fake/com/google/firebase/perf/metrics/HttpMetric.java +++ b/performance/src_java/fake/com/google/firebase/perf/metrics/HttpMetric.java @@ -1,7 +1,7 @@ package com.google.firebase.perf.metrics; -import androidx.annotation.Nullable; import android.util.Log; +import androidx.annotation.Nullable; import com.google.apps.tiktok.testing.errorprone.SuppressViolation; import com.google.firebase.perf.FirebasePerformance.HttpMethod; import com.google.firebase.perf.FirebasePerformanceAttributable; @@ -15,7 +15,6 @@ * request/response. This class is not thread safe. */ public class HttpMetric implements FirebasePerformanceAttributable { - private static final String LOG_TAG = "FirebasePerformanceFake"; private final Map attributes; diff --git a/performance/src_java/fake/com/google/firebase/perf/metrics/Trace.java b/performance/src_java/fake/com/google/firebase/perf/metrics/Trace.java index 5fbbd90546..c9cb476b69 100644 --- a/performance/src_java/fake/com/google/firebase/perf/metrics/Trace.java +++ b/performance/src_java/fake/com/google/firebase/perf/metrics/Trace.java @@ -1,8 +1,8 @@ package com.google.firebase.perf.metrics; import android.support.annotation.Keep; -import androidx.annotation.Nullable; import android.util.Log; +import androidx.annotation.Nullable; import com.google.firebase.perf.FirebasePerformanceAttributable; import com.google.firebase.testing.cppsdk.FakeReporter; import java.util.Date; @@ -117,18 +117,14 @@ public long getLongMetric(String metricName) { public void putMetric(String metricName, long value) { FakeReporter.addReport("Trace.putMetric", metricName, Long.toString(value)); if (!hasStarted()) { - Log.w( - LOG_TAG, - String.format( - "Cannot set value for metric '%s' for trace '%s' because it's not started", + Log.w(LOG_TAG, + String.format("Cannot set value for metric '%s' for trace '%s' because it's not started", metricName, name)); return; } if (isStopped()) { - Log.w( - LOG_TAG, - String.format( - "Cannot set value for metric '%s' for trace '%s' because it's been stopped", + Log.w(LOG_TAG, + String.format("Cannot set value for metric '%s' for trace '%s' because it's been stopped", metricName, name)); return; } @@ -144,8 +140,7 @@ protected void finalize() throws Throwable { try { // If trace is started but not stopped when it reaches finalize(), log a warning msg. if (isActive()) { - Log.w( - LOG_TAG, + Log.w(LOG_TAG, String.format("Trace '%s' is started but not stopped when it is destructed!", name)); } } finally { @@ -199,8 +194,7 @@ public void putAttribute(String attribute, String value) { attribute = attribute.trim(); value = value.trim(); } catch (Exception e) { - Log.e( - LOG_TAG, + Log.e(LOG_TAG, String.format( "Can not set attribute %s with value %s (%s)", attribute, value, e.getMessage())); noError = false; diff --git a/release_build_files/readme.md b/release_build_files/readme.md index 739dc91794..6f173209ad 100644 --- a/release_build_files/readme.md +++ b/release_build_files/readme.md @@ -569,11 +569,18 @@ code. ## Release Notes ### Next Release - Changes + - General: Fixed a data race that could manifest as null pointer + dereference in `FutureBase::Release()`. + ([#747](https://github.com/firebase/firebase-cpp-sdk/pull/747)) - Auth (Desktop): Fixed a crash in `error_code()` when a request is cancelled or times out. ([#737](https://github.com/firebase/firebase-cpp-sdk/issues/737)) - Messaging (Android): Fixed crash during termination. ([#739](https://github.com/firebase/firebase-cpp-sdk/pull/739)) + ([#745](https://github.com/firebase/firebase-cpp-sdk/pull/745)) + - Messaging (Android): Fixed crash during initialization. + ([#760](https://github.com/firebase/firebase-cpp-sdk/pull/760)) + ### 8.7.0 - Changes diff --git a/remote_config/src_java/fake/com/google/firebase/remoteconfig/FirebaseRemoteConfig.java b/remote_config/src_java/fake/com/google/firebase/remoteconfig/FirebaseRemoteConfig.java index 8339d2670c..6d58412f76 100644 --- a/remote_config/src_java/fake/com/google/firebase/remoteconfig/FirebaseRemoteConfig.java +++ b/remote_config/src_java/fake/com/google/firebase/remoteconfig/FirebaseRemoteConfig.java @@ -30,7 +30,6 @@ /** Fake FirebaseRemoteConfig */ public class FirebaseRemoteConfig { - private static final String FN_GET_LONG = "FirebaseRemoteConfig.getLong"; private static final String FN_GET_STRING = "FirebaseRemoteConfig.getString"; private static final String FN_GET_BOOLEAN = "FirebaseRemoteConfig.getBoolean"; @@ -216,5 +215,4 @@ private static List stringToStringList(String s) { } return Arrays.asList(arr); } - } diff --git a/remote_config/src_java/fake/com/google/firebase/remoteconfig/FirebaseRemoteConfigFetchThrottledException.java b/remote_config/src_java/fake/com/google/firebase/remoteconfig/FirebaseRemoteConfigFetchThrottledException.java index 8e72f08587..b2f5ab8be7 100644 --- a/remote_config/src_java/fake/com/google/firebase/remoteconfig/FirebaseRemoteConfigFetchThrottledException.java +++ b/remote_config/src_java/fake/com/google/firebase/remoteconfig/FirebaseRemoteConfigFetchThrottledException.java @@ -16,9 +16,7 @@ /** Fake FirebaseRemoteConfigFetchThrottledException */ public class FirebaseRemoteConfigFetchThrottledException { - - public long getThrottleEndTimeMillis() { - return 0; - } - + public long getThrottleEndTimeMillis() { + return 0; + } } diff --git a/remote_config/src_java/fake/com/google/firebase/remoteconfig/FirebaseRemoteConfigInfo.java b/remote_config/src_java/fake/com/google/firebase/remoteconfig/FirebaseRemoteConfigInfo.java index 5c61295168..1eefcac044 100644 --- a/remote_config/src_java/fake/com/google/firebase/remoteconfig/FirebaseRemoteConfigInfo.java +++ b/remote_config/src_java/fake/com/google/firebase/remoteconfig/FirebaseRemoteConfigInfo.java @@ -20,7 +20,6 @@ /** Fake FirebaseRemoteConfigInfo */ public class FirebaseRemoteConfigInfo { - public long getFetchTimeMillis() { ConfigRow row = ConfigAndroid.get("FirebaseRemoteConfigInfo.getFetchTimeMillis"); long result = row.returnvalue().tlong(); diff --git a/remote_config/src_java/fake/com/google/firebase/remoteconfig/FirebaseRemoteConfigSettings.java b/remote_config/src_java/fake/com/google/firebase/remoteconfig/FirebaseRemoteConfigSettings.java index da32edfb49..0cd609025e 100644 --- a/remote_config/src_java/fake/com/google/firebase/remoteconfig/FirebaseRemoteConfigSettings.java +++ b/remote_config/src_java/fake/com/google/firebase/remoteconfig/FirebaseRemoteConfigSettings.java @@ -20,7 +20,6 @@ /** Fake FirebaseRemoteConfigSettings */ public class FirebaseRemoteConfigSettings { - private static final String FN_GET_FETCH_TIMEOUT = "FirebaseRemoteConfig.getFetchTimeoutInSeconds"; private static final String FN_GET_MIN_FETCH_INTERVAL = diff --git a/remote_config/src_java/fake/com/google/firebase/remoteconfig/FirebaseRemoteConfigValue.java b/remote_config/src_java/fake/com/google/firebase/remoteconfig/FirebaseRemoteConfigValue.java index 1095739e48..dcb5bc44c8 100644 --- a/remote_config/src_java/fake/com/google/firebase/remoteconfig/FirebaseRemoteConfigValue.java +++ b/remote_config/src_java/fake/com/google/firebase/remoteconfig/FirebaseRemoteConfigValue.java @@ -22,7 +22,6 @@ /** Fake FirebaseRemoteConfigValue */ public class FirebaseRemoteConfigValue { - public FirebaseRemoteConfigValue() {} public long asLong() { diff --git a/scripts/format_code.py b/scripts/format_code.py index ac58fa8b11..49db3cabcb 100755 --- a/scripts/format_code.py +++ b/scripts/format_code.py @@ -54,7 +54,7 @@ flags.DEFINE_boolean("github_log", False, 'Pring special github log format items.') # Constants: -FILE_TYPE_EXTENSIONS = ('.cpp', '.cc', '.c', '.h') +FILE_TYPE_EXTENSIONS = ('.cpp', '.cc', '.c', '.h', '.m', '.mm', '.java') """Tuple: The file types to run clang-format on. Used to filter out results when searching across directories or git diffs. """ @@ -202,30 +202,6 @@ def validate_arguments(): return False return True -def is_file_objc_header(filename): - """Checks the contents of the file to determine if it contains language - constructs that appear in obj-c but not in C/C++. - - Args: - filename (string): the name of the file to check - - Returns: - bool: True if the header file contains known obj-c language definitions. - Returns False otherwise. - """ - _, ext = os.path.splitext(filename) - if ext != '.h': - return False - objective_c_tags = ('@end', '@class', '#import') - - with open(filename) as header_file: - lines = header_file.readlines() - for line in lines: - for tag in objective_c_tags: - if tag in line: - return True - return False - def main(argv): if not validate_arguments(): sys.exit(2) @@ -252,14 +228,10 @@ def main(argv): count = 0 for filename in filenames: if does_file_need_formatting(filename): - if is_file_objc_header(filename): - if FLAGS.verbose: - print(' - IGNORE OBJC: "{0}"'.format(filename)) - else: - if FLAGS.verbose: - print(' - FRMT: "{0}"'.format(filename)) - format_file(filename) - count += 1 + if FLAGS.verbose: + print(' - FRMT: "{0}"'.format(filename)) + format_file(filename) + count += 1 else: if FLAGS.verbose: print(' - OK: "{0}"'.format(filename)) @@ -268,7 +240,7 @@ def main(argv): github_log = ['::error ::FILE FORMATTING ERRORS:',''] count = 0 for filename in filenames: - if does_file_need_formatting(filename) and not is_file_objc_header(filename): + if does_file_need_formatting(filename): exit_code = 1 count += 1 github_log.append('- Requires reformatting: "{0}"'.format(filename)) diff --git a/scripts/gha/build_desktop.py b/scripts/gha/build_desktop.py index aaa4829d22..bedd14867c 100644 --- a/scripts/gha/build_desktop.py +++ b/scripts/gha/build_desktop.py @@ -56,12 +56,25 @@ def append_line_to_file(path, line): file.write("\n" + line + "\n") -def install_x86_support_libraries(): - """Install support libraries needed to build x86 on x86_64 hosts.""" +def install_x86_support_libraries(gha_build=False): + """Install support libraries needed to build x86 on x86_64 hosts. + + Args: + gha_build: Pass in True if running on a GitHub runner; this will activate + workarounds that might be undesirable on a personal system (e.g. + downgrading Ubuntu packages). + """ if utils.is_linux_os(): packages = ['gcc-multilib', 'g++-multilib', 'libglib2.0-dev:i386', 'libsecret-1-dev:i386', 'libpthread-stubs0-dev:i386', 'libssl-dev:i386'] + if gha_build: + # Workaround for GitHub runners, which have an incompatibility between the + # 64-bit and 32-bit versions of the Ubuntu package libpcre2-8-0. Downgrade + # the installed 64-bit version of the library to get around this issue. + # This will presumably be fixed in a future Ubuntu update. (If you remove + # it, remove the workaround further down this function as well.) + packages = ['--allow-downgrades'] + packages + ['libpcre2-8-0=10.34-7'] # First check if these packages exist on the machine already devnull = open(os.devnull, "w") @@ -70,9 +83,19 @@ def install_x86_support_libraries(): if process.returncode != 0: # This implies not all of the required packages are already installed on user's machine # Install them. - utils.run_command(['dpkg', '--add-architecture', 'i386'], as_root=True) - utils.run_command(['apt', 'update'], as_root=True) - utils.run_command(['apt', 'install', '-y'] + packages, as_root=True) + utils.run_command(['dpkg', '--add-architecture', 'i386'], as_root=True, check=True) + utils.run_command(['apt', 'update'], as_root=True, check=True) + utils.run_command(['apt', 'install', '-V', '-y'] + packages, as_root=True, check=True) + + if gha_build: + # One more workaround: downgrading libpcre2-8-0 above may have uninstalled + # libsecret, which is required for the Linux build. Force it to be + # reinstalled, but do it as a separate command to ensure that held + # packages aren't modified. (Once the workaround above is removed, this can + # be removed as well.) + # Note: "-f" = "fix" - let apt do what it needs to do to fix dependencies. + utils.run_command(['apt', 'install', '-f', '-V', '-y', 'libsecret-1-dev'], + as_root=True, check=True) def _install_cpp_dependencies_with_vcpkg(arch, msvc_runtime_library, use_openssl=False): @@ -94,7 +117,7 @@ def _install_cpp_dependencies_with_vcpkg(arch, msvc_runtime_library, use_openssl if not found_vcpkg_executable: script_absolute_path = utils.get_vcpkg_installation_script_path() # Example: ./external/vcpkg/bootstrap-sh - utils.run_command([script_absolute_path]) + utils.run_command([script_absolute_path], check=True) # Copy any of our custom defined vcpkg data to vcpkg submodule directory utils.copy_vcpkg_custom_data() @@ -113,7 +136,9 @@ def _install_cpp_dependencies_with_vcpkg(arch, msvc_runtime_library, use_openssl # Eg: ./external/vcpkg/vcpkg install @external/vcpkg_x64-osx_response_file.txt # --disable-metrics utils.run_command([vcpkg_executable_file_path, 'install', - '@' + vcpkg_response_file_path, '--disable-metrics']) + '@' + vcpkg_response_file_path, '--disable-metrics'], + check=True) + def install_cpp_dependencies_with_vcpkg(arch, msvc_runtime_library, cleanup=True, use_openssl=False): @@ -243,12 +268,12 @@ def main(): # Ensure that the submodules are initialized and updated # Example: vcpkg is a submodule (external/vcpkg) if not args.disable_vcpkg: - utils.run_command(['git', 'submodule', 'init']) - utils.run_command(['git', 'submodule', 'update']) + utils.run_command(['git', 'submodule', 'init'], check=True) + utils.run_command(['git', 'submodule', 'update'], check=True) # To build x86 on x86_64 linux hosts, we also need x86 support libraries if args.arch == 'x86' and utils.is_linux_os(): - install_x86_support_libraries() + install_x86_support_libraries(args.gha_build) # Install C++ dependencies using vcpkg if not args.disable_vcpkg: @@ -293,7 +318,7 @@ def parse_cmdline_args(): parser.add_argument('--target', nargs='+', help='A list of CMake build targets (eg: firebase_app firebase_auth)') parser.add_argument('--target_format', default=None, help='(Mac only) whether to output frameworks (default) or libraries.') parser.add_argument('--use_openssl', action='store_true', default=None, help='Use openssl for build instead of boringssl') - parser.add_argument('--gha_build', action='store_true', default=None, help='Set to true when building on GitHub, for metric tracking purposes') + parser.add_argument('--gha_build', action='store_true', default=None, help='Set to true when building on GitHub, for metric tracking purposes (also changes some prerequisite installation behavior).') args = parser.parse_args() return args diff --git a/scripts/gha/github.py b/scripts/gha/github.py index 204c50f363..e61458a4bf 100644 --- a/scripts/gha/github.py +++ b/scripts/gha/github.py @@ -21,6 +21,7 @@ import requests import json import shutil +import re from absl import logging from requests.adapters import HTTPAdapter @@ -35,9 +36,24 @@ REPO = 'firebase-cpp-sdk' BASE_URL = 'https://api.github.com' -FIREBASE_URL = '%s/repos/%s/%s' % (BASE_URL, OWNER, REPO) +GITHUB_API_URL = '%s/repos/%s/%s' % (BASE_URL, OWNER, REPO) logging.set_verbosity(logging.INFO) + +def set_repo_url(repo): + match = re.match(r'https://github\.com/([^/]+)/([^/.]+)', repo) + if not match: + logging.info('Error, only pattern https://github.com/\{repo_owner\}/\{repo_name\} are allowed.') + return False + + (repo_owner, repo_name) = match.groups() + global OWNER, REPO, GITHUB_API_URL + OWNER = repo_owner + REPO = repo_name + GITHUB_API_URL = '%s/repos/%s/%s' % (BASE_URL, OWNER, REPO) + return True + + def requests_retry_session(retries=RETRIES, backoff_factor=BACKOFF, status_forcelist=RETRY_STATUS): @@ -54,7 +70,7 @@ def requests_retry_session(retries=RETRIES, def create_issue(token, title, label, body): """Create an issue: https://docs.github.com/en/rest/reference/issues#create-an-issue""" - url = f'{FIREBASE_URL}/issues' + url = f'{GITHUB_API_URL}/issues' headers = {'Accept': 'application/vnd.github.v3+json', 'Authorization': f'token {token}'} data = {'title': title, 'labels': [label], 'body': body} with requests.post(url, headers=headers, data=json.dumps(data), timeout=TIMEOUT) as response: @@ -64,7 +80,7 @@ def create_issue(token, title, label, body): def get_issue_body(token, issue_number): """https://docs.github.com/en/rest/reference/issues#get-an-issue-comment""" - url = f'{FIREBASE_URL}/issues/{issue_number}' + url = f'{GITHUB_API_URL}/issues/{issue_number}' headers = {'Accept': 'application/vnd.github.v3+json', 'Authorization': f'token {token}'} with requests_retry_session().get(url, headers=headers, timeout=TIMEOUT) as response: logging.info("get_issue_body: %s response: %s", url, response) @@ -73,7 +89,7 @@ def get_issue_body(token, issue_number): def update_issue(token, issue_number, data): """Update an issue: https://docs.github.com/en/rest/reference/issues#update-an-issue""" - url = f'{FIREBASE_URL}/issues/{issue_number}' + url = f'{GITHUB_API_URL}/issues/{issue_number}' headers = {'Accept': 'application/vnd.github.v3+json', 'Authorization': f'token {token}'} with requests_retry_session().patch(url, headers=headers, data=json.dumps(data), timeout=TIMEOUT) as response: logging.info("update_issue: %s response: %s", url, response) @@ -102,7 +118,7 @@ def search_issues_by_label(label): def list_comments(token, issue_number): """https://docs.github.com/en/rest/reference/issues#list-issue-comments""" - url = f'{FIREBASE_URL}/issues/{issue_number}/comments' + url = f'{GITHUB_API_URL}/issues/{issue_number}/comments' headers = {'Accept': 'application/vnd.github.v3+json', 'Authorization': f'token {token}'} with requests_retry_session().get(url, headers=headers, timeout=TIMEOUT) as response: logging.info("list_comments: %s response: %s", url, response) @@ -111,7 +127,7 @@ def list_comments(token, issue_number): def add_comment(token, issue_number, comment): """https://docs.github.com/en/rest/reference/issues#create-an-issue-comment""" - url = f'{FIREBASE_URL}/issues/{issue_number}/comments' + url = f'{GITHUB_API_URL}/issues/{issue_number}/comments' headers = {'Accept': 'application/vnd.github.v3+json', 'Authorization': f'token {token}'} data = {'body': comment} with requests.post(url, headers=headers, data=json.dumps(data), timeout=TIMEOUT) as response: @@ -120,7 +136,7 @@ def add_comment(token, issue_number, comment): def update_comment(token, comment_id, comment): """https://docs.github.com/en/rest/reference/issues#update-an-issue-comment""" - url = f'{FIREBASE_URL}/issues/comments/{comment_id}' + url = f'{GITHUB_API_URL}/issues/comments/{comment_id}' headers = {'Accept': 'application/vnd.github.v3+json', 'Authorization': f'token {token}'} data = {'body': comment} with requests_retry_session().patch(url, headers=headers, data=json.dumps(data), timeout=TIMEOUT) as response: @@ -129,7 +145,7 @@ def update_comment(token, comment_id, comment): def delete_comment(token, comment_id): """https://docs.github.com/en/rest/reference/issues#delete-an-issue-comment""" - url = f'{FIREBASE_URL}/issues/comments/{comment_id}' + url = f'{GITHUB_API_URL}/issues/comments/{comment_id}' headers = {'Accept': 'application/vnd.github.v3+json', 'Authorization': f'token {token}'} with requests.delete(url, headers=headers, timeout=TIMEOUT) as response: logging.info("delete_comment: %s response: %s", url, response) @@ -137,7 +153,7 @@ def delete_comment(token, comment_id): def add_label(token, issue_number, label): """https://docs.github.com/en/rest/reference/issues#add-labels-to-an-issue""" - url = f'{FIREBASE_URL}/issues/{issue_number}/labels' + url = f'{GITHUB_API_URL}/issues/{issue_number}/labels' headers={} headers = {'Accept': 'application/vnd.github.v3+json', 'Authorization': f'token {token}'} data = [label] @@ -147,7 +163,7 @@ def add_label(token, issue_number, label): def delete_label(token, issue_number, label): """https://docs.github.com/en/rest/reference/issues#delete-a-label""" - url = f'{FIREBASE_URL}/issues/{issue_number}/labels/{label}' + url = f'{GITHUB_API_URL}/issues/{issue_number}/labels/{label}' headers = {'Accept': 'application/vnd.github.v3+json', 'Authorization': f'token {token}'} with requests.delete(url, headers=headers, timeout=TIMEOUT) as response: logging.info("delete_label: %s response: %s", url, response) @@ -155,7 +171,7 @@ def delete_label(token, issue_number, label): def list_artifacts(token, run_id): """https://docs.github.com/en/rest/reference/actions#list-workflow-run-artifacts""" - url = f'{FIREBASE_URL}/actions/runs/{run_id}/artifacts' + url = f'{GITHUB_API_URL}/actions/runs/{run_id}/artifacts' headers = {'Accept': 'application/vnd.github.v3+json', 'Authorization': f'token {token}'} with requests_retry_session().get(url, headers=headers, timeout=TIMEOUT) as response: logging.info("list_artifacts: %s response: %s", url, response) @@ -164,7 +180,7 @@ def list_artifacts(token, run_id): def download_artifact(token, artifact_id, output_path): """https://docs.github.com/en/rest/reference/actions#download-an-artifact""" - url = f'{FIREBASE_URL}/actions/artifacts/{artifact_id}/zip' + url = f'{GITHUB_API_URL}/actions/artifacts/{artifact_id}/zip' headers = {'Accept': 'application/vnd.github.v3+json', 'Authorization': f'token {token}'} with requests.get(url, headers=headers, stream=True, timeout=TIMEOUT) as response: logging.info("download_artifact: %s response: %s", url, response) @@ -174,7 +190,7 @@ def download_artifact(token, artifact_id, output_path): def dismiss_review(token, pull_number, review_id, message): """https://docs.github.com/en/rest/reference/pulls#dismiss-a-review-for-a-pull-request""" - url = f'{FIREBASE_URL}/pulls/{pull_number}/reviews/{review_id}/dismissals' + url = f'{GITHUB_API_URL}/pulls/{pull_number}/reviews/{review_id}/dismissals' headers = {'Accept': 'application/vnd.github.v3+json', 'Authorization': f'token {token}'} data = {'message': message} with requests_retry_session().put(url, headers=headers, data=json.dumps(data), @@ -182,9 +198,10 @@ def dismiss_review(token, pull_number, review_id, message): logging.info("dismiss_review: %s response: %s", url, response) return response.json() + def get_reviews(token, pull_number): """https://docs.github.com/en/rest/reference/pulls#list-reviews-for-a-pull-request""" - url = f'{FIREBASE_URL}/pulls/{pull_number}/reviews' + url = f'{GITHUB_API_URL}/pulls/{pull_number}/reviews' headers = {'Accept': 'application/vnd.github.v3+json', 'Authorization': f'token {token}'} page = 1 per_page = 100 @@ -203,19 +220,32 @@ def get_reviews(token, pull_number): return results -def workflow_dispatch(token, workflow_id, ref, inputs): +def create_workflow_dispatch(token, workflow_id, ref, inputs): """https://docs.github.com/en/rest/reference/actions#create-a-workflow-dispatch-event""" - url = f'{FIREBASE_URL}/actions/workflows/{workflow_id}/dispatches' + url = f'{GITHUB_API_URL}/actions/workflows/{workflow_id}/dispatches' headers = {'Accept': 'application/vnd.github.v3+json', 'Authorization': f'token {token}'} data = {'ref': ref, 'inputs': inputs} with requests.post(url, headers=headers, data=json.dumps(data), stream=True, timeout=TIMEOUT) as response: - logging.info("workflow_dispatch: %s response: %s", url, response) + logging.info("create_workflow_dispatch: %s response: %s", url, response) + # Response Status: 204 No Content + return True if response.status_code == 204 else False + + +def list_workflows(token, workflow_id, branch): + """https://docs.github.com/en/rest/reference/actions#list-workflow-runs-for-a-repository""" + url = f'{GITHUB_API_URL}/actions/workflows/{workflow_id}/runs' + headers = {'Accept': 'application/vnd.github.v3+json', 'Authorization': f'token {token}'} + data = {'event': 'workflow_dispatch', 'branch': branch} + with requests.get(url, headers=headers, data=json.dumps(data), + stream=True, timeout=TIMEOUT) as response: + logging.info("list_workflows: %s response: %s", url, response) + return response.json() def create_pull_request(token, head, base, title, body, maintainer_can_modify): """https://docs.github.com/en/rest/reference/pulls#create-a-pull-request""" - url = f'{FIREBASE_URL}/pulls' + url = f'{GITHUB_API_URL}/pulls' headers = {'Accept': 'application/vnd.github.v3+json', 'Authorization': f'token {token}'} data = {'head': head, 'base': base, 'title': title, 'body': body, 'maintainer_can_modify': maintainer_can_modify} @@ -224,9 +254,10 @@ def create_pull_request(token, head, base, title, body, maintainer_can_modify): logging.info("create_pull_request: %s response: %s", head, response) return True if response.status_code == 201 else False + def list_pull_requests(token, state, head, base): """https://docs.github.com/en/rest/reference/pulls#list-pull-requests""" - url = f'{FIREBASE_URL}/pulls' + url = f'{GITHUB_API_URL}/pulls' headers = {'Accept': 'application/vnd.github.v3+json', 'Authorization': f'token {token}'} page = 1 per_page = 100 diff --git a/scripts/gha/integration_testing/gameloop_android/build.gradle b/scripts/gha/integration_testing/gameloop_android/build.gradle index ed97082da3..fbb3465046 100644 --- a/scripts/gha/integration_testing/gameloop_android/build.gradle +++ b/scripts/gha/integration_testing/gameloop_android/build.gradle @@ -23,7 +23,7 @@ allprojects { ext { compileSdk = 28 - buildTools = '28.0.3' + buildTools = '29.0.2' minSdk = 16 targetSdk = 28 } diff --git a/scripts/gha/lint_commenter.py b/scripts/gha/lint_commenter.py index a08ef70964..d5560c98fc 100755 --- a/scripts/gha/lint_commenter.py +++ b/scripts/gha/lint_commenter.py @@ -41,6 +41,7 @@ 'build/include_subdir', 'readability/casting', 'whitespace/indent', + 'whitespace/line_length' ] # Exclude files within the following paths (specified as regexes) EXCLUDE_PATH_REGEX = [ diff --git a/scripts/gha/test_simulator.py b/scripts/gha/test_simulator.py index 274d8476d9..d0dfed9663 100644 --- a/scripts/gha/test_simulator.py +++ b/scripts/gha/test_simulator.py @@ -59,12 +59,12 @@ Device Information is stored in TEST_DEVICES in print_matrix_configuration.py Example: sdk id "system-images;android-29;google_apis;x86": - --android_sdk "system-images;android-29;google_apis;x86" --build_tools_version "28.0.3" + --android_sdk "system-images;android-29;google_apis;x86" --build_tools_version "29.0.2" Alternatively, to set an Android device, use the one of the values below: [emulator_min, emulator_target, emulator_latest] Example: - --android_device "emulator_target" --build_tools_version "28.0.3" + --android_device "emulator_target" --build_tools_version "29.0.2" Returns: 1: No iOS/Android integration_test apps found @@ -92,6 +92,14 @@ _GAMELOOP_PACKAGE = "com.google.firebase.gameloop" _RESULT_FILE = "Results1.json" _TEST_RETRY = 3 +_CMD_TIMEOUT = 300 + +_DEVICE_NONE = "None" +_DEVICE_ANDROID = "Android" +_DEVICE_APPLE = "Apple" + +_RESET_TYPE_REBOOT = 1 +_RESET_TYPE_WIPE_REBOOT = 2 FLAGS = flags.FLAGS @@ -129,7 +137,7 @@ "android_sdk", "system-images;android-29;google_apis;x86", "See module docstring for details on how to set and get this id.") flags.DEFINE_string( - "build_tools_version", "28.0.3", + "build_tools_version", "29.0.2", "android build_tools_version") flags.DEFINE_string( "logfile_name", "simulator-test", @@ -411,6 +419,20 @@ def _delete_simulator(device_id): subprocess.run(args=args, check=True) +def _reset_simulator_on_error(device_id, type=_RESET_TYPE_REBOOT): + _shutdown_simulator() + + if type == _RESET_TYPE_WIPE_REBOOT: + args = ["xcrun", "simctl", "erase", device_id] + logging.info("Erase my simulator: %s", " ".join(args)) + subprocess.run(args=args, check=True) + + # reboot simulator: _RESET_TYPE_WIPE_REBOOT, _RESET_TYPE_REBOOT + args = ["xcrun", "simctl", "boot", device_id] + logging.info("Reboot my simulator: %s", " ".join(args)) + subprocess.run(args=args, check=True) + + def _get_bundle_id(app_path, config): """Get app bundle id from build_testapps.json file.""" for api in config["apis"]: @@ -438,14 +460,14 @@ def _install_apple_app(app_path, device_id): """Install integration_test app into the simulator.""" args = ["xcrun", "simctl", "install", device_id, app_path] logging.info("Install testapp: %s", " ".join(args)) - subprocess.run(args=args, check=True) + _run_with_retry(args, device=device_id, type=_RESET_TYPE_WIPE_REBOOT) def _uninstall_apple_app(bundle_id, device_id): """Uninstall integration_test app from the simulator.""" args = ["xcrun", "simctl", "uninstall", device_id, bundle_id] logging.info("Uninstall testapp: %s", " ".join(args)) - subprocess.run(args=args, check=True) + _run_with_retry(args, device=device_id, type=_RESET_TYPE_REBOOT) def _get_apple_test_log(bundle_id, app_path, device_id): @@ -501,19 +523,19 @@ def _setup_android(platform_version, build_tool_version, sdk_id): "platforms;%s" % platform_version, "build-tools;%s" % build_tool_version] logging.info("Install packages: %s", " ".join(args)) - subprocess.run(args=args, check=True) + _run_with_retry(args) command = "yes | sdkmanager --licenses" logging.info("Accept all licenses: %s", command) - subprocess.run(command, shell=True, check=False) + _run_with_retry(command, shell=True, check=False) args = ["sdkmanager", sdk_id] logging.info("Download an emulator: %s", " ".join(args)) - subprocess.run(args=args, check=True) + _run_with_retry(args) args = ["sdkmanager", "--update"] logging.info("Update all installed packages: %s", " ".join(args)) - subprocess.run(args=args, check=True) + _run_with_retry(args, check=False) def _shutdown_emulator(): @@ -549,27 +571,32 @@ def _create_and_boot_emulator(sdk_id): logging.info("Wait for emulator to boot: %s", " ".join(args)) subprocess.run(args=args, check=True) if FLAGS.ci: - # wait extra 90 seconds to ensure emulator fully booted. - time.sleep(180) + # wait extra 210 seconds to ensure emulator fully booted. + time.sleep(210) else: time.sleep(45) -def _reset_emulator_on_error(instrumented_test_result): - logging.info("game-loop test result: %s", instrumented_test_result) - if "FAILURES!!!" in instrumented_test_result: - logging.info("game-loop test error!!! reboot emualtor...") - args = ["adb", "-e", "reboot"] - logging.info("Reboot android emulator: %s", " ".join(args)) +def _reset_emulator_on_error(type=_RESET_TYPE_REBOOT): + if type == _RESET_TYPE_WIPE_REBOOT: + # wipe emulator data + args = ["adb", "shell", "recovery", "--wipe_data"] + logging.info("Erase my Emulator: %s", " ".join(args)) subprocess.run(args=args, check=True) - args = ["adb", "wait-for-device"] - logging.info("Wait for emulator to boot: %s", " ".join(args)) - subprocess.run(args=args, check=True) - if FLAGS.ci: - # wait extra 90 seconds to ensure emulator booted. - time.sleep(90) - else: - time.sleep(45) + + # reboot emulator: _RESET_TYPE_WIPE_REBOOT, _RESET_TYPE_REBOOT + logging.info("game-loop test error!!! reboot emualtor...") + args = ["adb", "-e", "reboot"] + logging.info("Reboot android emulator: %s", " ".join(args)) + subprocess.run(args=args, check=True) + args = ["adb", "wait-for-device"] + logging.info("Wait for emulator to boot: %s", " ".join(args)) + subprocess.run(args=args, check=True) + if FLAGS.ci: + # wait extra 210 seconds to ensure emulator booted. + time.sleep(210) + else: + time.sleep(45) def _get_package_name(app_path): @@ -599,26 +626,29 @@ def _install_android_app(app_path): """Install integration_test app into the emulator.""" args = ["adb", "install", app_path] logging.info("Install testapp: %s", " ".join(args)) - subprocess.run(args=args, check=False) + _run_with_retry(args, device=_DEVICE_ANDROID, type=_RESET_TYPE_WIPE_REBOOT) def _uninstall_android_app(package_name): """Uninstall integration_test app from the emulator.""" args = ["adb", "uninstall", package_name] logging.info("Uninstall testapp: %s", " ".join(args)) - subprocess.run(args=args, check=False) + _run_with_retry(args, device=_DEVICE_ANDROID, type=_RESET_TYPE_REBOOT) def _install_android_gameloop_app(gameloop_project): os.chdir(gameloop_project) - logging.info("CD to gameloop_project: %s", gameloop_project) - _uninstall_android_app("com.google.firebase.gameloop") + logging.info("cd to gameloop_project: %s", gameloop_project) + args = ["adb", "uninstall", "com.google.firebase.gameloop"] + _run_with_retry(args, check=False, device=_DEVICE_ANDROID, type=_RESET_TYPE_REBOOT) + args = ["./gradlew", "clean"] logging.info("Clean game-loop cache: %s", " ".join(args)) - subprocess.run(args=args, check=False) + _run_with_retry(args, check=False, device=_DEVICE_ANDROID, type=_RESET_TYPE_REBOOT) + args = ["./gradlew", "installDebug", "installDebugAndroidTest"] logging.info("Installing game-loop app and test: %s", " ".join(args)) - subprocess.run(args=args, check=True) + _run_with_retry(args, device=_DEVICE_ANDROID, type=_RESET_TYPE_REBOOT) def _run_instrumented_test(): @@ -629,7 +659,8 @@ def _run_instrumented_test(): "-w", "%s.test/androidx.test.runner.AndroidJUnitRunner" % _GAMELOOP_PACKAGE] logging.info("Running game-loop test: %s", " ".join(args)) result = subprocess.run(args=args, capture_output=True, text=True, check=False) - _reset_emulator_on_error(result.stdout) + if "FAILURES!!!" in result.stdout: + _reset_emulator_on_error(_RESET_TYPE_REBOOT) def _get_android_test_log(test_package): @@ -643,6 +674,25 @@ def _get_android_test_log(test_package): return result.stdout +def _run_with_retry(args, shell=False, check=True, timeout=_CMD_TIMEOUT, retry_time=_TEST_RETRY, device=_DEVICE_NONE, type=_RESET_TYPE_REBOOT): + logging.info("run_with_retry: %s; remaining retry: %s", args, retry_time) + if retry_time > 1: + try: + subprocess.run(args, shell=shell, check=check, timeout=timeout) + except: + if device == _DEVICE_NONE: + pass + elif device == _DEVICE_ANDROID: + # Android + _reset_emulator_on_error(type) + else: + # Apple + _reset_simulator_on_error(device, type) + _run_with_retry(args, shell, check, timeout, retry_time-1, device, type) + else: + subprocess.run(args, shell=shell, check=check, timeout=timeout) + + if __name__ == '__main__': flags.mark_flag_as_required("testapp_dir") app.run(main) diff --git a/scripts/gha/trigger_workflow.py b/scripts/gha/trigger_workflow.py index f44312ced3..f1726f2339 100644 --- a/scripts/gha/trigger_workflow.py +++ b/scripts/gha/trigger_workflow.py @@ -29,70 +29,43 @@ """ import argparse -import json -import os -import re import subprocess import time import urllib.parse +import github def main(): args = parse_cmdline_args() - if args.repo is None: - args.repo=subprocess.check_output(['git', 'config', '--get', 'remote.origin.url']).decode('utf-8').rstrip('\n').lower() - print('autodetected repo: %s' % args.repo) if args.branch is None: - args.branch=subprocess.check_output(['git', 'rev-parse', '--abbrev-ref', 'HEAD']).decode('utf-8').rstrip('\n') - print('autodetected branch: %s' % args.branch) - if not args.repo.startswith('https://github.com/'): - print('Error, only https://github.com/ repositories are allowed.') + args.branch=subprocess.check_output(['git', 'rev-parse', '--abbrev-ref', 'HEAD']).decode('utf-8').rstrip('\n') + print('autodetected branch: %s' % args.branch) + if args.repo: # else use default firebase/firebase-cpp-sdk repo + if not github.set_repo_url(args.repo): exit(2) - (repo_owner, repo_name) = re.match(r'https://github\.com/([^/]+)/([^/.]+)', args.repo).groups() + else: + print('set repo url to: %s' % github.GITHUB_API_URL) - # POST /repos/{owner}/{repo}/actions/workflows/{workflow_id}/dispatches - request_url = 'https://api.github.com/repos/%s/%s/actions/workflows/%s/dispatches' % (repo_owner, repo_name, args.workflow) json_params = {} for param in args.param: - json_params[param[0]] = param[1] - json_text = '{"ref":%s,"inputs":%s}' % (json.dumps(args.branch), json.dumps(json_params)) + json_params[param[0]] = param[1] if args.verbose or args.dryrun: - print('request_url: %s' % request_url) - print('request_body: %s' % json_text) + print(f'request_url: {github.GITHUB_API_URL}/actions/workflows/{args.workflow}/dispatches') + print(f'request_body: ref: {args.branch}, inputs: {json_params}') if args.dryrun: return(0) print('Sending request to GitHub API...') - run_output = subprocess.check_output([args.curl, - '-s', '-o', '-', '-w', '\nHTTP status %{http_code}\n', - '-X', 'POST', - '-H', 'Accept: application/vnd.github.v3+json', - '-H', 'Authorization: token %s' % args.token, - request_url, '-d', json_text] - + ([] if not args.verbose else ['-v'])).decode('utf-8').rstrip('\n') - if args.verbose: - print(run_output) - if not re.search('HTTP status 2[0-9][0-9]$', run_output): - if not args.verbose: - print(run_output) - # Super quick and dirty way to get the message text since the appended status code means that - # the contents are not valid JSON. - error_message = re.search(r'"message": "([^"]+)"', run_output).group(1) - print('%sFailed to trigger workflow %s: %s' % ( - '::error ::' if args.in_github_action else '', args.workflow, error_message)) + if not github.create_workflow_dispatch(args.token, args.workflow, args.branch, json_params): + print('%sFailed to trigger workflow %s' % ( + '::error ::' if args.in_github_action else '', args.workflow)) return(-1) print('Success!') time.sleep(args.sleep) # Give a few seconds for the job to become queued. # Unfortunately, the GitHub REST API doesn't return the new workflow's run ID. # Query the list of workflows to find the one we just added. - request_url = 'https://api.github.com/repos/%s/%s/actions/workflows/%s/runs?event=workflow_dispatch&branch=%s' % (repo_owner, repo_name, args.workflow, args.branch) - run_output = subprocess.check_output([args.curl, - '-s', '-X', 'GET', - '-H', 'Accept: application/vnd.github.v3+json', - '-H', 'Authorization: token %s' % args.token, - request_url]).decode('utf-8').rstrip('\n') + workflows = github.list_workflows(args.token, args.workflow, args.branch) run_id = 0 - workflows = json.loads(run_output) if "workflow_runs" in workflows: branch_sha = subprocess.check_output(['git', 'rev-parse', args.branch]).decode('utf-8').rstrip('\n') for workflow in workflows['workflow_runs']: @@ -108,8 +81,8 @@ def main(): workflow_url = 'https://github.com/firebase/firebase-cpp-sdk/actions/runs/%s' % (run_id) else: # Couldn't get a run ID, use a generic URL. - workflow_url = 'https://github.com/%s/%s/actions/workflows/%s?query=%s+%s' % ( - repo_owner, repo_name, args.workflow, + workflow_url = '/%s/actions/workflows/%s?query=%s+%s' % ( + github.GITHUB_API_URL, args.workflow, urllib.parse.quote('event:workflow_dispatch', safe=''), urllib.parse.quote('branch:'+args.branch, safe='')) print('%sStarted workflow %s: %s' % ('::warning ::' if args.in_github_action else '', diff --git a/storage/src_java/com/google/firebase/storage/internal/cpp/CppByteUploader.java b/storage/src_java/com/google/firebase/storage/internal/cpp/CppByteUploader.java index 9a56331acc..977cfbcb9c 100644 --- a/storage/src_java/com/google/firebase/storage/internal/cpp/CppByteUploader.java +++ b/storage/src_java/com/google/firebase/storage/internal/cpp/CppByteUploader.java @@ -102,8 +102,7 @@ public int read(byte[] bytes, int bytesOffset, int numBytes) throws IOException int spaceAvailable = bytes.length - bytesOffset; if (numBytes < 0 || bytesOffset < 0 || numBytes > spaceAvailable) { throw new IndexOutOfBoundsException( - String.format( - "Attempt to read %d bytes into byte array with %d bytes in space available", + String.format("Attempt to read %d bytes into byte array with %d bytes in space available", numBytes, spaceAvailable)); } // Clamp the number of bytes to read by the data remaining in C++ buffer. @@ -153,11 +152,6 @@ public long skip(long bytesToSkip) throws IOException { *

This method should return the number of bytes copied into the Java byte array, -1 if at the * of the stream or < -1 if an error occurred or streaming was aborted. */ - private static native int readBytes( - long cppBufferPointer, - long cppBufferSize, - long cppBufferOffset, - byte[] bytes, - int bytesOffset, - int numBytesToRead); + private static native int readBytes(long cppBufferPointer, long cppBufferSize, + long cppBufferOffset, byte[] bytes, int bytesOffset, int numBytesToRead); }; diff --git a/testing/com/google/firebase/testing/cppsdk/FakeReporter.java b/testing/com/google/firebase/testing/cppsdk/FakeReporter.java index c0427eccc1..9a369daa02 100644 --- a/testing/com/google/firebase/testing/cppsdk/FakeReporter.java +++ b/testing/com/google/firebase/testing/cppsdk/FakeReporter.java @@ -21,7 +21,6 @@ /** Report what function was called and with wich arguments. */ public final class FakeReporter { - private static Map reports = new HashMap(); public static void reset() { @@ -64,7 +63,6 @@ public static String getFakeResult(String fake) { /** Report for each fake calling */ public static class ReportRow { - private String fake; private List args; diff --git a/testing/com/google/firebase/testing/cppsdk/TickerObserver.java b/testing/com/google/firebase/testing/cppsdk/TickerObserver.java index 70e29e9569..13819a626d 100644 --- a/testing/com/google/firebase/testing/cppsdk/TickerObserver.java +++ b/testing/com/google/firebase/testing/cppsdk/TickerObserver.java @@ -16,7 +16,6 @@ /** Observes the ticker and handle callbacks. */ public interface TickerObserver { - // After registered with TickerAndroid, this will be called per each ticker elapses. public void elapse(); } diff --git a/testing/config_ios.mm b/testing/config_ios.mm index d501e319b2..eddb8566bc 100644 --- a/testing/config_ios.mm +++ b/testing/config_ios.mm @@ -17,9 +17,9 @@ #include +#include "flatbuffers/idl.h" #include "testing/testdata_config_generated.h" #include "testing/testdata_config_resource.h" -#include "flatbuffers/idl.h" #import @@ -38,8 +38,7 @@ void ConfigSet(const char* test_data_in_json) { NSCAssert(parser.Parse(test_data_in_json), @"Invalid JSON:%s", parser.error_.c_str()); // Assign - internal::ConfigSetImpl(parser.builder_.GetBufferPointer(), - parser.builder_.GetSize()); + internal::ConfigSetImpl(parser.builder_.GetBufferPointer(), parser.builder_.GetSize()); } void ConfigReset() { internal::ConfigSetImpl(nullptr, 0); } @@ -60,8 +59,7 @@ void ConfigSet(const char* test_data_in_json) { } namespace internal { -void ConfigSetImpl(const uint8_t* test_data_binary, - flatbuffers::uoffset_t size) { +void ConfigSetImpl(const uint8_t* test_data_binary, flatbuffers::uoffset_t size) { delete[] g_test_data_config; if (test_data_binary != nullptr && size > 0) { g_test_data_config = new uint8_t[size]; diff --git a/testing/run_all_tests.mm b/testing/run_all_tests.mm index 78c7b9e068..069696806d 100644 --- a/testing/run_all_tests.mm +++ b/testing/run_all_tests.mm @@ -33,10 +33,8 @@ - (void)testAll { testing::UnitTest* unit_test = testing::UnitTest::GetInstance(); NSLog(@"Tests finished.\n passed tests: %d\n failed tests: %d\n" " disabled tests: %d\n total tests: %d", - unit_test->successful_test_count(), - unit_test->failed_test_count(), - unit_test->disabled_test_count(), - unit_test->total_test_count()); + unit_test->successful_test_count(), unit_test->failed_test_count(), + unit_test->disabled_test_count(), unit_test->total_test_count()); // Run test could succeed trivially if the test case is not linked. XCTAssertGreaterThan(unit_test->total_test_count(), 0); diff --git a/testing/sample_framework/src/android/java/com/google/firebase/example/LoggingUtils.java b/testing/sample_framework/src/android/java/com/google/firebase/example/LoggingUtils.java index 4ff20e8965..a8fabf28b1 100644 --- a/testing/sample_framework/src/android/java/com/google/firebase/example/LoggingUtils.java +++ b/testing/sample_framework/src/android/java/com/google/firebase/example/LoggingUtils.java @@ -71,37 +71,33 @@ public static void initLogWindow(Activity activity, boolean monospace) { window.setContentView(linearLayout); // Force the TextView to stay scrolled to the bottom. - textView.addTextChangedListener( - new TextWatcher() { - @Override - public void afterTextChanged(Editable e) { - // If the user never interacted with the screen, scroll to bottom. - if (scrollView != null && !didTouch) { - new Handler(Looper.getMainLooper()) - .post( - new Runnable() { - @Override - public void run() { - scrollView.fullScroll(View.FOCUS_DOWN); - } - }); + textView.addTextChangedListener(new TextWatcher() { + @Override + public void afterTextChanged(Editable e) { + // If the user never interacted with the screen, scroll to bottom. + if (scrollView != null && !didTouch) { + new Handler(Looper.getMainLooper()).post(new Runnable() { + @Override + public void run() { + scrollView.fullScroll(View.FOCUS_DOWN); } - } + }); + } + } - @Override - public void beforeTextChanged(CharSequence s, int start, int count, int after) {} + @Override + public void beforeTextChanged(CharSequence s, int start, int count, int after) {} - @Override - public void onTextChanged(CharSequence s, int start, int count, int after) {} - }); - textView.setOnTouchListener( - new View.OnTouchListener() { - @Override - public boolean onTouch(View v, MotionEvent event) { - didTouch = true; - return false; - } - }); + @Override + public void onTextChanged(CharSequence s, int start, int count, int after) {} + }); + textView.setOnTouchListener(new View.OnTouchListener() { + @Override + public boolean onTouch(View v, MotionEvent event) { + didTouch = true; + return false; + } + }); Intent launchIntent = activity.getIntent(); // Check if we are running on Firebase Test Lab, and set up a log file if we are. @@ -112,23 +108,21 @@ public boolean onTouch(View v, MotionEvent event) { /** Adds some text to the log window. */ public static void addLogText(final String text) { - new Handler(Looper.getMainLooper()) - .post( - new Runnable() { - @Override - public void run() { - if (textView != null) { - textView.append(text); - if (logFileStream != null) { - try { - logFileStream.writeBytes(text); - } catch (IOException e) { - // It doesn't really matter if something went wrong writing to the test log. - } - } - } - } - }); + new Handler(Looper.getMainLooper()).post(new Runnable() { + @Override + public void run() { + if (textView != null) { + textView.append(text); + if (logFileStream != null) { + try { + logFileStream.writeBytes(text); + } catch (IOException e) { + // It doesn't really matter if something went wrong writing to the test log. + } + } + } + } + }); } /** diff --git a/testing/sample_framework/src/android/java/com/google/firebase/example/TextEntryField.java b/testing/sample_framework/src/android/java/com/google/firebase/example/TextEntryField.java index 34c59fa55d..940b5e19ca 100644 --- a/testing/sample_framework/src/android/java/com/google/firebase/example/TextEntryField.java +++ b/testing/sample_framework/src/android/java/com/google/firebase/example/TextEntryField.java @@ -35,53 +35,47 @@ public static String readText( final Activity activity, final String title, final String message, final String placeholder) { resultText = null; // Show the alert dialog on the main thread. - activity.runOnUiThread( - new Runnable() { - @Override - public void run() { - AlertDialog.Builder alertBuilder = new AlertDialog.Builder(activity); - alertBuilder.setTitle(title); - alertBuilder.setMessage(message); + activity.runOnUiThread(new Runnable() { + @Override + public void run() { + AlertDialog.Builder alertBuilder = new AlertDialog.Builder(activity); + alertBuilder.setTitle(title); + alertBuilder.setMessage(message); - // Set up and add the text field. - final EditText textField = new EditText(activity); - textField.setHint(placeholder); - alertBuilder.setView(textField); + // Set up and add the text field. + final EditText textField = new EditText(activity); + textField.setHint(placeholder); + alertBuilder.setView(textField); - alertBuilder.setPositiveButton( - "OK", - new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int whichButton) { - synchronized (lock) { - resultText = textField.getText().toString(); - } - } - }); + alertBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int whichButton) { + synchronized (lock) { + resultText = textField.getText().toString(); + } + } + }); - alertBuilder.setNegativeButton( - "Cancel", - new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int whichButton) { - synchronized (lock) { - resultText = ""; - } - } - }); + alertBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int whichButton) { + synchronized (lock) { + resultText = ""; + } + } + }); - alertBuilder.setOnCancelListener( - new DialogInterface.OnCancelListener() { - @Override - public void onCancel(DialogInterface dialog) { - synchronized (lock) { - resultText = ""; - } - } - }); - alertBuilder.show(); + alertBuilder.setOnCancelListener(new DialogInterface.OnCancelListener() { + @Override + public void onCancel(DialogInterface dialog) { + synchronized (lock) { + resultText = ""; + } } }); + alertBuilder.show(); + } + }); // In our original thread, wait for the dialog to finish, then return its result. while (true) { diff --git a/testing/sample_framework/src/ios/ios_app_framework.mm b/testing/sample_framework/src/ios/ios_app_framework.mm old mode 100755 new mode 100644 index c692491fa8..b7a32a1bc3 --- a/testing/sample_framework/src/ios/ios_app_framework.mm +++ b/testing/sample_framework/src/ios/ios_app_framework.mm @@ -24,12 +24,12 @@ #include #include #include -#include #include +#include #include "app_framework.h" -@interface AppDelegate : UIResponder +@interface AppDelegate : UIResponder @property(nonatomic, strong) UIWindow *window; @@ -41,18 +41,14 @@ @interface FTAViewController : UIViewController @end -static NSString * const kGameLoopUrlPrefix= @"firebase-game-loop"; -static NSString * const kGameLoopCompleteUrlScheme= @"firebase-game-loop-complete://"; +static NSString *const kGameLoopUrlPrefix = @"firebase-game-loop"; +static NSString *const kGameLoopCompleteUrlScheme = @"firebase-game-loop-complete://"; static const float kGameLoopSecondsToPauseBeforeQuitting = 5.0f; // Test Loop on iOS doesn't provide the app under test a path to save logs to, so set it here. #define GAMELOOP_DEFAULT_LOG_FILE "Results1.json" -enum class RunningState { - kRunning, - kShuttingDown, - kShutDown -}; +enum class RunningState { kRunning, kShuttingDown, kShutDown }; // Note: g_running_state and g_exit_status must only be accessed while holding the lock from // g_running_state_condition; also, any changes to these values should be followed up with a @@ -103,7 +99,7 @@ - (void)viewDidLoad { namespace app_framework { bool ProcessEvents(int msec) { - NSDate* endDate = [NSDate dateWithTimeIntervalSinceNow:static_cast(msec) / 1000.0f]; + NSDate *endDate = [NSDate dateWithTimeIntervalSinceNow:static_cast(msec) / 1000.0f]; [g_running_state_condition lock]; if (g_running_state == RunningState::kRunning) { @@ -125,9 +121,7 @@ bool ProcessEvents(int msec) { [[documentsDirectory stringByStandardizingPath] stringByAppendingString:@"/"].UTF8String); } -WindowContext GetWindowContext() { - return g_parent_view; -} +WindowContext GetWindowContext() { return g_parent_view; } // Log a message that can be viewed in the console. void LogMessageV(bool suppress, const char *format, va_list list) { @@ -155,7 +149,7 @@ void LogMessage(const char *format, ...) { static bool g_save_full_log = false; static std::vector g_full_logs; // NOLINT -void AddToFullLog(const char* str) { g_full_logs.push_back(std::string(str)); } +void AddToFullLog(const char *str) { g_full_logs.push_back(std::string(str)); } bool GetPreserveFullLog() { return g_save_full_log; } void SetPreserveFullLog(bool b) { g_save_full_log = b; } @@ -191,7 +185,6 @@ void AddToTextView(const char *str) { [data writeToFile:g_file_url_path atomically:YES]; } } - } // Remove all lines starting with these strings. @@ -225,10 +218,10 @@ bool should_filter(const char *str) { return nullptr; } -void RunOnBackgroundThread(void* (*func)(void*), void* data) { +void RunOnBackgroundThread(void *(*func)(void *), void *data) { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ - func(data); - }); + func(data); + }); } // Create an alert dialog via UIAlertController, and prompt the user to enter a line of text. @@ -305,7 +298,7 @@ bool StartLoggingToFile(const char *file_path) { } // namespace app_framework -int main(int argc, char* argv[]) { +int main(int argc, char *argv[]) { // Pipe stdout to call LogToTextView so we can see the gtest output. int filedes[2]; assert(pipe(filedes) != -1); @@ -335,7 +328,7 @@ - (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary *)options { #if TARGET_OS_SIMULATOR - setenv("USE_FIRESTORE_EMULATOR","true",1); + setenv("USE_FIRESTORE_EMULATOR", "true", 1); #endif if ([url.scheme isEqual:kGameLoopUrlPrefix]) { @@ -348,8 +341,8 @@ - (BOOL)application:(UIApplication *)app return NO; } -- (BOOL)application:(UIApplication*)application - didFinishLaunchingWithOptions:(NSDictionary*)launchOptions { +- (BOOL)application:(UIApplication *)application + didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { g_running_state_condition = [[NSCondition alloc] init]; self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds]; @@ -362,7 +355,7 @@ - (BOOL)application:(UIApplication*)application g_text_view.accessibilityIdentifier = @"Logger"; #if TARGET_OS_IOS g_text_view.editable = NO; -#endif //TARGET_OS_IOS +#endif // TARGET_OS_IOS g_text_view.scrollEnabled = YES; g_text_view.userInteractionEnabled = YES; g_text_view.font = [UIFont fontWithName:@"Courier" size:10]; diff --git a/testing/util_ios.h b/testing/util_ios.h index 03c18c2af1..c20c06657f 100644 --- a/testing/util_ios.h +++ b/testing/util_ios.h @@ -20,8 +20,8 @@ #include #include -#include "testing/ticker_ios.h" #include "testing/config_ios.h" +#include "testing/ticker_ios.h" NS_ASSUME_NONNULL_BEGIN @@ -35,11 +35,9 @@ typedef void (^Callback)(NSError* _Nullable error); // A test helper class to make tickers which call back at certain ticks. class CallbackTicker : public firebase::testing::cppsdk::TickerObserver { public: - explicit CallbackTicker(NSString* config_key, ParamCallback completion, - id param, int error_code); + explicit CallbackTicker(NSString* config_key, ParamCallback completion, id param, int error_code); - explicit CallbackTicker(NSString* config_key, Callback completion, - int error_code); + explicit CallbackTicker(NSString* config_key, Callback completion, int error_code); void Elapse() override; diff --git a/testing/util_ios.mm b/testing/util_ios.mm index 5c529846f3..35b554bf90 100644 --- a/testing/util_ios.mm +++ b/testing/util_ios.mm @@ -85,7 +85,7 @@ [NSString stringWithUTF8String:row->futuregeneric()->exceptionmsg()->c_str()]; error_ = [NSError errorWithDomain:config_key code:error_code_ - userInfo:@{@"Error reason":errorMsg}]; + userInfo:@{@"Error reason" : errorMsg}]; return false; } else { return true; @@ -103,19 +103,16 @@ std::shared_ptr(new CallbackTicker(config_key, completion, error))); } - // Deprecated. void CallbackTickerManager::Add(NSString* config_key, ParamCallback completion, id param) { - tickers_.push_back( - std::shared_ptr(new CallbackTicker(config_key, completion, param, - DEPRECATED_DEFAULT_ERROR_VALUE))); + tickers_.push_back(std::shared_ptr( + new CallbackTicker(config_key, completion, param, DEPRECATED_DEFAULT_ERROR_VALUE))); } // Deprecated. void CallbackTickerManager::Add(NSString* config_key, Callback completion) { - tickers_.push_back( - std::shared_ptr(new CallbackTicker(config_key, completion, - DEPRECATED_DEFAULT_ERROR_VALUE))); + tickers_.push_back(std::shared_ptr( + new CallbackTicker(config_key, completion, DEPRECATED_DEFAULT_ERROR_VALUE))); } } // namespace cppsdk } // namespace testing diff --git a/testing/util_ios_test.mm b/testing/util_ios_test.mm index cc1197769b..b17b58b716 100644 --- a/testing/util_ios_test.mm +++ b/testing/util_ios_test.mm @@ -16,11 +16,11 @@ #include +#include "gmock/gmock.h" +#include "gtest/gtest.h" #include "testing/config.h" #include "testing/ticker.h" #include "testing/util_ios.h" -#include "gmock/gmock.h" -#include "gtest/gtest.h" namespace firebase { namespace testing { @@ -28,25 +28,38 @@ TEST(TickerTest, TestCallbackTicker) { TickerReset(); - ConfigSet( - "{" - " config:[" - " {fake:'a',futuregeneric:{throwexception:false,ticker:1}}," - " {fake:'b',futuregeneric:{throwexception:true,exceptionmsg:'failed',ticker:2}}," - " {fake:'c',futuregeneric:{throwexception:false,ticker:3}}," - " {fake:'d',futuregeneric:{throwexception:true,exceptionmsg:'failed',ticker:4}}" - " ]" - "}"); + ConfigSet("{" + " config:[" + " {fake:'a',futuregeneric:{throwexception:false,ticker:1}}," + " {fake:'b',futuregeneric:{throwexception:true,exceptionmsg:'failed',ticker:2}}," + " {fake:'c',futuregeneric:{throwexception:false,ticker:3}}," + " {fake:'d',futuregeneric:{throwexception:true,exceptionmsg:'failed',ticker:4}}" + " ]" + "}"); __block int count = 0; // Now we create four fake objects on the fly; all are managed by manager. CallbackTickerManager manager; // Without param. - manager.Add(@"a", ^(NSError* _Nullable error) { if (!error) count++; }); - manager.Add(@"b", ^(NSError* _Nullable error) { if (!error) count++; }); + manager.Add(@"a", ^(NSError* _Nullable error) { + if (!error) count++; + }); + manager.Add(@"b", ^(NSError* _Nullable error) { + if (!error) count++; + }); // With param. - manager.Add(@"c", ^(NSString* param, NSError* _Nullable error) { if (!error) count++; }, @"par"); - manager.Add(@"d", ^(NSString* param, NSError* _Nullable error) { if (!error) count++; }, @"par"); + manager.Add( + @"c", + ^(NSString* param, NSError* _Nullable error) { + if (!error) count++; + }, + @"par"); + manager.Add( + @"d", + ^(NSString* param, NSError* _Nullable error) { + if (!error) count++; + }, + @"par"); // nothing happens so far. EXPECT_EQ(0, count);