Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

crashlytics :Please verify the AAR which contains the com/google/firebase/crashlytics/internal/common/DataCollectionArbiter class is included in your app #758

Closed
Zhangyu754178 opened this issue Aug 19, 2020 · 31 comments
Assignees
Labels
api: core edm4u Issue related to External Dependency Manager for Unity type: bug type: process
Milestone

Comments

@Zhangyu754178
Copy link

Please fill in the following fields:

Unity editor version:
Firebase Unity SDK version: 6.15.2
Source you installed the SDK (.unitypackage or Unity Package Manager):FirebaseCrashlytics.unitypackage
Firebase plugins in use (Auth, Database, etc.):Catch Crash
Additional SDKs you are using (Facebook, AdMob, etc.):
Platform you are using the Unity editor on (Mac, Windows, or Linux): Mac
Platform you are targeting (iOS, Android, and/or desktop): Android
Scripting Runtime (Mono, and/or IL2CPP):IL2CPP

Please describe the issue here:

2020-08-19 14:27:25.588 25005-25377/onnect.connect.pair.matching.line.puzzle.match3d.tilemaster W/System.err: java.lang.NoSuchMethodError: no non-static method "Lcom/google/firebase/crashlytics/internal/common/DataCollectionArbiter;.setCrashlyticsDataCollectionEnabled(Z)V"
2020-08-19 14:27:25.588 25005-25377/onnect.connect.pair.matching.line.puzzle.match3d.tilemaster E/firebase: method_ids[i] || (method.optional == kMethodOptional)
2020-08-19 14:27:25.589 25005-25377/onnect.connect.pair.matching.line.puzzle.match3d.tilemaster E/firebase: Unable to find Method com/google/firebase/crashlytics/internal/common/DataCollectionArbiter.setCrashlyticsDataCollectionEnabled (signature '(Z)V', instance). Please verify the AAR which contains the com/google/firebase/crashlytics/internal/common/DataCollectionArbiter class is included in your app.

Please answer the following, if applicable:

Have you been able to reproduce this issue with just the Firebase Unity quickstarts (this GitHub project)?
Yes
What's the issue repro rate? (eg 100%, 1/5 etc)

@Zhangyu754178 Zhangyu754178 added the new New issue. label Aug 19, 2020
@napbla
Copy link

napbla commented Aug 20, 2020

I were also having this problem.
It is caused by the latest version of 'com.google.firebase.firebase-crashlytics-17.2.1' where they change the method name while the Unity wrapper 'com.google.firebase.firebase-crashlytics-unity-6.15.2' is not updated yet. Ref: (https://firebase.google.com/support/release-notes/android#crashlytics_v17-2-1)

Android resolver somehow automatically change the version in CrashlyticsDependencies.xml to the latest version which is troublesome. (I have check all *Dependencies.xml files and not a single file use .+ )

If you export to Android project, you can temporarily solve this by changing 'com.google.firebase.firebase-crashlytics-17.2.1' to 'com.google.firebase.firebase-crashlytics-17.1.1' in your Android project manifest and manually download version 17.1.1 aar from Maven: (https://mvnrepository.com/artifact/com.google.firebase/firebase-crashlytics/17.1.1)
Then put it in the Android project's "libs" folder.

If you export to apk or aab, go to Assets/Plugins/Android to find and replace the aar. Do not run Android Resolver again. You may have to change these file to the correct version too: ProjectSettings/AndroidResolverDependencies.xml and CrashlyticsDependencies.xml

UPDATE: You can simply solve this by downloading the old version and RENAME it to 17.2.1 then copy into Assets\Plugins\Android folder overwrite the real one.

@ronrejwan
Copy link

Can confirm this is happening for us as well.
Thanks @napbla; you saved me hours.

@cynthiajoan
Copy link
Contributor

Hi all, first thanks @napbla pointing out a manual modification to get unblocked.

I tried to repro the issue locally, and find out unity sdk 6.15.2 is pointing to com.google.firebase.firebase-crashlytics-17.0.0 in the CrashlyticsDependency.xml, and android resolver should only read from that info instead of modify that file. We'd like to understand if there's other 3rd party libraries used, and if can provide some environment for us to repro the issue, that will be really appreciated.

@cynthiajoan cynthiajoan added needs-info Need information for the developer type: question and removed new New issue. labels Aug 20, 2020
@mgrogin
Copy link

mgrogin commented Aug 23, 2020

Hi all, first thanks @napbla pointing out a manual modification to get unblocked.

I tried to repro the issue locally, and find out unity sdk 6.15.2 is pointing to com.google.firebase.firebase-crashlytics-17.0.0 in the CrashlyticsDependency.xml, and android resolver should only read from that info instead of modify that file. We'd like to understand if there's other 3rd party libraries used, and if can provide some environment for us to repro the issue, that will be really appreciated.

@cynthiajoan For me it looks like the ironsource admob adapter changes the version when resolving Android dependencies:
Task :process_com.ironsource.adapters.admobadapter-4.3.12.aarWARNING: Some conflicting dependencies were found. The following dependency versions were modified: ... ... com.google.firebase:firebase-analytics:17.4.1 --> com.google.firebase:firebase-analytics:+ com.google.firebase:firebase-auth:19.3.1 --> com.google.firebase:firebase-auth:+ com.google.firebase:firebase-common:19.3.0 --> com.google.firebase:firebase-common:+ com.google.firebase:firebase-config:19.1.4 --> com.google.firebase:firebase-config:+ com.google.firebase:firebase-crashlytics:17.0.0 --> com.google.firebase:firebase-crashlytics:+ com.google.firebase:firebase-database:19.3.0 --> com.google.firebase:firebase-database:+ com.google.firebase:firebase-messaging:20.1.7 --> com.google.firebase:firebase-messaging:+

It's probably related to the ISAdMobAdapterDependency: com.google.android.gms:play-services-ads:19.3.0

@pigerj
Copy link

pigerj commented Aug 24, 2020

@cynthiajoan for me this case happens when using firebase analytics,remote config,crashlytics + Facebook Audience Network https://developers.facebook.com/docs/audience-network/guides/adding-sdk/unity/

@napbla
Copy link

napbla commented Aug 24, 2020

Hi all, first thanks @napbla pointing out a manual modification to get unblocked.

I tried to repro the issue locally, and find out unity sdk 6.15.2 is pointing to com.google.firebase.firebase-crashlytics-17.0.0 in the CrashlyticsDependency.xml, and android resolver should only read from that info instead of modify that file. We'd like to understand if there's other 3rd party libraries used, and if can provide some environment for us to repro the issue, that will be really appreciated.

Android resolver try to resolve using 17.0.0 if it does not work it will try 17.0.+ and so on 17.+
That's why it ends up in 17.2.1.
Sorry I did not have time to investigate the long verbose log to see which one did cause the problem.

Here are the lists of all 3rd party plugins that our project uses:

  • Firebase Analytics 6.15.2
  • Firebase Auth 6.15.2
  • Firebase Crashlytics 6.15.2
  • Firebase InstanceId 6.15.2
  • Firebase Remote Config 6.15.2
  • Google Admob Mediation Plugins For Vungle
  • Google Admob Mediation Plugins For Unity Ads
  • Google Admob Mediation Plugins For AppLovin
  • Google Admob Mediation Plugins For Facebook Ads

If you need more information just ask me. Thank you for your help.

@google-oss-bot
Copy link

Hey @Zhangyu754178. We need more information to resolve this issue but there hasn't been an update in 5 weekdays. I'm marking the issue as stale and if there are no new updates in the next 5 days I will close it automatically.

If you have more information that will help us get to the bottom of this, just add a comment!

@mgrogin
Copy link

mgrogin commented Aug 31, 2020

Hey @Zhangyu754178. We need more information to resolve this issue but there hasn't been an update in 5 weekdays. I'm marking the issue as stale and if there are no new updates in the next 5 days I will close it automatically.

If you have more information that will help us get to the bottom of this, just add a comment!

What other information do you need?
Please see my comment where I write what causes the problem for me #758 (comment)

@google-oss-bot google-oss-bot removed the stale Don't have recent activity label Aug 31, 2020
@lfg-ryan
Copy link

lfg-ryan commented Sep 3, 2020

I also have this issue. Using similar setup to @napbla

Firebase Analytics 6.15.2
Firebase Auth 6.15.2
Firebase Crashlytics 6.15.2
Firebase InstanceId 6.15.2
Firebase Remote Config 6.15.2
Google Admob Mediation Plugins For Vungle
Google Admob Mediation Plugins For Unity Ads
Google Admob Mediation Plugins For AppLovin
Google Admob Mediation Plugins For Facebook Ads

I am also using Unity Cloud build.

I have the 17.1.1 arr file in Plugins/Android. I don't see anything that mentions 17.2.1 but I do see things looking for 17.0.0. My final build is somehow getting 17.2.1 and issue occurs.

Can we get an ETA of when Unity Packages will just support 17.2.1 and this problem will just go away?

@lfg-ryan
Copy link

lfg-ryan commented Sep 3, 2020

More detail in case it helps.

ApplicationException: Unable to find Method com/google/firebase/crashlytics/internal/common/DataCollectionArbiter.setCrashlyticsDataCollectionEnabled (signature '(Z)V', instance).  Please verify the AAR which contains the com/google/firebase/crashlytics/internal/common/DataCollectionArbiter class is included in your app.	
 at Firebase.Crashlytics.FirebaseCrashlyticsInternal.GetInstance (Firebase.FirebaseApp app, Firebase.InitResult& init_result_out) [0x00000] in <00000000000000000000000000000000>:0 	
 at Firebase.Crashlytics.AndroidImpl..ctor () [0x00000] in <00000000000000000000000000000000>:0 	
 at Firebase.Crashlytics.Impl.Make () [0x00000] in <00000000000000000000000000000000>:0 	
 at Firebase.Crashlytics.Crashlytics+PlatformAccessor..cctor () [0x00000] in <00000000000000000000000000000000>:0 	
 at Firebase.Crashlytics.Crashlytics.Initialize () [0x00000] in <00000000000000000000000000000000>:0 	
 at System.Reflection.MonoMethod.Invoke (System.Object obj, System.Reflection.BindingFlags invokeAttr, System.	

@chkuang-g chkuang-g added type: bug and removed needs-info Need information for the developer type: question labels Sep 3, 2020
@chkuang-g chkuang-g added this to the 6.16.0 milestone Sep 3, 2020
@chkuang-g
Copy link
Contributor

chkuang-g commented Sep 3, 2020

Hey folks,

As discussed in this thread, this is happening when Firebase Unity SDK depends on older version of gms package and some other Unity SDK depends on later version, ex. IronSource.

We are rolling up our Android dependency for the next release, which may alleviate this issue. However, Android dependency is a tough problem to crack while you have multiple Unity plugins relying on different version of Android libraries, directly or indirectly. EDM4U can only inform you when this happens and try it best to resolve it, but cannot magically make all conflicts go away. Some library like Crashlytics and Firestore are pretty sensitive when Android library version is changed.

I think the general way to resolve this is to balance the versions of Unity plugins in your project. In this case, perhaps downgrading some plugin may resolve the issue.

You should be able to have a quick glance about first level of Android dependency using menu item Assets > External Dependency Manager > Android Resolver > Display Library.

Currently EDM4U does not have the ability to show the full dependency graph and point out which Unity plugins are having conflict. However, this can be added to EDM4U in the future. Community contribution is welcome!

@lfg-ryan
Copy link

lfg-ryan commented Sep 3, 2020

Glad to hear your working on it. It's unfortunate that in this case, the dependencies are Google Firebase and Google Admob Mediation plugins. I would love to downgrade if you have a way to figure out what it is but all of Google's documentation says to keep things on the same versions.

Can anyone provide better detail on @napbla's workaround? We cannot ship our live service game on android right now because of this.

@chkuang-g
Copy link
Contributor

@lfg-ryan You should keep all Firebase plugin in the same version, correct.
However, I do not know how Admob Mediation plugin handle versions. Is it possible for you to install older version of Google Admob Mediation Plugins?

@lfg-ryan
Copy link

lfg-ryan commented Sep 4, 2020

I will try that however those plugins seem to be looking for 17.0.0 and as @napbla mentioned this resolves up to 17.2.1 instead of 17.1.1 which is compatible with the Unity firebase crashalytics package so it seems highly unlikely that asking for < 17.0.0 is going to yield a different result.

It would be super helpful to have a more detailed work around while we wait for the Unity package to update to the new API. I have been unable to get the workarounds to yield any different result. The built APK still has 17.2.1 despite not seeing any reference in any of the dependency xml's etc.

I am a novice when it comes to Android dependency management so I would greatly appreciate something more spelled out.

@chkuang-g chkuang-g added api: core edm4u Issue related to External Dependency Manager for Unity labels Sep 4, 2020
@napbla
Copy link

napbla commented Sep 4, 2020

I will try that however those plugins seem to be looking for 17.0.0 and as @napbla mentioned this resolves up to 17.2.1 instead of 17.1.1 which is compatible with the Unity firebase crashalytics package so it seems highly unlikely that asking for < 17.0.0 is going to yield a different result.

It would be super helpful to have a more detailed work around while we wait for the Unity package to update to the new API. I have been unable to get the workarounds to yield any different result. The built APK still has 17.2.1 despite not seeing any reference in any of the dependency xml's etc.

I am a novice when it comes to Android dependency management so I would greatly appreciate something more spelled out.

You can simply solve this by downloading the old version 17.1.1 and RENAME it to 17.2.1 then copy into Assets\Plugins\Android folder overwrite the real one.

@lfg-ryan
Copy link

lfg-ryan commented Sep 4, 2020

Still trying to get this to work. When I make a build it gets replaced again with a real 17.2.1. Seems like android dependency resolution is happening again as part of the build process. Not sure how to turn that off.

@lfg-ryan
Copy link

lfg-ryan commented Sep 5, 2020

Ok I finally got this. Here are some more detailed steps in case your as new to this dependency stuff as I am. @napbla had it there just is a few gotcha's along the way.

  1. Do a Force Resolve
      • Assets -> External Dependency Manager -> Android -> Force Resolve
  2. Disable pull on build
    • Assets -> External Dependency Manager -> Android -> Settings
    • Uncheck Enable Resolution on Build, scroll down and click "ok" to save the setting
  3. Download the Crashlytics 17.1.1 library (https://maven.google.com/com/google/firebase/firebase-crashlytics/17.1.1/firebase-crashlytics-17.1.1.aar)
  4. Delete the 17.2.1 library in Assets/Plugins/Android and rename the 17.1.1 library to the same name (should look something like com.google.firebase.firebase-crashlytics-17.2.1.aar)
  5. Done! Builds should work now. Remember to not do a Resolve or Force Resolve or you will need to repeat these steps.

Thank you @napbla and @chkuang-g, the "Enable Resolution on Build" was the thing tripping me up.

@chkuang-g
Copy link
Contributor

chkuang-g commented Sep 9, 2020

@lfg-ryan

Thank you for offering the workaround.
For more complicated cases like this, disabling Android Resolver (both auth resolution and resolution on build) might be a better solution.
However, you may run into risk that some Unity plugin might be expecting new functions from firebase-crashlytics-17.2.1.aar.

In short, as long as you can thoroughly test your app, this kind of workaround can works.

@napbla
Copy link

napbla commented Sep 11, 2020

@lfg-ryan

Thank you for offering the workaround.
For more complicated cases like this, disabling Android Resolver (both auth resolution and resolution on build) might be a better solution.
However, you may run into risk that some Unity plugin might be expecting new functions from firebase-crashlytics-17.2.1.aar.

In short, as long as you can thoroughly test your app, this kind of workaround can works.

@lfg-ryan
It's true that "some Unity plugin might be expecting new functions" but you can look at the XXXDependencies.xml file to see what version it does need. In this case is 17.0.0 so correctly we should change it back to 17.0.0.
However last time when it worked, it uses 17.1.1 so I assumed that 17.1.1 will work fine.

@Otarius0
Copy link

In my project with the same problem, I fixed the plugin version using square brackets.
<androidPackage spec = "com.google.firebase: firebase-crashlytics: [17.0.0]">
Now the resolver does not upgrade the version

@Mishgan
Copy link

Mishgan commented Oct 9, 2020

I can confirm that the same issue is actual for Firebase Unity SDK v6.16.0 and External Dependency Resolver (v 1.2.160).
The project has com.google.firebase.firebase-crashlytics-17.2.2.aar and com.google.firebase.firebase-crashlytics-unity-6.16.0.aar files.

W/System.err: java.lang.NoSuchMethodError: no non-static method "Lcom/google/firebase/crashlytics/internal/common/DataCollectionArbiter;.setCrashlyticsDataCollectionEnabled(Z)V"
W/System.err:     at com.unity3d.player.UnityPlayer.nativeRender(Native Method)
W/System.err:     at com.unity3d.player.UnityPlayer.c(Unknown Source:0)
W/System.err:     at com.unity3d.player.UnityPlayer$e$1.handleMessage(Unknown Source:95)
W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:102)
W/System.err:     at android.os.Looper.loop(Looper.java:193)
W/System.err:     at com.unity3d.player.UnityPlayer$e.run(Unknown Source:20)
E/firebase: method_ids[i] || (method.optional == kMethodOptional)
E/firebase: Unable to find Method com/google/firebase/crashlytics/internal/common/DataCollectionArbiter.setCrashlyticsDataCollectionEnabled (signature '(Z)V', instance).  Please verify the AAR which contains the com/google/firebase/crashlytics/internal/common/DataCollectionArbiter class is included in your app.


ApplicationException: Unable to find Method com/google/firebase/crashlytics/internal/common/DataCollectionArbiter.setCrashlyticsDataCollectionEnabled (signature '(Z)V', instance).  Please verify the AAR which contains the com/google/firebase/crashlytics/internal/common/DataCollectionArbiter class is included in your app.
      at Firebase.Crashlytics.FirebaseCrashlyticsInternal.GetInstance (Firebase.FirebaseApp app, Firebase.InitResult& init_result_out) [0x00000] in <00000000000000000000000000000000>:0 
      at Firebase.Crashlytics.AndroidImpl..ctor () [0x00000] in <00000000000000000000000000000000>:0 
      at Firebase.Crashlytics.Impl.Make () [0x00000] in <00000000000000000000000000000000>:0 
      at Firebase.Crashlytics.Crashlytics+PlatformAccessor..cctor () [0x00000] in <00000000000000000000000000000000>:0 
      at Firebase.Crashlytics.Crashlytics.Initialize () [0x00000] in <00000000000000000000000000000000>:0 
      at System.Reflection.MonoMethod.Invoke (System.Object obj, System.Reflection.BindingFlags invokeAttr, System.

@battlearchers
Copy link

Firebase Unity SDK v6.16.0 and External Dependency Resolver (v 1.2.160) have the same issue...

@chkuang-g
Copy link
Contributor

chkuang-g commented Oct 14, 2020

@Mishgan @battlearchers

The reason for that error is because:
Android SDK updated the function signature from bool to Boolean from 17.2.1
firebase/firebase-android-sdk@ed4d371
But the C++ reflection code does not update it, hence unable to find the Java function.

I have made the changes internally, both bumping up the Crashlytics version to 17.2.2 and update the reflection code.
Unfortunately it is safe to say that Firebase Crashlytics Unity SDK 6.16.0 only work with Crashlytics Android SDK up to 17.1.1

See if you can lock their version to 17.0.0 or 17.1.1 as @Otarius0 suggested in #758 (comment). (You need to change Assets/Firebase/Editor/CrashlyticsDependencies.xml)

@vimanyu
Copy link
Contributor

vimanyu commented Oct 21, 2020

We just rolled out 6.16.1 and this issue should be fixed. Please let us know if you are still running into this.

@chkuang-g
Copy link
Contributor

Hey folks,

Unity SDK 6.16.1 can properly support Crashlytics Android SDK 17.2.2 now.

Dependency unfortunately is a pretty complicated issue. We are thinking about improving EDM4U to produce better debug information when dependency resolution conflict happens in the future.

I'll close this issue for now. If you still experience issue, please open a new ticket and refer to this one.

Shawn

@mgrogin
Copy link

mgrogin commented Oct 22, 2020

@chkuang-g To get this to work I had to uncheck "patch gradleTemplate.properties" in android resolver settings <projectSetting name="GooglePlayServices.PatchPropertiesTemplateGradle" value="False" />
'Custom Gradle Properties Template' found under Player Settings is disabled (wasnt working when I enabled it as suggested by android resolver)

Seems strange that in the logs it's Initializing two versions Crashlytics 17.1.1 and 17.2.1

10-22 08:28:09.483 25062-25062/? I/FirebaseCrashlytics: Initializing Crashlytics 17.1.1 10-22 08:28:21.563 25560-25560/? I/CrashlyticsInitProvider: CrashlyticsInitProvider skipping initialization 10-22 08:28:23.143 25560-25560/? I/CrashlyticsCore: Initializing Crashlytics Core 2.7.0.33 10-22 08:28:26.933 25696-25696/? I/FirebaseCrashlytics: Initializing Crashlytics 17.1.1 10-22 08:28:28.553 25763-25763/? I/FirebaseCrashlytics: Initializing Crashlytics 17.1.1 10-22 08:28:50.783 26061-26061/? I/FirebaseCrashlytics: Initializing Crashlytics 17.2.1 10-22 08:28:50.893 26061-26102/? D/libcrashlytics: Initializing libcrashlytics version 2.0.5 10-22 08:28:50.893 26061-26102/? D/libcrashlytics: Initializing native crash handling successful. 10-22 08:28:50.893 26061-26102/? I/FirebaseCrashlytics: Crashlytics NDK initialization successful

@chkuang-g
Copy link
Contributor

@mgrogin

For the Android Resolver issue, you probably got caught by this issue googlesamples/unity-jar-resolver@88403b0. This should be fixed and included in the later version of FEDM4U and Firebase SDK. Otherwise, you don't really need to disable anything (And it will be helpful when you started to use mainTemplate.gradle)

For the log you saw, that looks...fine to me. Are you concerned about that CrashlyticsInitProvider skipping initialization part? Were you able to see the crash log from Firebase console? If so, you are good.
Also, make sure you are using Firebase Unity 16.1.1, which is compatible to Crashlytics 17.2.1.

@mgrogin
Copy link

mgrogin commented Oct 28, 2020

@chkuang-g I think the same thing is happening to me now with remote config arr files. I wrote about it here: #846

@cszhongit
Copy link

cszhongit commented Nov 1, 2020

@mgrogin I meet the same question,it is happening to remoteConfig.aar in firebase6.16.1.How do you to resolve it?

@mgrogin
Copy link

mgrogin commented Nov 1, 2020

@mgrogin I meet the same question,it is happening to remoteConfig.aar in firebase6.16.1.How do you to resolve it?

Add square brackets to androidPackage dependency in PackageCache (file location: /Users/<userName>/projects/<projectName>/Library/PackageCache/com.google.firebase.remote-config@6.16.1/Firebase/Editor/RemoteConfigDependencies.xml)
So it looks like this
<androidPackage spec="com.google.firebase:firebase-config:[19.2.0]">

full file:

<!-- Copyright (C) 2018 Google Inc. All Rights Reserved.

FirebaseRemoteConfig iOS and Android Dependencies.
-->

<dependencies>
  <iosPods>
    <iosPod name="Firebase/RemoteConfig" version="6.32.2" minTargetSdk="8.0">
    </iosPod>
  </iosPods>
  <androidPackages>
    <androidPackage spec="com.google.firebase:firebase-config:[19.2.0]">
    </androidPackage>
    <androidPackage spec="com.google.firebase:firebase-analytics:17.5.0">
    </androidPackage>
    <androidPackage spec="com.google.firebase:firebase-config-unity:6.16.1">
      <repositories>
        <repository>Assets/Firebase/m2repository</repository>
      </repositories>
    </androidPackage>
  </androidPackages>
</dependencies>

@mgrogin
Copy link

mgrogin commented Nov 1, 2020

Putting this file in a folder called Editor should solve the problem for now.
Feel free to share improvements to the code and make it more generic:

#if UNITY_ANDROID

using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Linq;

using UnityEditor;
using UnityEditor.Build;
#if UNITY_2018_1_OR_NEWER
using UnityEditor.Build.Reporting;
#endif
using UnityEngine;

using System;
using UnityEditor.PackageManager;
//using System.Threading.Tasks;

#if UNITY_2018_1_OR_NEWER
public class PackageCacheDependencyProcessor : IPreprocessBuildWithReport
#else
public class PackageCacheDependencyProcessor : IPreprocessBuild
#endif
{

    private const string FIREBASE_UNITY_VERSION = "6.16.1";

    public int callbackOrder { get { return 0; } }

#if UNITY_2018_1_OR_NEWER
    public void OnPreprocessBuild(BuildReport report)
#else
    public void OnPreprocessBuild(BuildTarget target, string path)
#endif
    {
        string packageCacheFolder = Path.GetFullPath(Path.Combine(Application.dataPath, "../Library/PackageCache"));

        Dictionary<string, string> androidPackageToWantedVersion = new Dictionary<string, string>();
        Dictionary<string, string> androidPackageToDeppendencyFileName = new Dictionary<string, string>();
        Dictionary<string, string> androidPackageNameIdToDeppendencySpecPrefix = new Dictionary<string, string>();

        string packageNameID = "com.google.firebase.remote-config";
        string deppendencySpecPrefix = "com.google.firebase:firebase-config";
        androidPackageNameIdToDeppendencySpecPrefix[packageNameID] = deppendencySpecPrefix;
        androidPackageToWantedVersion[packageNameID] = "19.2.0";
        androidPackageToDeppendencyFileName[packageNameID] = "remoteConfigDependencies.xml";


        foreach (var packageNameIDKey in androidPackageToWantedVersion.Keys)
        {            
            var package = UnityEditor.PackageManager.Client.Search(packageNameID, true);
            //if (package == null || package.Result == null || package.Result.Count() == 0)
            //{
            //    StopBuildWithMessage(packageNameID + " package is missing. check installed packages or that name matches package.");
            //}
            for (var i = 0; i < 100; ++i)
            {

                if (package.Status != StatusCode.InProgress) break;

                System.Threading.Thread.Sleep(100);

            }
            if (package.Status != StatusCode.Success)
            {
                StopBuildWithMessage(packageNameID + " package is missing. check installed packages or that name matches package. " + $"{package.Status}/{package.Error?.message}");
            }
            if (package.Result.Count() == 0)
            {
                StopBuildWithMessage(packageNameID + " package is missing. check installed packages or that name matches package.");
            }

            var result = package.Result.First();
            if (result.version != FIREBASE_UNITY_VERSION)
            {
                StopBuildWithMessage(packageNameIDKey + " used version " + result.version + " doesnt match version defined in PackageCacheDependencyProcessor " + FIREBASE_UNITY_VERSION + " - adjust dictionary in code.");

            }
            //result.resolvedPath
            string firebaseFolder = result.resolvedPath; // string.Format("{0}@{1}", packageNameIDKey, FIREBASE_UNITY_VERSION); // "com.google.firebase.remote-config@6.16.1";            
            if (!androidPackageToDeppendencyFileName.ContainsKey(packageNameIDKey))
            {
                StopBuildWithMessage(packageNameIDKey + " is missing deppendency file name. Add to dictionary in code.");
            }
            string dependencyFileName = androidPackageToDeppendencyFileName[packageNameIDKey]; // "remoteConfigDependencies.xml";
            string dependenciesXmlPath = Path.Combine(packageCacheFolder, firebaseFolder,"Firebase","Editor", dependencyFileName);
            
            XDocument dependencies = null;
            try
            {
                dependencies = XDocument.Load(dependenciesXmlPath);
            }
    #pragma warning disable 0168
            catch (IOException e)
    #pragma warning restore 0168
            {
                StopBuildWithMessage(dependencyFileName + " is missing. Try re-importing the plugin.");
            }

            XElement elemDependencies = dependencies.Element("dependencies");
            if (elemDependencies == null)
            {
                StopBuildWithMessage(dependencyFileName + " is not valid. Try re-importing the plugin.");
            }

            XElement elemAndroidPackages = elemDependencies.Element("androidPackages");
            if (elemAndroidPackages == null)
            {
                StopBuildWithMessage(dependencyFileName + " is not valid. Try re-importing the plugin.");
            }

            IEnumerable<XElement> androidPackages = elemAndroidPackages.Descendants()
                    .Where(elem => elem.Name.LocalName.Equals("androidPackage"));
            string androidPackageNamePrefix = packageNameIDKey + ":"; // "com.google.firebase:firebase-config:"
            if (androidPackageNameIdToDeppendencySpecPrefix.ContainsKey(packageNameID))
            {
                androidPackageNamePrefix = androidPackageNameIdToDeppendencySpecPrefix[packageNameID] + ":";
            }
            var androidPackageElement = GetAndroidPackageElement(androidPackages, androidPackageNamePrefix);
            if (androidPackageElement != null)
            {
                string newspec = string.Format("{0}[{1}]",androidPackageNamePrefix, androidPackageToWantedVersion[packageNameIDKey]);
                androidPackageElement.SetAttributeValue("spec", newspec); // androidPackageElement.SetAttributeValue("spec", "com.google.firebase:firebase-config:[19.2.0]");
            }
            else
            {
                Debug.LogWarning("couldnt find spec " + androidPackageNamePrefix+  " in " + dependencyFileName);
            }
            elemDependencies.Save(dependenciesXmlPath);
        }

       

    }
    private XElement GetAndroidPackageElement(IEnumerable<XElement> androidPackages, string SpecNamePre)
    {
        foreach (XElement elem in androidPackages)
        {
            IEnumerable<XAttribute> attrs = elem.Attributes();
            foreach (XAttribute attr in attrs)
            {
                if (attr.Name.LocalName.Equals("spec") && attr.Value.StartsWith(SpecNamePre))
                {
                    return elem;
                }
            }
        }
        return null;
    }

    private void StopBuildWithMessage(string message)
    {
        string prefix = "[PackageCacheDependencyProcessor] ";
#if UNITY_2017_1_OR_NEWER
        throw new BuildPlayerWindow.BuildMethodException(prefix + message);
#else
        // Unity 5.6 or lower does not support BuildMethodException.
        // Log an error log instead.
        Debug.LogError(prefix + message);
#endif
    }
}

#endif

@firebase firebase locked and limited conversation to collaborators Nov 21, 2020
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
api: core edm4u Issue related to External Dependency Manager for Unity type: bug type: process
Projects
None yet
Development

No branches or pull requests