Skip to content
Permalink
Browse files
Add automatic script updates and notifications
  • Loading branch information
Neo committed Jul 22, 2020
1 parent 4329079 commit fd9caeaffcf25747b7a9cbd39b56d67b2025b16c
Showing 12 changed files with 1,860 additions and 1,161 deletions.
@@ -358,3 +358,5 @@ MigrationBackup/

# Fody - auto-generated XML schema
FodyWeavers.xsd

RayshiftTranslateFGO.Android/google-services.json
@@ -9,31 +9,120 @@
using Android.Views;
using Android.Widget;
using Android.OS;
using Android.Gms.Common;
using Android.Util;
using Firebase.Messaging;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
using Platform = Xamarin.Essentials.Platform;

namespace RayshiftTranslateFGO.Droid
{
[Activity(Label = "Translate Fate/GO", Icon = "@mipmap/ic_launcher", Theme = "@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
public class MainActivity : FormsAppCompatActivity
{
public Context Context;
#if DEBUG
internal static readonly string CHANNEL_ID = "announcements_debug";
public const string UPDATE_CHANNEL_NAME = "update_debug";
#else
internal static readonly string CHANNEL_ID = "announcements";
public const string UPDATE_CHANNEL_NAME = "update";
#endif

internal static readonly int NOTIFICATION_ID = 100;
public const string TAG = "MainActivity";
public bool GooglePlayAvailable { get; set; }
protected override void OnCreate(Bundle savedInstanceState)
{
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
Context = this.ApplicationContext;

base.OnCreate(savedInstanceState);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
Platform.Init(this, savedInstanceState);
Forms.Init(this, savedInstanceState);
AssetManager assets = this.Assets;

#if DEBUG
if (Intent.Extras != null)
{
foreach (var key in Intent.Extras.KeySet())
{
if (key != null)
{
var value = Intent.Extras.GetString(key);
Log.Debug(TAG, "Key: {0} Value: {1}", key, value);
}
}
}
#endif
IsPlayServicesAvailable();
CreateNotificationChannel();

FirebaseMessaging.Instance.SubscribeToTopic(CHANNEL_ID);
FirebaseMessaging.Instance.SubscribeToTopic(UPDATE_CHANNEL_NAME);

LoadApplication(new App());
}
public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Permission[] grantResults)
{
Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);
Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);

base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
}

public bool IsPlayServicesAvailable()
{
int resultCode = GoogleApiAvailability.Instance.IsGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.Success)
{
if (GoogleApiAvailability.Instance.IsUserResolvableError(resultCode))
GooglePlayAvailable = false;
else
{
Finish();
}
return false;
}
else
{
GooglePlayAvailable = true;
return true;
}
}

void CreateNotificationChannel()
{
if (Build.VERSION.SdkInt < BuildVersionCodes.O)
{
// Notification channels are new in API 26 (and not a part of the
// support library). There is no need to create a notification
// channel on older versions of Android.
return;
}

var channel = new NotificationChannel(CHANNEL_ID,
"Announcements",
NotificationImportance.Default)
{

Description = "Rayshift Translate FGO announcements"
};

var notificationManager = (NotificationManager)GetSystemService(Context.NotificationService);
notificationManager.CreateNotificationChannel(channel);

var channel2 = new NotificationChannel(UPDATE_CHANNEL_NAME,
"Updates",
NotificationImportance.Default)
{

Description = "Rayshift Translate FGO script updates"
};

var notificationManager2 = (NotificationManager)GetSystemService(Context.NotificationService);
notificationManager.CreateNotificationChannel(channel);
}
}
}
@@ -1,7 +1,20 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="101" android:versionName="1.01" package="io.rayshift.translatefgo" android:installLocation="auto">
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="102" android:versionName="1.02" package="io.rayshift.translatefgo" android:installLocation="auto">
<uses-sdk android:minSdkVersion="16" android:targetSdkVersion="28" />
<application android:roundIcon="@mipmap/ic_launcher_round" android:label="Translate Fate/GO" android:icon="@mipmap/ic_launcher"></application>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<application android:roundIcon="@mipmap/ic_launcher_round" android:label="Translate Fate/GO" android:icon="@mipmap/ic_launcher">
<receiver android:name="com.google.firebase.iid.FirebaseInstanceIdInternalReceiver" android:exported="false" />
<receiver android:name="com.google.firebase.iid.FirebaseInstanceIdReceiver" android:exported="true" android:permission="com.google.android.c2dm.permission.SEND">
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<category android:name="${applicationId}" />
</intent-filter>
</receiver>
</application>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
@@ -0,0 +1,89 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Support.V4.App;
using Android.Util;
using Android.Views;
using Android.Widget;
using AndroidX.Work;
using Firebase.Messaging;
using RayshiftTranslateFGO.Services;
using Xamarin.Essentials;

namespace RayshiftTranslateFGO.Droid
{
[Service]
[IntentFilter(new[] { "com.google.firebase.MESSAGING_EVENT" })]
[IntentFilter(new[] { "com.google.firebase.INSTANCE_ID_EVENT" })]
public class RayshiftFirebaseMessagingService : FirebaseMessagingService
{
const string TAG = "RayshiftFirebaseMsgService";

public override void OnMessageReceived(RemoteMessage message)
{
//Log.Debug(TAG, "From: " + message.From);
//var body = message.GetNotification().Body;
//Log.Debug(TAG, "Notification Message Body: " + body);
Log.Info(TAG, $"Received a firebase request from {message.From}.");
if (message.From == $"/topics/{MainActivity.CHANNEL_ID}")
{
Log.Debug(TAG, "Received an announcement.");
SendNotification(message.GetNotification().Body, message.GetNotification().Title, message.Data);
}
else if (message.From == $"/topics/{MainActivity.UPDATE_CHANNEL_NAME}" &&
!Preferences.ContainsKey("DisableAutoUpdate") &&
Preferences.Get("InstalledScript", null) != null)
{
Log.Debug(TAG, "Received an update request.");

OneTimeWorkRequest request = OneTimeWorkRequest.Builder.From<RayshiftTranslationUpdateWorker>().Build();
WorkManager.Instance.Enqueue(request);
}
}
void SendNotification(string messageBody, string messageTitle, IDictionary<string, string> data)
{
var intent = new Intent(this, typeof(MainActivity));
intent.AddFlags(ActivityFlags.ClearTop);
foreach (var key in data.Keys)
{
intent.PutExtra(key, data[key]);
}

var pendingIntent = PendingIntent.GetActivity(this,
MainActivity.NOTIFICATION_ID,
intent,
PendingIntentFlags.OneShot);

var notificationBuilder = new NotificationCompat.Builder(this, MainActivity.CHANNEL_ID)
.SetSmallIcon(Resource.Drawable.ic_stat_ic_notification)
.SetContentTitle(messageTitle)
.SetContentText(messageBody)
.SetAutoCancel(true)
.SetContentIntent(pendingIntent);

var notificationManager = NotificationManagerCompat.From(this);
notificationManager.Notify(MainActivity.NOTIFICATION_ID, notificationBuilder.Build());
}

public override void OnNewToken(string token)
{
#if DEBUG
Log.Debug(TAG, "FCM token: " + token);
#endif
SendRegistrationToServer(token);
}

async void SendRegistrationToServer(string token)
{
var rest = new RestfulAPI();
await rest.SendRegistrationToken(token);
}
}
}
@@ -56,15 +56,35 @@
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Xamarin.Android.Arch.Work.Runtime">
<Version>1.0.0.3</Version>
</PackageReference>
<PackageReference Include="Xamarin.Firebase.Analytics">
<Version>71.1630.4</Version>
</PackageReference>
<PackageReference Include="Xamarin.FireBase.Analytics.Impl">
<Version>71.1630.4</Version>
</PackageReference>
<PackageReference Include="Xamarin.Firebase.Messaging">
<Version>71.1740.4</Version>
</PackageReference>
<PackageReference Include="Xamarin.Forms" Version="4.6.0.726" />
<PackageReference Include="Xamarin.Essentials" Version="1.5.3.1" />
<PackageReference Include="Xamarin.GooglePlayServices.Base">
<Version>71.1610.4</Version>
</PackageReference>
</ItemGroup>
<ItemGroup>
<Compile Include="MainActivity.cs" />
<Compile Include="RayshiftFirebaseMessageService.cs" />
<Compile Include="RayshiftTranslationUpdateWorker.cs" />
<Compile Include="Resources\Resource.designer.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<GoogleServicesJson Include="google-services.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</GoogleServicesJson>
<None Include="Resources\AboutResources.txt" />
<None Include="Assets\AboutAssets.txt" />
<None Include="Properties\AndroidManifest.xml" />
@@ -134,10 +154,12 @@
</ItemGroup>
<ItemGroup>
<Folder Include="Assets\Mock\" />
<Folder Include="Resources\drawable\" />
</ItemGroup>
<ItemGroup>
<AndroidResource Include="Resources\values\ic_launcher_background.xml" />
</ItemGroup>
<ItemGroup>
<AndroidResource Include="Resources\drawable\ic_stat_ic_notification.png" />
</ItemGroup>
<Import Project="$(MSBuildExtensionsPath)\Xamarin\Android\Xamarin.Android.CSharp.targets" />
</Project>

0 comments on commit fd9caea

Please sign in to comment.