bitwarden-android/src/Android/MainActivity.cs

468 lines
18 KiB
C#
Raw Normal View History

2019-03-28 06:44:54 +03:00
using Android.App;
2019-03-28 03:12:44 +03:00
using Android.Content.PM;
using Android.Runtime;
using Android.OS;
2019-05-11 06:43:35 +03:00
using Bit.Core;
using System.Linq;
using Bit.App.Abstractions;
using Bit.Core.Utilities;
using Bit.Core.Abstractions;
using System.IO;
using System;
using Android.Content;
using Bit.Droid.Utilities;
2019-05-16 19:30:20 +03:00
using Bit.Droid.Receivers;
2019-05-17 19:03:35 +03:00
using Bit.App.Models;
using Bit.Core.Enums;
using Android.Nfc;
2019-05-29 22:50:20 +03:00
using Bit.App.Utilities;
2019-05-30 18:22:35 +03:00
using System.Threading.Tasks;
using AndroidX.Core.Content;
using ZXing.Net.Mobile.Android;
2019-03-28 03:12:44 +03:00
namespace Bit.Droid
{
[Activity(
Label = "Bitwarden",
Icon = "@mipmap/ic_launcher",
Theme = "@style/LaunchTheme",
2019-06-05 22:09:13 +03:00
MainLauncher = true,
LaunchMode = LaunchMode.SingleTask,
ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation |
ConfigChanges.Keyboard | ConfigChanges.KeyboardHidden |
ConfigChanges.Navigation)]
[IntentFilter(
new[] { Intent.ActionSend },
Categories = new[] { Intent.CategoryDefault },
DataMimeTypes = new[]
{
@"application/*",
@"image/*",
@"video/*",
@"text/*"
})]
2019-03-28 03:12:44 +03:00
[Register("com.x8bit.bitwarden.MainActivity")]
2019-03-28 06:44:54 +03:00
public class MainActivity : Xamarin.Forms.Platform.Android.FormsAppCompatActivity
2019-03-28 03:12:44 +03:00
{
2019-05-11 06:43:35 +03:00
private IDeviceActionService _deviceActionService;
private IMessagingService _messagingService;
2019-05-16 19:30:20 +03:00
private IBroadcasterService _broadcasterService;
2019-05-29 06:14:02 +03:00
private IUserService _userService;
private IAppIdService _appIdService;
2019-05-30 18:22:35 +03:00
private IStorageService _storageService;
2019-07-13 00:29:40 +03:00
private IEventService _eventService;
2019-05-30 18:22:35 +03:00
private PendingIntent _clearClipboardPendingIntent;
2019-07-13 00:29:40 +03:00
private PendingIntent _eventUploadPendingIntent;
2019-05-17 19:03:35 +03:00
private AppOptions _appOptions;
private string _activityKey = $"{nameof(MainActivity)}_{Java.Lang.JavaSystem.CurrentTimeMillis().ToString()}";
2019-05-28 16:54:08 +03:00
private Java.Util.Regex.Pattern _otpPattern =
Java.Util.Regex.Pattern.Compile("^.*?([cbdefghijklnrtuv]{32,64})$");
2019-05-11 06:43:35 +03:00
2019-03-28 03:12:44 +03:00
protected override void OnCreate(Bundle savedInstanceState)
{
2019-07-13 00:29:40 +03:00
var eventUploadIntent = new Intent(this, typeof(EventUploadReceiver));
_eventUploadPendingIntent = PendingIntent.GetBroadcast(this, 0, eventUploadIntent,
PendingIntentFlags.UpdateCurrent);
2019-05-30 18:22:35 +03:00
var clearClipboardIntent = new Intent(this, typeof(ClearClipboardAlarmReceiver));
_clearClipboardPendingIntent = PendingIntent.GetBroadcast(this, 0, clearClipboardIntent,
PendingIntentFlags.UpdateCurrent);
2019-05-16 19:30:20 +03:00
2019-05-29 06:03:03 +03:00
var policy = new StrictMode.ThreadPolicy.Builder().PermitAll().Build();
StrictMode.SetThreadPolicy(policy);
2019-05-11 06:43:35 +03:00
_deviceActionService = ServiceContainer.Resolve<IDeviceActionService>("deviceActionService");
_messagingService = ServiceContainer.Resolve<IMessagingService>("messagingService");
2019-05-16 19:30:20 +03:00
_broadcasterService = ServiceContainer.Resolve<IBroadcasterService>("broadcasterService");
2019-05-29 06:14:02 +03:00
_userService = ServiceContainer.Resolve<IUserService>("userService");
_appIdService = ServiceContainer.Resolve<IAppIdService>("appIdService");
2019-05-30 18:22:35 +03:00
_storageService = ServiceContainer.Resolve<IStorageService>("storageService");
2019-07-13 00:29:40 +03:00
_eventService = ServiceContainer.Resolve<IEventService>("eventService");
2019-05-11 06:43:35 +03:00
2019-03-28 03:12:44 +03:00
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
2019-06-24 21:29:23 +03:00
UpdateTheme(ThemeManager.GetTheme(true));
2019-03-28 03:12:44 +03:00
base.OnCreate(savedInstanceState);
if (!CoreHelpers.InDebugMode())
2019-05-29 06:04:01 +03:00
{
Window.AddFlags(Android.Views.WindowManagerFlags.Secure);
}
2019-05-29 06:14:02 +03:00
#if !FDROID
var appCenterHelper = new AppCenterHelper(_appIdService, _userService);
var appCenterTask = appCenterHelper.InitAsync();
2019-05-29 06:14:02 +03:00
#endif
2019-03-28 06:44:54 +03:00
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
Xamarin.Forms.Forms.Init(this, savedInstanceState);
2019-05-17 19:03:35 +03:00
_appOptions = GetOptions();
LoadApplication(new App.App(_appOptions));
2019-05-16 19:30:20 +03:00
_broadcasterService.Subscribe(_activityKey, (message) =>
2019-05-16 19:30:20 +03:00
{
if (message.Command == "startEventTimer")
2019-07-13 00:29:40 +03:00
{
StartEventAlarm();
}
else if (message.Command == "stopEventTimer")
2019-07-13 00:29:40 +03:00
{
var task = StopEventAlarmAsync();
}
else if (message.Command == "finishMainActivity")
2019-05-17 21:46:31 +03:00
{
2019-05-31 03:40:50 +03:00
Xamarin.Forms.Device.BeginInvokeOnMainThread(() => Finish());
2019-05-17 21:46:31 +03:00
}
else if (message.Command == "listenYubiKeyOTP")
2019-05-28 16:54:08 +03:00
{
ListenYubiKey((bool)message.Data);
}
else if (message.Command == "updatedTheme")
2019-05-29 22:50:20 +03:00
{
2019-05-30 06:02:30 +03:00
RestartApp();
2019-05-29 22:50:20 +03:00
}
else if (message.Command == "exit")
2019-05-30 07:29:00 +03:00
{
ExitApp();
}
else if (message.Command == "copiedToClipboard")
2019-05-30 18:22:35 +03:00
{
var task = ClearClipboardAlarmAsync(message.Data as Tuple<string, int?, bool>);
}
2019-05-16 19:30:20 +03:00
});
2019-03-28 03:12:44 +03:00
}
2019-03-28 06:44:54 +03:00
2019-05-28 16:54:08 +03:00
protected override void OnPause()
{
base.OnPause();
ListenYubiKey(false);
}
protected override void OnResume()
{
base.OnResume();
Xamarin.Essentials.Platform.OnResume();
if (_deviceActionService.SupportsNfc())
2019-05-28 16:54:08 +03:00
{
try
{
_messagingService.Send("resumeYubiKey");
}
catch { }
}
2020-02-10 22:07:06 +03:00
var setRestrictions = AndroidHelpers.SetPreconfiguredRestrictionSettingsAsync(this);
2019-05-28 16:54:08 +03:00
}
protected override void OnNewIntent(Intent intent)
{
base.OnNewIntent(intent);
try
{
if (intent.GetBooleanExtra("generatorTile", false))
2019-06-07 03:34:59 +03:00
{
_messagingService.Send("popAllAndGoToTabGenerator");
if (_appOptions != null)
{
_appOptions.GeneratorTile = true;
}
2019-06-07 03:34:59 +03:00
}
else if (intent.GetBooleanExtra("myVaultTile", false))
2019-06-07 03:34:59 +03:00
{
_messagingService.Send("popAllAndGoToTabMyVault");
if (_appOptions != null)
{
_appOptions.MyVaultTile = true;
}
2019-06-07 03:34:59 +03:00
}
else if (intent.Action == Intent.ActionSend && intent.Type != null)
{
if (_appOptions != null)
{
_appOptions.CreateSend = GetCreateSendRequest(intent);
}
_messagingService.Send("popAllAndGoToTabSend");
}
else
{
ParseYubiKey(intent.DataString);
}
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine(">>> {0}: {1}", e.GetType(), e.StackTrace);
}
2019-05-28 16:54:08 +03:00
}
2019-05-11 06:43:35 +03:00
public async override void OnRequestPermissionsResult(int requestCode, string[] permissions,
2019-03-28 06:44:54 +03:00
[GeneratedEnum] Permission[] grantResults)
{
if (requestCode == Constants.SelectFilePermissionRequestCode)
2019-05-11 06:43:35 +03:00
{
if (grantResults.Any(r => r != Permission.Granted))
2019-05-11 06:43:35 +03:00
{
_messagingService.Send("selectFileCameraPermissionDenied");
}
await _deviceActionService.SelectFileAsync();
}
else
{
Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);
PermissionsHandler.OnRequestPermissionsResult(requestCode, permissions, grantResults);
2019-05-11 06:43:35 +03:00
}
2019-03-28 06:44:54 +03:00
base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
}
2019-05-11 06:43:35 +03:00
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
if (resultCode == Result.Ok &&
(requestCode == Constants.SelectFileRequestCode || requestCode == Constants.SaveFileRequestCode))
2019-05-11 06:43:35 +03:00
{
Android.Net.Uri uri = null;
string fileName = null;
if (data != null && data.Data != null)
2019-05-11 06:43:35 +03:00
{
uri = data.Data;
fileName = AndroidHelpers.GetFileName(ApplicationContext, uri);
}
else
{
// camera
2019-06-25 18:54:31 +03:00
var file = new Java.IO.File(FilesDir, "temp_camera_photo.jpg");
uri = FileProvider.GetUriForFile(this, "com.x8bit.bitwarden.fileprovider", file);
2019-05-11 06:43:35 +03:00
fileName = $"photo_{DateTime.UtcNow.ToString("yyyyMMddHHmmss")}.jpg";
}
if (uri == null)
2019-05-11 06:43:35 +03:00
{
return;
}
if (requestCode == Constants.SaveFileRequestCode)
{
_messagingService.Send("selectSaveFileResult",
new Tuple<string, string>(uri.ToString(), fileName));
return;
}
2019-05-11 06:43:35 +03:00
try
{
using (var stream = ContentResolver.OpenInputStream(uri))
using (var memoryStream = new MemoryStream())
2019-05-11 06:43:35 +03:00
{
stream.CopyTo(memoryStream);
_messagingService.Send("selectFileResult",
new Tuple<byte[], string>(memoryStream.ToArray(), fileName ?? "unknown_file_name"));
}
}
catch (Java.IO.FileNotFoundException)
2019-05-11 06:43:35 +03:00
{
return;
}
}
}
2019-05-17 19:03:35 +03:00
protected override void OnDestroy()
{
base.OnDestroy();
_broadcasterService.Unsubscribe(_activityKey);
}
2019-05-17 19:03:35 +03:00
private void ListenYubiKey(bool listen)
{
if (!_deviceActionService.SupportsNfc())
2019-05-17 19:03:35 +03:00
{
return;
}
var adapter = NfcAdapter.GetDefaultAdapter(this);
if (listen)
2019-05-17 19:03:35 +03:00
{
var intent = new Intent(this, Class);
intent.AddFlags(ActivityFlags.SingleTop);
var pendingIntent = PendingIntent.GetActivity(this, 0, intent, 0);
// register for all NDEF tags starting with http och https
var ndef = new IntentFilter(NfcAdapter.ActionNdefDiscovered);
ndef.AddDataScheme("http");
ndef.AddDataScheme("https");
var filters = new IntentFilter[] { ndef };
try
{
// register for foreground dispatch so we'll receive tags according to our intent filters
adapter.EnableForegroundDispatch(this, pendingIntent, filters, null);
}
catch { }
}
else
{
2019-06-06 15:59:54 +03:00
try
{
adapter.DisableForegroundDispatch(this);
}
catch { }
2019-05-17 19:03:35 +03:00
}
}
private AppOptions GetOptions()
{
var options = new AppOptions
{
Uri = Intent.GetStringExtra("uri") ?? Intent.GetStringExtra("autofillFrameworkUri"),
MyVaultTile = Intent.GetBooleanExtra("myVaultTile", false),
GeneratorTile = Intent.GetBooleanExtra("generatorTile", false),
FromAutofillFramework = Intent.GetBooleanExtra("autofillFramework", false),
CreateSend = GetCreateSendRequest(Intent)
2019-05-17 19:03:35 +03:00
};
var fillType = Intent.GetIntExtra("autofillFrameworkFillType", 0);
if (fillType > 0)
2019-05-17 19:03:35 +03:00
{
options.FillType = (CipherType)fillType;
}
if (Intent.GetBooleanExtra("autofillFrameworkSave", false))
2019-05-17 19:03:35 +03:00
{
options.SaveType = (CipherType)Intent.GetIntExtra("autofillFrameworkType", 0);
options.SaveName = Intent.GetStringExtra("autofillFrameworkName");
options.SaveUsername = Intent.GetStringExtra("autofillFrameworkUsername");
options.SavePassword = Intent.GetStringExtra("autofillFrameworkPassword");
options.SaveCardName = Intent.GetStringExtra("autofillFrameworkCardName");
options.SaveCardNumber = Intent.GetStringExtra("autofillFrameworkCardNumber");
options.SaveCardExpMonth = Intent.GetStringExtra("autofillFrameworkCardExpMonth");
options.SaveCardExpYear = Intent.GetStringExtra("autofillFrameworkCardExpYear");
options.SaveCardCode = Intent.GetStringExtra("autofillFrameworkCardCode");
}
return options;
}
2019-05-28 16:54:08 +03:00
private Tuple<SendType, string, byte[], string> GetCreateSendRequest(Intent intent)
{
if (intent.Action == Intent.ActionSend && intent.Type != null)
{
if ((intent.Flags & ActivityFlags.LaunchedFromHistory) == ActivityFlags.LaunchedFromHistory)
{
// don't re-deliver intent if resuming from app switcher
return null;
}
var type = intent.Type;
if (type.Contains("text/"))
{
var subject = intent.GetStringExtra(Intent.ExtraSubject);
var text = intent.GetStringExtra(Intent.ExtraText);
return new Tuple<SendType, string, byte[], string>(SendType.Text, subject, null, text);
}
else
{
var data = intent.ClipData?.GetItemAt(0);
var uri = data?.Uri;
var filename = AndroidHelpers.GetFileName(ApplicationContext, uri);
try
{
using (var stream = ContentResolver.OpenInputStream(uri))
using (var memoryStream = new MemoryStream())
{
stream.CopyTo(memoryStream);
return new Tuple<SendType, string, byte[], string>(SendType.File, filename, memoryStream.ToArray(), null);
}
}
catch (Java.IO.FileNotFoundException) { }
}
}
return null;
}
2019-05-28 16:54:08 +03:00
private void ParseYubiKey(string data)
{
if (data == null)
2019-05-28 16:54:08 +03:00
{
return;
}
var otpMatch = _otpPattern.Matcher(data);
if (otpMatch.Matches())
2019-05-28 16:54:08 +03:00
{
var otp = otpMatch.Group(1);
_messagingService.Send("gotYubiKeyOTP", otp);
}
}
2019-05-29 22:50:20 +03:00
private void UpdateTheme(string theme)
{
if (theme == "light")
{
SetTheme(Resource.Style.LightTheme);
}
else if (theme == "dark")
2019-05-29 22:50:20 +03:00
{
SetTheme(Resource.Style.DarkTheme);
}
else if (theme == "black")
2019-06-02 06:59:17 +03:00
{
SetTheme(Resource.Style.BlackTheme);
}
else if (theme == "nord")
2019-06-05 18:36:58 +03:00
{
SetTheme(Resource.Style.NordTheme);
}
2019-05-29 22:50:20 +03:00
else
{
if (_deviceActionService.UsingDarkTheme())
{
SetTheme(Resource.Style.DarkTheme);
}
else
{
SetTheme(Resource.Style.LightTheme);
}
2019-05-29 22:50:20 +03:00
}
}
2019-05-30 06:02:30 +03:00
private void RestartApp()
{
2019-06-05 22:09:13 +03:00
var intent = new Intent(this, typeof(MainActivity));
2019-05-30 06:02:30 +03:00
var pendingIntent = PendingIntent.GetActivity(this, 5923650, intent, PendingIntentFlags.CancelCurrent);
var alarmManager = GetSystemService(AlarmService) as AlarmManager;
var triggerMs = Java.Lang.JavaSystem.CurrentTimeMillis() + 500;
alarmManager.Set(AlarmType.Rtc, triggerMs, pendingIntent);
Java.Lang.JavaSystem.Exit(0);
}
2019-05-30 07:29:00 +03:00
private void ExitApp()
{
FinishAffinity();
Java.Lang.JavaSystem.Exit(0);
}
2019-05-30 18:22:35 +03:00
private async Task ClearClipboardAlarmAsync(Tuple<string, int?, bool> data)
{
if (data.Item3)
2019-05-30 18:22:35 +03:00
{
return;
}
var clearMs = data.Item2;
if (clearMs == null)
2019-05-30 18:22:35 +03:00
{
var clearSeconds = await _storageService.GetAsync<int?>(Constants.ClearClipboardKey);
if (clearSeconds != null)
2019-05-30 18:22:35 +03:00
{
clearMs = clearSeconds.Value * 1000;
}
}
if (clearMs == null)
2019-05-30 18:22:35 +03:00
{
return;
}
var triggerMs = Java.Lang.JavaSystem.CurrentTimeMillis() + clearMs.Value;
var alarmManager = GetSystemService(AlarmService) as AlarmManager;
alarmManager.Set(AlarmType.Rtc, triggerMs, _clearClipboardPendingIntent);
}
2019-07-13 00:29:40 +03:00
private void StartEventAlarm()
{
var alarmManager = GetSystemService(AlarmService) as AlarmManager;
alarmManager.SetInexactRepeating(AlarmType.ElapsedRealtime, 120000, 300000, _eventUploadPendingIntent);
}
private async Task StopEventAlarmAsync()
{
var alarmManager = GetSystemService(AlarmService) as AlarmManager;
alarmManager.Cancel(_eventUploadPendingIntent);
await _eventService.UploadEventsAsync();
}
2019-03-28 03:12:44 +03:00
}
2019-03-28 06:44:54 +03:00
}