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

Make Android OnReceived condition virtual, fix UnsubscribeAll ios Bug and Update to new firebase sdk #444

Open
wants to merge 10 commits into
base: master
Choose a base branch
from
8 changes: 4 additions & 4 deletions Directory.build.props
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@

<ItemGroup Condition="'$(IsTestProject)' != 'true' and '$(SourceLinkEnabled)' != 'false' and '$(IsLibraryProject)' == 'true'">
<PackageReference Include="SourceLink.Create.CommandLine" Version="2.8.3" PrivateAssets="All" />
<PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.0.0" PrivateAssets="All" />
<PackageReference Include="Microsoft.SourceLink.GitHub" Version="8.0.0" PrivateAssets="All" />
</ItemGroup>

<PropertyGroup>
Expand All @@ -71,15 +71,15 @@
</ItemGroup>

<ItemGroup>
<PackageReference Include="Roslynator.Analyzers" Version="2.3.0">
<PackageReference Include="Roslynator.Analyzers" Version="4.12.1">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="AsyncFixer" Version="1.1.6">
<PackageReference Include="AsyncFixer" Version="1.6.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.CodeAnalysis.FxCopAnalyzers" Version="2.9.8">
<PackageReference Include="Microsoft.CodeAnalysis.NetAnalyzers" Version="8.0.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
Expand Down Expand Up @@ -153,7 +153,7 @@ public virtual void OnReceived(IDictionary<string, object> parameters)
{
System.Diagnostics.Debug.WriteLine($"{DomainTag} - OnReceived");

if ((parameters.TryGetValue(SilentKey, out var silent) && (silent.ToString() == "true" || silent.ToString() == "1")) || (IsInForeground() && (!(!parameters.ContainsKey(ChannelIdKey) && parameters.TryGetValue(PriorityKey, out var imp) && ($"{imp}" == "high" || $"{imp}" == "max")) || (!parameters.ContainsKey(PriorityKey) && !parameters.ContainsKey(ChannelIdKey) && FirebasePushNotificationManager.DefaultNotificationChannelImportance != NotificationImportance.High && FirebasePushNotificationManager.DefaultNotificationChannelImportance != NotificationImportance.Max))))
if (SkipNotificationProcessing(parameters))
{
return;
}
Expand Down Expand Up @@ -228,12 +228,12 @@ public virtual void OnReceived(IDictionary<string, object> parameters)

if (parameters.TryGetValue(ShowWhenKey, out var shouldShowWhen))
{
showWhenVisible = $"{shouldShowWhen}".ToLower() == "true";
showWhenVisible = $"{shouldShowWhen}".Equals("true", StringComparison.CurrentCultureIgnoreCase);
}

if (parameters.TryGetValue(BigTextStyleKey, out var shouldUseBigTextStyle) && shouldUseBigTextStyle != null)
{
useBigTextStyle = $"{shouldUseBigTextStyle}".ToLower() == "true";
useBigTextStyle = $"{shouldUseBigTextStyle}".Equals("true", StringComparison.CurrentCultureIgnoreCase);
}

if (parameters.TryGetValue(TagKey, out var tagContent))
Expand Down Expand Up @@ -606,6 +606,18 @@ public virtual void OnError(string error)
/// <param name="parameters">Notification parameters.</param>
public virtual void OnBuildNotification(NotificationCompat.Builder notificationBuilder, IDictionary<string, object> parameters) { }

/// <summary>
/// Override to implement own condition to skip notification processing or not.
/// </summary>
/// <param name="parameters">Notification parameters.</param>
/// <returns>true to skip processing or false to continue</returns>
public virtual bool SkipNotificationProcessing(IDictionary<string, object> parameters)
{
var result = (parameters.TryGetValue(SilentKey, out var silent) && (silent.ToString() == "true" || silent.ToString() == "1")) || (IsInForeground() && (!(!parameters.ContainsKey(ChannelIdKey) && parameters.TryGetValue(PriorityKey, out var imp) && ($"{imp}" == "high" || $"{imp}" == "max")) || (!parameters.ContainsKey(PriorityKey) && !parameters.ContainsKey(ChannelIdKey) && FirebasePushNotificationManager.DefaultNotificationChannelImportance != NotificationImportance.High && FirebasePushNotificationManager.DefaultNotificationChannelImportance != NotificationImportance.Max)));
System.Diagnostics.Debug.WriteLine($"{DomainTag} - {nameof(SkipNotificationProcessing)}: {result}");
return result;
}

private bool IsInForeground()
{
bool isInForeground;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using System;
using System;
using Firebase.Messaging;
using System.Collections.Generic;
using Android.Content;
Expand Down Expand Up @@ -61,9 +61,9 @@ public static void ProcessIntent(Activity activity, Intent intent, bool enableDe
var parameters = new Dictionary<string, object>();
foreach (var key in extras.KeySet())
{
if (!parameters.ContainsKey(key) && extras.Get(key) != null)
if (!parameters.ContainsKey(key) && !string.IsNullOrWhiteSpace(extras.GetString(key)))
{
parameters.Add(key, $"{extras.Get(key)}");
parameters.Add(key, extras.GetString(key));
}
}

Expand Down Expand Up @@ -197,7 +197,7 @@ public static void Initialize(Context context, NotificationUserCategory[] notifi
RegisterUserNotificationCategories(notificationCategories);

}

public static void Reset()
{
ThreadPool.QueueUserWorkItem(state =>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
using System.Threading.Tasks;
using Firebase.CloudMessaging;
using Firebase.Core;
using Firebase.InstanceID;
//using Firebase.InstanceID; //Old
using Foundation;
using UIKit;
using UserNotifications;
Expand All @@ -24,7 +24,7 @@ public class FirebasePushNotificationManager : NSObject, IFirebasePushNotificati
private static NSString FirebaseTopicsKey = new NSString("FirebaseTopics");
private const string FirebaseTokenKey = "FirebaseToken";
private static NSMutableArray currentTopics = (NSUserDefaults.StandardUserDefaults.ValueForKey(FirebaseTopicsKey) as NSArray ?? new NSArray()).MutableCopy() as NSMutableArray;
public string Token { get { return string.IsNullOrEmpty(Messaging.SharedInstance.FcmToken) ? (NSUserDefaults.StandardUserDefaults.StringForKey(FirebaseTokenKey) ?? string.Empty) : Messaging.SharedInstance.FcmToken; } }
public string Token { get { return string.IsNullOrEmpty(Messaging.SharedInstance?.FcmToken) ? (NSUserDefaults.StandardUserDefaults.StringForKey(FirebaseTokenKey) ?? string.Empty) : Messaging.SharedInstance?.FcmToken; } }

private static IList<NotificationUserCategory> usernNotificationCategories = new List<NotificationUserCategory>();
private static FirebasePushNotificationTokenEventHandler _onTokenRefresh;
Expand Down Expand Up @@ -302,7 +302,8 @@ public void UnregisterForPushNotifications()
Messaging.SharedInstance.AutoInitEnabled = false;
UIApplication.SharedApplication.UnregisterForRemoteNotifications();
NSUserDefaults.StandardUserDefaults.SetString(string.Empty, FirebaseTokenKey);
InstanceId.SharedInstance.DeleteId((h) => { });
Messaging.SharedInstance.DeleteToken((h) => { });
//InstanceId.SharedInstance.DeleteId((h) => { }); Old
}
// To receive notifications in foreground on iOS 10 devices.
[Export("userNotificationCenter:willPresentNotification:withCompletionHandler:")]
Expand All @@ -315,15 +316,15 @@ public void WillPresentNotification(UNUserNotificationCenter center, UNNotificat
_onNotificationReceived?.Invoke(CrossFirebasePushNotification.Current, new FirebasePushNotificationDataEventArgs(parameters));
CrossFirebasePushNotification.Current.NotificationHandler?.OnReceived(parameters);

if ((parameters.TryGetValue("priority", out var priority) && ($"{priority}".ToLower() == "high" || $"{priority}".ToLower() == "max")))
if ((parameters.TryGetValue("priority", out var priority) && ($"{priority}".Equals("high", StringComparison.CurrentCultureIgnoreCase) || $"{priority}".Equals("max", StringComparison.CurrentCultureIgnoreCase))))
{
if (!CurrentNotificationPresentationOption.HasFlag(UNNotificationPresentationOptions.Alert))
{
CurrentNotificationPresentationOption |= UNNotificationPresentationOptions.Alert;

}
}
else if ($"{priority}".ToLower() == "default" || $"{priority}".ToLower() == "low" || $"{priority}".ToLower() == "min")
else if ($"{priority}".Equals("default", StringComparison.CurrentCultureIgnoreCase) || $"{priority}".Equals("low", StringComparison.CurrentCultureIgnoreCase) || $"{priority}".Equals("min", StringComparison.CurrentCultureIgnoreCase))
{
if (CurrentNotificationPresentationOption.HasFlag(UNNotificationPresentationOptions.Alert))
{
Expand Down Expand Up @@ -361,14 +362,15 @@ public static void RemoteNotificationRegistrationFailed(NSError error)
_onNotificationError?.Invoke(CrossFirebasePushNotification.Current, new FirebasePushNotificationErrorEventArgs(FirebasePushNotificationErrorType.RegistrationFailed, error.Description));
}

public void ApplicationReceivedRemoteMessage(RemoteMessage remoteMessage)
{
System.Console.WriteLine(remoteMessage.AppData);
System.Diagnostics.Debug.WriteLine("ApplicationReceivedRemoteMessage");
var parameters = GetParameters(remoteMessage.AppData);
_onNotificationReceived?.Invoke(CrossFirebasePushNotification.Current, new FirebasePushNotificationDataEventArgs(parameters));
CrossFirebasePushNotification.Current.NotificationHandler?.OnReceived(parameters);
}
//public void ApplicationReceivedRemoteMessage(RemoteMessage remoteMessage)
//{
// Firebase.CloudMessaging.MessageStatus.
// System.Console.WriteLine(remoteMessage.AppData);
// System.Diagnostics.Debug.WriteLine("ApplicationReceivedRemoteMessage");
// var parameters = GetParameters(remoteMessage.AppData);
// _onNotificationReceived?.Invoke(CrossFirebasePushNotification.Current, new FirebasePushNotificationDataEventArgs(parameters));
// CrossFirebasePushNotification.Current.NotificationHandler?.OnReceived(parameters);
//}

private static IDictionary<string, object> GetParameters(NSDictionary data)
{
Expand Down Expand Up @@ -446,10 +448,7 @@ public void Subscribe(string topic)

public void UnsubscribeAll()
{
for (nuint i = 0; i < currentTopics.Count; i++)
{
Unsubscribe(currentTopics.GetItem<NSString>(i));
}
Unsubscribe(SubscribedTopics);
}

public void Unsubscribe(string[] topics)
Expand Down Expand Up @@ -483,6 +482,7 @@ public void Unsubscribe(string topic)

}

[Obsolete("Upstream messaging through direct channel is deprecated. Not working anymore.", true)]
public void SendDeviceGroupMessage(IDictionary<string, string> parameters, string groupKey, string messageId, int timeOfLive)
{
if (hasToken)
Expand All @@ -494,9 +494,9 @@ public void SendDeviceGroupMessage(IDictionary<string, string> parameters, strin
message.Add(new NSString(p.Key), new NSString(p.Value));
}

Messaging.SharedInstance.SendMessage(message, groupKey, messageId, timeOfLive);
// Messaging.SharedInstance.SendMessage(message, groupKey, messageId, timeOfLive); //Old
}

}
}

Expand Down Expand Up @@ -612,8 +612,8 @@ public async void RemoveNotification(int id)

public async Task<string> GetTokenAsync()
{
var result = await InstanceId.SharedInstance.GetInstanceIdAsync();
return result?.Token;
var result = await Messaging.SharedInstance.FetchTokenAsync();//InstanceId.SharedInstance.GetInstanceIdAsync(); Old
return result;
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

<PropertyGroup>

<TargetFrameworks>netstandard2.0;xamarin.ios10;monoandroid12.0</TargetFrameworks>
<TargetFrameworks>netstandard2.0;xamarin.ios10;monoandroid13.0</TargetFrameworks>
<!--<TargetFrameworks>netstandard2.0;xamarin.ios10;xamarin.mac20;xamarin.tvos10;xamarin.watchos10;monoandroid10.0;tizen40;netcoreapp3.1;net472</TargetFrameworks>
<TargetFrameworks Condition=" '$(OS)' == 'Windows_NT' ">uap10.0.17763;$(TargetFrameworks)</TargetFrameworks>-->

Expand Down Expand Up @@ -66,8 +66,9 @@
<Compile Include="Platforms\Ios\**\*.cs" />
<Compile Include="Platforms\Xamarin\**\*.cs" />
<Compile Include="**\*.ios.cs" />
<Compile Include="**\*.ios.*.cs" />
<PackageReference Include="Xamarin.Firebase.iOS.CloudMessaging" Version="4.3.0" />
<Compile Include="**\*.ios.*.cs" />
<!--<PackageReference Include="Xamarin.Firebase.iOS.CloudMessaging" Version="4.3.0" />-->
<PackageReference Include="AdamE.Firebase.iOS.CloudMessaging" Version="10.16.0" />
</ItemGroup>

<ItemGroup Condition=" $(TargetFramework.StartsWith('xamarin.mac')) ">
Expand Down Expand Up @@ -106,9 +107,8 @@
<AndroidResource Include="Resources\**\*.json" Generator="MSBuild:UpdateAndroidResources" />
<Compile Include="**\*.android.cs" />
<Compile Include="**\*.android.*.cs" />
<PackageReference Include="Xamarin.Firebase.Common" Version="120.0.0.5" />
<PackageReference Include="Xamarin.Firebase.Messaging" Version="122.0.0.5" />
<PackageReference Include="Xamarin.GooglePlayServices.Base" Version="118.0.1" />
<PackageReference Include="Xamarin.Firebase.Common" Version="120.4.2.2" />
<PackageReference Include="Xamarin.Firebase.Messaging" Version="123.3.1.2" />
</ItemGroup>

<ItemGroup Condition=" $(TargetFramework.StartsWith('tizen')) ">
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@ public override void OnReceive(Context context, Intent intent)
{
foreach (var key in extras.KeySet())
{
parameters.Add(key, $"{extras.Get(key)}");
System.Diagnostics.Debug.WriteLine(key, $"{extras.Get(key)}");
parameters.Add(key, extras.GetString(key));
System.Diagnostics.Debug.WriteLine(key, extras.GetString(key));
}
}
FirebasePushNotificationManager.RegisterAction(parameters);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ public override void OnReceive(Context context, Intent intent)
{
foreach (var key in extras.KeySet())
{
parameters.Add(key, $"{extras.Get(key)}");
System.Diagnostics.Debug.WriteLine(key, $"{extras.Get(key)}");
parameters.Add(key, extras.GetString(key));
System.Diagnostics.Debug.WriteLine(key, extras.GetString(key));
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
<AndroidResgenFile>Resources\Resource.Designer.cs</AndroidResgenFile>
<GenerateSerializationAssemblies>Off</GenerateSerializationAssemblies>
<AndroidManifest>Properties\AndroidManifest.xml</AndroidManifest>
<TargetFrameworkVersion>v12.0</TargetFrameworkVersion>
<TargetFrameworkVersion>v13.0</TargetFrameworkVersion>
<AndroidStoreUncompressedFileExtensions />
<MandroidI18n />
<JavaMaximumHeapSize />
Expand Down
1 change: 1 addition & 0 deletions samples/FirebasePushSample/FirebasePushSample.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
</ItemGroup>

<ItemGroup>
<PackageReference Include="AdamE.Firebase.iOS.CloudMessaging" Version="10.16.0" />
<PackageReference Include="Xamarin.Essentials" Version="1.7.2" />
<PackageReference Include="Xamarin.Forms" Version="5.0.0.2401" />
</ItemGroup>
Expand Down
Loading