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

feat: add forcedupdate firebase implementation #409

Draft
wants to merge 4 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -325,3 +325,7 @@ ASALocalRun/

# MFractors (Xamarin productivity tool) working folder
.mfractor/

# Firebase
*google-services.json
*GoogleService-Info.plist
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,13 @@ public sealed class UpdateRequiredService : IUpdateRequiredService, IDisposable
public UpdateRequiredService(IMinimumVersionReposiory minimumVersionReposiory)
{
_subscription = minimumVersionReposiory.MinimumVersionObservable
.Subscribe(_ => UpdateRequired?.Invoke(this, EventArgs.Empty));
.Subscribe(version =>
{
if (version > new Version("1.1.0"))
{
UpdateRequired?.Invoke(this, EventArgs.Empty);
}
});
}

/// <inheritdoc />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@
<PublishTrimmed>True</PublishTrimmed>
<TrimMode>partial</TrimMode>
</PropertyGroup>
<ItemGroup>
<Compile Remove="Android\RemoteConfigRepository.cs" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Chinook.BackButtonManager.Uno.WinUI" Version="2.1.0" />
<PackageReference Include="Chinook.DataLoader.Uno.WinUI" Version="2.0.0" />
Expand Down Expand Up @@ -100,8 +103,11 @@
<ItemGroup>
<PackageReference Include="Uno.UniversalImageLoader" Version="1.9.36" />
<PackageReference Include="Mono.AotProfiler.Android" Version="7.0.0" />
<PackageReference Include="Xamarin.Kotlin.StdLib.Jdk8" Version="1.9.23.1" />
<PackageReference Include="Xamarin.Kotlin.StdLib.Jdk8" Version="1.9.22.1" />
<PackageReference Include="Xamarin.Firebase.Config" Version="121.6.1.1" />
</ItemGroup>

<!-- Android Firebase configuration. -->
<ItemGroup>
<AndroidAotProfile Include="custom.aprof" />
<AndroidEnvironment Include="Android\environment.conf" />
Expand Down Expand Up @@ -149,10 +155,19 @@
<MtouchExtraArgs>$(MtouchExtraArgs) --registrar:static</MtouchExtraArgs>
<!-- See https://github.com/xamarin/xamarin-macios/issues/14812 for more details. -->
<MtouchExtraArgs>$(MtouchExtraArgs) --marshal-objectivec-exceptions:disable</MtouchExtraArgs>
<!-- Required with AdamE.Firebase.iOS.CloudMessaging 10.17+. -->
<MtouchExtraArgs Condition="'$(Platform)'=='iPhone'">$(MtouchExtraArgs) --gcc_flags -L/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos</MtouchExtraArgs>
<MtouchExtraArgs Condition="'$(Platform)'=='simulator'">$(MtouchExtraArgs) --gcc_flags -L/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/</MtouchExtraArgs>
<CodesignEntitlements>iOS\Entitlements.plist</CodesignEntitlements>
<!-- Workaround for clang++ error on iOS simulator on ARM base macOS system. See "https://github.com/dotnet/maui/issues/16778#issuecomment-1683343255" for more detail. -->
<ForceSimulatorX64ArchitectureInIDE>true</ForceSimulatorX64ArchitectureInIDE>
</PropertyGroup>
<!-- iOS Firebase configuration. -->
<ItemGroup>
<BundleResource Include="iOS\GoogleService-Info.plist">
<Link>GoogleService-Info.plist</Link>
</BundleResource>
</ItemGroup>
<Choose>
<When Condition="'$(Configuration)'=='Debug'">
<PropertyGroup>
Expand Down Expand Up @@ -201,6 +216,7 @@
</Choose>
<ItemGroup>
<PackageReference Include="Uno.Extensions.Logging.OSLog" Version="1.7.0" />
<PackageReference Include="AdamE.Firebase.iOS.RemoteConfig" Version="10.22.0-alpha1" />
</ItemGroup>
<ItemGroup>
<TrimmerRootDescriptor Include="iOS\LinkerExclusions.xml" />
Expand Down Expand Up @@ -268,4 +284,8 @@
</When>
</Choose>
<Import Project="..\ApplicationTemplate.Shared.Views\ApplicationTemplate.Shared.Views.projitems" Label="Shared" />


<!-- Required with AdamE.Firebase.iOS.CloudMessaging https://github.com/AdamEssenmacher/GoogleApisForiOSComponents?tab=readme-ov-file#firebase-analytics -->
<Import Project="..\..\..\LinkWithSwiftSystemLibrariesWorkaround.targets" Condition="'$(TargetFramework)' == 'net7.0-ios'" />
</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@

<Project>
<!-- Target needed until LinkWithSwiftSystemLibraries makes it into the SDK: https://github.com/xamarin/xamarin-macios/pull/20463 -->
<Target Name="LinkWithSwift" DependsOnTargets="_ParseBundlerArguments;_DetectSdkLocations" BeforeTargets="_LinkNativeExecutable">
<PropertyGroup>
<_SwiftPlatform Condition="$(RuntimeIdentifier.StartsWith('iossimulator-'))">iphonesimulator</_SwiftPlatform>
<_SwiftPlatform Condition="$(RuntimeIdentifier.StartsWith('ios-'))">iphoneos</_SwiftPlatform>
</PropertyGroup>
<ItemGroup>
<_CustomLinkFlags Include="-L" />
<_CustomLinkFlags Include="/usr/lib/swift" />
<_CustomLinkFlags Include="-L" />
<_CustomLinkFlags Include="$(_SdkDevPath)/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/$(_SwiftPlatform)" />
<_CustomLinkFlags Include="-Wl,-rpath" />
<_CustomLinkFlags Include="-Wl,/usr/lib/swift" />
</ItemGroup>
</Target>
</Project>
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,6 @@ public static IServiceCollection AddApi(this IServiceCollection services, IConfi
.AddAuthentication()
.AddPosts(configuration)
.AddUserProfile()
.AddMinimumVersion()
.AddKillSwitch()
.AddDadJokes(configuration);

return services;
Expand All @@ -55,18 +53,6 @@ private static IServiceCollection AddUserProfile(this IServiceCollection service
return services.AddSingleton<IUserProfileRepository, UserProfileRepositoryMock>();
}

private static IServiceCollection AddMinimumVersion(this IServiceCollection services)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Don't you need to keep those for the functional tests to work?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The services exist in the view layer, this doesnt have access to the service?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I guess we could try to create some sort of thing that would get the viewservice here, would that be something we really want to do?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Functional tests don't use anything from the View layer. So I guess this adds to my original question. 😋

{
// This one doesn't have an actual remote API yet. It's always a mock implementation.
return services.AddSingleton<IMinimumVersionReposiory, MinimumVersionRepositoryMock>();
}

private static IServiceCollection AddKillSwitch(this IServiceCollection services)
{
// This one doesn't have an actual remote API yet. It's always a mock implementation.
return services.AddSingleton<IKillSwitchRepository, KillSwitchRepositoryMock>();
}

private static IServiceCollection AddAuthentication(this IServiceCollection services)
{
// This one doesn't have an actual remote API yet. It's always a mock implementation.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,8 @@
<Compile Include="$(MSBuildThisFileDirectory)Helpers\DependencyObjectExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Helpers\FrameworkElementExtension.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Helpers\ObservableExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)RemoteConfigRepository.Android.cs" />
<Compile Include="$(MSBuildThisFileDirectory)RemoteConfigRepository.Ios.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Shell.xaml.cs">
<DependentUpon>Shell.xaml</DependentUpon>
</Compile>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.Reactive.Concurrency;
using ApplicationTemplate.DataAccess;
using Chinook.DynamicMvvm;
using MessageDialogService;
using Microsoft.Extensions.DependencyInjection;
Expand Down Expand Up @@ -34,6 +35,14 @@ public static IServiceCollection AddViewServices(this IServiceCollection service
.AddSingleton<IEmailService, EmailService>()
.AddSingleton<IMemoryProvider, MemoryProvider>()
.AddSingleton<IReviewPrompter, ReviewPrompter>()
#if __ANDROID__ || __IOS__
.AddSingleton<RemoteConfigRepository>()
.AddSingleton<IKillSwitchRepository>(s => s.GetRequiredService<RemoteConfigRepository>())
.AddSingleton<IMinimumVersionReposiory>(s => s.GetRequiredService<RemoteConfigRepository>())
#else
.AddSingleton<IKillSwitchRepository, KillSwitchRepositoryMock>()
.AddSingleton<IMinimumVersionReposiory, MinimumVersionRepositoryMock>()
#endif
.AddMessageDialog();
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
#if __ANDROID__
using System;
using System.Reactive.Subjects;
using ApplicationTemplate.DataAccess;
using Firebase.RemoteConfig;

namespace ApplicationTemplate.Views;

/// <summary>
/// RemoteConfigRepository is a repository for Firebase Remote Config.
/// </summary>
public sealed class RemoteConfigRepository : IKillSwitchRepository, IMinimumVersionReposiory, IDisposable
{
private Subject<bool> _killSwitchSubject = new Subject<bool>();
private Subject<Version> _versionSubject = new Subject<Version>();

/// <summary>
/// Initializes a new instance of the <see cref="RemoteConfigRepository"/> class.
/// </summary>
public RemoteConfigRepository()
{
FirebaseRemoteConfig mFirebaseRemoteConfig = FirebaseRemoteConfig.Instance;
FirebaseRemoteConfigSettings configSettings = new FirebaseRemoteConfigSettings.Builder()
.SetMinimumFetchIntervalInSeconds(3600)
.Build();
mFirebaseRemoteConfig.SetConfigSettingsAsync(configSettings);

FetchRemoteConfig();
ListenForRealTimeChanges();
}

private void FetchRemoteConfig()
{
FirebaseRemoteConfig mFirebaseRemoteConfig = FirebaseRemoteConfig.Instance;
mFirebaseRemoteConfig.FetchAndActivate()
.AddOnCompleteListener(new FetchCompleteListener(this));
}

private void ListenForRealTimeChanges()
{
FirebaseRemoteConfig mFirebaseRemoteConfig = FirebaseRemoteConfig.Instance;

mFirebaseRemoteConfig.AddOnConfigUpdateListener(new ConfigUpdateListener(this));
}

/// <inheritdoc />
public IObservable<Version> MinimumVersionObservable => _versionSubject;

/// <inheritdoc />
public void CheckMinimumVersion()
{
throw new NotImplementedException();
}

/// <inheritdoc />
public IObservable<bool> ObserveKillSwitchActivation()
{
return _killSwitchSubject;
}

/// <inheritdoc />
public void Dispose()
{
_killSwitchSubject.Dispose();
_versionSubject.Dispose();
}

private sealed class FetchCompleteListener : Java.Lang.Object, Android.Gms.Tasks.IOnCompleteListener
{
private readonly RemoteConfigRepository _repository;

public FetchCompleteListener(RemoteConfigRepository repository)
{
_repository = repository;
}

public void OnComplete(Android.Gms.Tasks.Task task)
{
if (task.IsSuccessful)
{
_repository._killSwitchSubject.OnNext(FirebaseRemoteConfig.Instance.GetBoolean("kill_switch"));
_repository._versionSubject.OnNext(new Version(FirebaseRemoteConfig.Instance.GetString("minimum_version")));
}
}
}

private sealed class ConfigUpdateListener : Java.Lang.Object, IConfigUpdateListener
{
private readonly RemoteConfigRepository _repository;

public ConfigUpdateListener(RemoteConfigRepository repository)
{
_repository = repository;
}

public void OnError(FirebaseRemoteConfigException p0)
{
throw new NotImplementedException();
}

public void OnUpdate(ConfigUpdate p0)
{
var instance = FirebaseRemoteConfig.Instance;

instance.FetchAndActivate();
var isKillSwitchActivated = FirebaseRemoteConfig.Instance.GetBoolean("kill_switch");
var minimumVersion = new Version(FirebaseRemoteConfig.Instance.GetString("minimum_version"));

_repository._killSwitchSubject.OnNext(isKillSwitchActivated);
_repository._versionSubject.OnNext(minimumVersion);
}
}
}
#endif
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
#if __IOS__
using System;
using System.Reactive.Subjects;
using ApplicationTemplate.DataAccess;
using Firebase.RemoteConfig;
using Foundation;

namespace ApplicationTemplate.Views;

/// <summary>
/// Implementation of the killswitch repository and the minimum version with Firebase Remote Config for iOS.
/// </summary>
public sealed class RemoteConfigRepository : IKillSwitchRepository, IMinimumVersionReposiory, IDisposable
{
private BehaviorSubject<bool> _killSwitchSubject = new BehaviorSubject<bool>(default);
private BehaviorSubject<Version> _versionSubject = new BehaviorSubject<Version>(default);

/// <summary>
/// Initializes a new instance of the <see cref="RemoteConfigRepository"/> class.
/// </summary>
public RemoteConfigRepository()
{
Firebase.Core.App.Configure();
// Enabling developer mode, allows for frequent refreshes of the cache
RemoteConfig.SharedInstance.ConfigSettings = new RemoteConfigSettings();

object[] values = { false, "1.0.0" };
object[] keys = { "kill_switch", "minimum_version" };
var defaultValues = NSDictionary.FromObjectsAndKeys(values, keys, keys.Length);
RemoteConfig.SharedInstance.SetDefaults(defaultValues);

// CacheExpirationSeconds is set to CacheExpiration here, indicating that any previously
// fetched and cached config would be considered expired because it would have been fetched
// more than CacheExpiration seconds ago. Thus the next fetch would go to the server unless
// throttling is in progress. The default expiration duration is 43200 (12 hours).
RemoteConfig.SharedInstance.Fetch(10, (status, error) =>
{
switch (status)
{
case RemoteConfigFetchStatus.Success:
Console.WriteLine("Config Fetched!");

// Call this method to make fetched parameter values available to your app
RemoteConfig.SharedInstance.Activate();

_killSwitchSubject.OnNext(RemoteConfig.SharedInstance["kill_switch"].BoolValue);
_versionSubject.OnNext(new Version(RemoteConfig.SharedInstance["minimum_version"].StringValue));
break;

case RemoteConfigFetchStatus.Throttled:
case RemoteConfigFetchStatus.NoFetchYet:
case RemoteConfigFetchStatus.Failure:
Console.WriteLine("Config not fetched...");
break;
}
});

RemoteConfig.SharedInstance.AddObserver(new NSString("kill_switch"), NSKeyValueObservingOptions.New, (nSObservedChange) =>
{
if (nSObservedChange.NewValue is NSNumber nSNumber)
{
_killSwitchSubject.OnNext(nSNumber.BoolValue);
}
});
RemoteConfig.SharedInstance.AddObserver(new NSString("minimum_version"), NSKeyValueObservingOptions.New, (nSObservedChange) =>
{
if (nSObservedChange.NewValue is NSString nSString)
{
_versionSubject.OnNext(new Version(nSString));
}
});
}

/// <inheritdoc />
public IObservable<Version> MinimumVersionObservable => _versionSubject;

/// <inheritdoc />
public void CheckMinimumVersion()
{
throw new NotImplementedException();
}

/// <inheritdoc />
public IObservable<bool> ObserveKillSwitchActivation()
{
return _killSwitchSubject;
}

/// <inheritdoc />
public void Dispose()
{
_killSwitchSubject.Dispose();
_versionSubject.Dispose();
}
}
#endif
Loading