Changed all C# control flow block statements to include space between keyword and open paren (#800)

This commit is contained in:
Chad Scharf 2020-03-28 09:16:28 -04:00 committed by GitHub
parent 6c00ac43fc
commit 3c18fd7636
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
225 changed files with 2406 additions and 2406 deletions

View File

@ -35,7 +35,7 @@ namespace Bit.Droid.Accessibility
protected override void OnResume() protected override void OnResume()
{ {
base.OnResume(); base.OnResume();
if(!Intent.HasExtra("uri")) if (!Intent.HasExtra("uri"))
{ {
Finish(); Finish();
return; return;
@ -46,7 +46,7 @@ namespace Bit.Droid.Accessibility
protected override void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data) protected override void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data)
{ {
base.OnActivityResult(requestCode, resultCode, data); base.OnActivityResult(requestCode, resultCode, data);
if(data == null) if (data == null)
{ {
AccessibilityHelpers.LastCredentials = null; AccessibilityHelpers.LastCredentials = null;
} }
@ -54,7 +54,7 @@ namespace Bit.Droid.Accessibility
{ {
try try
{ {
if(data.GetStringExtra("canceled") != null) if (data.GetStringExtra("canceled") != null)
{ {
AccessibilityHelpers.LastCredentials = null; AccessibilityHelpers.LastCredentials = null;
} }
@ -82,7 +82,7 @@ namespace Bit.Droid.Accessibility
private void HandleIntent(Intent callingIntent, int requestCode) private void HandleIntent(Intent callingIntent, int requestCode)
{ {
if(callingIntent?.GetBooleanExtra("autofillTileClicked", false) ?? false) if (callingIntent?.GetBooleanExtra("autofillTileClicked", false) ?? false)
{ {
Intent.RemoveExtra("autofillTileClicked"); Intent.RemoveExtra("autofillTileClicked");
var messagingService = ServiceContainer.Resolve<IMessagingService>("messagingService"); var messagingService = ServiceContainer.Resolve<IMessagingService>("messagingService");
@ -98,20 +98,20 @@ namespace Bit.Droid.Accessibility
private void LaunchMainActivity(Intent callingIntent, int requestCode) private void LaunchMainActivity(Intent callingIntent, int requestCode)
{ {
_lastQueriedUri = callingIntent?.GetStringExtra("uri"); _lastQueriedUri = callingIntent?.GetStringExtra("uri");
if(_lastQueriedUri == null) if (_lastQueriedUri == null)
{ {
Finish(); Finish();
return; return;
} }
var now = DateTime.UtcNow; var now = DateTime.UtcNow;
if(_lastLaunch.HasValue && (now - _lastLaunch.Value) <= TimeSpan.FromSeconds(2)) if (_lastLaunch.HasValue && (now - _lastLaunch.Value) <= TimeSpan.FromSeconds(2))
{ {
return; return;
} }
_lastLaunch = now; _lastLaunch = now;
var intent = new Intent(this, typeof(MainActivity)); var intent = new Intent(this, typeof(MainActivity));
if(!callingIntent.Flags.HasFlag(ActivityFlags.LaunchedFromHistory)) if (!callingIntent.Flags.HasFlag(ActivityFlags.LaunchedFromHistory))
{ {
intent.PutExtra("uri", _lastQueriedUri); intent.PutExtra("uri", _lastQueriedUri);
} }

View File

@ -105,7 +105,7 @@ namespace Bit.Droid.Accessibility
{ {
var testNodes = GetWindowNodes(root, e, n => n.ViewIdResourceName != null && n.Text != null, false); var testNodes = GetWindowNodes(root, e, n => n.ViewIdResourceName != null && n.Text != null, false);
var testNodesData = testNodes.Select(n => new { id = n.ViewIdResourceName, text = n.Text }); var testNodesData = testNodes.Select(n => new { id = n.ViewIdResourceName, text = n.Text });
foreach(var node in testNodesData) foreach (var node in testNodesData)
{ {
System.Diagnostics.Debug.WriteLine("Node: {0} = {1}", node.id, node.text); System.Diagnostics.Debug.WriteLine("Node: {0} = {1}", node.id, node.text);
} }
@ -114,21 +114,21 @@ namespace Bit.Droid.Accessibility
public static string GetUri(AccessibilityNodeInfo root) public static string GetUri(AccessibilityNodeInfo root)
{ {
var uri = string.Concat(Constants.AndroidAppProtocol, root.PackageName); var uri = string.Concat(Constants.AndroidAppProtocol, root.PackageName);
if(SupportedBrowsers.ContainsKey(root.PackageName)) if (SupportedBrowsers.ContainsKey(root.PackageName))
{ {
var browser = SupportedBrowsers[root.PackageName]; var browser = SupportedBrowsers[root.PackageName];
AccessibilityNodeInfo addressNode = null; AccessibilityNodeInfo addressNode = null;
foreach(var uriViewId in browser.UriViewId.Split(",")) foreach (var uriViewId in browser.UriViewId.Split(","))
{ {
addressNode = root.FindAccessibilityNodeInfosByViewId( addressNode = root.FindAccessibilityNodeInfosByViewId(
$"{root.PackageName}:id/{uriViewId}").FirstOrDefault(); $"{root.PackageName}:id/{uriViewId}").FirstOrDefault();
if(addressNode != null) if (addressNode != null)
{ {
break; break;
} }
} }
if(addressNode != null) if (addressNode != null)
{ {
uri = ExtractUri(uri, addressNode, browser); uri = ExtractUri(uri, addressNode, browser);
addressNode.Recycle(); addressNode.Recycle();
@ -145,28 +145,28 @@ namespace Bit.Droid.Accessibility
public static string ExtractUri(string uri, AccessibilityNodeInfo addressNode, Browser browser) public static string ExtractUri(string uri, AccessibilityNodeInfo addressNode, Browser browser)
{ {
if(addressNode?.Text == null) if (addressNode?.Text == null)
{ {
return uri; return uri;
} }
if(addressNode.Text == null) if (addressNode.Text == null)
{ {
return uri; return uri;
} }
uri = browser.GetUriFunction(addressNode.Text)?.Trim(); uri = browser.GetUriFunction(addressNode.Text)?.Trim();
if(uri != null && uri.Contains(".")) if (uri != null && uri.Contains("."))
{ {
if(!uri.Contains("://") && !uri.Contains(" ")) if (!uri.Contains("://") && !uri.Contains(" "))
{ {
uri = string.Concat("http://", uri); uri = string.Concat("http://", uri);
} }
else if(Build.VERSION.SdkInt <= BuildVersionCodes.KitkatWatch) else if (Build.VERSION.SdkInt <= BuildVersionCodes.KitkatWatch)
{ {
var parts = uri.Split(new string[] { ". " }, StringSplitOptions.None); var parts = uri.Split(new string[] { ". " }, StringSplitOptions.None);
if(parts.Length > 1) if (parts.Length > 1)
{ {
var urlPart = parts.FirstOrDefault(p => p.StartsWith("http")); var urlPart = parts.FirstOrDefault(p => p.StartsWith("http"));
if(urlPart != null) if (urlPart != null)
{ {
uri = urlPart.Trim(); uri = urlPart.Trim();
} }
@ -181,11 +181,11 @@ namespace Bit.Droid.Accessibility
/// </summary> /// </summary>
public static bool NeedToAutofill(Credentials credentials, string currentUriString) public static bool NeedToAutofill(Credentials credentials, string currentUriString)
{ {
if(credentials == null) if (credentials == null)
{ {
return false; return false;
} }
if(Uri.TryCreate(credentials.LastUri, UriKind.Absolute, out Uri lastUri) && if (Uri.TryCreate(credentials.LastUri, UriKind.Absolute, out Uri lastUri) &&
Uri.TryCreate(currentUriString, UriKind.Absolute, out Uri currentUri)) Uri.TryCreate(currentUriString, UriKind.Absolute, out Uri currentUri))
{ {
return lastUri.Host == currentUri.Host; return lastUri.Host == currentUri.Host;
@ -202,7 +202,7 @@ namespace Bit.Droid.Accessibility
IEnumerable<AccessibilityNodeInfo> passwordNodes) IEnumerable<AccessibilityNodeInfo> passwordNodes)
{ {
FillEditText(usernameNode, LastCredentials?.Username); FillEditText(usernameNode, LastCredentials?.Username);
foreach(var n in passwordNodes) foreach (var n in passwordNodes)
{ {
FillEditText(n, LastCredentials?.Password); FillEditText(n, LastCredentials?.Password);
} }
@ -210,7 +210,7 @@ namespace Bit.Droid.Accessibility
public static void FillEditText(AccessibilityNodeInfo editTextNode, string value) public static void FillEditText(AccessibilityNodeInfo editTextNode, string value)
{ {
if(editTextNode == null || value == null) if (editTextNode == null || value == null)
{ {
return; return;
} }
@ -223,35 +223,35 @@ namespace Bit.Droid.Accessibility
Func<AccessibilityNodeInfo, bool> condition, bool disposeIfUnused, NodeList nodes = null, Func<AccessibilityNodeInfo, bool> condition, bool disposeIfUnused, NodeList nodes = null,
int recursionDepth = 0) int recursionDepth = 0)
{ {
if(nodes == null) if (nodes == null)
{ {
nodes = new NodeList(); nodes = new NodeList();
} }
var dispose = disposeIfUnused; var dispose = disposeIfUnused;
if(n != null && recursionDepth < 100) if (n != null && recursionDepth < 100)
{ {
var add = n.WindowId == e.WindowId && var add = n.WindowId == e.WindowId &&
!(n.ViewIdResourceName?.StartsWith(SystemUiPackage) ?? false) && !(n.ViewIdResourceName?.StartsWith(SystemUiPackage) ?? false) &&
condition(n); condition(n);
if(add) if (add)
{ {
dispose = false; dispose = false;
nodes.Add(n); nodes.Add(n);
} }
for(var i = 0; i < n.ChildCount; i++) for (var i = 0; i < n.ChildCount; i++)
{ {
var childNode = n.GetChild(i); var childNode = n.GetChild(i);
if(childNode == null) if (childNode == null)
{ {
continue; continue;
} }
else if(i > 100) else if (i > 100)
{ {
Android.Util.Log.Info(BitwardenTag, "Too many child iterations."); Android.Util.Log.Info(BitwardenTag, "Too many child iterations.");
break; break;
} }
else if(childNode.GetHashCode() == n.GetHashCode()) else if (childNode.GetHashCode() == n.GetHashCode())
{ {
Android.Util.Log.Info(BitwardenTag, "Child node is the same as parent for some reason."); Android.Util.Log.Info(BitwardenTag, "Child node is the same as parent for some reason.");
} }
@ -261,7 +261,7 @@ namespace Bit.Droid.Accessibility
} }
} }
} }
if(dispose) if (dispose)
{ {
n?.Recycle(); n?.Recycle();
n?.Dispose(); n?.Dispose();
@ -283,9 +283,9 @@ namespace Bit.Droid.Accessibility
IEnumerable<AccessibilityNodeInfo> allEditTexts) IEnumerable<AccessibilityNodeInfo> allEditTexts)
{ {
AccessibilityNodeInfo previousEditText = null; AccessibilityNodeInfo previousEditText = null;
foreach(var editText in allEditTexts) foreach (var editText in allEditTexts)
{ {
if(editText.Password) if (editText.Password)
{ {
return previousEditText; return previousEditText;
} }
@ -300,7 +300,7 @@ namespace Bit.Droid.Accessibility
var usernameEditText = GetUsernameEditTextIfPasswordExists(allEditTexts); var usernameEditText = GetUsernameEditTextIfPasswordExists(allEditTexts);
var isUsernameEditText = false; var isUsernameEditText = false;
if(usernameEditText != null) if (usernameEditText != null)
{ {
isUsernameEditText = IsSameNode(usernameEditText, e.Source); isUsernameEditText = IsSameNode(usernameEditText, e.Source);
} }
@ -311,7 +311,7 @@ namespace Bit.Droid.Accessibility
public static bool IsSameNode(AccessibilityNodeInfo node1, AccessibilityNodeInfo node2) public static bool IsSameNode(AccessibilityNodeInfo node1, AccessibilityNodeInfo node2)
{ {
if(node1 != null && node2 != null) if (node1 != null && node2 != null)
{ {
return node1.Equals(node2) || node1.GetHashCode() == node2.GetHashCode(); return node1.Equals(node2) || node1.GetHashCode() == node2.GetHashCode();
} }
@ -320,7 +320,7 @@ namespace Bit.Droid.Accessibility
public static bool OverlayPermitted() public static bool OverlayPermitted()
{ {
if(Build.VERSION.SdkInt >= BuildVersionCodes.M) if (Build.VERSION.SdkInt >= BuildVersionCodes.M)
{ {
return Settings.CanDrawOverlays(Android.App.Application.Context); return Settings.CanDrawOverlays(Android.App.Application.Context);
} }
@ -347,7 +347,7 @@ namespace Bit.Droid.Accessibility
public static WindowManagerLayoutParams GetOverlayLayoutParams() public static WindowManagerLayoutParams GetOverlayLayoutParams()
{ {
WindowManagerTypes windowManagerType; WindowManagerTypes windowManagerType;
if(Build.VERSION.SdkInt >= BuildVersionCodes.O) if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
{ {
windowManagerType = WindowManagerTypes.ApplicationOverlay; windowManagerType = WindowManagerTypes.ApplicationOverlay;
} }
@ -376,7 +376,7 @@ namespace Bit.Droid.Accessibility
var anchorViewY = isOverlayAboveAnchor ? anchorViewRect.Top : anchorViewRect.Bottom; var anchorViewY = isOverlayAboveAnchor ? anchorViewRect.Top : anchorViewRect.Bottom;
anchorViewRect.Dispose(); anchorViewRect.Dispose();
if(isOverlayAboveAnchor) if (isOverlayAboveAnchor)
{ {
anchorViewY -= overlayViewHeight; anchorViewY -= overlayViewHeight;
} }
@ -389,15 +389,15 @@ namespace Bit.Droid.Accessibility
IEnumerable<AccessibilityWindowInfo> windows, int overlayViewHeight, bool isOverlayAboveAnchor) IEnumerable<AccessibilityWindowInfo> windows, int overlayViewHeight, bool isOverlayAboveAnchor)
{ {
Point point = null; Point point = null;
if(anchorNode != null) if (anchorNode != null)
{ {
// Update node's info since this is still a reference from an older event // Update node's info since this is still a reference from an older event
anchorNode.Refresh(); anchorNode.Refresh();
if(!anchorNode.VisibleToUser) if (!anchorNode.VisibleToUser)
{ {
return new Point(-1, -1); return new Point(-1, -1);
} }
if(!anchorNode.Focused) if (!anchorNode.Focused)
{ {
return null; return null;
} }
@ -406,9 +406,9 @@ namespace Bit.Droid.Accessibility
// of visibility // of visibility
var minY = 0; var minY = 0;
int maxY; int maxY;
if(windows != null) if (windows != null)
{ {
if(IsStatusBarExpanded(windows)) if (IsStatusBarExpanded(windows))
{ {
return new Point(-1, -1); return new Point(-1, -1);
} }
@ -417,7 +417,7 @@ namespace Bit.Droid.Accessibility
else else
{ {
var rootNodeHeight = GetNodeHeight(root); var rootNodeHeight = GetNodeHeight(root);
if(rootNodeHeight == -1) if (rootNodeHeight == -1)
{ {
return null; return null;
} }
@ -425,9 +425,9 @@ namespace Bit.Droid.Accessibility
} }
point = GetOverlayAnchorPosition(anchorNode, overlayViewHeight, isOverlayAboveAnchor); point = GetOverlayAnchorPosition(anchorNode, overlayViewHeight, isOverlayAboveAnchor);
if(point.Y < minY) if (point.Y < minY)
{ {
if(isOverlayAboveAnchor) if (isOverlayAboveAnchor)
{ {
// view nearing bounds, anchor to bottom // view nearing bounds, anchor to bottom
point.X = -1; point.X = -1;
@ -440,9 +440,9 @@ namespace Bit.Droid.Accessibility
point.Y = -1; point.Y = -1;
} }
} }
else if(point.Y > maxY) else if (point.Y > maxY)
{ {
if(isOverlayAboveAnchor) if (isOverlayAboveAnchor)
{ {
// view out of bounds, hide overlay // view out of bounds, hide overlay
point.X = -1; point.X = -1;
@ -455,7 +455,7 @@ namespace Bit.Droid.Accessibility
point.Y = -1; point.Y = -1;
} }
} }
else if(isOverlayAboveAnchor && point.Y < (maxY - overlayViewHeight - GetNodeHeight(anchorNode))) else if (isOverlayAboveAnchor && point.Y < (maxY - overlayViewHeight - GetNodeHeight(anchorNode)))
{ {
// This else block forces the overlay to return to bottom alignment as soon as space is available // This else block forces the overlay to return to bottom alignment as soon as space is available
// below the anchor view. Removing this will change the behavior to wait until there isn't enough // below the anchor view. Removing this will change the behavior to wait until there isn't enough
@ -469,12 +469,12 @@ namespace Bit.Droid.Accessibility
public static bool IsStatusBarExpanded(IEnumerable<AccessibilityWindowInfo> windows) public static bool IsStatusBarExpanded(IEnumerable<AccessibilityWindowInfo> windows)
{ {
if(windows != null && windows.Any()) if (windows != null && windows.Any())
{ {
var isSystemWindowsOnly = true; var isSystemWindowsOnly = true;
foreach(var window in windows) foreach (var window in windows)
{ {
if(window.Type != AccessibilityWindowType.System) if (window.Type != AccessibilityWindowType.System)
{ {
isSystemWindowsOnly = false; isSystemWindowsOnly = false;
break; break;
@ -489,13 +489,13 @@ namespace Bit.Droid.Accessibility
{ {
var appWindowHeight = 0; var appWindowHeight = 0;
var nonAppWindowHeight = 0; var nonAppWindowHeight = 0;
if(windows != null) if (windows != null)
{ {
foreach(var window in windows) foreach (var window in windows)
{ {
var windowRect = new Rect(); var windowRect = new Rect();
window.GetBoundsInScreen(windowRect); window.GetBoundsInScreen(windowRect);
if(window.Type == AccessibilityWindowType.Application) if (window.Type == AccessibilityWindowType.Application)
{ {
appWindowHeight += windowRect.Height(); appWindowHeight += windowRect.Height();
} }
@ -510,7 +510,7 @@ namespace Bit.Droid.Accessibility
public static int GetNodeHeight(AccessibilityNodeInfo node) public static int GetNodeHeight(AccessibilityNodeInfo node)
{ {
if(node == null) if (node == null)
{ {
return -1; return -1;
} }
@ -536,7 +536,7 @@ namespace Bit.Droid.Accessibility
var activity = (MainActivity)CrossCurrentActivity.Current.Activity; var activity = (MainActivity)CrossCurrentActivity.Current.Activity;
var barHeight = 0; var barHeight = 0;
var resourceId = activity.Resources.GetIdentifier(resName, "dimen", "android"); var resourceId = activity.Resources.GetIdentifier(resName, "dimen", "android");
if(resourceId > 0) if (resourceId > 0)
{ {
barHeight = activity.Resources.GetDimensionPixelSize(resourceId); barHeight = activity.Resources.GetDimensionPixelSize(resourceId);
} }

View File

@ -56,7 +56,7 @@ namespace Bit.Droid.Accessibility
var settingsTask = LoadSettingsAsync(); var settingsTask = LoadSettingsAsync();
_broadcasterService.Subscribe(nameof(AccessibilityService), (message) => _broadcasterService.Subscribe(nameof(AccessibilityService), (message) =>
{ {
if(message.Command == "OnAutofillTileClick") if (message.Command == "OnAutofillTileClick")
{ {
var runnable = new Java.Lang.Runnable(OnAutofillTileClick); var runnable = new Java.Lang.Runnable(OnAutofillTileClick);
_handler.PostDelayed(runnable, 250); _handler.PostDelayed(runnable, 250);
@ -76,18 +76,18 @@ namespace Bit.Droid.Accessibility
try try
{ {
var powerManager = GetSystemService(PowerService) as PowerManager; var powerManager = GetSystemService(PowerService) as PowerManager;
if(Build.VERSION.SdkInt > BuildVersionCodes.KitkatWatch && !powerManager.IsInteractive) if (Build.VERSION.SdkInt > BuildVersionCodes.KitkatWatch && !powerManager.IsInteractive)
{ {
return; return;
} }
else if(Build.VERSION.SdkInt < BuildVersionCodes.Lollipop && !powerManager.IsScreenOn) else if (Build.VERSION.SdkInt < BuildVersionCodes.Lollipop && !powerManager.IsScreenOn)
{ {
return; return;
} }
if(SkipPackage(e?.PackageName)) if (SkipPackage(e?.PackageName))
{ {
if(e?.PackageName != "com.android.systemui") if (e?.PackageName != "com.android.systemui")
{ {
CancelOverlayPrompt(); CancelOverlayPrompt();
} }
@ -100,28 +100,28 @@ namespace Bit.Droid.Accessibility
var settingsTask = LoadSettingsAsync(); var settingsTask = LoadSettingsAsync();
AccessibilityNodeInfo root = null; AccessibilityNodeInfo root = null;
switch(e.EventType) switch (e.EventType)
{ {
case EventTypes.ViewFocused: case EventTypes.ViewFocused:
case EventTypes.ViewClicked: case EventTypes.ViewClicked:
if(e.Source == null || e.PackageName == BitwardenPackage) if (e.Source == null || e.PackageName == BitwardenPackage)
{ {
CancelOverlayPrompt(); CancelOverlayPrompt();
break; break;
} }
root = RootInActiveWindow; root = RootInActiveWindow;
if(root == null || root.PackageName != e.PackageName) if (root == null || root.PackageName != e.PackageName)
{ {
break; break;
} }
if(!(e.Source?.Password ?? false) && !AccessibilityHelpers.IsUsernameEditText(root, e)) if (!(e.Source?.Password ?? false) && !AccessibilityHelpers.IsUsernameEditText(root, e))
{ {
CancelOverlayPrompt(); CancelOverlayPrompt();
break; break;
} }
if(ScanAndAutofill(root, e)) if (ScanAndAutofill(root, e))
{ {
CancelOverlayPrompt(); CancelOverlayPrompt();
} }
@ -132,22 +132,22 @@ namespace Bit.Droid.Accessibility
break; break;
case EventTypes.WindowContentChanged: case EventTypes.WindowContentChanged:
case EventTypes.WindowStateChanged: case EventTypes.WindowStateChanged:
if(AccessibilityHelpers.LastCredentials == null) if (AccessibilityHelpers.LastCredentials == null)
{ {
break; break;
} }
if(e.PackageName == BitwardenPackage) if (e.PackageName == BitwardenPackage)
{ {
CancelOverlayPrompt(); CancelOverlayPrompt();
break; break;
} }
root = RootInActiveWindow; root = RootInActiveWindow;
if(root == null || root.PackageName != e.PackageName) if (root == null || root.PackageName != e.PackageName)
{ {
break; break;
} }
if(ScanAndAutofill(root, e)) if (ScanAndAutofill(root, e))
{ {
CancelOverlayPrompt(); CancelOverlayPrompt();
} }
@ -157,7 +157,7 @@ namespace Bit.Droid.Accessibility
} }
} }
// Suppress exceptions so that service doesn't crash. // Suppress exceptions so that service doesn't crash.
catch(Exception ex) catch (Exception ex)
{ {
System.Diagnostics.Debug.WriteLine(">>> {0}: {1}", ex.GetType(), ex.StackTrace); System.Diagnostics.Debug.WriteLine(">>> {0}: {1}", ex.GetType(), ex.StackTrace);
} }
@ -172,12 +172,12 @@ namespace Bit.Droid.Accessibility
{ {
var filled = false; var filled = false;
var passwordNodes = AccessibilityHelpers.GetWindowNodes(root, e, n => n.Password, false); var passwordNodes = AccessibilityHelpers.GetWindowNodes(root, e, n => n.Password, false);
if(passwordNodes.Count > 0) if (passwordNodes.Count > 0)
{ {
var uri = AccessibilityHelpers.GetUri(root); var uri = AccessibilityHelpers.GetUri(root);
if(uri != null && !uri.Contains(BitwardenWebsite)) if (uri != null && !uri.Contains(BitwardenWebsite))
{ {
if(AccessibilityHelpers.NeedToAutofill(AccessibilityHelpers.LastCredentials, uri)) if (AccessibilityHelpers.NeedToAutofill(AccessibilityHelpers.LastCredentials, uri))
{ {
AccessibilityHelpers.GetNodesAndFill(root, e, passwordNodes); AccessibilityHelpers.GetNodesAndFill(root, e, passwordNodes);
filled = true; filled = true;
@ -186,7 +186,7 @@ namespace Bit.Droid.Accessibility
} }
AccessibilityHelpers.LastCredentials = null; AccessibilityHelpers.LastCredentials = null;
} }
else if(AccessibilityHelpers.LastCredentials != null) else if (AccessibilityHelpers.LastCredentials != null)
{ {
Task.Run(async () => Task.Run(async () =>
{ {
@ -203,12 +203,12 @@ namespace Bit.Droid.Accessibility
CancelOverlayPrompt(); CancelOverlayPrompt();
var root = RootInActiveWindow; var root = RootInActiveWindow;
if(root != null && root.PackageName != BitwardenPackage && if (root != null && root.PackageName != BitwardenPackage &&
root.PackageName != AccessibilityHelpers.SystemUiPackage && root.PackageName != AccessibilityHelpers.SystemUiPackage &&
!SkipPackage(root.PackageName)) !SkipPackage(root.PackageName))
{ {
var uri = AccessibilityHelpers.GetUri(root); var uri = AccessibilityHelpers.GetUri(root);
if(!string.IsNullOrWhiteSpace(uri)) if (!string.IsNullOrWhiteSpace(uri))
{ {
var intent = new Intent(this, typeof(AccessibilityActivity)); var intent = new Intent(this, typeof(AccessibilityActivity));
intent.PutExtra("uri", uri); intent.PutExtra("uri", uri);
@ -225,7 +225,7 @@ namespace Bit.Droid.Accessibility
{ {
_overlayAnchorObserverRunning = false; _overlayAnchorObserverRunning = false;
if(_windowManager != null && _overlayView != null) if (_windowManager != null && _overlayView != null)
{ {
try try
{ {
@ -240,7 +240,7 @@ namespace Bit.Droid.Accessibility
_lastAnchorY = 0; _lastAnchorY = 0;
_isOverlayAboveAnchor = false; _isOverlayAboveAnchor = false;
if(_anchorNode != null) if (_anchorNode != null)
{ {
_anchorNode.Recycle(); _anchorNode.Recycle();
_anchorNode = null; _anchorNode = null;
@ -249,9 +249,9 @@ namespace Bit.Droid.Accessibility
private void OverlayPromptToAutofill(AccessibilityNodeInfo root, AccessibilityEvent e) private void OverlayPromptToAutofill(AccessibilityNodeInfo root, AccessibilityEvent e)
{ {
if(!AccessibilityHelpers.OverlayPermitted()) if (!AccessibilityHelpers.OverlayPermitted())
{ {
if(!AccessibilityHelpers.IsAutofillTileAdded) if (!AccessibilityHelpers.IsAutofillTileAdded)
{ {
// The user has the option of only using the autofill tile and leaving the overlay permission // The user has the option of only using the autofill tile and leaving the overlay permission
// disabled, so only show this toast if they're using accessibility without overlay permission and // disabled, so only show this toast if they're using accessibility without overlay permission and
@ -262,23 +262,23 @@ namespace Bit.Droid.Accessibility
return; return;
} }
if(_overlayView != null || _anchorNode != null || _overlayAnchorObserverRunning) if (_overlayView != null || _anchorNode != null || _overlayAnchorObserverRunning)
{ {
CancelOverlayPrompt(); CancelOverlayPrompt();
} }
if(Java.Lang.JavaSystem.CurrentTimeMillis() - _lastAutoFillTime < 1000) if (Java.Lang.JavaSystem.CurrentTimeMillis() - _lastAutoFillTime < 1000)
{ {
return; return;
} }
var uri = AccessibilityHelpers.GetUri(root); var uri = AccessibilityHelpers.GetUri(root);
var fillable = !string.IsNullOrWhiteSpace(uri); var fillable = !string.IsNullOrWhiteSpace(uri);
if(fillable) if (fillable)
{ {
if(_blacklistedUris != null && _blacklistedUris.Any()) if (_blacklistedUris != null && _blacklistedUris.Any())
{ {
if(Uri.TryCreate(uri, UriKind.Absolute, out var parsedUri) && parsedUri.Scheme.StartsWith("http")) if (Uri.TryCreate(uri, UriKind.Absolute, out var parsedUri) && parsedUri.Scheme.StartsWith("http"))
{ {
fillable = !_blacklistedUris.Contains( fillable = !_blacklistedUris.Contains(
string.Format("{0}://{1}", parsedUri.Scheme, parsedUri.Host)); string.Format("{0}://{1}", parsedUri.Scheme, parsedUri.Host));
@ -289,7 +289,7 @@ namespace Bit.Droid.Accessibility
} }
} }
} }
if(!fillable) if (!fillable)
{ {
return; return;
} }
@ -314,7 +314,7 @@ namespace Bit.Droid.Accessibility
layoutParams.X = anchorPosition.X; layoutParams.X = anchorPosition.X;
layoutParams.Y = anchorPosition.Y; layoutParams.Y = anchorPosition.Y;
if(_windowManager == null) if (_windowManager == null)
{ {
_windowManager = GetSystemService(WindowService).JavaCast<IWindowManager>(); _windowManager = GetSystemService(WindowService).JavaCast<IWindowManager>();
} }
@ -333,7 +333,7 @@ namespace Bit.Droid.Accessibility
private void StartOverlayAnchorObserver() private void StartOverlayAnchorObserver()
{ {
if(_overlayAnchorObserverRunning) if (_overlayAnchorObserverRunning)
{ {
return; return;
} }
@ -341,7 +341,7 @@ namespace Bit.Droid.Accessibility
_overlayAnchorObserverRunning = true; _overlayAnchorObserverRunning = true;
_overlayAnchorObserverRunnable = new Java.Lang.Runnable(() => _overlayAnchorObserverRunnable = new Java.Lang.Runnable(() =>
{ {
if(_overlayAnchorObserverRunning) if (_overlayAnchorObserverRunning)
{ {
AdjustOverlayForScroll(); AdjustOverlayForScroll();
_handler.PostDelayed(_overlayAnchorObserverRunnable, 250); _handler.PostDelayed(_overlayAnchorObserverRunnable, 250);
@ -353,7 +353,7 @@ namespace Bit.Droid.Accessibility
private void AdjustOverlayForScroll() private void AdjustOverlayForScroll()
{ {
if(_overlayView == null || _anchorNode == null) if (_overlayView == null || _anchorNode == null)
{ {
CancelOverlayPrompt(); CancelOverlayPrompt();
return; return;
@ -361,42 +361,42 @@ namespace Bit.Droid.Accessibility
var root = RootInActiveWindow; var root = RootInActiveWindow;
IEnumerable<AccessibilityWindowInfo> windows = null; IEnumerable<AccessibilityWindowInfo> windows = null;
if(Build.VERSION.SdkInt > BuildVersionCodes.Kitkat) if (Build.VERSION.SdkInt > BuildVersionCodes.Kitkat)
{ {
windows = Windows; windows = Windows;
} }
var anchorPosition = AccessibilityHelpers.GetOverlayAnchorPosition(_anchorNode, root, windows, var anchorPosition = AccessibilityHelpers.GetOverlayAnchorPosition(_anchorNode, root, windows,
_overlayViewHeight, _isOverlayAboveAnchor); _overlayViewHeight, _isOverlayAboveAnchor);
if(anchorPosition == null) if (anchorPosition == null)
{ {
CancelOverlayPrompt(); CancelOverlayPrompt();
return; return;
} }
else if(anchorPosition.X == -1 && anchorPosition.Y == -1) else if (anchorPosition.X == -1 && anchorPosition.Y == -1)
{ {
if(_overlayView.Visibility != ViewStates.Gone) if (_overlayView.Visibility != ViewStates.Gone)
{ {
_overlayView.Visibility = ViewStates.Gone; _overlayView.Visibility = ViewStates.Gone;
System.Diagnostics.Debug.WriteLine(">>> Accessibility Overlay View Hidden"); System.Diagnostics.Debug.WriteLine(">>> Accessibility Overlay View Hidden");
} }
return; return;
} }
else if(anchorPosition.X == -1) else if (anchorPosition.X == -1)
{ {
_isOverlayAboveAnchor = false; _isOverlayAboveAnchor = false;
System.Diagnostics.Debug.WriteLine(">>> Accessibility Overlay View Below Anchor"); System.Diagnostics.Debug.WriteLine(">>> Accessibility Overlay View Below Anchor");
return; return;
} }
else if(anchorPosition.Y == -1) else if (anchorPosition.Y == -1)
{ {
_isOverlayAboveAnchor = true; _isOverlayAboveAnchor = true;
System.Diagnostics.Debug.WriteLine(">>> Accessibility Overlay View Above Anchor"); System.Diagnostics.Debug.WriteLine(">>> Accessibility Overlay View Above Anchor");
return; return;
} }
else if(anchorPosition.X == _lastAnchorX && anchorPosition.Y == _lastAnchorY) else if (anchorPosition.X == _lastAnchorX && anchorPosition.Y == _lastAnchorY)
{ {
if(_overlayView.Visibility != ViewStates.Visible) if (_overlayView.Visibility != ViewStates.Visible)
{ {
_overlayView.Visibility = ViewStates.Visible; _overlayView.Visibility = ViewStates.Visible;
} }
@ -412,7 +412,7 @@ namespace Bit.Droid.Accessibility
_windowManager.UpdateViewLayout(_overlayView, layoutParams); _windowManager.UpdateViewLayout(_overlayView, layoutParams);
if(_overlayView.Visibility != ViewStates.Visible) if (_overlayView.Visibility != ViewStates.Visible)
{ {
_overlayView.Visibility = ViewStates.Visible; _overlayView.Visibility = ViewStates.Visible;
} }
@ -423,13 +423,13 @@ namespace Bit.Droid.Accessibility
private bool SkipPackage(string eventPackageName) private bool SkipPackage(string eventPackageName)
{ {
if(string.IsNullOrWhiteSpace(eventPackageName) || if (string.IsNullOrWhiteSpace(eventPackageName) ||
AccessibilityHelpers.FilteredPackageNames.Contains(eventPackageName) || AccessibilityHelpers.FilteredPackageNames.Contains(eventPackageName) ||
eventPackageName.Contains("launcher")) eventPackageName.Contains("launcher"))
{ {
return true; return true;
} }
if(_launcherPackageNames == null || _lastLauncherSetBuilt == null || if (_launcherPackageNames == null || _lastLauncherSetBuilt == null ||
(DateTime.Now - _lastLauncherSetBuilt.Value) > _rebuildLauncherSpan) (DateTime.Now - _lastLauncherSetBuilt.Value) > _rebuildLauncherSpan)
{ {
// refresh launcher list every now and then // refresh launcher list every now and then
@ -444,11 +444,11 @@ namespace Bit.Droid.Accessibility
private void LoadServices() private void LoadServices()
{ {
if(_storageService == null) if (_storageService == null)
{ {
_storageService = ServiceContainer.Resolve<IStorageService>("storageService"); _storageService = ServiceContainer.Resolve<IStorageService>("storageService");
} }
if(_broadcasterService == null) if (_broadcasterService == null)
{ {
_broadcasterService = ServiceContainer.Resolve<IBroadcasterService>("broadcasterService"); _broadcasterService = ServiceContainer.Resolve<IBroadcasterService>("broadcasterService");
} }
@ -457,11 +457,11 @@ namespace Bit.Droid.Accessibility
private async Task LoadSettingsAsync() private async Task LoadSettingsAsync()
{ {
var now = DateTime.UtcNow; var now = DateTime.UtcNow;
if(_lastSettingsReload == null || (now - _lastSettingsReload.Value) > _settingsReloadSpan) if (_lastSettingsReload == null || (now - _lastSettingsReload.Value) > _settingsReloadSpan)
{ {
_lastSettingsReload = now; _lastSettingsReload = now;
var uris = await _storageService.GetAsync<List<string>>(Constants.AutofillBlacklistedUrisKey); var uris = await _storageService.GetAsync<List<string>>(Constants.AutofillBlacklistedUrisKey);
if(uris != null) if (uris != null)
{ {
_blacklistedUris = new HashSet<string>(uris); _blacklistedUris = new HashSet<string>(uris);
} }

View File

@ -8,7 +8,7 @@ namespace Bit.Droid.Accessibility
{ {
public void Dispose() public void Dispose()
{ {
foreach(var item in this) foreach (var item in this)
{ {
item.Recycle(); item.Recycle();
item.Dispose(); item.Dispose();

View File

@ -75,17 +75,17 @@ namespace Bit.Droid.Autofill
public static async Task<List<FilledItem>> GetFillItemsAsync(Parser parser, ICipherService cipherService) public static async Task<List<FilledItem>> GetFillItemsAsync(Parser parser, ICipherService cipherService)
{ {
if(parser.FieldCollection.FillableForLogin) if (parser.FieldCollection.FillableForLogin)
{ {
var ciphers = await cipherService.GetAllDecryptedByUrlAsync(parser.Uri); var ciphers = await cipherService.GetAllDecryptedByUrlAsync(parser.Uri);
if(ciphers.Item1.Any() || ciphers.Item2.Any()) if (ciphers.Item1.Any() || ciphers.Item2.Any())
{ {
var allCiphers = ciphers.Item1.ToList(); var allCiphers = ciphers.Item1.ToList();
allCiphers.AddRange(ciphers.Item2.ToList()); allCiphers.AddRange(ciphers.Item2.ToList());
return allCiphers.Select(c => new FilledItem(c)).ToList(); return allCiphers.Select(c => new FilledItem(c)).ToList();
} }
} }
else if(parser.FieldCollection.FillableForCard) else if (parser.FieldCollection.FillableForCard)
{ {
var ciphers = await cipherService.GetAllDecryptedAsync(); var ciphers = await cipherService.GetAllDecryptedAsync();
return ciphers.Where(c => c.Type == CipherType.Card).Select(c => new FilledItem(c)).ToList(); return ciphers.Where(c => c.Type == CipherType.Card).Select(c => new FilledItem(c)).ToList();
@ -96,12 +96,12 @@ namespace Bit.Droid.Autofill
public static FillResponse BuildFillResponse(Parser parser, List<FilledItem> items, bool locked) public static FillResponse BuildFillResponse(Parser parser, List<FilledItem> items, bool locked)
{ {
var responseBuilder = new FillResponse.Builder(); var responseBuilder = new FillResponse.Builder();
if(items != null && items.Count > 0) if (items != null && items.Count > 0)
{ {
foreach(var item in items) foreach (var item in items)
{ {
var dataset = BuildDataset(parser.ApplicationContext, parser.FieldCollection, item); var dataset = BuildDataset(parser.ApplicationContext, parser.FieldCollection, item);
if(dataset != null) if (dataset != null)
{ {
responseBuilder.AddDataset(dataset); responseBuilder.AddDataset(dataset);
} }
@ -118,7 +118,7 @@ namespace Bit.Droid.Autofill
{ {
var datasetBuilder = new Dataset.Builder( var datasetBuilder = new Dataset.Builder(
BuildListView(filledItem.Name, filledItem.Subtitle, filledItem.Icon, context)); BuildListView(filledItem.Name, filledItem.Subtitle, filledItem.Icon, context));
if(filledItem.ApplyToFields(fields, datasetBuilder)) if (filledItem.ApplyToFields(fields, datasetBuilder))
{ {
return datasetBuilder.Build(); return datasetBuilder.Build();
} }
@ -129,15 +129,15 @@ namespace Bit.Droid.Autofill
{ {
var intent = new Intent(context, typeof(MainActivity)); var intent = new Intent(context, typeof(MainActivity));
intent.PutExtra("autofillFramework", true); intent.PutExtra("autofillFramework", true);
if(fields.FillableForLogin) if (fields.FillableForLogin)
{ {
intent.PutExtra("autofillFrameworkFillType", (int)CipherType.Login); intent.PutExtra("autofillFrameworkFillType", (int)CipherType.Login);
} }
else if(fields.FillableForCard) else if (fields.FillableForCard)
{ {
intent.PutExtra("autofillFrameworkFillType", (int)CipherType.Card); intent.PutExtra("autofillFrameworkFillType", (int)CipherType.Card);
} }
else if(fields.FillableForIdentity) else if (fields.FillableForIdentity)
{ {
intent.PutExtra("autofillFrameworkFillType", (int)CipherType.Identity); intent.PutExtra("autofillFrameworkFillType", (int)CipherType.Identity);
} }
@ -159,7 +159,7 @@ namespace Bit.Droid.Autofill
datasetBuilder.SetAuthentication(pendingIntent.IntentSender); datasetBuilder.SetAuthentication(pendingIntent.IntentSender);
// Dataset must have a value set. We will reset this in the main activity when the real item is chosen. // Dataset must have a value set. We will reset this in the main activity when the real item is chosen.
foreach(var autofillId in fields.AutofillIds) foreach (var autofillId in fields.AutofillIds)
{ {
datasetBuilder.SetValue(autofillId, AutofillValue.ForText("PLACEHOLDER")); datasetBuilder.SetValue(autofillId, AutofillValue.ForText("PLACEHOLDER"));
} }
@ -181,24 +181,24 @@ namespace Bit.Droid.Autofill
// Docs state that password fields cannot be reliably saved in Compat mode since they will show as // Docs state that password fields cannot be reliably saved in Compat mode since they will show as
// masked values. // masked values.
var compatBrowser = CompatBrowsers.Contains(parser.PackageName); var compatBrowser = CompatBrowsers.Contains(parser.PackageName);
if(compatBrowser && fields.SaveType == SaveDataType.Password) if (compatBrowser && fields.SaveType == SaveDataType.Password)
{ {
return; return;
} }
var requiredIds = fields.GetRequiredSaveFields(); var requiredIds = fields.GetRequiredSaveFields();
if(fields.SaveType == SaveDataType.Generic || requiredIds.Length == 0) if (fields.SaveType == SaveDataType.Generic || requiredIds.Length == 0)
{ {
return; return;
} }
var saveBuilder = new SaveInfo.Builder(fields.SaveType, requiredIds); var saveBuilder = new SaveInfo.Builder(fields.SaveType, requiredIds);
var optionalIds = fields.GetOptionalSaveIds(); var optionalIds = fields.GetOptionalSaveIds();
if(optionalIds.Length > 0) if (optionalIds.Length > 0)
{ {
saveBuilder.SetOptionalIds(optionalIds); saveBuilder.SetOptionalIds(optionalIds);
} }
if(compatBrowser) if (compatBrowser)
{ {
saveBuilder.SetFlags(SaveFlags.SaveOnAllViewsInvisible); saveBuilder.SetFlags(SaveFlags.SaveOnAllViewsInvisible);
} }

View File

@ -28,7 +28,7 @@ namespace Bit.Droid.Autofill
FillCallback callback) FillCallback callback)
{ {
var structure = request.FillContexts?.LastOrDefault()?.Structure; var structure = request.FillContexts?.LastOrDefault()?.Structure;
if(structure == null) if (structure == null)
{ {
return; return;
} }
@ -36,27 +36,27 @@ namespace Bit.Droid.Autofill
var parser = new Parser(structure, ApplicationContext); var parser = new Parser(structure, ApplicationContext);
parser.Parse(); parser.Parse();
if(_storageService == null) if (_storageService == null)
{ {
_storageService = ServiceContainer.Resolve<IStorageService>("storageService"); _storageService = ServiceContainer.Resolve<IStorageService>("storageService");
} }
var shouldAutofill = await parser.ShouldAutofillAsync(_storageService); var shouldAutofill = await parser.ShouldAutofillAsync(_storageService);
if(!shouldAutofill) if (!shouldAutofill)
{ {
return; return;
} }
if(_lockService == null) if (_lockService == null)
{ {
_lockService = ServiceContainer.Resolve<ILockService>("lockService"); _lockService = ServiceContainer.Resolve<ILockService>("lockService");
} }
List<FilledItem> items = null; List<FilledItem> items = null;
var locked = await _lockService.IsLockedAsync(); var locked = await _lockService.IsLockedAsync();
if(!locked) if (!locked)
{ {
if(_cipherService == null) if (_cipherService == null)
{ {
_cipherService = ServiceContainer.Resolve<ICipherService>("cipherService"); _cipherService = ServiceContainer.Resolve<ICipherService>("cipherService");
} }
@ -71,18 +71,18 @@ namespace Bit.Droid.Autofill
public async override void OnSaveRequest(SaveRequest request, SaveCallback callback) public async override void OnSaveRequest(SaveRequest request, SaveCallback callback)
{ {
var structure = request.FillContexts?.LastOrDefault()?.Structure; var structure = request.FillContexts?.LastOrDefault()?.Structure;
if(structure == null) if (structure == null)
{ {
return; return;
} }
if(_storageService == null) if (_storageService == null)
{ {
_storageService = ServiceContainer.Resolve<IStorageService>("storageService"); _storageService = ServiceContainer.Resolve<IStorageService>("storageService");
} }
var disableSavePrompt = await _storageService.GetAsync<bool?>(Constants.AutofillDisableSavePromptKey); var disableSavePrompt = await _storageService.GetAsync<bool?>(Constants.AutofillDisableSavePromptKey);
if(disableSavePrompt.GetValueOrDefault()) if (disableSavePrompt.GetValueOrDefault())
{ {
return; return;
} }
@ -91,7 +91,7 @@ namespace Bit.Droid.Autofill
parser.Parse(); parser.Parse();
var savedItem = parser.FieldCollection.GetSavedItem(); var savedItem = parser.FieldCollection.GetSavedItem();
if(savedItem == null) if (savedItem == null)
{ {
Toast.MakeText(this, "Unable to save this form.", ToastLength.Short).Show(); Toast.MakeText(this, "Unable to save this form.", ToastLength.Short).Show();
return; return;
@ -102,7 +102,7 @@ namespace Bit.Droid.Autofill
intent.PutExtra("autofillFramework", true); intent.PutExtra("autofillFramework", true);
intent.PutExtra("autofillFrameworkSave", true); intent.PutExtra("autofillFrameworkSave", true);
intent.PutExtra("autofillFrameworkType", (int)savedItem.Type); intent.PutExtra("autofillFrameworkType", (int)savedItem.Type);
switch(savedItem.Type) switch (savedItem.Type)
{ {
case CipherType.Login: case CipherType.Login:
intent.PutExtra("autofillFrameworkName", parser.Uri intent.PutExtra("autofillFrameworkName", parser.Uri

View File

@ -31,26 +31,26 @@ namespace Bit.Droid.Autofill
HtmlInfo = node.HtmlInfo; HtmlInfo = node.HtmlInfo;
Node = node; Node = node;
if(node.AutofillValue != null) if (node.AutofillValue != null)
{ {
if(node.AutofillValue.IsList) if (node.AutofillValue.IsList)
{ {
var autofillOptions = node.GetAutofillOptions(); var autofillOptions = node.GetAutofillOptions();
if(autofillOptions != null && autofillOptions.Length > 0) if (autofillOptions != null && autofillOptions.Length > 0)
{ {
ListValue = node.AutofillValue.ListValue; ListValue = node.AutofillValue.ListValue;
TextValue = autofillOptions[node.AutofillValue.ListValue]; TextValue = autofillOptions[node.AutofillValue.ListValue];
} }
} }
else if(node.AutofillValue.IsDate) else if (node.AutofillValue.IsDate)
{ {
DateValue = node.AutofillValue.DateValue; DateValue = node.AutofillValue.DateValue;
} }
else if(node.AutofillValue.IsText) else if (node.AutofillValue.IsText)
{ {
TextValue = node.AutofillValue.TextValue; TextValue = node.AutofillValue.TextValue;
} }
else if(node.AutofillValue.IsToggle) else if (node.AutofillValue.IsToggle)
{ {
ToggleValue = node.AutofillValue.ToggleValue; ToggleValue = node.AutofillValue.ToggleValue;
} }
@ -93,20 +93,20 @@ namespace Bit.Droid.Autofill
public override bool Equals(object obj) public override bool Equals(object obj)
{ {
if(this == obj) if (this == obj)
{ {
return true; return true;
} }
if(obj == null || GetType() != obj.GetType()) if (obj == null || GetType() != obj.GetType())
{ {
return false; return false;
} }
var field = obj as Field; var field = obj as Field;
if(TextValue != null ? !TextValue.Equals(field.TextValue) : field.TextValue != null) if (TextValue != null ? !TextValue.Equals(field.TextValue) : field.TextValue != null)
{ {
return false; return false;
} }
if(DateValue != null ? !DateValue.Equals(field.DateValue) : field.DateValue != null) if (DateValue != null ? !DateValue.Equals(field.DateValue) : field.DateValue != null)
{ {
return false; return false;
} }
@ -128,7 +128,7 @@ namespace Bit.Droid.Autofill
private static bool IsValidHint(string hint) private static bool IsValidHint(string hint)
{ {
switch(hint) switch (hint)
{ {
case View.AutofillHintCreditCardExpirationDate: case View.AutofillHintCreditCardExpirationDate:
case View.AutofillHintCreditCardExpirationDay: case View.AutofillHintCreditCardExpirationDay:
@ -152,14 +152,14 @@ namespace Bit.Droid.Autofill
private void UpdateSaveTypeFromHints() private void UpdateSaveTypeFromHints()
{ {
SaveType = SaveDataType.Generic; SaveType = SaveDataType.Generic;
if(_hints == null) if (_hints == null)
{ {
return; return;
} }
foreach(var hint in _hints) foreach (var hint in _hints)
{ {
switch(hint) switch (hint)
{ {
case View.AutofillHintCreditCardExpirationDate: case View.AutofillHintCreditCardExpirationDate:
case View.AutofillHintCreditCardExpirationDay: case View.AutofillHintCreditCardExpirationDay:

View File

@ -19,11 +19,11 @@ namespace Bit.Droid.Autofill
{ {
get get
{ {
if(FillableForLogin) if (FillableForLogin)
{ {
return SaveDataType.Password; return SaveDataType.Password;
} }
else if(FillableForCard) else if (FillableForCard)
{ {
return SaveDataType.CreditCard; return SaveDataType.CreditCard;
} }
@ -43,14 +43,14 @@ namespace Bit.Droid.Autofill
{ {
get get
{ {
if(_passwordFields != null) if (_passwordFields != null)
{ {
return _passwordFields; return _passwordFields;
} }
if(Hints.Any()) if (Hints.Any())
{ {
_passwordFields = new List<Field>(); _passwordFields = new List<Field>();
if(HintToFieldsMap.ContainsKey(View.AutofillHintPassword)) if (HintToFieldsMap.ContainsKey(View.AutofillHintPassword))
{ {
_passwordFields.AddRange(HintToFieldsMap[View.AutofillHintPassword]); _passwordFields.AddRange(HintToFieldsMap[View.AutofillHintPassword]);
} }
@ -58,7 +58,7 @@ namespace Bit.Droid.Autofill
else else
{ {
_passwordFields = Fields.Where(f => FieldIsPassword(f)).ToList(); _passwordFields = Fields.Where(f => FieldIsPassword(f)).ToList();
if(!_passwordFields.Any()) if (!_passwordFields.Any())
{ {
_passwordFields = Fields.Where(f => FieldHasPasswordTerms(f)).ToList(); _passwordFields = Fields.Where(f => FieldHasPasswordTerms(f)).ToList();
} }
@ -71,29 +71,29 @@ namespace Bit.Droid.Autofill
{ {
get get
{ {
if(_usernameFields != null) if (_usernameFields != null)
{ {
return _usernameFields; return _usernameFields;
} }
_usernameFields = new List<Field>(); _usernameFields = new List<Field>();
if(Hints.Any()) if (Hints.Any())
{ {
if(HintToFieldsMap.ContainsKey(View.AutofillHintEmailAddress)) if (HintToFieldsMap.ContainsKey(View.AutofillHintEmailAddress))
{ {
_usernameFields.AddRange(HintToFieldsMap[View.AutofillHintEmailAddress]); _usernameFields.AddRange(HintToFieldsMap[View.AutofillHintEmailAddress]);
} }
if(HintToFieldsMap.ContainsKey(View.AutofillHintUsername)) if (HintToFieldsMap.ContainsKey(View.AutofillHintUsername))
{ {
_usernameFields.AddRange(HintToFieldsMap[View.AutofillHintUsername]); _usernameFields.AddRange(HintToFieldsMap[View.AutofillHintUsername]);
} }
} }
else else
{ {
foreach(var passwordField in PasswordFields) foreach (var passwordField in PasswordFields)
{ {
var usernameField = Fields.TakeWhile(f => f.AutofillId != passwordField.AutofillId) var usernameField = Fields.TakeWhile(f => f.AutofillId != passwordField.AutofillId)
.LastOrDefault(); .LastOrDefault();
if(usernameField != null) if (usernameField != null)
{ {
_usernameFields.Add(usernameField); _usernameFields.Add(usernameField);
} }
@ -127,7 +127,7 @@ namespace Bit.Droid.Autofill
public void Add(Field field) public void Add(Field field)
{ {
if(field == null || FieldTrackingIds.Contains(field.TrackingId)) if (field == null || FieldTrackingIds.Contains(field.TrackingId))
{ {
return; return;
} }
@ -137,16 +137,16 @@ namespace Bit.Droid.Autofill
Fields.Add(field); Fields.Add(field);
AutofillIds.Add(field.AutofillId); AutofillIds.Add(field.AutofillId);
if(field.Hints != null) if (field.Hints != null)
{ {
foreach(var hint in field.Hints) foreach (var hint in field.Hints)
{ {
Hints.Add(hint); Hints.Add(hint);
if(field.Focused) if (field.Focused)
{ {
FocusedHints.Add(hint); FocusedHints.Add(hint);
} }
if(!HintToFieldsMap.ContainsKey(hint)) if (!HintToFieldsMap.ContainsKey(hint))
{ {
HintToFieldsMap.Add(hint, new List<Field>()); HintToFieldsMap.Add(hint, new List<Field>());
} }
@ -157,10 +157,10 @@ namespace Bit.Droid.Autofill
public SavedItem GetSavedItem() public SavedItem GetSavedItem()
{ {
if(SaveType == SaveDataType.Password) if (SaveType == SaveDataType.Password)
{ {
var passwordField = PasswordFields.FirstOrDefault(f => !string.IsNullOrWhiteSpace(f.TextValue)); var passwordField = PasswordFields.FirstOrDefault(f => !string.IsNullOrWhiteSpace(f.TextValue));
if(passwordField == null) if (passwordField == null)
{ {
return null; return null;
} }
@ -178,7 +178,7 @@ namespace Bit.Droid.Autofill
savedItem.Login.Username = GetFieldValue(usernameField); savedItem.Login.Username = GetFieldValue(usernameField);
return savedItem; return savedItem;
} }
else if(SaveType == SaveDataType.CreditCard) else if (SaveType == SaveDataType.CreditCard)
{ {
var savedItem = new SavedItem var savedItem = new SavedItem
{ {
@ -199,26 +199,26 @@ namespace Bit.Droid.Autofill
public AutofillId[] GetOptionalSaveIds() public AutofillId[] GetOptionalSaveIds()
{ {
if(SaveType == SaveDataType.Password) if (SaveType == SaveDataType.Password)
{ {
return UsernameFields.Select(f => f.AutofillId).ToArray(); return UsernameFields.Select(f => f.AutofillId).ToArray();
} }
else if(SaveType == SaveDataType.CreditCard) else if (SaveType == SaveDataType.CreditCard)
{ {
var fieldList = new List<Field>(); var fieldList = new List<Field>();
if(HintToFieldsMap.ContainsKey(View.AutofillHintCreditCardSecurityCode)) if (HintToFieldsMap.ContainsKey(View.AutofillHintCreditCardSecurityCode))
{ {
fieldList.AddRange(HintToFieldsMap[View.AutofillHintCreditCardSecurityCode]); fieldList.AddRange(HintToFieldsMap[View.AutofillHintCreditCardSecurityCode]);
} }
if(HintToFieldsMap.ContainsKey(View.AutofillHintCreditCardExpirationYear)) if (HintToFieldsMap.ContainsKey(View.AutofillHintCreditCardExpirationYear))
{ {
fieldList.AddRange(HintToFieldsMap[View.AutofillHintCreditCardExpirationYear]); fieldList.AddRange(HintToFieldsMap[View.AutofillHintCreditCardExpirationYear]);
} }
if(HintToFieldsMap.ContainsKey(View.AutofillHintCreditCardExpirationMonth)) if (HintToFieldsMap.ContainsKey(View.AutofillHintCreditCardExpirationMonth))
{ {
fieldList.AddRange(HintToFieldsMap[View.AutofillHintCreditCardExpirationMonth]); fieldList.AddRange(HintToFieldsMap[View.AutofillHintCreditCardExpirationMonth]);
} }
if(HintToFieldsMap.ContainsKey(View.AutofillHintName)) if (HintToFieldsMap.ContainsKey(View.AutofillHintName))
{ {
fieldList.AddRange(HintToFieldsMap[View.AutofillHintName]); fieldList.AddRange(HintToFieldsMap[View.AutofillHintName]);
} }
@ -229,11 +229,11 @@ namespace Bit.Droid.Autofill
public AutofillId[] GetRequiredSaveFields() public AutofillId[] GetRequiredSaveFields()
{ {
if(SaveType == SaveDataType.Password) if (SaveType == SaveDataType.Password)
{ {
return PasswordFields.Select(f => f.AutofillId).ToArray(); return PasswordFields.Select(f => f.AutofillId).ToArray();
} }
else if(SaveType == SaveDataType.CreditCard && HintToFieldsMap.ContainsKey(View.AutofillHintCreditCardNumber)) else if (SaveType == SaveDataType.CreditCard && HintToFieldsMap.ContainsKey(View.AutofillHintCreditCardNumber))
{ {
return HintToFieldsMap[View.AutofillHintCreditCardNumber].Select(f => f.AutofillId).ToArray(); return HintToFieldsMap[View.AutofillHintCreditCardNumber].Select(f => f.AutofillId).ToArray();
} }
@ -247,12 +247,12 @@ namespace Bit.Droid.Autofill
private string GetFieldValue(string hint, bool monthValue = false) private string GetFieldValue(string hint, bool monthValue = false)
{ {
if(HintToFieldsMap.ContainsKey(hint)) if (HintToFieldsMap.ContainsKey(hint))
{ {
foreach(var field in HintToFieldsMap[hint]) foreach (var field in HintToFieldsMap[hint])
{ {
var val = GetFieldValue(field, monthValue); var val = GetFieldValue(field, monthValue);
if(!string.IsNullOrWhiteSpace(val)) if (!string.IsNullOrWhiteSpace(val))
{ {
return val; return val;
} }
@ -263,30 +263,30 @@ namespace Bit.Droid.Autofill
private string GetFieldValue(Field field, bool monthValue = false) private string GetFieldValue(Field field, bool monthValue = false)
{ {
if(field == null) if (field == null)
{ {
return null; return null;
} }
if(!string.IsNullOrWhiteSpace(field.TextValue)) if (!string.IsNullOrWhiteSpace(field.TextValue))
{ {
if(field.AutofillType == AutofillType.List && field.ListValue.HasValue && monthValue) if (field.AutofillType == AutofillType.List && field.ListValue.HasValue && monthValue)
{ {
if(field.AutofillOptions.Count == 13) if (field.AutofillOptions.Count == 13)
{ {
return field.ListValue.ToString(); return field.ListValue.ToString();
} }
else if(field.AutofillOptions.Count == 12) else if (field.AutofillOptions.Count == 12)
{ {
return (field.ListValue + 1).ToString(); return (field.ListValue + 1).ToString();
} }
} }
return field.TextValue; return field.TextValue;
} }
else if(field.DateValue.HasValue) else if (field.DateValue.HasValue)
{ {
return field.DateValue.Value.ToString(); return field.DateValue.Value.ToString();
} }
else if(field.ToggleValue.HasValue) else if (field.ToggleValue.HasValue)
{ {
return field.ToggleValue.Value.ToString(); return field.ToggleValue.Value.ToString();
} }
@ -300,20 +300,20 @@ namespace Bit.Droid.Autofill
f.InputType.HasFlag(InputTypes.TextVariationWebPassword); f.InputType.HasFlag(InputTypes.TextVariationWebPassword);
// For whatever reason, multi-line input types are coming through with TextVariationPassword flags // For whatever reason, multi-line input types are coming through with TextVariationPassword flags
if(inputTypePassword && f.InputType.HasFlag(InputTypes.TextVariationPassword) && if (inputTypePassword && f.InputType.HasFlag(InputTypes.TextVariationPassword) &&
f.InputType.HasFlag(InputTypes.TextFlagMultiLine)) f.InputType.HasFlag(InputTypes.TextFlagMultiLine))
{ {
inputTypePassword = false; inputTypePassword = false;
} }
if(!inputTypePassword && f.HtmlInfo != null && f.HtmlInfo.Tag == "input" && if (!inputTypePassword && f.HtmlInfo != null && f.HtmlInfo.Tag == "input" &&
(f.HtmlInfo.Attributes?.Any() ?? false)) (f.HtmlInfo.Attributes?.Any() ?? false))
{ {
foreach(var a in f.HtmlInfo.Attributes) foreach (var a in f.HtmlInfo.Attributes)
{ {
var key = a.First as Java.Lang.String; var key = a.First as Java.Lang.String;
var val = a.Second as Java.Lang.String; var val = a.Second as Java.Lang.String;
if(key != null && val != null && key.ToString() == "type" && val.ToString() == "password") if (key != null && val != null && key.ToString() == "type" && val.ToString() == "password")
{ {
return true; return true;
} }
@ -331,7 +331,7 @@ namespace Bit.Droid.Autofill
private bool ValueContainsAnyTerms(string value, HashSet<string> terms) private bool ValueContainsAnyTerms(string value, HashSet<string> terms)
{ {
if(string.IsNullOrWhiteSpace(value)) if (string.IsNullOrWhiteSpace(value))
{ {
return false; return false;
} }

View File

@ -27,7 +27,7 @@ namespace Bit.Droid.Autofill
Type = cipher.Type; Type = cipher.Type;
Subtitle = cipher.SubTitle; Subtitle = cipher.SubTitle;
switch(Type) switch (Type)
{ {
case CipherType.Login: case CipherType.Login:
Icon = Resource.Drawable.login; Icon = Resource.Drawable.login;
@ -62,32 +62,32 @@ namespace Bit.Droid.Autofill
public bool ApplyToFields(FieldCollection fieldCollection, Dataset.Builder datasetBuilder) public bool ApplyToFields(FieldCollection fieldCollection, Dataset.Builder datasetBuilder)
{ {
if(!fieldCollection?.Fields.Any() ?? true) if (!fieldCollection?.Fields.Any() ?? true)
{ {
return false; return false;
} }
var setValues = false; var setValues = false;
if(Type == CipherType.Login) if (Type == CipherType.Login)
{ {
if(fieldCollection.PasswordFields.Any() && !string.IsNullOrWhiteSpace(_password)) if (fieldCollection.PasswordFields.Any() && !string.IsNullOrWhiteSpace(_password))
{ {
foreach(var f in fieldCollection.PasswordFields) foreach (var f in fieldCollection.PasswordFields)
{ {
var val = ApplyValue(f, _password); var val = ApplyValue(f, _password);
if(val != null) if (val != null)
{ {
setValues = true; setValues = true;
datasetBuilder.SetValue(f.AutofillId, val); datasetBuilder.SetValue(f.AutofillId, val);
} }
} }
} }
if(fieldCollection.UsernameFields.Any() && !string.IsNullOrWhiteSpace(Subtitle)) if (fieldCollection.UsernameFields.Any() && !string.IsNullOrWhiteSpace(Subtitle))
{ {
foreach(var f in fieldCollection.UsernameFields) foreach (var f in fieldCollection.UsernameFields)
{ {
var val = ApplyValue(f, Subtitle); var val = ApplyValue(f, Subtitle);
if(val != null) if (val != null)
{ {
setValues = true; setValues = true;
datasetBuilder.SetValue(f.AutofillId, val); datasetBuilder.SetValue(f.AutofillId, val);
@ -95,59 +95,59 @@ namespace Bit.Droid.Autofill
} }
} }
} }
else if(Type == CipherType.Card) else if (Type == CipherType.Card)
{ {
if(ApplyValue(datasetBuilder, fieldCollection, Android.Views.View.AutofillHintCreditCardNumber, if (ApplyValue(datasetBuilder, fieldCollection, Android.Views.View.AutofillHintCreditCardNumber,
_cardNumber)) _cardNumber))
{ {
setValues = true; setValues = true;
} }
if(ApplyValue(datasetBuilder, fieldCollection, Android.Views.View.AutofillHintCreditCardSecurityCode, if (ApplyValue(datasetBuilder, fieldCollection, Android.Views.View.AutofillHintCreditCardSecurityCode,
_cardCode)) _cardCode))
{ {
setValues = true; setValues = true;
} }
if(ApplyValue(datasetBuilder, fieldCollection, if (ApplyValue(datasetBuilder, fieldCollection,
Android.Views.View.AutofillHintCreditCardExpirationMonth, _cardExpMonth, true)) Android.Views.View.AutofillHintCreditCardExpirationMonth, _cardExpMonth, true))
{ {
setValues = true; setValues = true;
} }
if(ApplyValue(datasetBuilder, fieldCollection, Android.Views.View.AutofillHintCreditCardExpirationYear, if (ApplyValue(datasetBuilder, fieldCollection, Android.Views.View.AutofillHintCreditCardExpirationYear,
_cardExpYear)) _cardExpYear))
{ {
setValues = true; setValues = true;
} }
if(ApplyValue(datasetBuilder, fieldCollection, Android.Views.View.AutofillHintName, _cardName)) if (ApplyValue(datasetBuilder, fieldCollection, Android.Views.View.AutofillHintName, _cardName))
{ {
setValues = true; setValues = true;
} }
} }
else if(Type == CipherType.Identity) else if (Type == CipherType.Identity)
{ {
if(ApplyValue(datasetBuilder, fieldCollection, Android.Views.View.AutofillHintPhone, _idPhone)) if (ApplyValue(datasetBuilder, fieldCollection, Android.Views.View.AutofillHintPhone, _idPhone))
{ {
setValues = true; setValues = true;
} }
if(ApplyValue(datasetBuilder, fieldCollection, Android.Views.View.AutofillHintEmailAddress, _idEmail)) if (ApplyValue(datasetBuilder, fieldCollection, Android.Views.View.AutofillHintEmailAddress, _idEmail))
{ {
setValues = true; setValues = true;
} }
if(ApplyValue(datasetBuilder, fieldCollection, Android.Views.View.AutofillHintUsername, if (ApplyValue(datasetBuilder, fieldCollection, Android.Views.View.AutofillHintUsername,
_idUsername)) _idUsername))
{ {
setValues = true; setValues = true;
} }
if(ApplyValue(datasetBuilder, fieldCollection, Android.Views.View.AutofillHintPostalAddress, if (ApplyValue(datasetBuilder, fieldCollection, Android.Views.View.AutofillHintPostalAddress,
_idAddress)) _idAddress))
{ {
setValues = true; setValues = true;
} }
if(ApplyValue(datasetBuilder, fieldCollection, Android.Views.View.AutofillHintPostalCode, if (ApplyValue(datasetBuilder, fieldCollection, Android.Views.View.AutofillHintPostalCode,
_idPostalCode)) _idPostalCode))
{ {
setValues = true; setValues = true;
} }
if(ApplyValue(datasetBuilder, fieldCollection, Android.Views.View.AutofillHintName, Subtitle)) if (ApplyValue(datasetBuilder, fieldCollection, Android.Views.View.AutofillHintName, Subtitle))
{ {
setValues = true; setValues = true;
} }
@ -159,12 +159,12 @@ namespace Bit.Droid.Autofill
string hint, string value, bool monthValue = false) string hint, string value, bool monthValue = false)
{ {
bool setValues = false; bool setValues = false;
if(fieldCollection.HintToFieldsMap.ContainsKey(hint) && !string.IsNullOrWhiteSpace(value)) if (fieldCollection.HintToFieldsMap.ContainsKey(hint) && !string.IsNullOrWhiteSpace(value))
{ {
foreach(var f in fieldCollection.HintToFieldsMap[hint]) foreach (var f in fieldCollection.HintToFieldsMap[hint])
{ {
var val = ApplyValue(f, value, monthValue); var val = ApplyValue(f, value, monthValue);
if(val != null) if (val != null)
{ {
setValues = true; setValues = true;
builder.SetValue(f.AutofillId, val); builder.SetValue(f.AutofillId, val);
@ -176,31 +176,31 @@ namespace Bit.Droid.Autofill
private static AutofillValue ApplyValue(Field field, string value, bool monthValue = false) private static AutofillValue ApplyValue(Field field, string value, bool monthValue = false)
{ {
switch(field.AutofillType) switch (field.AutofillType)
{ {
case AutofillType.Date: case AutofillType.Date:
if(long.TryParse(value, out long dateValue)) if (long.TryParse(value, out long dateValue))
{ {
return AutofillValue.ForDate(dateValue); return AutofillValue.ForDate(dateValue);
} }
break; break;
case AutofillType.List: case AutofillType.List:
if(field.AutofillOptions != null) if (field.AutofillOptions != null)
{ {
if(monthValue && int.TryParse(value, out int monthIndex)) if (monthValue && int.TryParse(value, out int monthIndex))
{ {
if(field.AutofillOptions.Count == 13) if (field.AutofillOptions.Count == 13)
{ {
return AutofillValue.ForList(monthIndex); return AutofillValue.ForList(monthIndex);
} }
else if(field.AutofillOptions.Count >= monthIndex) else if (field.AutofillOptions.Count >= monthIndex)
{ {
return AutofillValue.ForList(monthIndex - 1); return AutofillValue.ForList(monthIndex - 1);
} }
} }
for(var i = 0; i < field.AutofillOptions.Count; i++) for (var i = 0; i < field.AutofillOptions.Count; i++)
{ {
if(field.AutofillOptions[i].Equals(value)) if (field.AutofillOptions[i].Equals(value))
{ {
return AutofillValue.ForList(i); return AutofillValue.ForList(i);
} }
@ -210,7 +210,7 @@ namespace Bit.Droid.Autofill
case AutofillType.Text: case AutofillType.Text:
return AutofillValue.ForText(value); return AutofillValue.ForText(value);
case AutofillType.Toggle: case AutofillType.Toggle:
if(bool.TryParse(value, out bool toggleValue)) if (bool.TryParse(value, out bool toggleValue))
{ {
return AutofillValue.ForToggle(toggleValue); return AutofillValue.ForToggle(toggleValue);
} }

View File

@ -33,16 +33,16 @@ namespace Bit.Droid.Autofill
{ {
get get
{ {
if(!string.IsNullOrWhiteSpace(_uri)) if (!string.IsNullOrWhiteSpace(_uri))
{ {
return _uri; return _uri;
} }
var websiteNull = string.IsNullOrWhiteSpace(Website); var websiteNull = string.IsNullOrWhiteSpace(Website);
if(websiteNull && string.IsNullOrWhiteSpace(PackageName)) if (websiteNull && string.IsNullOrWhiteSpace(PackageName))
{ {
_uri = null; _uri = null;
} }
else if(!websiteNull) else if (!websiteNull)
{ {
_uri = Website; _uri = Website;
} }
@ -59,7 +59,7 @@ namespace Bit.Droid.Autofill
get => _packageName; get => _packageName;
set set
{ {
if(string.IsNullOrWhiteSpace(value)) if (string.IsNullOrWhiteSpace(value))
{ {
_packageName = _uri = null; _packageName = _uri = null;
} }
@ -72,7 +72,7 @@ namespace Bit.Droid.Autofill
get => _website; get => _website;
set set
{ {
if(string.IsNullOrWhiteSpace(value)) if (string.IsNullOrWhiteSpace(value))
{ {
_website = _uri = null; _website = _uri = null;
} }
@ -84,10 +84,10 @@ namespace Bit.Droid.Autofill
{ {
var fillable = !string.IsNullOrWhiteSpace(Uri) && !AutofillHelpers.BlacklistedUris.Contains(Uri) && var fillable = !string.IsNullOrWhiteSpace(Uri) && !AutofillHelpers.BlacklistedUris.Contains(Uri) &&
FieldCollection != null && FieldCollection.Fillable; FieldCollection != null && FieldCollection.Fillable;
if(fillable) if (fillable)
{ {
var blacklistedUris = await storageService.GetAsync<List<string>>(Constants.AutofillBlacklistedUrisKey); var blacklistedUris = await storageService.GetAsync<List<string>>(Constants.AutofillBlacklistedUrisKey);
if(blacklistedUris != null && blacklistedUris.Count > 0) if (blacklistedUris != null && blacklistedUris.Count > 0)
{ {
fillable = !new HashSet<string>(blacklistedUris).Contains(Uri); fillable = !new HashSet<string>(blacklistedUris).Contains(Uri);
} }
@ -98,20 +98,20 @@ namespace Bit.Droid.Autofill
public void Parse() public void Parse()
{ {
string titlePackageId = null; string titlePackageId = null;
for(var i = 0; i < _structure.WindowNodeCount; i++) for (var i = 0; i < _structure.WindowNodeCount; i++)
{ {
var node = _structure.GetWindowNodeAt(i); var node = _structure.GetWindowNodeAt(i);
if(i == 0) if (i == 0)
{ {
titlePackageId = GetTitlePackageId(node); titlePackageId = GetTitlePackageId(node);
} }
ParseNode(node.RootViewNode); ParseNode(node.RootViewNode);
} }
if(string.IsNullOrWhiteSpace(PackageName) && string.IsNullOrWhiteSpace(Website)) if (string.IsNullOrWhiteSpace(PackageName) && string.IsNullOrWhiteSpace(Website))
{ {
PackageName = titlePackageId; PackageName = titlePackageId;
} }
if(!AutofillHelpers.TrustedBrowsers.Contains(PackageName) && if (!AutofillHelpers.TrustedBrowsers.Contains(PackageName) &&
!AutofillHelpers.CompatBrowsers.Contains(PackageName)) !AutofillHelpers.CompatBrowsers.Contains(PackageName))
{ {
Website = null; Website = null;
@ -123,7 +123,7 @@ namespace Bit.Droid.Autofill
SetPackageAndDomain(node); SetPackageAndDomain(node);
var hints = node.GetAutofillHints(); var hints = node.GetAutofillHints();
var isEditText = node.ClassName == "android.widget.EditText" || node?.HtmlInfo?.Tag == "input"; var isEditText = node.ClassName == "android.widget.EditText" || node?.HtmlInfo?.Tag == "input";
if(isEditText || (hints?.Length ?? 0) > 0) if (isEditText || (hints?.Length ?? 0) > 0)
{ {
FieldCollection.Add(new Field(node)); FieldCollection.Add(new Field(node));
} }
@ -132,7 +132,7 @@ namespace Bit.Droid.Autofill
FieldCollection.IgnoreAutofillIds.Add(node.AutofillId); FieldCollection.IgnoreAutofillIds.Add(node.AutofillId);
} }
for(var i = 0; i < node.ChildCount; i++) for (var i = 0; i < node.ChildCount; i++)
{ {
ParseNode(node.GetChildAt(i)); ParseNode(node.GetChildAt(i));
} }
@ -140,15 +140,15 @@ namespace Bit.Droid.Autofill
private void SetPackageAndDomain(ViewNode node) private void SetPackageAndDomain(ViewNode node)
{ {
if(string.IsNullOrWhiteSpace(PackageName) && !string.IsNullOrWhiteSpace(node.IdPackage) && if (string.IsNullOrWhiteSpace(PackageName) && !string.IsNullOrWhiteSpace(node.IdPackage) &&
!_excludedPackageIds.Contains(node.IdPackage)) !_excludedPackageIds.Contains(node.IdPackage))
{ {
PackageName = node.IdPackage; PackageName = node.IdPackage;
} }
if(string.IsNullOrWhiteSpace(Website) && !string.IsNullOrWhiteSpace(node.WebDomain)) if (string.IsNullOrWhiteSpace(Website) && !string.IsNullOrWhiteSpace(node.WebDomain))
{ {
var scheme = "http"; var scheme = "http";
if((int)Build.VERSION.SdkInt >= 28) if ((int)Build.VERSION.SdkInt >= 28)
{ {
scheme = node.WebScheme; scheme = node.WebScheme;
} }
@ -158,13 +158,13 @@ namespace Bit.Droid.Autofill
private string GetTitlePackageId(WindowNode node) private string GetTitlePackageId(WindowNode node)
{ {
if(node != null && !string.IsNullOrWhiteSpace(node.Title)) if (node != null && !string.IsNullOrWhiteSpace(node.Title))
{ {
var slashPosition = node.Title.IndexOf('/'); var slashPosition = node.Title.IndexOf('/');
if(slashPosition > -1) if (slashPosition > -1)
{ {
var packageId = node.Title.Substring(0, slashPosition); var packageId = node.Title.Substring(0, slashPosition);
if(packageId.Contains(".")) if (packageId.Contains("."))
{ {
return packageId; return packageId;
} }

View File

@ -10,7 +10,7 @@ namespace Bit.Droid.Effects
{ {
protected override void OnAttached () protected override void OnAttached ()
{ {
if(Control is Android.Widget.Button button) if (Control is Android.Widget.Button button)
{ {
var gd = new GradientDrawable(); var gd = new GradientDrawable();
gd.SetColor(((Color)Application.Current.Resources["FabColor"]).ToAndroid()); gd.SetColor(((Color)Application.Current.Resources["FabColor"]).ToAndroid());

View File

@ -10,7 +10,7 @@ namespace Bit.Droid.Effects
{ {
protected override void OnAttached() protected override void OnAttached()
{ {
if(Element is Label label && Control is TextView textView) if (Element is Label label && Control is TextView textView)
{ {
textView.SetTextSize(Android.Util.ComplexUnitType.Pt, (float)label.FontSize); textView.SetTextSize(Android.Util.ComplexUnitType.Pt, (float)label.FontSize);
} }

View File

@ -10,7 +10,7 @@ namespace Bit.Droid.Effects
{ {
protected override void OnAttached() protected override void OnAttached()
{ {
if(Control is TextView textView) if (Control is TextView textView)
{ {
textView.SetTextIsSelectable(true); textView.SetTextIsSelectable(true);
} }

View File

@ -12,11 +12,11 @@ namespace Bit.Droid.Effects
{ {
protected override void OnAttached() protected override void OnAttached()
{ {
if(!(Container.GetChildAt(0) is ViewGroup layout)) if (!(Container.GetChildAt(0) is ViewGroup layout))
{ {
return; return;
} }
if(!(layout.GetChildAt(1) is BottomNavigationView bottomNavigationView)) if (!(layout.GetChildAt(1) is BottomNavigationView bottomNavigationView))
{ {
return; return;
} }

View File

@ -73,7 +73,7 @@ namespace Bit.Droid
UpdateTheme(ThemeManager.GetTheme(true)); UpdateTheme(ThemeManager.GetTheme(true));
base.OnCreate(savedInstanceState); base.OnCreate(savedInstanceState);
if(!CoreHelpers.InDebugMode()) if (!CoreHelpers.InDebugMode())
{ {
Window.AddFlags(Android.Views.WindowManagerFlags.Secure); Window.AddFlags(Android.Views.WindowManagerFlags.Secure);
} }
@ -90,7 +90,7 @@ namespace Bit.Droid
_broadcasterService.Subscribe(_activityKey, (message) => _broadcasterService.Subscribe(_activityKey, (message) =>
{ {
if(message.Command == "scheduleLockTimer") if (message.Command == "scheduleLockTimer")
{ {
var alarmManager = GetSystemService(AlarmService) as AlarmManager; var alarmManager = GetSystemService(AlarmService) as AlarmManager;
var lockOptionMinutes = (int)message.Data; var lockOptionMinutes = (int)message.Data;
@ -98,36 +98,36 @@ namespace Bit.Droid
var triggerMs = Java.Lang.JavaSystem.CurrentTimeMillis() + lockOptionMs + 10; var triggerMs = Java.Lang.JavaSystem.CurrentTimeMillis() + lockOptionMs + 10;
alarmManager.Set(AlarmType.RtcWakeup, triggerMs, _lockAlarmPendingIntent); alarmManager.Set(AlarmType.RtcWakeup, triggerMs, _lockAlarmPendingIntent);
} }
else if(message.Command == "cancelLockTimer") else if (message.Command == "cancelLockTimer")
{ {
var alarmManager = GetSystemService(AlarmService) as AlarmManager; var alarmManager = GetSystemService(AlarmService) as AlarmManager;
alarmManager.Cancel(_lockAlarmPendingIntent); alarmManager.Cancel(_lockAlarmPendingIntent);
} }
else if(message.Command == "startEventTimer") else if (message.Command == "startEventTimer")
{ {
StartEventAlarm(); StartEventAlarm();
} }
else if(message.Command == "stopEventTimer") else if (message.Command == "stopEventTimer")
{ {
var task = StopEventAlarmAsync(); var task = StopEventAlarmAsync();
} }
else if(message.Command == "finishMainActivity") else if (message.Command == "finishMainActivity")
{ {
Xamarin.Forms.Device.BeginInvokeOnMainThread(() => Finish()); Xamarin.Forms.Device.BeginInvokeOnMainThread(() => Finish());
} }
else if(message.Command == "listenYubiKeyOTP") else if (message.Command == "listenYubiKeyOTP")
{ {
ListenYubiKey((bool)message.Data); ListenYubiKey((bool)message.Data);
} }
else if(message.Command == "updatedTheme") else if (message.Command == "updatedTheme")
{ {
RestartApp(); RestartApp();
} }
else if(message.Command == "exit") else if (message.Command == "exit")
{ {
ExitApp(); ExitApp();
} }
else if(message.Command == "copiedToClipboard") else if (message.Command == "copiedToClipboard")
{ {
var task = ClearClipboardAlarmAsync(message.Data as Tuple<string, int?, bool>); var task = ClearClipboardAlarmAsync(message.Data as Tuple<string, int?, bool>);
} }
@ -143,7 +143,7 @@ namespace Bit.Droid
protected override void OnResume() protected override void OnResume()
{ {
base.OnResume(); base.OnResume();
if(_deviceActionService.SupportsNfc()) if (_deviceActionService.SupportsNfc())
{ {
try try
{ {
@ -157,18 +157,18 @@ namespace Bit.Droid
protected override void OnNewIntent(Intent intent) protected override void OnNewIntent(Intent intent)
{ {
base.OnNewIntent(intent); base.OnNewIntent(intent);
if(intent.GetBooleanExtra("generatorTile", false)) if (intent.GetBooleanExtra("generatorTile", false))
{ {
_messagingService.Send("popAllAndGoToTabGenerator"); _messagingService.Send("popAllAndGoToTabGenerator");
if(_appOptions != null) if (_appOptions != null)
{ {
_appOptions.GeneratorTile = true; _appOptions.GeneratorTile = true;
} }
} }
if(intent.GetBooleanExtra("myVaultTile", false)) if (intent.GetBooleanExtra("myVaultTile", false))
{ {
_messagingService.Send("popAllAndGoToTabMyVault"); _messagingService.Send("popAllAndGoToTabMyVault");
if(_appOptions != null) if (_appOptions != null)
{ {
_appOptions.MyVaultTile = true; _appOptions.MyVaultTile = true;
} }
@ -182,9 +182,9 @@ namespace Bit.Droid
public async override void OnRequestPermissionsResult(int requestCode, string[] permissions, public async override void OnRequestPermissionsResult(int requestCode, string[] permissions,
[GeneratedEnum] Permission[] grantResults) [GeneratedEnum] Permission[] grantResults)
{ {
if(requestCode == Constants.SelectFilePermissionRequestCode) if (requestCode == Constants.SelectFilePermissionRequestCode)
{ {
if(grantResults.Any(r => r != Permission.Granted)) if (grantResults.Any(r => r != Permission.Granted))
{ {
_messagingService.Send("selectFileCameraPermissionDenied"); _messagingService.Send("selectFileCameraPermissionDenied");
} }
@ -201,12 +201,12 @@ namespace Bit.Droid
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data) protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{ {
if(resultCode == Result.Ok && if (resultCode == Result.Ok &&
(requestCode == Constants.SelectFileRequestCode || requestCode == Constants.SaveFileRequestCode)) (requestCode == Constants.SelectFileRequestCode || requestCode == Constants.SaveFileRequestCode))
{ {
Android.Net.Uri uri = null; Android.Net.Uri uri = null;
string fileName = null; string fileName = null;
if(data != null && data.Data != null) if (data != null && data.Data != null)
{ {
uri = data.Data; uri = data.Data;
fileName = AndroidHelpers.GetFileName(ApplicationContext, uri); fileName = AndroidHelpers.GetFileName(ApplicationContext, uri);
@ -219,12 +219,12 @@ namespace Bit.Droid
fileName = $"photo_{DateTime.UtcNow.ToString("yyyyMMddHHmmss")}.jpg"; fileName = $"photo_{DateTime.UtcNow.ToString("yyyyMMddHHmmss")}.jpg";
} }
if(uri == null) if (uri == null)
{ {
return; return;
} }
if(requestCode == Constants.SaveFileRequestCode) if (requestCode == Constants.SaveFileRequestCode)
{ {
_messagingService.Send("selectSaveFileResult", _messagingService.Send("selectSaveFileResult",
new Tuple<string, string>(uri.ToString(), fileName)); new Tuple<string, string>(uri.ToString(), fileName));
@ -233,15 +233,15 @@ namespace Bit.Droid
try try
{ {
using(var stream = ContentResolver.OpenInputStream(uri)) using (var stream = ContentResolver.OpenInputStream(uri))
using(var memoryStream = new MemoryStream()) using (var memoryStream = new MemoryStream())
{ {
stream.CopyTo(memoryStream); stream.CopyTo(memoryStream);
_messagingService.Send("selectFileResult", _messagingService.Send("selectFileResult",
new Tuple<byte[], string>(memoryStream.ToArray(), fileName ?? "unknown_file_name")); new Tuple<byte[], string>(memoryStream.ToArray(), fileName ?? "unknown_file_name"));
} }
} }
catch(Java.IO.FileNotFoundException) catch (Java.IO.FileNotFoundException)
{ {
return; return;
} }
@ -256,12 +256,12 @@ namespace Bit.Droid
private void ListenYubiKey(bool listen) private void ListenYubiKey(bool listen)
{ {
if(!_deviceActionService.SupportsNfc()) if (!_deviceActionService.SupportsNfc())
{ {
return; return;
} }
var adapter = NfcAdapter.GetDefaultAdapter(this); var adapter = NfcAdapter.GetDefaultAdapter(this);
if(listen) if (listen)
{ {
var intent = new Intent(this, Class); var intent = new Intent(this, Class);
intent.AddFlags(ActivityFlags.SingleTop); intent.AddFlags(ActivityFlags.SingleTop);
@ -298,11 +298,11 @@ namespace Bit.Droid
FromAutofillFramework = Intent.GetBooleanExtra("autofillFramework", false) FromAutofillFramework = Intent.GetBooleanExtra("autofillFramework", false)
}; };
var fillType = Intent.GetIntExtra("autofillFrameworkFillType", 0); var fillType = Intent.GetIntExtra("autofillFrameworkFillType", 0);
if(fillType > 0) if (fillType > 0)
{ {
options.FillType = (CipherType)fillType; options.FillType = (CipherType)fillType;
} }
if(Intent.GetBooleanExtra("autofillFrameworkSave", false)) if (Intent.GetBooleanExtra("autofillFrameworkSave", false))
{ {
options.SaveType = (CipherType)Intent.GetIntExtra("autofillFrameworkType", 0); options.SaveType = (CipherType)Intent.GetIntExtra("autofillFrameworkType", 0);
options.SaveName = Intent.GetStringExtra("autofillFrameworkName"); options.SaveName = Intent.GetStringExtra("autofillFrameworkName");
@ -319,12 +319,12 @@ namespace Bit.Droid
private void ParseYubiKey(string data) private void ParseYubiKey(string data)
{ {
if(data == null) if (data == null)
{ {
return; return;
} }
var otpMatch = _otpPattern.Matcher(data); var otpMatch = _otpPattern.Matcher(data);
if(otpMatch.Matches()) if (otpMatch.Matches())
{ {
var otp = otpMatch.Group(1); var otp = otpMatch.Group(1);
_messagingService.Send("gotYubiKeyOTP", otp); _messagingService.Send("gotYubiKeyOTP", otp);
@ -333,15 +333,15 @@ namespace Bit.Droid
private void UpdateTheme(string theme) private void UpdateTheme(string theme)
{ {
if(theme == "dark") if (theme == "dark")
{ {
SetTheme(Resource.Style.DarkTheme); SetTheme(Resource.Style.DarkTheme);
} }
else if(theme == "black") else if (theme == "black")
{ {
SetTheme(Resource.Style.BlackTheme); SetTheme(Resource.Style.BlackTheme);
} }
else if(theme == "nord") else if (theme == "nord")
{ {
SetTheme(Resource.Style.NordTheme); SetTheme(Resource.Style.NordTheme);
} }
@ -369,20 +369,20 @@ namespace Bit.Droid
private async Task ClearClipboardAlarmAsync(Tuple<string, int?, bool> data) private async Task ClearClipboardAlarmAsync(Tuple<string, int?, bool> data)
{ {
if(data.Item3) if (data.Item3)
{ {
return; return;
} }
var clearMs = data.Item2; var clearMs = data.Item2;
if(clearMs == null) if (clearMs == null)
{ {
var clearSeconds = await _storageService.GetAsync<int?>(Constants.ClearClipboardKey); var clearSeconds = await _storageService.GetAsync<int?>(Constants.ClearClipboardKey);
if(clearSeconds != null) if (clearSeconds != null)
{ {
clearMs = clearSeconds.Value * 1000; clearMs = clearSeconds.Value * 1000;
} }
} }
if(clearMs == null) if (clearMs == null)
{ {
return; return;
} }

View File

@ -37,14 +37,14 @@ namespace Bit.Droid
public MainApplication(IntPtr handle, JniHandleOwnership transer) public MainApplication(IntPtr handle, JniHandleOwnership transer)
: base(handle, transer) : base(handle, transer)
{ {
if(ServiceContainer.RegisteredServices.Count == 0) if (ServiceContainer.RegisteredServices.Count == 0)
{ {
RegisterLocalServices(); RegisterLocalServices();
var deviceActionService = ServiceContainer.Resolve<IDeviceActionService>("deviceActionService"); var deviceActionService = ServiceContainer.Resolve<IDeviceActionService>("deviceActionService");
ServiceContainer.Init(deviceActionService.DeviceUserAgent); ServiceContainer.Init(deviceActionService.DeviceUserAgent);
} }
#if !FDROID #if !FDROID
if(Build.VERSION.SdkInt <= BuildVersionCodes.Kitkat) if (Build.VERSION.SdkInt <= BuildVersionCodes.Kitkat)
{ {
ProviderInstaller.InstallIfNeededAsync(ApplicationContext, this); ProviderInstaller.InstallIfNeededAsync(ApplicationContext, this);
} }

View File

@ -16,12 +16,12 @@ namespace Bit.Droid.Push
{ {
public async override void OnMessageReceived(RemoteMessage message) public async override void OnMessageReceived(RemoteMessage message)
{ {
if(message?.Data == null) if (message?.Data == null)
{ {
return; return;
} }
var data = message.Data.ContainsKey("data") ? message.Data["data"] : null; var data = message.Data.ContainsKey("data") ? message.Data["data"] : null;
if(data == null) if (data == null)
{ {
return; return;
} }
@ -32,7 +32,7 @@ namespace Bit.Droid.Push
"pushNotificationListenerService"); "pushNotificationListenerService");
await listener.OnMessageAsync(obj, Device.Android); await listener.OnMessageAsync(obj, Device.Android);
} }
catch(JsonReaderException ex) catch (JsonReaderException ex)
{ {
System.Diagnostics.Debug.WriteLine(ex.ToString()); System.Diagnostics.Debug.WriteLine(ex.ToString());
} }

View File

@ -12,7 +12,7 @@ namespace Bit.Droid.Receivers
public override void OnReceive(Context context, Intent intent) public override void OnReceive(Context context, Intent intent)
{ {
var clipboardManager = context.GetSystemService(Context.ClipboardService) as ClipboardManager; var clipboardManager = context.GetSystemService(Context.ClipboardService) as ClipboardManager;
if(StaticStore.LastClipboardValue != null && StaticStore.LastClipboardValue == clipboardManager.Text) if (StaticStore.LastClipboardValue != null && StaticStore.LastClipboardValue == clipboardManager.Text)
{ {
clipboardManager.Text = string.Empty; clipboardManager.Text = string.Empty;
} }

View File

@ -14,7 +14,7 @@ namespace Bit.Droid.Receivers
{ {
public async override void OnReceive(Context context, Intent intent) public async override void OnReceive(Context context, Intent intent)
{ {
if(intent.Action == Intent.ActionApplicationRestrictionsChanged) if (intent.Action == Intent.ActionApplicationRestrictionsChanged)
{ {
await AndroidHelpers.SetPreconfiguredRestrictionSettingsAsync(context); await AndroidHelpers.SetPreconfiguredRestrictionSettingsAsync(context);
} }

View File

@ -32,25 +32,25 @@ namespace Bit.Droid.Renderers
protected override Android.Views.View GetCellCore(Cell item, Android.Views.View convertView, protected override Android.Views.View GetCellCore(Cell item, Android.Views.View convertView,
ViewGroup parent, Context context) ViewGroup parent, Context context)
{ {
if(_faTypeface == null) if (_faTypeface == null)
{ {
_faTypeface = Typeface.CreateFromAsset(context.Assets, "FontAwesome.ttf"); _faTypeface = Typeface.CreateFromAsset(context.Assets, "FontAwesome.ttf");
} }
if(_miTypeface == null) if (_miTypeface == null)
{ {
_miTypeface = Typeface.CreateFromAsset(context.Assets, "MaterialIcons_Regular.ttf"); _miTypeface = Typeface.CreateFromAsset(context.Assets, "MaterialIcons_Regular.ttf");
} }
if(_textColor == default(Android.Graphics.Color)) if (_textColor == default(Android.Graphics.Color))
{ {
_textColor = ((Xamarin.Forms.Color)Xamarin.Forms.Application.Current.Resources["TextColor"]) _textColor = ((Xamarin.Forms.Color)Xamarin.Forms.Application.Current.Resources["TextColor"])
.ToAndroid(); .ToAndroid();
} }
if(_mutedColor == default(Android.Graphics.Color)) if (_mutedColor == default(Android.Graphics.Color))
{ {
_mutedColor = ((Xamarin.Forms.Color)Xamarin.Forms.Application.Current.Resources["MutedColor"]) _mutedColor = ((Xamarin.Forms.Color)Xamarin.Forms.Application.Current.Resources["MutedColor"])
.ToAndroid(); .ToAndroid();
} }
if(_disabledIconColor == default(Android.Graphics.Color)) if (_disabledIconColor == default(Android.Graphics.Color))
{ {
_disabledIconColor = _disabledIconColor =
((Xamarin.Forms.Color)Xamarin.Forms.Application.Current.Resources["DisabledIconColor"]) ((Xamarin.Forms.Color)Xamarin.Forms.Application.Current.Resources["DisabledIconColor"])
@ -59,7 +59,7 @@ namespace Bit.Droid.Renderers
var cipherCell = item as CipherViewCell; var cipherCell = item as CipherViewCell;
_cell = convertView as AndroidCipherCell; _cell = convertView as AndroidCipherCell;
if(_cell == null) if (_cell == null)
{ {
_cell = new AndroidCipherCell(context, cipherCell, _faTypeface, _miTypeface); _cell = new AndroidCipherCell(context, cipherCell, _faTypeface, _miTypeface);
} }
@ -77,11 +77,11 @@ namespace Bit.Droid.Renderers
{ {
var cipherCell = sender as CipherViewCell; var cipherCell = sender as CipherViewCell;
_cell.CipherViewCell = cipherCell; _cell.CipherViewCell = cipherCell;
if(e.PropertyName == CipherViewCell.CipherProperty.PropertyName) if (e.PropertyName == CipherViewCell.CipherProperty.PropertyName)
{ {
_cell.UpdateCell(cipherCell); _cell.UpdateCell(cipherCell);
} }
else if(e.PropertyName == CipherViewCell.WebsiteIconsEnabledProperty.PropertyName) else if (e.PropertyName == CipherViewCell.WebsiteIconsEnabledProperty.PropertyName)
{ {
_cell.UpdateIconImage(cipherCell); _cell.UpdateIconImage(cipherCell);
} }
@ -145,7 +145,7 @@ namespace Bit.Droid.Renderers
var cipher = cipherCell.Cipher; var cipher = cipherCell.Cipher;
Name.Text = cipher.Name; Name.Text = cipher.Name;
if(!string.IsNullOrWhiteSpace(cipher.SubTitle)) if (!string.IsNullOrWhiteSpace(cipher.SubTitle))
{ {
SubTitle.Text = cipher.SubTitle; SubTitle.Text = cipher.SubTitle;
SubTitle.Visibility = ViewStates.Visible; SubTitle.Visibility = ViewStates.Visible;
@ -160,7 +160,7 @@ namespace Bit.Droid.Renderers
public void UpdateIconImage(CipherViewCell cipherCell) public void UpdateIconImage(CipherViewCell cipherCell)
{ {
if(_currentTask != null && !_currentTask.IsCancelled && !_currentTask.IsCompleted) if (_currentTask != null && !_currentTask.IsCancelled && !_currentTask.IsCompleted)
{ {
_currentTask.Cancel(); _currentTask.Cancel();
} }
@ -168,7 +168,7 @@ namespace Bit.Droid.Renderers
var cipher = cipherCell.Cipher; var cipher = cipherCell.Cipher;
var iconImage = cipherCell.GetIconImage(cipher); var iconImage = cipherCell.GetIconImage(cipher);
if(iconImage.Item2 != null) if (iconImage.Item2 != null)
{ {
IconImage.SetImageResource(Resource.Drawable.login); IconImage.SetImageResource(Resource.Drawable.login);
IconImage.Visibility = ViewStates.Visible; IconImage.Visibility = ViewStates.Visible;
@ -197,7 +197,7 @@ namespace Bit.Droid.Renderers
private void MoreButton_Click(object sender, EventArgs e) private void MoreButton_Click(object sender, EventArgs e)
{ {
if(CipherViewCell.ButtonCommand?.CanExecute(CipherViewCell.Cipher) ?? false) if (CipherViewCell.ButtonCommand?.CanExecute(CipherViewCell.Cipher) ?? false)
{ {
CipherViewCell.ButtonCommand.Execute(CipherViewCell.Cipher); CipherViewCell.ButtonCommand.Execute(CipherViewCell.Cipher);
} }
@ -205,7 +205,7 @@ namespace Bit.Droid.Renderers
protected override void Dispose(bool disposing) protected override void Dispose(bool disposing)
{ {
if(disposing) if (disposing)
{ {
MoreButton.Click -= MoreButton_Click; MoreButton.Click -= MoreButton_Click;
} }

View File

@ -16,7 +16,7 @@ namespace Bit.Droid.Renderers
protected override void OnElementChanged(ElementChangedEventArgs<Editor> e) protected override void OnElementChanged(ElementChangedEventArgs<Editor> e)
{ {
base.OnElementChanged(e); base.OnElementChanged(e);
if(Control != null && e.NewElement != null) if (Control != null && e.NewElement != null)
{ {
Control.SetPadding(Control.PaddingLeft, Control.PaddingTop - 10, Control.PaddingRight, Control.SetPadding(Control.PaddingLeft, Control.PaddingTop - 10, Control.PaddingRight,
Control.PaddingBottom + 20); Control.PaddingBottom + 20);

View File

@ -16,7 +16,7 @@ namespace Bit.Droid.Renderers
protected override void OnElementChanged(ElementChangedEventArgs<Entry> e) protected override void OnElementChanged(ElementChangedEventArgs<Entry> e)
{ {
base.OnElementChanged(e); base.OnElementChanged(e);
if(Control != null && e.NewElement != null) if (Control != null && e.NewElement != null)
{ {
Control.SetPadding(Control.PaddingLeft, Control.PaddingTop - 10, Control.PaddingRight, Control.SetPadding(Control.PaddingLeft, Control.PaddingTop - 10, Control.PaddingRight,
Control.PaddingBottom + 20); Control.PaddingBottom + 20);

View File

@ -15,7 +15,7 @@ namespace Bit.Droid.Renderers
protected override void OnElementChanged(ElementChangedEventArgs<Picker> e) protected override void OnElementChanged(ElementChangedEventArgs<Picker> e)
{ {
base.OnElementChanged(e); base.OnElementChanged(e);
if(Control != null && e.NewElement != null) if (Control != null && e.NewElement != null)
{ {
Control.SetPadding(Control.PaddingLeft, Control.PaddingTop - 10, Control.PaddingRight, Control.SetPadding(Control.PaddingLeft, Control.PaddingTop - 10, Control.PaddingRight,
Control.PaddingBottom + 20); Control.PaddingBottom + 20);

View File

@ -16,7 +16,7 @@ namespace Bit.Droid.Renderers
protected override void OnElementChanged(ElementChangedEventArgs<SearchBar> e) protected override void OnElementChanged(ElementChangedEventArgs<SearchBar> e)
{ {
base.OnElementChanged(e); base.OnElementChanged(e);
if(Control != null && e.NewElement != null) if (Control != null && e.NewElement != null)
{ {
try try
{ {

View File

@ -17,7 +17,7 @@ namespace Bit.Droid.Renderers
protected override void OnElementChanged(ElementChangedEventArgs<ListView> e) protected override void OnElementChanged(ElementChangedEventArgs<ListView> e)
{ {
base.OnElementChanged(e); base.OnElementChanged(e);
if(Control != null && e.NewElement != null && e.NewElement is ExtendedListView listView) if (Control != null && e.NewElement != null && e.NewElement is ExtendedListView listView)
{ {
// Pad for FAB // Pad for FAB
Control.SetPadding(0, 0, 0, 170); Control.SetPadding(0, 0, 0, 170);

View File

@ -18,12 +18,12 @@ namespace Bit.Droid.Renderers
protected override void OnElementChanged(ElementChangedEventArgs<Slider> e) protected override void OnElementChanged(ElementChangedEventArgs<Slider> e)
{ {
base.OnElementChanged(e); base.OnElementChanged(e);
if(Control != null && Element is ExtendedSlider view) if (Control != null && Element is ExtendedSlider view)
{ {
var t = ResourcesCompat.GetDrawable(Resources, Resource.Drawable.slider_thumb, null); var t = ResourcesCompat.GetDrawable(Resources, Resource.Drawable.slider_thumb, null);
if(t is GradientDrawable thumb) if (t is GradientDrawable thumb)
{ {
if(view.ThumbColor == Color.Default) if (view.ThumbColor == Color.Default)
{ {
thumb.SetColor(Color.White.ToAndroid()); thumb.SetColor(Color.White.ToAndroid());
} }

View File

@ -28,20 +28,20 @@ namespace Bit.Droid.Renderers
{ {
base.OnElementChanged(e); base.OnElementChanged(e);
if(Control == null) if (Control == null)
{ {
var webView = new AWebkit.WebView(_context); var webView = new AWebkit.WebView(_context);
webView.Settings.JavaScriptEnabled = true; webView.Settings.JavaScriptEnabled = true;
webView.SetWebViewClient(new JSWebViewClient(string.Format("javascript: {0}", JSFunction))); webView.SetWebViewClient(new JSWebViewClient(string.Format("javascript: {0}", JSFunction)));
SetNativeControl(webView); SetNativeControl(webView);
} }
if(e.OldElement != null) if (e.OldElement != null)
{ {
Control.RemoveJavascriptInterface("jsBridge"); Control.RemoveJavascriptInterface("jsBridge");
var hybridWebView = e.OldElement as HybridWebView; var hybridWebView = e.OldElement as HybridWebView;
hybridWebView.Cleanup(); hybridWebView.Cleanup();
} }
if(e.NewElement != null) if (e.NewElement != null)
{ {
Control.AddJavascriptInterface(new JSBridge(this), "jsBridge"); Control.AddJavascriptInterface(new JSBridge(this), "jsBridge");
Control.LoadUrl(Element.Uri); Control.LoadUrl(Element.Uri);
@ -51,7 +51,7 @@ namespace Bit.Droid.Renderers
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e) protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{ {
base.OnElementPropertyChanged(sender, e); base.OnElementPropertyChanged(sender, e);
if(e.PropertyName == HybridWebView.UriProperty.PropertyName) if (e.PropertyName == HybridWebView.UriProperty.PropertyName)
{ {
Control.LoadUrl(Element.Uri); Control.LoadUrl(Element.Uri);
} }
@ -70,7 +70,7 @@ namespace Bit.Droid.Renderers
[Export("invokeAction")] [Export("invokeAction")]
public void InvokeAction(string data) public void InvokeAction(string data)
{ {
if(_hybridWebViewRenderer != null && if (_hybridWebViewRenderer != null &&
_hybridWebViewRenderer.TryGetTarget(out HybridWebViewRenderer hybridRenderer)) _hybridWebViewRenderer.TryGetTarget(out HybridWebViewRenderer hybridRenderer))
{ {
hybridRenderer.Element.InvokeAction(data); hybridRenderer.Element.InvokeAction(data);

View File

@ -30,7 +30,7 @@ namespace Bit.Droid.Services
{ {
var registeredToken = await _storageService.GetAsync<string>(Constants.PushRegisteredTokenKey); var registeredToken = await _storageService.GetAsync<string>(Constants.PushRegisteredTokenKey);
var currentToken = await GetTokenAsync(); var currentToken = await GetTokenAsync();
if(!string.IsNullOrWhiteSpace(registeredToken) && registeredToken != currentToken) if (!string.IsNullOrWhiteSpace(registeredToken) && registeredToken != currentToken)
{ {
await _pushNotificationListenerService.OnRegisteredAsync(registeredToken, Device.Android); await _pushNotificationListenerService.OnRegisteredAsync(registeredToken, Device.Android);
} }

View File

@ -14,12 +14,12 @@ namespace Bit.Droid.Services
{ {
int keySize = 256; int keySize = 256;
IDigest digest = null; IDigest digest = null;
if(algorithm == CryptoHashAlgorithm.Sha256) if (algorithm == CryptoHashAlgorithm.Sha256)
{ {
keySize = 256; keySize = 256;
digest = new Sha256Digest(); digest = new Sha256Digest();
} }
else if(algorithm == CryptoHashAlgorithm.Sha512) else if (algorithm == CryptoHashAlgorithm.Sha512)
{ {
keySize = 512; keySize = 512;
digest = new Sha512Digest(); digest = new Sha512Digest();

View File

@ -59,7 +59,7 @@ namespace Bit.Droid.Services
_broadcasterService.Subscribe(nameof(DeviceActionService), (message) => _broadcasterService.Subscribe(nameof(DeviceActionService), (message) =>
{ {
if(message.Command == "selectFileCameraPermissionDenied") if (message.Command == "selectFileCameraPermissionDenied")
{ {
_cameraPermissionsDenied = true; _cameraPermissionsDenied = true;
} }
@ -70,7 +70,7 @@ namespace Bit.Droid.Services
{ {
get get
{ {
if(string.IsNullOrWhiteSpace(_userAgent)) if (string.IsNullOrWhiteSpace(_userAgent))
{ {
_userAgent = $"Bitwarden_Mobile/{Xamarin.Essentials.AppInfo.VersionString} " + _userAgent = $"Bitwarden_Mobile/{Xamarin.Essentials.AppInfo.VersionString} " +
$"(Android {Build.VERSION.Release}; SDK {Build.VERSION.Sdk}; Model {Build.Model})"; $"(Android {Build.VERSION.Release}; SDK {Build.VERSION.Sdk}; Model {Build.Model})";
@ -83,7 +83,7 @@ namespace Bit.Droid.Services
public void Toast(string text, bool longDuration = false) public void Toast(string text, bool longDuration = false)
{ {
if(_toast != null) if (_toast != null)
{ {
_toast.Cancel(); _toast.Cancel();
_toast.Dispose(); _toast.Dispose();
@ -99,7 +99,7 @@ namespace Bit.Droid.Services
var activity = CrossCurrentActivity.Current.Activity; var activity = CrossCurrentActivity.Current.Activity;
appName = appName.Replace("androidapp://", string.Empty); appName = appName.Replace("androidapp://", string.Empty);
var launchIntent = activity.PackageManager.GetLaunchIntentForPackage(appName); var launchIntent = activity.PackageManager.GetLaunchIntentForPackage(appName);
if(launchIntent != null) if (launchIntent != null)
{ {
activity.StartActivity(launchIntent); activity.StartActivity(launchIntent);
} }
@ -108,7 +108,7 @@ namespace Bit.Droid.Services
public async Task ShowLoadingAsync(string text) public async Task ShowLoadingAsync(string text)
{ {
if(_progressDialog != null) if (_progressDialog != null)
{ {
await HideLoadingAsync(); await HideLoadingAsync();
} }
@ -121,7 +121,7 @@ namespace Bit.Droid.Services
public Task HideLoadingAsync() public Task HideLoadingAsync()
{ {
if(_progressDialog != null) if (_progressDialog != null)
{ {
_progressDialog.Dismiss(); _progressDialog.Dismiss();
_progressDialog.Dispose(); _progressDialog.Dispose();
@ -136,7 +136,7 @@ namespace Bit.Droid.Services
{ {
var activity = (MainActivity)CrossCurrentActivity.Current.Activity; var activity = (MainActivity)CrossCurrentActivity.Current.Activity;
var intent = BuildOpenFileIntent(fileData, fileName); var intent = BuildOpenFileIntent(fileData, fileName);
if(intent == null) if (intent == null)
{ {
return false; return false;
} }
@ -153,7 +153,7 @@ namespace Bit.Droid.Services
{ {
var activity = (MainActivity)CrossCurrentActivity.Current.Activity; var activity = (MainActivity)CrossCurrentActivity.Current.Activity;
var intent = BuildOpenFileIntent(new byte[0], string.Concat("opentest_", fileName)); var intent = BuildOpenFileIntent(new byte[0], string.Concat("opentest_", fileName));
if(intent == null) if (intent == null)
{ {
return false; return false;
} }
@ -168,12 +168,12 @@ namespace Bit.Droid.Services
private Intent BuildOpenFileIntent(byte[] fileData, string fileName) private Intent BuildOpenFileIntent(byte[] fileData, string fileName)
{ {
var extension = MimeTypeMap.GetFileExtensionFromUrl(fileName.Replace(' ', '_').ToLower()); var extension = MimeTypeMap.GetFileExtensionFromUrl(fileName.Replace(' ', '_').ToLower());
if(extension == null) if (extension == null)
{ {
return null; return null;
} }
var mimeType = MimeTypeMap.Singleton.GetMimeTypeFromExtension(extension); var mimeType = MimeTypeMap.Singleton.GetMimeTypeFromExtension(extension);
if(mimeType == null) if (mimeType == null)
{ {
return null; return null;
} }
@ -183,7 +183,7 @@ namespace Bit.Droid.Services
var filePath = Path.Combine(cachePath.Path, fileName); var filePath = Path.Combine(cachePath.Path, fileName);
File.WriteAllBytes(filePath, fileData); File.WriteAllBytes(filePath, fileData);
var file = new Java.IO.File(cachePath, fileName); var file = new Java.IO.File(cachePath, fileName);
if(!file.IsFile) if (!file.IsFile)
{ {
return null; return null;
} }
@ -207,7 +207,7 @@ namespace Bit.Droid.Services
{ {
var activity = (MainActivity)CrossCurrentActivity.Current.Activity; var activity = (MainActivity)CrossCurrentActivity.Current.Activity;
if(contentUri != null) if (contentUri != null)
{ {
var uri = Android.Net.Uri.Parse(contentUri); var uri = Android.Net.Uri.Parse(contentUri);
var stream = activity.ContentResolver.OpenOutputStream(uri); var stream = activity.ContentResolver.OpenOutputStream(uri);
@ -222,13 +222,13 @@ namespace Bit.Droid.Services
// Prompt for location to save file // Prompt for location to save file
var extension = MimeTypeMap.GetFileExtensionFromUrl(fileName.Replace(' ', '_').ToLower()); var extension = MimeTypeMap.GetFileExtensionFromUrl(fileName.Replace(' ', '_').ToLower());
if(extension == null) if (extension == null)
{ {
return false; return false;
} }
string mimeType = MimeTypeMap.Singleton.GetMimeTypeFromExtension(extension); string mimeType = MimeTypeMap.Singleton.GetMimeTypeFromExtension(extension);
if(mimeType == null) if (mimeType == null)
{ {
// Unable to identify so fall back to generic "any" type // Unable to identify so fall back to generic "any" type
mimeType = "*/*"; mimeType = "*/*";
@ -242,7 +242,7 @@ namespace Bit.Droid.Services
activity.StartActivityForResult(intent, Constants.SaveFileRequestCode); activity.StartActivityForResult(intent, Constants.SaveFileRequestCode);
return true; return true;
} }
catch(Exception ex) catch (Exception ex)
{ {
System.Diagnostics.Debug.WriteLine(">>> {0}: {1}", ex.GetType(), ex.StackTrace); System.Diagnostics.Debug.WriteLine(">>> {0}: {1}", ex.GetType(), ex.StackTrace);
} }
@ -256,7 +256,7 @@ namespace Bit.Droid.Services
DeleteDir(CrossCurrentActivity.Current.Activity.CacheDir); DeleteDir(CrossCurrentActivity.Current.Activity.CacheDir);
await _storageService.SaveAsync(Constants.LastFileCacheClearKey, DateTime.UtcNow); await _storageService.SaveAsync(Constants.LastFileCacheClearKey, DateTime.UtcNow);
} }
catch(Exception) { } catch (Exception) { }
} }
public Task SelectFileAsync() public Task SelectFileAsync()
@ -265,25 +265,25 @@ namespace Bit.Droid.Services
var hasStorageWritePermission = !_cameraPermissionsDenied && var hasStorageWritePermission = !_cameraPermissionsDenied &&
HasPermission(Manifest.Permission.WriteExternalStorage); HasPermission(Manifest.Permission.WriteExternalStorage);
var additionalIntents = new List<IParcelable>(); var additionalIntents = new List<IParcelable>();
if(activity.PackageManager.HasSystemFeature(PackageManager.FeatureCamera)) if (activity.PackageManager.HasSystemFeature(PackageManager.FeatureCamera))
{ {
var hasCameraPermission = !_cameraPermissionsDenied && HasPermission(Manifest.Permission.Camera); var hasCameraPermission = !_cameraPermissionsDenied && HasPermission(Manifest.Permission.Camera);
if(!_cameraPermissionsDenied && !hasStorageWritePermission) if (!_cameraPermissionsDenied && !hasStorageWritePermission)
{ {
AskPermission(Manifest.Permission.WriteExternalStorage); AskPermission(Manifest.Permission.WriteExternalStorage);
return Task.FromResult(0); return Task.FromResult(0);
} }
if(!_cameraPermissionsDenied && !hasCameraPermission) if (!_cameraPermissionsDenied && !hasCameraPermission)
{ {
AskPermission(Manifest.Permission.Camera); AskPermission(Manifest.Permission.Camera);
return Task.FromResult(0); return Task.FromResult(0);
} }
if(!_cameraPermissionsDenied && hasCameraPermission && hasStorageWritePermission) if (!_cameraPermissionsDenied && hasCameraPermission && hasStorageWritePermission)
{ {
try try
{ {
var file = new Java.IO.File(activity.FilesDir, "temp_camera_photo.jpg"); var file = new Java.IO.File(activity.FilesDir, "temp_camera_photo.jpg");
if(!file.Exists()) if (!file.Exists())
{ {
file.ParentFile.Mkdirs(); file.ParentFile.Mkdirs();
file.CreateNewFile(); file.CreateNewFile();
@ -292,7 +292,7 @@ namespace Bit.Droid.Services
"com.x8bit.bitwarden.fileprovider", file); "com.x8bit.bitwarden.fileprovider", file);
additionalIntents.AddRange(GetCameraIntents(outputFileUri)); additionalIntents.AddRange(GetCameraIntents(outputFileUri));
} }
catch(Java.IO.IOException) { } catch (Java.IO.IOException) { }
} }
} }
@ -300,7 +300,7 @@ namespace Bit.Droid.Services
docIntent.AddCategory(Intent.CategoryOpenable); docIntent.AddCategory(Intent.CategoryOpenable);
docIntent.SetType("*/*"); docIntent.SetType("*/*");
var chooserIntent = Intent.CreateChooser(docIntent, AppResources.FileSource); var chooserIntent = Intent.CreateChooser(docIntent, AppResources.FileSource);
if(additionalIntents.Count > 0) if (additionalIntents.Count > 0)
{ {
chooserIntent.PutExtra(Intent.ExtraInitialIntents, additionalIntents.ToArray()); chooserIntent.PutExtra(Intent.ExtraInitialIntents, additionalIntents.ToArray());
} }
@ -313,7 +313,7 @@ namespace Bit.Droid.Services
bool numericKeyboard = false, bool autofocus = true) bool numericKeyboard = false, bool autofocus = true)
{ {
var activity = (MainActivity)CrossCurrentActivity.Current.Activity; var activity = (MainActivity)CrossCurrentActivity.Current.Activity;
if(activity == null) if (activity == null)
{ {
return Task.FromResult<string>(null); return Task.FromResult<string>(null);
} }
@ -325,11 +325,11 @@ namespace Bit.Droid.Services
{ {
InputType = InputTypes.ClassText InputType = InputTypes.ClassText
}; };
if(text == null) if (text == null)
{ {
text = string.Empty; text = string.Empty;
} }
if(numericKeyboard) if (numericKeyboard)
{ {
input.InputType = InputTypes.ClassNumber | InputTypes.NumberFlagDecimal | InputTypes.NumberFlagSigned; input.InputType = InputTypes.ClassNumber | InputTypes.NumberFlagDecimal | InputTypes.NumberFlagSigned;
#pragma warning disable CS0618 // Type or member is obsolete #pragma warning disable CS0618 // Type or member is obsolete
@ -359,7 +359,7 @@ namespace Bit.Droid.Services
var alert = alertBuilder.Create(); var alert = alertBuilder.Create();
alert.Window.SetSoftInputMode(Android.Views.SoftInput.StateVisible); alert.Window.SetSoftInputMode(Android.Views.SoftInput.StateVisible);
alert.Show(); alert.Show();
if(autofocus) if (autofocus)
{ {
input.RequestFocus(); input.RequestFocus();
} }
@ -374,7 +374,7 @@ namespace Bit.Droid.Services
var rateIntent = RateIntentForUrl("market://details", activity); var rateIntent = RateIntentForUrl("market://details", activity);
activity.StartActivity(rateIntent); activity.StartActivity(rateIntent);
} }
catch(ActivityNotFoundException) catch (ActivityNotFoundException)
{ {
var rateIntent = RateIntentForUrl("https://play.google.com/store/apps/details", activity); var rateIntent = RateIntentForUrl("https://play.google.com/store/apps/details", activity);
activity.StartActivity(rateIntent); activity.StartActivity(rateIntent);
@ -399,7 +399,7 @@ namespace Bit.Droid.Services
public async Task<bool> BiometricAvailableAsync() public async Task<bool> BiometricAvailableAsync()
{ {
if(UseNativeBiometric()) if (UseNativeBiometric())
{ {
var activity = (MainActivity)CrossCurrentActivity.Current.Activity; var activity = (MainActivity)CrossCurrentActivity.Current.Activity;
var manager = activity.GetSystemService(Context.BiometricService) as BiometricManager; var manager = activity.GetSystemService(Context.BiometricService) as BiometricManager;
@ -425,13 +425,13 @@ namespace Bit.Droid.Services
public Task<bool> AuthenticateBiometricAsync(string text = null) public Task<bool> AuthenticateBiometricAsync(string text = null)
{ {
if(string.IsNullOrWhiteSpace(text)) if (string.IsNullOrWhiteSpace(text))
{ {
text = AppResources.BiometricsDirection; text = AppResources.BiometricsDirection;
} }
var activity = (MainActivity)CrossCurrentActivity.Current.Activity; var activity = (MainActivity)CrossCurrentActivity.Current.Activity;
using(var builder = new BiometricPrompt.Builder(activity)) using (var builder = new BiometricPrompt.Builder(activity))
{ {
builder.SetTitle(text); builder.SetTitle(text);
builder.SetConfirmationRequired(false); builder.SetConfirmationRequired(false);
@ -468,7 +468,7 @@ namespace Bit.Droid.Services
public bool SupportsAutofillService() public bool SupportsAutofillService()
{ {
if(Build.VERSION.SdkInt < BuildVersionCodes.O) if (Build.VERSION.SdkInt < BuildVersionCodes.O)
{ {
return false; return false;
} }
@ -498,7 +498,7 @@ namespace Bit.Droid.Services
public Task<string> DisplayAlertAsync(string title, string message, string cancel, params string[] buttons) public Task<string> DisplayAlertAsync(string title, string message, string cancel, params string[] buttons)
{ {
var activity = (MainActivity)CrossCurrentActivity.Current.Activity; var activity = (MainActivity)CrossCurrentActivity.Current.Activity;
if(activity == null) if (activity == null)
{ {
return Task.FromResult<string>(null); return Task.FromResult<string>(null);
} }
@ -507,11 +507,11 @@ namespace Bit.Droid.Services
var alertBuilder = new AlertDialog.Builder(activity); var alertBuilder = new AlertDialog.Builder(activity);
alertBuilder.SetTitle(title); alertBuilder.SetTitle(title);
if(!string.IsNullOrWhiteSpace(message)) if (!string.IsNullOrWhiteSpace(message))
{ {
if(buttons != null && buttons.Length > 2) if (buttons != null && buttons.Length > 2)
{ {
if(!string.IsNullOrWhiteSpace(title)) if (!string.IsNullOrWhiteSpace(title))
{ {
alertBuilder.SetTitle($"{title}: {message}"); alertBuilder.SetTitle($"{title}: {message}");
} }
@ -526,9 +526,9 @@ namespace Bit.Droid.Services
} }
} }
if(buttons != null) if (buttons != null)
{ {
if(buttons.Length > 2) if (buttons.Length > 2)
{ {
alertBuilder.SetItems(buttons, (sender, args) => alertBuilder.SetItems(buttons, (sender, args) =>
{ {
@ -537,14 +537,14 @@ namespace Bit.Droid.Services
} }
else else
{ {
if(buttons.Length > 0) if (buttons.Length > 0)
{ {
alertBuilder.SetPositiveButton(buttons[0], (sender, args) => alertBuilder.SetPositiveButton(buttons[0], (sender, args) =>
{ {
result.TrySetResult(buttons[0]); result.TrySetResult(buttons[0]);
}); });
} }
if(buttons.Length > 1) if (buttons.Length > 1)
{ {
alertBuilder.SetNeutralButton(buttons[1], (sender, args) => alertBuilder.SetNeutralButton(buttons[1], (sender, args) =>
{ {
@ -554,7 +554,7 @@ namespace Bit.Droid.Services
} }
} }
if(!string.IsNullOrWhiteSpace(cancel)) if (!string.IsNullOrWhiteSpace(cancel))
{ {
alertBuilder.SetNegativeButton(cancel, (sender, args) => alertBuilder.SetNegativeButton(cancel, (sender, args) =>
{ {
@ -571,13 +571,13 @@ namespace Bit.Droid.Services
public void Autofill(CipherView cipher) public void Autofill(CipherView cipher)
{ {
var activity = (MainActivity)CrossCurrentActivity.Current.Activity; var activity = (MainActivity)CrossCurrentActivity.Current.Activity;
if(activity == null) if (activity == null)
{ {
return; return;
} }
if(activity.Intent.GetBooleanExtra("autofillFramework", false)) if (activity.Intent.GetBooleanExtra("autofillFramework", false))
{ {
if(cipher == null) if (cipher == null)
{ {
activity.SetResult(Result.Canceled); activity.SetResult(Result.Canceled);
activity.Finish(); activity.Finish();
@ -585,7 +585,7 @@ namespace Bit.Droid.Services
} }
var structure = activity.Intent.GetParcelableExtra( var structure = activity.Intent.GetParcelableExtra(
AutofillManager.ExtraAssistStructure) as AssistStructure; AutofillManager.ExtraAssistStructure) as AssistStructure;
if(structure == null) if (structure == null)
{ {
activity.SetResult(Result.Canceled); activity.SetResult(Result.Canceled);
activity.Finish(); activity.Finish();
@ -593,7 +593,7 @@ namespace Bit.Droid.Services
} }
var parser = new Parser(structure, activity.ApplicationContext); var parser = new Parser(structure, activity.ApplicationContext);
parser.Parse(); parser.Parse();
if((!parser.FieldCollection?.Fields?.Any() ?? true) || string.IsNullOrWhiteSpace(parser.Uri)) if ((!parser.FieldCollection?.Fields?.Any() ?? true) || string.IsNullOrWhiteSpace(parser.Uri))
{ {
activity.SetResult(Result.Canceled); activity.SetResult(Result.Canceled);
activity.Finish(); activity.Finish();
@ -610,7 +610,7 @@ namespace Bit.Droid.Services
else else
{ {
var data = new Intent(); var data = new Intent();
if(cipher == null) if (cipher == null)
{ {
data.PutExtra("canceled", "true"); data.PutExtra("canceled", "true");
} }
@ -621,7 +621,7 @@ namespace Bit.Droid.Services
data.PutExtra("username", cipher.Login.Username); data.PutExtra("username", cipher.Login.Username);
data.PutExtra("password", cipher.Login.Password); data.PutExtra("password", cipher.Login.Password);
} }
if(activity.Parent == null) if (activity.Parent == null)
{ {
activity.SetResult(Result.Ok, data); activity.SetResult(Result.Ok, data);
} }
@ -631,7 +631,7 @@ namespace Bit.Droid.Services
} }
activity.Finish(); activity.Finish();
_messagingService.Send("finishMainActivity"); _messagingService.Send("finishMainActivity");
if(cipher != null) if (cipher != null)
{ {
var eventTask = _eventServiceFunc().CollectAsync(EventType.Cipher_ClientAutofilled, cipher.Id); var eventTask = _eventServiceFunc().CollectAsync(EventType.Cipher_ClientAutofilled, cipher.Id);
} }
@ -646,7 +646,7 @@ namespace Bit.Droid.Services
public void Background() public void Background()
{ {
var activity = (MainActivity)CrossCurrentActivity.Current.Activity; var activity = (MainActivity)CrossCurrentActivity.Current.Activity;
if(activity.Intent.GetBooleanExtra("autofillFramework", false)) if (activity.Intent.GetBooleanExtra("autofillFramework", false))
{ {
activity.SetResult(Result.Canceled); activity.SetResult(Result.Canceled);
activity.Finish(); activity.Finish();
@ -687,7 +687,7 @@ namespace Bit.Droid.Services
intent.SetData(Android.Net.Uri.Parse("package:com.x8bit.bitwarden")); intent.SetData(Android.Net.Uri.Parse("package:com.x8bit.bitwarden"));
activity.StartActivity(intent); activity.StartActivity(intent);
} }
catch(ActivityNotFoundException) catch (ActivityNotFoundException)
{ {
// can't open overlay permission management, fall back to app settings // can't open overlay permission management, fall back to app settings
var intent = new Intent(Settings.ActionApplicationDetailsSettings); var intent = new Intent(Settings.ActionApplicationDetailsSettings);
@ -709,7 +709,7 @@ namespace Bit.Droid.Services
public bool AutofillServiceEnabled() public bool AutofillServiceEnabled()
{ {
if(Build.VERSION.SdkInt < BuildVersionCodes.O) if (Build.VERSION.SdkInt < BuildVersionCodes.O)
{ {
return false; return false;
} }
@ -746,7 +746,7 @@ namespace Bit.Droid.Services
intent.SetData(Android.Net.Uri.Parse("package:com.x8bit.bitwarden")); intent.SetData(Android.Net.Uri.Parse("package:com.x8bit.bitwarden"));
activity.StartActivity(intent); activity.StartActivity(intent);
} }
catch(ActivityNotFoundException) catch (ActivityNotFoundException)
{ {
var alertBuilder = new AlertDialog.Builder(activity); var alertBuilder = new AlertDialog.Builder(activity);
alertBuilder.SetMessage(AppResources.BitwardenAutofillGoToSettings); alertBuilder.SetMessage(AppResources.BitwardenAutofillGoToSettings);
@ -766,20 +766,20 @@ namespace Bit.Droid.Services
private bool DeleteDir(Java.IO.File dir) private bool DeleteDir(Java.IO.File dir)
{ {
if(dir != null && dir.IsDirectory) if (dir != null && dir.IsDirectory)
{ {
var children = dir.List(); var children = dir.List();
for(int i = 0; i < children.Length; i++) for (int i = 0; i < children.Length; i++)
{ {
var success = DeleteDir(new Java.IO.File(dir, children[i])); var success = DeleteDir(new Java.IO.File(dir, children[i]));
if(!success) if (!success)
{ {
return false; return false;
} }
} }
return dir.Delete(); return dir.Delete();
} }
else if(dir != null && dir.IsFile) else if (dir != null && dir.IsFile)
{ {
return dir.Delete(); return dir.Delete();
} }
@ -807,7 +807,7 @@ namespace Bit.Droid.Services
var pm = CrossCurrentActivity.Current.Activity.PackageManager; var pm = CrossCurrentActivity.Current.Activity.PackageManager;
var captureIntent = new Intent(MediaStore.ActionImageCapture); var captureIntent = new Intent(MediaStore.ActionImageCapture);
var listCam = pm.QueryIntentActivities(captureIntent, 0); var listCam = pm.QueryIntentActivities(captureIntent, 0);
foreach(var res in listCam) foreach (var res in listCam)
{ {
var packageName = res.ActivityInfo.PackageName; var packageName = res.ActivityInfo.PackageName;
var intent = new Intent(captureIntent); var intent = new Intent(captureIntent);
@ -823,7 +823,7 @@ namespace Bit.Droid.Services
{ {
var intent = new Intent(Intent.ActionView, Android.Net.Uri.Parse($"{url}?id={activity.PackageName}")); var intent = new Intent(Intent.ActionView, Android.Net.Uri.Parse($"{url}?id={activity.PackageName}"));
var flags = ActivityFlags.NoHistory | ActivityFlags.MultipleTask; var flags = ActivityFlags.NoHistory | ActivityFlags.MultipleTask;
if((int)Build.VERSION.SdkInt >= 21) if ((int)Build.VERSION.SdkInt >= 21)
{ {
flags |= ActivityFlags.NewDocument; flags |= ActivityFlags.NewDocument;
} }
@ -838,16 +838,16 @@ namespace Bit.Droid.Services
private async Task CopyTotpAsync(CipherView cipher) private async Task CopyTotpAsync(CipherView cipher)
{ {
if(!string.IsNullOrWhiteSpace(cipher?.Login?.Totp)) if (!string.IsNullOrWhiteSpace(cipher?.Login?.Totp))
{ {
var userService = ServiceContainer.Resolve<IUserService>("userService"); var userService = ServiceContainer.Resolve<IUserService>("userService");
var autoCopyDisabled = await _storageService.GetAsync<bool?>(Constants.DisableAutoTotpCopyKey); var autoCopyDisabled = await _storageService.GetAsync<bool?>(Constants.DisableAutoTotpCopyKey);
var canAccessPremium = await userService.CanAccessPremiumAsync(); var canAccessPremium = await userService.CanAccessPremiumAsync();
if((canAccessPremium || cipher.OrganizationUseTotp) && !autoCopyDisabled.GetValueOrDefault()) if ((canAccessPremium || cipher.OrganizationUseTotp) && !autoCopyDisabled.GetValueOrDefault())
{ {
var totpService = ServiceContainer.Resolve<ITotpService>("totpService"); var totpService = ServiceContainer.Resolve<ITotpService>("totpService");
var totp = await totpService.GetCodeAsync(cipher.Login.Totp); var totp = await totpService.GetCodeAsync(cipher.Login.Totp);
if(totp != null) if (totp != null)
{ {
CopyToClipboard(totp); CopyToClipboard(totp);
} }

View File

@ -18,7 +18,7 @@ namespace Bit.Droid.Services
{ {
ci = new CultureInfo(netLanguage); ci = new CultureInfo(netLanguage);
} }
catch(CultureNotFoundException e1) catch (CultureNotFoundException e1)
{ {
// iOS locale not valid .NET culture (eg. "en-ES" : English in Spain) // iOS locale not valid .NET culture (eg. "en-ES" : English in Spain)
// fallback to first characters, in this case "en" // fallback to first characters, in this case "en"
@ -28,7 +28,7 @@ namespace Bit.Droid.Services
Console.WriteLine(netLanguage + " failed, trying " + fallback + " (" + e1.Message + ")"); Console.WriteLine(netLanguage + " failed, trying " + fallback + " (" + e1.Message + ")");
ci = new CultureInfo(fallback); ci = new CultureInfo(fallback);
} }
catch(CultureNotFoundException e2) catch (CultureNotFoundException e2)
{ {
// iOS language not valid .NET culture, falling back to English // iOS language not valid .NET culture, falling back to English
Console.WriteLine(netLanguage + " couldn't be set, using 'en' (" + e2.Message + ")"); Console.WriteLine(netLanguage + " couldn't be set, using 'en' (" + e2.Message + ")");
@ -42,9 +42,9 @@ namespace Bit.Droid.Services
{ {
Console.WriteLine("Android Language:" + androidLanguage); Console.WriteLine("Android Language:" + androidLanguage);
var netLanguage = androidLanguage; var netLanguage = androidLanguage;
if(androidLanguage.StartsWith("zh")) if (androidLanguage.StartsWith("zh"))
{ {
if(androidLanguage.Contains("Hant") || androidLanguage.Contains("TW") || if (androidLanguage.Contains("Hant") || androidLanguage.Contains("TW") ||
androidLanguage.Contains("HK") || androidLanguage.Contains("MO")) androidLanguage.Contains("HK") || androidLanguage.Contains("MO"))
{ {
netLanguage = "zh-Hant"; netLanguage = "zh-Hant";
@ -54,7 +54,7 @@ namespace Bit.Droid.Services
netLanguage = "zh-Hans"; netLanguage = "zh-Hans";
} }
} }
else if(androidLanguage.StartsWith("iw")) else if (androidLanguage.StartsWith("iw"))
{ {
// Uncomment when we support RTL // Uncomment when we support RTL
// netLanguage = "he"; // netLanguage = "he";
@ -62,7 +62,7 @@ namespace Bit.Droid.Services
else else
{ {
// Certain languages need to be converted to CultureInfo equivalent // Certain languages need to be converted to CultureInfo equivalent
switch(androidLanguage) switch (androidLanguage)
{ {
case "ms-BN": // "Malaysian (Brunei)" not supported .NET culture case "ms-BN": // "Malaysian (Brunei)" not supported .NET culture
case "ms-MY": // "Malaysian (Malaysia)" not supported .NET culture case "ms-MY": // "Malaysian (Malaysia)" not supported .NET culture
@ -87,7 +87,7 @@ namespace Bit.Droid.Services
{ {
Console.WriteLine(".NET Fallback Language:" + platCulture.LanguageCode); Console.WriteLine(".NET Fallback Language:" + platCulture.LanguageCode);
var netLanguage = platCulture.LanguageCode; // use the first part of the identifier (two chars, usually); var netLanguage = platCulture.LanguageCode; // use the first part of the identifier (two chars, usually);
switch(platCulture.LanguageCode) switch (platCulture.LanguageCode)
{ {
case "gsw": case "gsw":
netLanguage = "de-CH"; // equivalent to German (Switzerland) for this app netLanguage = "de-CH"; // equivalent to German (Switzerland) for this app

View File

@ -46,7 +46,7 @@ namespace Bit.Droid.Tile
{ {
base.OnClick(); base.OnClick();
if(IsLocked) if (IsLocked)
{ {
UnlockAndRun(new Runnable(ScanAndFill)); UnlockAndRun(new Runnable(ScanAndFill));
} }
@ -59,7 +59,7 @@ namespace Bit.Droid.Tile
private void SetTileAdded(bool isAdded) private void SetTileAdded(bool isAdded)
{ {
AccessibilityHelpers.IsAutofillTileAdded = isAdded; AccessibilityHelpers.IsAutofillTileAdded = isAdded;
if(_storageService == null) if (_storageService == null)
{ {
_storageService = ServiceContainer.Resolve<IStorageService>("storageService"); _storageService = ServiceContainer.Resolve<IStorageService>("storageService");
} }
@ -68,7 +68,7 @@ namespace Bit.Droid.Tile
private void ScanAndFill() private void ScanAndFill()
{ {
if(!AccessibilityHelpers.IsAccessibilityBroadcastReady) if (!AccessibilityHelpers.IsAccessibilityBroadcastReady)
{ {
ShowConfigErrorDialog(); ShowConfigErrorDialog();
return; return;

View File

@ -44,7 +44,7 @@ namespace Bit.Droid.Tile
{ {
base.OnClick(); base.OnClick();
if(IsLocked) if (IsLocked)
{ {
UnlockAndRun(new Runnable(() => UnlockAndRun(new Runnable(() =>
{ {

View File

@ -44,7 +44,7 @@ namespace Bit.Droid.Tile
{ {
base.OnClick(); base.OnClick();
if(IsLocked) if (IsLocked)
{ {
UnlockAndRun(new Runnable(() => UnlockAndRun(new Runnable(() =>
{ {

View File

@ -15,11 +15,11 @@ namespace Bit.Droid.Utilities
string name = null; string name = null;
string[] projection = { MediaStore.MediaColumns.DisplayName }; string[] projection = { MediaStore.MediaColumns.DisplayName };
var metaCursor = context.ContentResolver.Query(uri, projection, null, null, null); var metaCursor = context.ContentResolver.Query(uri, projection, null, null, null);
if(metaCursor != null) if (metaCursor != null)
{ {
try try
{ {
if(metaCursor.MoveToFirst()) if (metaCursor.MoveToFirst())
{ {
name = metaCursor.GetString(0); name = metaCursor.GetString(0);
} }
@ -37,12 +37,12 @@ namespace Bit.Droid.Utilities
var restrictionsManager = (RestrictionsManager)context.GetSystemService(Context.RestrictionsService); var restrictionsManager = (RestrictionsManager)context.GetSystemService(Context.RestrictionsService);
var restrictions = restrictionsManager.ApplicationRestrictions; var restrictions = restrictionsManager.ApplicationRestrictions;
var dict = new Dictionary<string, string>(); var dict = new Dictionary<string, string>();
if(restrictions.ContainsKey(BaseEnvironmentUrlRestrictionKey)) if (restrictions.ContainsKey(BaseEnvironmentUrlRestrictionKey))
{ {
dict.Add(BaseEnvironmentUrlRestrictionKey, restrictions.GetString(BaseEnvironmentUrlRestrictionKey)); dict.Add(BaseEnvironmentUrlRestrictionKey, restrictions.GetString(BaseEnvironmentUrlRestrictionKey));
} }
if(dict.Count > 0) if (dict.Count > 0)
{ {
await AppHelpers.SetPreconfiguredSettingsAsync(dict); await AppHelpers.SetPreconfiguredSettingsAsync(dict);
} }

View File

@ -45,7 +45,7 @@ namespace Bit.Droid.Utilities
{ {
get get
{ {
if(_userId != null && _appId != null) if (_userId != null && _appId != null)
{ {
return JsonConvert.SerializeObject(new return JsonConvert.SerializeObject(new
{ {

View File

@ -69,7 +69,7 @@ namespace Bit.App
Bootstrap(); Bootstrap();
_broadcasterService.Subscribe(nameof(App), async (message) => _broadcasterService.Subscribe(nameof(App), async (message) =>
{ {
if(message.Command == "showDialog") if (message.Command == "showDialog")
{ {
var details = message.Data as DialogDetails; var details = message.Data as DialogDetails;
var confirmed = true; var confirmed = true;
@ -77,7 +77,7 @@ namespace Bit.App
AppResources.Ok : details.ConfirmText; AppResources.Ok : details.ConfirmText;
Device.BeginInvokeOnMainThread(async () => Device.BeginInvokeOnMainThread(async () =>
{ {
if(!string.IsNullOrWhiteSpace(details.CancelText)) if (!string.IsNullOrWhiteSpace(details.CancelText))
{ {
confirmed = await Current.MainPage.DisplayAlert(details.Title, details.Text, confirmText, confirmed = await Current.MainPage.DisplayAlert(details.Title, details.Text, confirmText,
details.CancelText); details.CancelText);
@ -89,55 +89,55 @@ namespace Bit.App
_messagingService.Send("showDialogResolve", new Tuple<int, bool>(details.DialogId, confirmed)); _messagingService.Send("showDialogResolve", new Tuple<int, bool>(details.DialogId, confirmed));
}); });
} }
else if(message.Command == "locked") else if (message.Command == "locked")
{ {
await LockedAsync(!(message.Data as bool?).GetValueOrDefault()); await LockedAsync(!(message.Data as bool?).GetValueOrDefault());
} }
else if(message.Command == "lockVault") else if (message.Command == "lockVault")
{ {
await _lockService.LockAsync(true); await _lockService.LockAsync(true);
} }
else if(message.Command == "logout") else if (message.Command == "logout")
{ {
Device.BeginInvokeOnMainThread(async () => Device.BeginInvokeOnMainThread(async () =>
await LogOutAsync((message.Data as bool?).GetValueOrDefault())); await LogOutAsync((message.Data as bool?).GetValueOrDefault()));
} }
else if(message.Command == "loggedOut") else if (message.Command == "loggedOut")
{ {
// Clean up old migrated key if they ever log out. // Clean up old migrated key if they ever log out.
await _secureStorageService.RemoveAsync("oldKey"); await _secureStorageService.RemoveAsync("oldKey");
} }
else if(message.Command == "resumed") else if (message.Command == "resumed")
{ {
if(Device.RuntimePlatform == Device.iOS) if (Device.RuntimePlatform == Device.iOS)
{ {
ResumedAsync(); ResumedAsync();
} }
} }
else if(message.Command == "slept") else if (message.Command == "slept")
{ {
if(Device.RuntimePlatform == Device.iOS) if (Device.RuntimePlatform == Device.iOS)
{ {
await SleptAsync(); await SleptAsync();
} }
} }
else if(message.Command == "migrated") else if (message.Command == "migrated")
{ {
await Task.Delay(1000); await Task.Delay(1000);
await SetMainPageAsync(); await SetMainPageAsync();
} }
else if(message.Command == "popAllAndGoToTabGenerator" || else if (message.Command == "popAllAndGoToTabGenerator" ||
message.Command == "popAllAndGoToTabMyVault") message.Command == "popAllAndGoToTabMyVault")
{ {
Device.BeginInvokeOnMainThread(async () => Device.BeginInvokeOnMainThread(async () =>
{ {
if(Current.MainPage is TabsPage tabsPage) if (Current.MainPage is TabsPage tabsPage)
{ {
while(tabsPage.Navigation.ModalStack.Count > 0) while (tabsPage.Navigation.ModalStack.Count > 0)
{ {
await tabsPage.Navigation.PopModalAsync(false); await tabsPage.Navigation.PopModalAsync(false);
} }
if(message.Command == "popAllAndGoToTabMyVault") if (message.Command == "popAllAndGoToTabMyVault")
{ {
_appOptions.MyVaultTile = false; _appOptions.MyVaultTile = false;
tabsPage.ResetToVaultPage(); tabsPage.ResetToVaultPage();
@ -161,13 +161,13 @@ namespace Bit.App
var maxTimeInMillis = 5000; var maxTimeInMillis = 5000;
var count = 0; var count = 0;
while(!_isResumed) while (!_isResumed)
{ {
Task.Delay(checkFrequencyInMillis).Wait(); Task.Delay(checkFrequencyInMillis).Wait();
count += checkFrequencyInMillis; count += checkFrequencyInMillis;
// don't let this run forever // don't let this run forever
if(count >= maxTimeInMillis) if (count >= maxTimeInMillis)
{ {
break; break;
} }
@ -180,11 +180,11 @@ namespace Bit.App
await ClearCacheIfNeededAsync(); await ClearCacheIfNeededAsync();
await TryClearCiphersCacheAsync(); await TryClearCiphersCacheAsync();
Prime(); Prime();
if(string.IsNullOrWhiteSpace(_appOptions.Uri)) if (string.IsNullOrWhiteSpace(_appOptions.Uri))
{ {
var updated = await AppHelpers.PerformUpdateTasksAsync(_syncService, _deviceActionService, var updated = await AppHelpers.PerformUpdateTasksAsync(_syncService, _deviceActionService,
_storageService); _storageService);
if(!updated) if (!updated)
{ {
SyncIfNeeded(); SyncIfNeeded();
} }
@ -196,10 +196,10 @@ namespace Bit.App
{ {
System.Diagnostics.Debug.WriteLine("XF App: OnSleep"); System.Diagnostics.Debug.WriteLine("XF App: OnSleep");
_isResumed = false; _isResumed = false;
if(Device.RuntimePlatform == Device.Android) if (Device.RuntimePlatform == Device.Android)
{ {
var isLocked = await _lockService.IsLockedAsync(); var isLocked = await _lockService.IsLockedAsync();
if(!isLocked) if (!isLocked)
{ {
await _storageService.SaveAsync(Constants.LastActiveKey, DateTime.UtcNow); await _storageService.SaveAsync(Constants.LastActiveKey, DateTime.UtcNow);
} }
@ -212,7 +212,7 @@ namespace Bit.App
{ {
System.Diagnostics.Debug.WriteLine("XF App: OnResume"); System.Diagnostics.Debug.WriteLine("XF App: OnResume");
_isResumed = true; _isResumed = true;
if(Device.RuntimePlatform == Device.Android) if (Device.RuntimePlatform == Device.Android)
{ {
ResumedAsync(); ResumedAsync();
} }
@ -232,9 +232,9 @@ namespace Bit.App
await TryClearCiphersCacheAsync(); await TryClearCiphersCacheAsync();
Prime(); Prime();
SyncIfNeeded(); SyncIfNeeded();
if(Current.MainPage is NavigationPage navPage && navPage.CurrentPage is LockPage lockPage) if (Current.MainPage is NavigationPage navPage && navPage.CurrentPage is LockPage lockPage)
{ {
if(Device.RuntimePlatform == Device.Android) if (Device.RuntimePlatform == Device.Android)
{ {
// Workaround for https://github.com/xamarin/Xamarin.Forms/issues/7478 // Workaround for https://github.com/xamarin/Xamarin.Forms/issues/7478
await Task.Delay(100); await Task.Delay(100);
@ -273,7 +273,7 @@ namespace Bit.App
_authService.LogOut(() => _authService.LogOut(() =>
{ {
Current.MainPage = new HomePage(); Current.MainPage = new HomePage();
if(expired) if (expired)
{ {
_platformUtilsService.ShowToast("warning", null, AppResources.LoginExpired); _platformUtilsService.ShowToast("warning", null, AppResources.LoginExpired);
} }
@ -283,17 +283,17 @@ namespace Bit.App
private async Task SetMainPageAsync() private async Task SetMainPageAsync()
{ {
var authed = await _userService.IsAuthenticatedAsync(); var authed = await _userService.IsAuthenticatedAsync();
if(authed) if (authed)
{ {
if(await _lockService.IsLockedAsync()) if (await _lockService.IsLockedAsync())
{ {
Current.MainPage = new NavigationPage(new LockPage(_appOptions)); Current.MainPage = new NavigationPage(new LockPage(_appOptions));
} }
else if(_appOptions.FromAutofillFramework && _appOptions.SaveType.HasValue) else if (_appOptions.FromAutofillFramework && _appOptions.SaveType.HasValue)
{ {
Current.MainPage = new NavigationPage(new AddEditPage(appOptions: _appOptions)); Current.MainPage = new NavigationPage(new AddEditPage(appOptions: _appOptions));
} }
else if(_appOptions.Uri != null) else if (_appOptions.Uri != null)
{ {
Current.MainPage = new NavigationPage(new AutofillCiphersPage(_appOptions)); Current.MainPage = new NavigationPage(new AutofillCiphersPage(_appOptions));
} }
@ -310,26 +310,26 @@ namespace Bit.App
private async Task HandleLockingAsync() private async Task HandleLockingAsync()
{ {
if(await _lockService.IsLockedAsync()) if (await _lockService.IsLockedAsync())
{ {
return; return;
} }
var authed = await _userService.IsAuthenticatedAsync(); var authed = await _userService.IsAuthenticatedAsync();
if(!authed) if (!authed)
{ {
return; return;
} }
var lockOption = _platformUtilsService.LockTimeout(); var lockOption = _platformUtilsService.LockTimeout();
if(lockOption == null) if (lockOption == null)
{ {
lockOption = await _storageService.GetAsync<int?>(Constants.LockOptionKey); lockOption = await _storageService.GetAsync<int?>(Constants.LockOptionKey);
} }
lockOption = lockOption.GetValueOrDefault(-1); lockOption = lockOption.GetValueOrDefault(-1);
if(lockOption > 0) if (lockOption > 0)
{ {
_messagingService.Send("scheduleLockTimer", lockOption.Value); _messagingService.Send("scheduleLockTimer", lockOption.Value);
} }
else if(lockOption == 0) else if (lockOption == 0)
{ {
await _lockService.LockAsync(true); await _lockService.LockAsync(true);
} }
@ -338,7 +338,7 @@ namespace Bit.App
private async Task ClearCacheIfNeededAsync() private async Task ClearCacheIfNeededAsync()
{ {
var lastClear = await _storageService.GetAsync<DateTime?>(Constants.LastFileCacheClearKey); var lastClear = await _storageService.GetAsync<DateTime?>(Constants.LastFileCacheClearKey);
if((DateTime.UtcNow - lastClear.GetValueOrDefault(DateTime.MinValue)).TotalDays >= 1) if ((DateTime.UtcNow - lastClear.GetValueOrDefault(DateTime.MinValue)).TotalDays >= 1)
{ {
var task = Task.Run(() => _deviceActionService.ClearCacheAsync()); var task = Task.Run(() => _deviceActionService.ClearCacheAsync());
} }
@ -346,7 +346,7 @@ namespace Bit.App
private void SetTabsPageFromAutofill(bool isLocked) private void SetTabsPageFromAutofill(bool isLocked)
{ {
if(Device.RuntimePlatform == Device.Android && !string.IsNullOrWhiteSpace(_appOptions.Uri) && if (Device.RuntimePlatform == Device.Android && !string.IsNullOrWhiteSpace(_appOptions.Uri) &&
!_appOptions.FromAutofillFramework) !_appOptions.FromAutofillFramework)
{ {
Task.Run(() => Task.Run(() =>
@ -354,7 +354,7 @@ namespace Bit.App
Device.BeginInvokeOnMainThread(() => Device.BeginInvokeOnMainThread(() =>
{ {
_appOptions.Uri = null; _appOptions.Uri = null;
if(isLocked) if (isLocked)
{ {
Current.MainPage = new NavigationPage(new LockPage()); Current.MainPage = new NavigationPage(new LockPage());
} }
@ -388,14 +388,14 @@ namespace Bit.App
private void SyncIfNeeded() private void SyncIfNeeded()
{ {
if(Xamarin.Essentials.Connectivity.NetworkAccess == Xamarin.Essentials.NetworkAccess.None) if (Xamarin.Essentials.Connectivity.NetworkAccess == Xamarin.Essentials.NetworkAccess.None)
{ {
return; return;
} }
Task.Run(async () => Task.Run(async () =>
{ {
var lastSync = await _syncService.GetLastSyncAsync(); var lastSync = await _syncService.GetLastSyncAsync();
if(lastSync == null || ((DateTime.UtcNow - lastSync) > TimeSpan.FromMinutes(30))) if (lastSync == null || ((DateTime.UtcNow - lastSync) > TimeSpan.FromMinutes(30)))
{ {
await Task.Delay(1000); await Task.Delay(1000);
await _syncService.FullSyncAsync(false); await _syncService.FullSyncAsync(false);
@ -405,12 +405,12 @@ namespace Bit.App
private async Task TryClearCiphersCacheAsync() private async Task TryClearCiphersCacheAsync()
{ {
if(Device.RuntimePlatform != Device.iOS) if (Device.RuntimePlatform != Device.iOS)
{ {
return; return;
} }
var clearCache = await _storageService.GetAsync<bool?>(Constants.ClearCiphersCacheKey); var clearCache = await _storageService.GetAsync<bool?>(Constants.ClearCiphersCacheKey);
if(clearCache.GetValueOrDefault()) if (clearCache.GetValueOrDefault())
{ {
_cipherService.ClearCache(); _cipherService.ClearCache();
await _storageService.RemoveAsync(Constants.ClearCiphersCacheKey); await _storageService.RemoveAsync(Constants.ClearCiphersCacheKey);
@ -420,26 +420,26 @@ namespace Bit.App
private async Task LockedAsync(bool autoPromptFingerprint) private async Task LockedAsync(bool autoPromptFingerprint)
{ {
await _stateService.PurgeAsync(); await _stateService.PurgeAsync();
if(autoPromptFingerprint && Device.RuntimePlatform == Device.iOS) if (autoPromptFingerprint && Device.RuntimePlatform == Device.iOS)
{ {
var lockOptions = await _storageService.GetAsync<int?>(Constants.LockOptionKey); var lockOptions = await _storageService.GetAsync<int?>(Constants.LockOptionKey);
if(lockOptions == 0) if (lockOptions == 0)
{ {
autoPromptFingerprint = false; autoPromptFingerprint = false;
} }
} }
else if(autoPromptFingerprint && Device.RuntimePlatform == Device.Android && else if (autoPromptFingerprint && Device.RuntimePlatform == Device.Android &&
_deviceActionService.UseNativeBiometric()) _deviceActionService.UseNativeBiometric())
{ {
autoPromptFingerprint = false; autoPromptFingerprint = false;
} }
PreviousPageInfo lastPageBeforeLock = null; PreviousPageInfo lastPageBeforeLock = null;
if(Current.MainPage is TabbedPage tabbedPage && tabbedPage.Navigation.ModalStack.Count > 0) if (Current.MainPage is TabbedPage tabbedPage && tabbedPage.Navigation.ModalStack.Count > 0)
{ {
var topPage = tabbedPage.Navigation.ModalStack[tabbedPage.Navigation.ModalStack.Count - 1]; var topPage = tabbedPage.Navigation.ModalStack[tabbedPage.Navigation.ModalStack.Count - 1];
if(topPage is NavigationPage navPage) if (topPage is NavigationPage navPage)
{ {
if(navPage.CurrentPage is ViewPage viewPage) if (navPage.CurrentPage is ViewPage viewPage)
{ {
lastPageBeforeLock = new PreviousPageInfo lastPageBeforeLock = new PreviousPageInfo
{ {
@ -447,7 +447,7 @@ namespace Bit.App
CipherId = viewPage.ViewModel.CipherId CipherId = viewPage.ViewModel.CipherId
}; };
} }
else if(navPage.CurrentPage is AddEditPage addEditPage && addEditPage.ViewModel.EditMode) else if (navPage.CurrentPage is AddEditPage addEditPage && addEditPage.ViewModel.EditMode)
{ {
lastPageBeforeLock = new PreviousPageInfo lastPageBeforeLock = new PreviousPageInfo
{ {

View File

@ -28,7 +28,7 @@ namespace Bit.App.Controls
public CipherViewCell() public CipherViewCell()
{ {
_environmentService = ServiceContainer.Resolve<IEnvironmentService>("environmentService"); _environmentService = ServiceContainer.Resolve<IEnvironmentService>("environmentService");
if(Device.RuntimePlatform == Device.iOS) if (Device.RuntimePlatform == Device.iOS)
{ {
InitializeComponent(); InitializeComponent();
_viewModel = _grid.BindingContext as CipherViewCellViewModel; _viewModel = _grid.BindingContext as CipherViewCellViewModel;
@ -60,11 +60,11 @@ namespace Bit.App.Controls
protected override void OnPropertyChanged(string propertyName = null) protected override void OnPropertyChanged(string propertyName = null)
{ {
base.OnPropertyChanged(propertyName); base.OnPropertyChanged(propertyName);
if(_usingNativeCell) if (_usingNativeCell)
{ {
return; return;
} }
if(propertyName == CipherProperty.PropertyName) if (propertyName == CipherProperty.PropertyName)
{ {
_viewModel.Cipher = Cipher; _viewModel.Cipher = Cipher;
} }
@ -73,25 +73,25 @@ namespace Bit.App.Controls
protected override void OnBindingContextChanged() protected override void OnBindingContextChanged()
{ {
base.OnBindingContextChanged(); base.OnBindingContextChanged();
if(_usingNativeCell) if (_usingNativeCell)
{ {
return; return;
} }
_image.Source = null; _image.Source = null;
CipherView cipher = null; CipherView cipher = null;
if(BindingContext is GroupingsPageListItem groupingsPageListItem) if (BindingContext is GroupingsPageListItem groupingsPageListItem)
{ {
cipher = groupingsPageListItem.Cipher; cipher = groupingsPageListItem.Cipher;
} }
else if(BindingContext is CipherView cv) else if (BindingContext is CipherView cv)
{ {
cipher = cv; cipher = cv;
} }
if(cipher != null) if (cipher != null)
{ {
var iconImage = GetIconImage(cipher); var iconImage = GetIconImage(cipher);
if(iconImage.Item2 != null) if (iconImage.Item2 != null)
{ {
_image.IsVisible = true; _image.IsVisible = true;
_icon.IsVisible = false; _icon.IsVisible = false;
@ -111,7 +111,7 @@ namespace Bit.App.Controls
{ {
string icon = null; string icon = null;
string image = null; string image = null;
switch(cipher.Type) switch (cipher.Type)
{ {
case CipherType.Login: case CipherType.Login:
var loginIconImage = GetLoginIconImage(cipher); var loginIconImage = GetLoginIconImage(cipher);
@ -137,36 +137,36 @@ namespace Bit.App.Controls
{ {
string icon = ""; string icon = "";
string image = null; string image = null;
if(cipher.Login.Uri != null) if (cipher.Login.Uri != null)
{ {
var hostnameUri = cipher.Login.Uri; var hostnameUri = cipher.Login.Uri;
var isWebsite = false; var isWebsite = false;
if(hostnameUri.StartsWith(Constants.AndroidAppProtocol)) if (hostnameUri.StartsWith(Constants.AndroidAppProtocol))
{ {
icon = ""; icon = "";
} }
else if(hostnameUri.StartsWith(Constants.iOSAppProtocol)) else if (hostnameUri.StartsWith(Constants.iOSAppProtocol))
{ {
icon = ""; icon = "";
} }
else if(WebsiteIconsEnabled && !hostnameUri.Contains("://") && hostnameUri.Contains(".")) else if (WebsiteIconsEnabled && !hostnameUri.Contains("://") && hostnameUri.Contains("."))
{ {
hostnameUri = string.Concat("http://", hostnameUri); hostnameUri = string.Concat("http://", hostnameUri);
isWebsite = true; isWebsite = true;
} }
else if(WebsiteIconsEnabled) else if (WebsiteIconsEnabled)
{ {
isWebsite = hostnameUri.StartsWith("http") && hostnameUri.Contains("."); isWebsite = hostnameUri.StartsWith("http") && hostnameUri.Contains(".");
} }
if(WebsiteIconsEnabled && isWebsite) if (WebsiteIconsEnabled && isWebsite)
{ {
var hostname = CoreHelpers.GetHostname(hostnameUri); var hostname = CoreHelpers.GetHostname(hostnameUri);
var iconsUrl = _environmentService.IconsUrl; var iconsUrl = _environmentService.IconsUrl;
if(string.IsNullOrWhiteSpace(iconsUrl)) if (string.IsNullOrWhiteSpace(iconsUrl))
{ {
if(!string.IsNullOrWhiteSpace(_environmentService.BaseUrl)) if (!string.IsNullOrWhiteSpace(_environmentService.BaseUrl))
{ {
iconsUrl = string.Format("{0}/icons", _environmentService.BaseUrl); iconsUrl = string.Format("{0}/icons", _environmentService.BaseUrl);
} }

View File

@ -8,10 +8,10 @@ namespace Bit.App.Controls
{ {
public ExtendedSearchBar() public ExtendedSearchBar()
{ {
if(Device.RuntimePlatform == Device.iOS) if (Device.RuntimePlatform == Device.iOS)
{ {
var deviceActionService = ServiceContainer.Resolve<IDeviceActionService>("deviceActionService", true); var deviceActionService = ServiceContainer.Resolve<IDeviceActionService>("deviceActionService", true);
if(!deviceActionService?.UsingDarkTheme() ?? false) if (!deviceActionService?.UsingDarkTheme() ?? false)
{ {
TextColor = Color.Black; TextColor = Color.Black;
} }

View File

@ -7,7 +7,7 @@ namespace Bit.App.Controls
public FaButton() public FaButton()
{ {
Padding = 0; Padding = 0;
switch(Device.RuntimePlatform) switch (Device.RuntimePlatform)
{ {
case Device.iOS: case Device.iOS:
FontFamily = "FontAwesome"; FontFamily = "FontAwesome";

View File

@ -6,7 +6,7 @@ namespace Bit.App.Controls
{ {
public FaLabel() public FaLabel()
{ {
switch(Device.RuntimePlatform) switch (Device.RuntimePlatform)
{ {
case Device.iOS: case Device.iOS:
FontFamily = "FontAwesome"; FontFamily = "FontAwesome";

View File

@ -7,7 +7,7 @@ namespace Bit.App.Controls
public MiButton() public MiButton()
{ {
Padding = 0; Padding = 0;
switch(Device.RuntimePlatform) switch (Device.RuntimePlatform)
{ {
case Device.iOS: case Device.iOS:
FontFamily = "Material Icons"; FontFamily = "Material Icons";

View File

@ -6,7 +6,7 @@ namespace Bit.App.Controls
{ {
public MiLabel() public MiLabel()
{ {
switch(Device.RuntimePlatform) switch (Device.RuntimePlatform)
{ {
case Device.iOS: case Device.iOS:
FontFamily = "Material Icons"; FontFamily = "Material Icons";

View File

@ -6,7 +6,7 @@ namespace Bit.App.Controls
{ {
public MonoEntry() public MonoEntry()
{ {
switch(Device.RuntimePlatform) switch (Device.RuntimePlatform)
{ {
case Device.iOS: case Device.iOS:
FontFamily = "Menlo-Regular"; FontFamily = "Menlo-Regular";

View File

@ -6,7 +6,7 @@ namespace Bit.App.Controls
{ {
public MonoLabel() public MonoLabel()
{ {
switch(Device.RuntimePlatform) switch (Device.RuntimePlatform)
{ {
case Device.iOS: case Device.iOS:
FontFamily = "Menlo-Regular"; FontFamily = "Menlo-Regular";

View File

@ -39,7 +39,7 @@ namespace Bit.App.Controls
protected override void OnPropertyChanged(string propertyName = null) protected override void OnPropertyChanged(string propertyName = null)
{ {
base.OnPropertyChanged(propertyName); base.OnPropertyChanged(propertyName);
if(propertyName == ItemTemplateProperty.PropertyName || propertyName == ItemsSourceProperty.PropertyName) if (propertyName == ItemTemplateProperty.PropertyName || propertyName == ItemsSourceProperty.PropertyName)
{ {
Populate(); Populate();
} }
@ -55,9 +55,9 @@ namespace Bit.App.Controls
{ {
View view = null; View view = null;
var template = ItemTemplate; var template = ItemTemplate;
if(template != null) if (template != null)
{ {
if(template is DataTemplateSelector selector) if (template is DataTemplateSelector selector)
{ {
template = selector.SelectTemplate(item, this); template = selector.SelectTemplate(item, this);
} }
@ -70,10 +70,10 @@ namespace Bit.App.Controls
private void Populate() private void Populate()
{ {
if(ItemsSource != null) if (ItemsSource != null)
{ {
Children.Clear(); Children.Clear();
foreach(var item in ItemsSource) foreach (var item in ItemsSource)
{ {
Children.Add(ViewFor(item)); Children.Add(ViewFor(item));
} }
@ -82,11 +82,11 @@ namespace Bit.App.Controls
private static void ItemsSourceChanging(BindableObject bindable, object oldValue, object newValue) private static void ItemsSourceChanging(BindableObject bindable, object oldValue, object newValue)
{ {
if(oldValue != null && oldValue is INotifyCollectionChanged ov) if (oldValue != null && oldValue is INotifyCollectionChanged ov)
{ {
ov.CollectionChanged -= (bindable as RepeaterView).OnCollectionChanged; ov.CollectionChanged -= (bindable as RepeaterView).OnCollectionChanged;
} }
if(newValue != null && newValue is INotifyCollectionChanged nv) if (newValue != null && newValue is INotifyCollectionChanged nv)
{ {
nv.CollectionChanged += (bindable as RepeaterView).OnCollectionChanged; nv.CollectionChanged += (bindable as RepeaterView).OnCollectionChanged;
} }

View File

@ -6,7 +6,7 @@ namespace Bit.App.Models
{ {
public PlatformCulture(string platformCultureString) public PlatformCulture(string platformCultureString)
{ {
if(string.IsNullOrWhiteSpace(platformCultureString)) if (string.IsNullOrWhiteSpace(platformCultureString))
{ {
throw new ArgumentException("Expected culture identifier.", nameof(platformCultureString)); throw new ArgumentException("Expected culture identifier.", nameof(platformCultureString));
} }
@ -14,7 +14,7 @@ namespace Bit.App.Models
// .NET expects dash, not underscore // .NET expects dash, not underscore
PlatformString = platformCultureString.Replace("_", "-"); PlatformString = platformCultureString.Replace("_", "-");
var dashIndex = PlatformString.IndexOf("-", StringComparison.Ordinal); var dashIndex = PlatformString.IndexOf("-", StringComparison.Ordinal);
if(dashIndex > 0) if (dashIndex > 0)
{ {
var parts = PlatformString.Split('-'); var parts = PlatformString.Split('-');
LanguageCode = parts[0]; LanguageCode = parts[0];

View File

@ -17,7 +17,7 @@ namespace Bit.App.Pages
InitializeComponent(); InitializeComponent();
_vm = BindingContext as EnvironmentPageViewModel; _vm = BindingContext as EnvironmentPageViewModel;
_vm.Page = this; _vm.Page = this;
if(Device.RuntimePlatform == Device.Android) if (Device.RuntimePlatform == Device.Android)
{ {
ToolbarItems.RemoveAt(0); ToolbarItems.RemoveAt(0);
} }
@ -32,7 +32,7 @@ namespace Bit.App.Pages
private async void Submit_Clicked(object sender, EventArgs e) private async void Submit_Clicked(object sender, EventArgs e)
{ {
if(DoOnce()) if (DoOnce())
{ {
await _vm.SubmitAsync(); await _vm.SubmitAsync();
} }
@ -40,7 +40,7 @@ namespace Bit.App.Pages
private async void Close_Clicked(object sender, EventArgs e) private async void Close_Clicked(object sender, EventArgs e)
{ {
if(DoOnce()) if (DoOnce())
{ {
_messagingService.Send("showStatusBar", false); _messagingService.Send("showStatusBar", false);
await Navigation.PopModalAsync(); await Navigation.PopModalAsync();

View File

@ -12,7 +12,7 @@ namespace Bit.App.Pages
InitializeComponent(); InitializeComponent();
_vm = BindingContext as HintPageViewModel; _vm = BindingContext as HintPageViewModel;
_vm.Page = this; _vm.Page = this;
if(Device.RuntimePlatform == Device.Android) if (Device.RuntimePlatform == Device.Android)
{ {
ToolbarItems.RemoveAt(0); ToolbarItems.RemoveAt(0);
} }
@ -26,7 +26,7 @@ namespace Bit.App.Pages
private async void Submit_Clicked(object sender, EventArgs e) private async void Submit_Clicked(object sender, EventArgs e)
{ {
if(DoOnce()) if (DoOnce())
{ {
await _vm.SubmitAsync(); await _vm.SubmitAsync();
} }
@ -34,7 +34,7 @@ namespace Bit.App.Pages
private async void Close_Clicked(object sender, System.EventArgs e) private async void Close_Clicked(object sender, System.EventArgs e)
{ {
if(DoOnce()) if (DoOnce())
{ {
await Navigation.PopModalAsync(); await Navigation.PopModalAsync();
} }

View File

@ -29,20 +29,20 @@ namespace Bit.App.Pages
public async Task SubmitAsync() public async Task SubmitAsync()
{ {
if(Xamarin.Essentials.Connectivity.NetworkAccess == Xamarin.Essentials.NetworkAccess.None) if (Xamarin.Essentials.Connectivity.NetworkAccess == Xamarin.Essentials.NetworkAccess.None)
{ {
await _platformUtilsService.ShowDialogAsync(AppResources.InternetConnectionRequiredMessage, await _platformUtilsService.ShowDialogAsync(AppResources.InternetConnectionRequiredMessage,
AppResources.InternetConnectionRequiredTitle); AppResources.InternetConnectionRequiredTitle);
return; return;
} }
if(string.IsNullOrWhiteSpace(Email)) if (string.IsNullOrWhiteSpace(Email))
{ {
await Page.DisplayAlert(AppResources.AnErrorHasOccurred, await Page.DisplayAlert(AppResources.AnErrorHasOccurred,
string.Format(AppResources.ValidationFieldRequired, AppResources.EmailAddress), string.Format(AppResources.ValidationFieldRequired, AppResources.EmailAddress),
AppResources.Ok); AppResources.Ok);
return; return;
} }
if(!Email.Contains("@")) if (!Email.Contains("@"))
{ {
await Page.DisplayAlert(AppResources.AnErrorHasOccurred, AppResources.InvalidEmail, AppResources.Ok); await Page.DisplayAlert(AppResources.AnErrorHasOccurred, AppResources.InvalidEmail, AppResources.Ok);
return; return;
@ -57,10 +57,10 @@ namespace Bit.App.Pages
await Page.DisplayAlert(null, AppResources.PasswordHintAlert, AppResources.Ok); await Page.DisplayAlert(null, AppResources.PasswordHintAlert, AppResources.Ok);
await Page.Navigation.PopModalAsync(); await Page.Navigation.PopModalAsync();
} }
catch(ApiException e) catch (ApiException e)
{ {
await _deviceActionService.HideLoadingAsync(); await _deviceActionService.HideLoadingAsync();
if(e?.Error != null) if (e?.Error != null)
{ {
await _platformUtilsService.ShowDialogAsync(e.Error.GetSingleMessage(), await _platformUtilsService.ShowDialogAsync(e.Error.GetSingleMessage(),
AppResources.AnErrorHasOccurred); AppResources.AnErrorHasOccurred);

View File

@ -33,7 +33,7 @@ namespace Bit.App.Pages
private void LogIn_Clicked(object sender, EventArgs e) private void LogIn_Clicked(object sender, EventArgs e)
{ {
if(DoOnce()) if (DoOnce())
{ {
Navigation.PushModalAsync(new NavigationPage(new LoginPage())); Navigation.PushModalAsync(new NavigationPage(new LoginPage()));
} }
@ -41,7 +41,7 @@ namespace Bit.App.Pages
private void Register_Clicked(object sender, EventArgs e) private void Register_Clicked(object sender, EventArgs e)
{ {
if(DoOnce()) if (DoOnce())
{ {
Navigation.PushModalAsync(new NavigationPage(new RegisterPage(this))); Navigation.PushModalAsync(new NavigationPage(new RegisterPage(this)));
} }
@ -49,7 +49,7 @@ namespace Bit.App.Pages
private void Settings_Clicked(object sender, EventArgs e) private void Settings_Clicked(object sender, EventArgs e)
{ {
if(DoOnce()) if (DoOnce())
{ {
Navigation.PushModalAsync(new NavigationPage(new EnvironmentPage())); Navigation.PushModalAsync(new NavigationPage(new EnvironmentPage()));
} }

View File

@ -36,10 +36,10 @@ namespace Bit.App.Pages
public async Task PromptFingerprintAfterResumeAsync() public async Task PromptFingerprintAfterResumeAsync()
{ {
if(_vm.FingerprintLock) if (_vm.FingerprintLock)
{ {
await Task.Delay(500); await Task.Delay(500);
if(!_promptedAfterResume) if (!_promptedAfterResume)
{ {
_promptedAfterResume = true; _promptedAfterResume = true;
await _vm?.PromptFingerprintAsync(); await _vm?.PromptFingerprintAsync();
@ -50,15 +50,15 @@ namespace Bit.App.Pages
protected override async void OnAppearing() protected override async void OnAppearing()
{ {
base.OnAppearing(); base.OnAppearing();
if(_appeared) if (_appeared)
{ {
return; return;
} }
_appeared = true; _appeared = true;
await _vm.InitAsync(_autoPromptFingerprint); await _vm.InitAsync(_autoPromptFingerprint);
if(!_vm.FingerprintLock) if (!_vm.FingerprintLock)
{ {
if(_vm.PinLock) if (_vm.PinLock)
{ {
RequestFocus(PinEntry); RequestFocus(PinEntry);
} }
@ -71,7 +71,7 @@ namespace Bit.App.Pages
private void Unlock_Clicked(object sender, EventArgs e) private void Unlock_Clicked(object sender, EventArgs e)
{ {
if(DoOnce()) if (DoOnce())
{ {
var tasks = Task.Run(async () => var tasks = Task.Run(async () =>
{ {
@ -83,7 +83,7 @@ namespace Bit.App.Pages
private async void LogOut_Clicked(object sender, EventArgs e) private async void LogOut_Clicked(object sender, EventArgs e)
{ {
if(DoOnce()) if (DoOnce())
{ {
await _vm.LogOutAsync(); await _vm.LogOutAsync();
} }
@ -91,7 +91,7 @@ namespace Bit.App.Pages
private async void Fingerprint_Clicked(object sender, EventArgs e) private async void Fingerprint_Clicked(object sender, EventArgs e)
{ {
if(DoOnce()) if (DoOnce())
{ {
await _vm.PromptFingerprintAsync(); await _vm.PromptFingerprintAsync();
} }
@ -99,21 +99,21 @@ namespace Bit.App.Pages
private async Task UnlockedAsync() private async Task UnlockedAsync()
{ {
if(_appOptions != null) if (_appOptions != null)
{ {
if(_appOptions.FromAutofillFramework && _appOptions.SaveType.HasValue) if (_appOptions.FromAutofillFramework && _appOptions.SaveType.HasValue)
{ {
Application.Current.MainPage = new NavigationPage(new AddEditPage(appOptions: _appOptions)); Application.Current.MainPage = new NavigationPage(new AddEditPage(appOptions: _appOptions));
return; return;
} }
else if(_appOptions.Uri != null) else if (_appOptions.Uri != null)
{ {
Application.Current.MainPage = new NavigationPage(new AutofillCiphersPage(_appOptions)); Application.Current.MainPage = new NavigationPage(new AutofillCiphersPage(_appOptions));
return; return;
} }
} }
var previousPage = await _storageService.GetAsync<PreviousPageInfo>(Constants.PreviousPageKey); var previousPage = await _storageService.GetAsync<PreviousPageInfo>(Constants.PreviousPageKey);
if(previousPage != null) if (previousPage != null)
{ {
await _storageService.RemoveAsync(Constants.PreviousPageKey); await _storageService.RemoveAsync(Constants.PreviousPageKey);
} }

View File

@ -107,13 +107,13 @@ namespace Bit.App.Pages
FingerprintLock = await _lockService.IsFingerprintLockSetAsync(); FingerprintLock = await _lockService.IsFingerprintLockSetAsync();
_email = await _userService.GetEmailAsync(); _email = await _userService.GetEmailAsync();
var webVault = _environmentService.GetWebVaultUrl(); var webVault = _environmentService.GetWebVaultUrl();
if(string.IsNullOrWhiteSpace(webVault)) if (string.IsNullOrWhiteSpace(webVault))
{ {
webVault = "https://bitwarden.com"; webVault = "https://bitwarden.com";
} }
var webVaultHostname = CoreHelpers.GetHostname(webVault); var webVaultHostname = CoreHelpers.GetHostname(webVault);
LoggedInAsText = string.Format(AppResources.LoggedInAsOn, _email, webVaultHostname); LoggedInAsText = string.Format(AppResources.LoggedInAsOn, _email, webVaultHostname);
if(PinLock) if (PinLock)
{ {
PageTitle = AppResources.VerifyPIN; PageTitle = AppResources.VerifyPIN;
LockedVerifyText = AppResources.VaultLockedPIN; LockedVerifyText = AppResources.VaultLockedPIN;
@ -124,14 +124,14 @@ namespace Bit.App.Pages
LockedVerifyText = AppResources.VaultLockedMasterPassword; LockedVerifyText = AppResources.VaultLockedMasterPassword;
} }
if(FingerprintLock) if (FingerprintLock)
{ {
var supportsFace = await _deviceActionService.SupportsFaceBiometricAsync(); var supportsFace = await _deviceActionService.SupportsFaceBiometricAsync();
if(Device.RuntimePlatform == Device.iOS && supportsFace) if (Device.RuntimePlatform == Device.iOS && supportsFace)
{ {
FingerprintButtonText = AppResources.UseFaceIDToUnlock; FingerprintButtonText = AppResources.UseFaceIDToUnlock;
} }
else if(Device.RuntimePlatform == Device.Android && _deviceActionService.UseNativeBiometric()) else if (Device.RuntimePlatform == Device.Android && _deviceActionService.UseNativeBiometric())
{ {
FingerprintButtonText = AppResources.UseBiometricsToUnlock; FingerprintButtonText = AppResources.UseBiometricsToUnlock;
} }
@ -139,7 +139,7 @@ namespace Bit.App.Pages
{ {
FingerprintButtonText = AppResources.UseFingerprintToUnlock; FingerprintButtonText = AppResources.UseFingerprintToUnlock;
} }
if(autoPromptFingerprint) if (autoPromptFingerprint)
{ {
var tasks = Task.Run(async () => var tasks = Task.Run(async () =>
{ {
@ -152,14 +152,14 @@ namespace Bit.App.Pages
public async Task SubmitAsync() public async Task SubmitAsync()
{ {
if(PinLock && string.IsNullOrWhiteSpace(Pin)) if (PinLock && string.IsNullOrWhiteSpace(Pin))
{ {
await Page.DisplayAlert(AppResources.AnErrorHasOccurred, await Page.DisplayAlert(AppResources.AnErrorHasOccurred,
string.Format(AppResources.ValidationFieldRequired, AppResources.PIN), string.Format(AppResources.ValidationFieldRequired, AppResources.PIN),
AppResources.Ok); AppResources.Ok);
return; return;
} }
if(!PinLock && string.IsNullOrWhiteSpace(MasterPassword)) if (!PinLock && string.IsNullOrWhiteSpace(MasterPassword))
{ {
await Page.DisplayAlert(AppResources.AnErrorHasOccurred, await Page.DisplayAlert(AppResources.AnErrorHasOccurred,
string.Format(AppResources.ValidationFieldRequired, AppResources.MasterPassword), string.Format(AppResources.ValidationFieldRequired, AppResources.MasterPassword),
@ -171,12 +171,12 @@ namespace Bit.App.Pages
var kdf = await _userService.GetKdfAsync(); var kdf = await _userService.GetKdfAsync();
var kdfIterations = await _userService.GetKdfIterationsAsync(); var kdfIterations = await _userService.GetKdfIterationsAsync();
if(PinLock) if (PinLock)
{ {
var failed = true; var failed = true;
try try
{ {
if(_pinSet.Item1) if (_pinSet.Item1)
{ {
var key = await _cryptoService.MakeKeyFromPinAsync(Pin, _email, var key = await _cryptoService.MakeKeyFromPinAsync(Pin, _email,
kdf.GetValueOrDefault(KdfType.PBKDF2_SHA256), kdfIterations.GetValueOrDefault(5000), kdf.GetValueOrDefault(KdfType.PBKDF2_SHA256), kdfIterations.GetValueOrDefault(5000),
@ -185,7 +185,7 @@ namespace Bit.App.Pages
var protectedPin = await _storageService.GetAsync<string>(Constants.ProtectedPin); var protectedPin = await _storageService.GetAsync<string>(Constants.ProtectedPin);
var decPin = await _cryptoService.DecryptToUtf8Async(new CipherString(protectedPin), encKey); var decPin = await _cryptoService.DecryptToUtf8Async(new CipherString(protectedPin), encKey);
failed = decPin != Pin; failed = decPin != Pin;
if(!failed) if (!failed)
{ {
Pin = string.Empty; Pin = string.Empty;
await SetKeyAndContinueAsync(key); await SetKeyAndContinueAsync(key);
@ -204,10 +204,10 @@ namespace Bit.App.Pages
{ {
failed = true; failed = true;
} }
if(failed) if (failed)
{ {
_invalidPinAttempts++; _invalidPinAttempts++;
if(_invalidPinAttempts >= 5) if (_invalidPinAttempts >= 5)
{ {
_messagingService.Send("logout"); _messagingService.Send("logout");
return; return;
@ -221,19 +221,19 @@ namespace Bit.App.Pages
var key = await _cryptoService.MakeKeyAsync(MasterPassword, _email, kdf, kdfIterations); var key = await _cryptoService.MakeKeyAsync(MasterPassword, _email, kdf, kdfIterations);
var keyHash = await _cryptoService.HashPasswordAsync(MasterPassword, key); var keyHash = await _cryptoService.HashPasswordAsync(MasterPassword, key);
var storedKeyHash = await _cryptoService.GetKeyHashAsync(); var storedKeyHash = await _cryptoService.GetKeyHashAsync();
if(storedKeyHash == null) if (storedKeyHash == null)
{ {
var oldKey = await _secureStorageService.GetAsync<string>("oldKey"); var oldKey = await _secureStorageService.GetAsync<string>("oldKey");
if(key.KeyB64 == oldKey) if (key.KeyB64 == oldKey)
{ {
await _secureStorageService.RemoveAsync("oldKey"); await _secureStorageService.RemoveAsync("oldKey");
await _cryptoService.SetKeyHashAsync(keyHash); await _cryptoService.SetKeyHashAsync(keyHash);
storedKeyHash = keyHash; storedKeyHash = keyHash;
} }
} }
if(storedKeyHash != null && keyHash != null && storedKeyHash == keyHash) if (storedKeyHash != null && keyHash != null && storedKeyHash == keyHash)
{ {
if(_pinSet.Item1) if (_pinSet.Item1)
{ {
var protectedPin = await _storageService.GetAsync<string>(Constants.ProtectedPin); var protectedPin = await _storageService.GetAsync<string>(Constants.ProtectedPin);
var encKey = await _cryptoService.GetEncKeyAsync(key); var encKey = await _cryptoService.GetEncKeyAsync(key);
@ -257,7 +257,7 @@ namespace Bit.App.Pages
{ {
var confirmed = await _platformUtilsService.ShowDialogAsync(AppResources.LogoutConfirmation, var confirmed = await _platformUtilsService.ShowDialogAsync(AppResources.LogoutConfirmation,
AppResources.LogOut, AppResources.Yes, AppResources.Cancel); AppResources.LogOut, AppResources.Yes, AppResources.Cancel);
if(confirmed) if (confirmed)
{ {
_messagingService.Send("logout"); _messagingService.Send("logout");
} }
@ -273,7 +273,7 @@ namespace Bit.App.Pages
public async Task PromptFingerprintAsync() public async Task PromptFingerprintAsync()
{ {
if(!FingerprintLock) if (!FingerprintLock)
{ {
return; return;
} }
@ -281,7 +281,7 @@ namespace Bit.App.Pages
PinLock ? AppResources.PIN : AppResources.MasterPassword, () => PinLock ? AppResources.PIN : AppResources.MasterPassword, () =>
{ {
var page = Page as LockPage; var page = Page as LockPage;
if(PinLock) if (PinLock)
{ {
page.PinEntry.Focus(); page.PinEntry.Focus();
} }
@ -291,7 +291,7 @@ namespace Bit.App.Pages
} }
}); });
_lockService.FingerprintLocked = !success; _lockService.FingerprintLocked = !success;
if(success) if (success)
{ {
await DoContinueAsync(); await DoContinueAsync();
} }
@ -300,7 +300,7 @@ namespace Bit.App.Pages
private async Task SetKeyAndContinueAsync(SymmetricCryptoKey key) private async Task SetKeyAndContinueAsync(SymmetricCryptoKey key)
{ {
var hasKey = await _cryptoService.HasKeyAsync(); var hasKey = await _cryptoService.HasKeyAsync();
if(!hasKey) if (!hasKey)
{ {
await _cryptoService.SetKeyAsync(key); await _cryptoService.SetKeyAsync(key);
} }

View File

@ -19,7 +19,7 @@ namespace Bit.App.Pages
_vm.Page = this; _vm.Page = this;
_vm.Email = email; _vm.Email = email;
MasterPasswordEntry = _masterPassword; MasterPasswordEntry = _masterPassword;
if(Device.RuntimePlatform == Device.Android) if (Device.RuntimePlatform == Device.Android)
{ {
ToolbarItems.RemoveAt(0); ToolbarItems.RemoveAt(0);
} }
@ -34,7 +34,7 @@ namespace Bit.App.Pages
{ {
base.OnAppearing(); base.OnAppearing();
await _vm.InitAsync(); await _vm.InitAsync();
if(string.IsNullOrWhiteSpace(_vm.Email)) if (string.IsNullOrWhiteSpace(_vm.Email))
{ {
RequestFocus(_email); RequestFocus(_email);
} }
@ -46,7 +46,7 @@ namespace Bit.App.Pages
private async void LogIn_Clicked(object sender, EventArgs e) private async void LogIn_Clicked(object sender, EventArgs e)
{ {
if(DoOnce()) if (DoOnce())
{ {
await _vm.LogInAsync(); await _vm.LogInAsync();
} }
@ -54,7 +54,7 @@ namespace Bit.App.Pages
private void Hint_Clicked(object sender, EventArgs e) private void Hint_Clicked(object sender, EventArgs e)
{ {
if(DoOnce()) if (DoOnce())
{ {
Navigation.PushModalAsync(new NavigationPage(new HintPage())); Navigation.PushModalAsync(new NavigationPage(new HintPage()));
} }
@ -62,7 +62,7 @@ namespace Bit.App.Pages
private async void Close_Clicked(object sender, EventArgs e) private async void Close_Clicked(object sender, EventArgs e)
{ {
if(DoOnce()) if (DoOnce())
{ {
_messagingService.Send("showStatusBar", false); _messagingService.Send("showStatusBar", false);
await Navigation.PopModalAsync(); await Navigation.PopModalAsync();

View File

@ -68,7 +68,7 @@ namespace Bit.App.Pages
public async Task InitAsync() public async Task InitAsync()
{ {
if(string.IsNullOrWhiteSpace(Email)) if (string.IsNullOrWhiteSpace(Email))
{ {
Email = await _storageService.GetAsync<string>(Keys_RememberedEmail); Email = await _storageService.GetAsync<string>(Keys_RememberedEmail);
} }
@ -78,25 +78,25 @@ namespace Bit.App.Pages
public async Task LogInAsync() public async Task LogInAsync()
{ {
if(Xamarin.Essentials.Connectivity.NetworkAccess == Xamarin.Essentials.NetworkAccess.None) if (Xamarin.Essentials.Connectivity.NetworkAccess == Xamarin.Essentials.NetworkAccess.None)
{ {
await _platformUtilsService.ShowDialogAsync(AppResources.InternetConnectionRequiredMessage, await _platformUtilsService.ShowDialogAsync(AppResources.InternetConnectionRequiredMessage,
AppResources.InternetConnectionRequiredTitle); AppResources.InternetConnectionRequiredTitle);
return; return;
} }
if(string.IsNullOrWhiteSpace(Email)) if (string.IsNullOrWhiteSpace(Email))
{ {
await Page.DisplayAlert(AppResources.AnErrorHasOccurred, await Page.DisplayAlert(AppResources.AnErrorHasOccurred,
string.Format(AppResources.ValidationFieldRequired, AppResources.EmailAddress), string.Format(AppResources.ValidationFieldRequired, AppResources.EmailAddress),
AppResources.Ok); AppResources.Ok);
return; return;
} }
if(!Email.Contains("@")) if (!Email.Contains("@"))
{ {
await Page.DisplayAlert(AppResources.AnErrorHasOccurred, AppResources.InvalidEmail, AppResources.Ok); await Page.DisplayAlert(AppResources.AnErrorHasOccurred, AppResources.InvalidEmail, AppResources.Ok);
return; return;
} }
if(string.IsNullOrWhiteSpace(MasterPassword)) if (string.IsNullOrWhiteSpace(MasterPassword))
{ {
await Page.DisplayAlert(AppResources.AnErrorHasOccurred, await Page.DisplayAlert(AppResources.AnErrorHasOccurred,
string.Format(AppResources.ValidationFieldRequired, AppResources.MasterPassword), string.Format(AppResources.ValidationFieldRequired, AppResources.MasterPassword),
@ -110,7 +110,7 @@ namespace Bit.App.Pages
await _deviceActionService.ShowLoadingAsync(AppResources.LoggingIn); await _deviceActionService.ShowLoadingAsync(AppResources.LoggingIn);
var response = await _authService.LogInAsync(Email, MasterPassword); var response = await _authService.LogInAsync(Email, MasterPassword);
MasterPassword = string.Empty; MasterPassword = string.Empty;
if(RememberEmail) if (RememberEmail)
{ {
await _storageService.SaveAsync(Keys_RememberedEmail, Email); await _storageService.SaveAsync(Keys_RememberedEmail, Email);
} }
@ -119,7 +119,7 @@ namespace Bit.App.Pages
await _storageService.RemoveAsync(Keys_RememberedEmail); await _storageService.RemoveAsync(Keys_RememberedEmail);
} }
await _deviceActionService.HideLoadingAsync(); await _deviceActionService.HideLoadingAsync();
if(response.TwoFactor) if (response.TwoFactor)
{ {
var page = new TwoFactorPage(); var page = new TwoFactorPage();
await Page.Navigation.PushModalAsync(new NavigationPage(page)); await Page.Navigation.PushModalAsync(new NavigationPage(page));
@ -132,10 +132,10 @@ namespace Bit.App.Pages
Application.Current.MainPage = new TabsPage(); Application.Current.MainPage = new TabsPage();
} }
} }
catch(ApiException e) catch (ApiException e)
{ {
await _deviceActionService.HideLoadingAsync(); await _deviceActionService.HideLoadingAsync();
if(e?.Error != null) if (e?.Error != null)
{ {
await _platformUtilsService.ShowDialogAsync(e.Error.GetSingleMessage(), await _platformUtilsService.ShowDialogAsync(e.Error.GetSingleMessage(),
AppResources.AnErrorHasOccurred); AppResources.AnErrorHasOccurred);

View File

@ -19,14 +19,14 @@ namespace Bit.App.Pages
_vm.Page = this; _vm.Page = this;
_vm.RegistrationSuccess = async () => _vm.RegistrationSuccess = async () =>
{ {
if(homePage != null) if (homePage != null)
{ {
await homePage.DismissRegisterPageAndLogInAsync(_vm.Email); await homePage.DismissRegisterPageAndLogInAsync(_vm.Email);
} }
}; };
MasterPasswordEntry = _masterPassword; MasterPasswordEntry = _masterPassword;
ConfirmMasterPasswordEntry = _confirmMasterPassword; ConfirmMasterPasswordEntry = _confirmMasterPassword;
if(Device.RuntimePlatform == Device.Android) if (Device.RuntimePlatform == Device.Android)
{ {
ToolbarItems.RemoveAt(0); ToolbarItems.RemoveAt(0);
} }
@ -50,7 +50,7 @@ namespace Bit.App.Pages
private async void Submit_Clicked(object sender, EventArgs e) private async void Submit_Clicked(object sender, EventArgs e)
{ {
if(DoOnce()) if (DoOnce())
{ {
await _vm.SubmitAsync(); await _vm.SubmitAsync();
} }
@ -58,7 +58,7 @@ namespace Bit.App.Pages
private async void Close_Clicked(object sender, EventArgs e) private async void Close_Clicked(object sender, EventArgs e)
{ {
if(DoOnce()) if (DoOnce())
{ {
_messagingService.Send("showStatusBar", false); _messagingService.Send("showStatusBar", false);
await Navigation.PopModalAsync(); await Navigation.PopModalAsync();

View File

@ -55,38 +55,38 @@ namespace Bit.App.Pages
public async Task SubmitAsync() public async Task SubmitAsync()
{ {
if(Xamarin.Essentials.Connectivity.NetworkAccess == Xamarin.Essentials.NetworkAccess.None) if (Xamarin.Essentials.Connectivity.NetworkAccess == Xamarin.Essentials.NetworkAccess.None)
{ {
await _platformUtilsService.ShowDialogAsync(AppResources.InternetConnectionRequiredMessage, await _platformUtilsService.ShowDialogAsync(AppResources.InternetConnectionRequiredMessage,
AppResources.InternetConnectionRequiredTitle); AppResources.InternetConnectionRequiredTitle);
return; return;
} }
if(string.IsNullOrWhiteSpace(Email)) if (string.IsNullOrWhiteSpace(Email))
{ {
await Page.DisplayAlert(AppResources.AnErrorHasOccurred, await Page.DisplayAlert(AppResources.AnErrorHasOccurred,
string.Format(AppResources.ValidationFieldRequired, AppResources.EmailAddress), string.Format(AppResources.ValidationFieldRequired, AppResources.EmailAddress),
AppResources.Ok); AppResources.Ok);
return; return;
} }
if(!Email.Contains("@")) if (!Email.Contains("@"))
{ {
await Page.DisplayAlert(AppResources.AnErrorHasOccurred, AppResources.InvalidEmail, AppResources.Ok); await Page.DisplayAlert(AppResources.AnErrorHasOccurred, AppResources.InvalidEmail, AppResources.Ok);
return; return;
} }
if(string.IsNullOrWhiteSpace(MasterPassword)) if (string.IsNullOrWhiteSpace(MasterPassword))
{ {
await Page.DisplayAlert(AppResources.AnErrorHasOccurred, await Page.DisplayAlert(AppResources.AnErrorHasOccurred,
string.Format(AppResources.ValidationFieldRequired, AppResources.MasterPassword), string.Format(AppResources.ValidationFieldRequired, AppResources.MasterPassword),
AppResources.Ok); AppResources.Ok);
return; return;
} }
if(MasterPassword.Length < 8) if (MasterPassword.Length < 8)
{ {
await Page.DisplayAlert(AppResources.AnErrorHasOccurred, await Page.DisplayAlert(AppResources.AnErrorHasOccurred,
AppResources.MasterPasswordLengthValMessage, AppResources.Ok); AppResources.MasterPasswordLengthValMessage, AppResources.Ok);
return; return;
} }
if(MasterPassword != ConfirmMasterPassword) if (MasterPassword != ConfirmMasterPassword)
{ {
await Page.DisplayAlert(AppResources.AnErrorHasOccurred, await Page.DisplayAlert(AppResources.AnErrorHasOccurred,
AppResources.MasterPasswordConfirmationValMessage, AppResources.Ok); AppResources.MasterPasswordConfirmationValMessage, AppResources.Ok);
@ -132,10 +132,10 @@ namespace Bit.App.Pages
}); });
RegistrationSuccess?.Invoke(); RegistrationSuccess?.Invoke();
} }
catch(ApiException e) catch (ApiException e)
{ {
await _deviceActionService.HideLoadingAsync(); await _deviceActionService.HideLoadingAsync();
if(e?.Error != null) if (e?.Error != null)
{ {
await _platformUtilsService.ShowDialogAsync(e.Error.GetSingleMessage(), await _platformUtilsService.ShowDialogAsync(e.Error.GetSingleMessage(),
AppResources.AnErrorHasOccurred); AppResources.AnErrorHasOccurred);

View File

@ -24,7 +24,7 @@ namespace Bit.App.Pages
_vm = BindingContext as TwoFactorPageViewModel; _vm = BindingContext as TwoFactorPageViewModel;
_vm.Page = this; _vm.Page = this;
DuoWebView = _duoWebView; DuoWebView = _duoWebView;
if(Device.RuntimePlatform == Device.Android) if (Device.RuntimePlatform == Device.Android)
{ {
ToolbarItems.Remove(_cancelItem); ToolbarItems.Remove(_cancelItem);
} }
@ -34,7 +34,7 @@ namespace Bit.App.Pages
public void AddContinueButton() public void AddContinueButton()
{ {
if(!ToolbarItems.Contains(_continueItem)) if (!ToolbarItems.Contains(_continueItem))
{ {
ToolbarItems.Add(_continueItem); ToolbarItems.Add(_continueItem);
} }
@ -42,7 +42,7 @@ namespace Bit.App.Pages
public void RemoveContinueButton() public void RemoveContinueButton()
{ {
if(ToolbarItems.Contains(_continueItem)) if (ToolbarItems.Contains(_continueItem))
{ {
ToolbarItems.Remove(_continueItem); ToolbarItems.Remove(_continueItem);
} }
@ -53,10 +53,10 @@ namespace Bit.App.Pages
base.OnAppearing(); base.OnAppearing();
_broadcasterService.Subscribe(nameof(TwoFactorPage), (message) => _broadcasterService.Subscribe(nameof(TwoFactorPage), (message) =>
{ {
if(message.Command == "gotYubiKeyOTP") if (message.Command == "gotYubiKeyOTP")
{ {
var token = (string)message.Data; var token = (string)message.Data;
if(_vm.YubikeyMethod && !string.IsNullOrWhiteSpace(token) && if (_vm.YubikeyMethod && !string.IsNullOrWhiteSpace(token) &&
token.Length == 44 && !token.Contains(" ")) token.Length == 44 && !token.Contains(" "))
{ {
Device.BeginInvokeOnMainThread(async () => Device.BeginInvokeOnMainThread(async () =>
@ -66,22 +66,22 @@ namespace Bit.App.Pages
}); });
} }
} }
else if(message.Command == "resumeYubiKey") else if (message.Command == "resumeYubiKey")
{ {
if(_vm.YubikeyMethod) if (_vm.YubikeyMethod)
{ {
_messagingService.Send("listenYubiKeyOTP", true); _messagingService.Send("listenYubiKeyOTP", true);
} }
} }
}); });
if(!_inited) if (!_inited)
{ {
_inited = true; _inited = true;
await LoadOnAppearedAsync(_scrollView, true, () => await LoadOnAppearedAsync(_scrollView, true, () =>
{ {
_vm.Init(); _vm.Init();
if(_vm.TotpMethod) if (_vm.TotpMethod)
{ {
RequestFocus(_totpEntry); RequestFocus(_totpEntry);
} }
@ -93,7 +93,7 @@ namespace Bit.App.Pages
protected override void OnDisappearing() protected override void OnDisappearing()
{ {
base.OnDisappearing(); base.OnDisappearing();
if(!_vm.YubikeyMethod) if (!_vm.YubikeyMethod)
{ {
_messagingService.Send("listenYubiKeyOTP", false); _messagingService.Send("listenYubiKeyOTP", false);
_broadcasterService.Unsubscribe(nameof(TwoFactorPage)); _broadcasterService.Unsubscribe(nameof(TwoFactorPage));
@ -101,7 +101,7 @@ namespace Bit.App.Pages
} }
protected override bool OnBackButtonPressed() protected override bool OnBackButtonPressed()
{ {
if(_vm.YubikeyMethod) if (_vm.YubikeyMethod)
{ {
_messagingService.Send("listenYubiKeyOTP", false); _messagingService.Send("listenYubiKeyOTP", false);
_broadcasterService.Unsubscribe(nameof(TwoFactorPage)); _broadcasterService.Unsubscribe(nameof(TwoFactorPage));
@ -111,7 +111,7 @@ namespace Bit.App.Pages
private async void Continue_Clicked(object sender, EventArgs e) private async void Continue_Clicked(object sender, EventArgs e)
{ {
if(DoOnce()) if (DoOnce())
{ {
await _vm.SubmitAsync(); await _vm.SubmitAsync();
} }
@ -119,7 +119,7 @@ namespace Bit.App.Pages
private async void Methods_Clicked(object sender, EventArgs e) private async void Methods_Clicked(object sender, EventArgs e)
{ {
if(DoOnce()) if (DoOnce())
{ {
await _vm.AnotherMethodAsync(); await _vm.AnotherMethodAsync();
} }
@ -127,7 +127,7 @@ namespace Bit.App.Pages
private async void ResendEmail_Clicked(object sender, EventArgs e) private async void ResendEmail_Clicked(object sender, EventArgs e)
{ {
if(DoOnce()) if (DoOnce())
{ {
await _vm.SendEmailAsync(true, true); await _vm.SendEmailAsync(true, true);
} }
@ -135,7 +135,7 @@ namespace Bit.App.Pages
private async void Close_Clicked(object sender, System.EventArgs e) private async void Close_Clicked(object sender, System.EventArgs e)
{ {
if(DoOnce()) if (DoOnce())
{ {
await Navigation.PopModalAsync(); await Navigation.PopModalAsync();
} }
@ -143,9 +143,9 @@ namespace Bit.App.Pages
private void TryAgain_Clicked(object sender, EventArgs e) private void TryAgain_Clicked(object sender, EventArgs e)
{ {
if(DoOnce()) if (DoOnce())
{ {
if(_vm.YubikeyMethod) if (_vm.YubikeyMethod)
{ {
_messagingService.Send("listenYubiKeyOTP", true); _messagingService.Send("listenYubiKeyOTP", true);
} }

View File

@ -91,7 +91,7 @@ namespace Bit.App.Pages
public void Init() public void Init()
{ {
if(string.IsNullOrWhiteSpace(_authService.Email) || if (string.IsNullOrWhiteSpace(_authService.Email) ||
string.IsNullOrWhiteSpace(_authService.MasterPasswordHash) || string.IsNullOrWhiteSpace(_authService.MasterPasswordHash) ||
_authService.TwoFactorProvidersData == null) _authService.TwoFactorProvidersData == null)
{ {
@ -99,11 +99,11 @@ namespace Bit.App.Pages
return; return;
} }
if(!string.IsNullOrWhiteSpace(_environmentService.BaseUrl)) if (!string.IsNullOrWhiteSpace(_environmentService.BaseUrl))
{ {
_webVaultUrl = _environmentService.BaseUrl; _webVaultUrl = _environmentService.BaseUrl;
} }
else if(!string.IsNullOrWhiteSpace(_environmentService.WebVaultUrl)) else if (!string.IsNullOrWhiteSpace(_environmentService.WebVaultUrl))
{ {
_webVaultUrl = _environmentService.WebVaultUrl; _webVaultUrl = _environmentService.WebVaultUrl;
} }
@ -117,7 +117,7 @@ namespace Bit.App.Pages
public void Load() public void Load()
{ {
if(SelectedProviderType == null) if (SelectedProviderType == null)
{ {
PageTitle = AppResources.LoginUnavailable; PageTitle = AppResources.LoginUnavailable;
return; return;
@ -125,7 +125,7 @@ namespace Bit.App.Pages
var page = Page as TwoFactorPage; var page = Page as TwoFactorPage;
PageTitle = _authService.TwoFactorProviders[SelectedProviderType.Value].Name; PageTitle = _authService.TwoFactorProviders[SelectedProviderType.Value].Name;
var providerData = _authService.TwoFactorProvidersData[SelectedProviderType.Value]; var providerData = _authService.TwoFactorProvidersData[SelectedProviderType.Value];
switch(SelectedProviderType.Value) switch (SelectedProviderType.Value)
{ {
case TwoFactorProviderType.U2f: case TwoFactorProviderType.U2f:
// TODO // TODO
@ -148,7 +148,7 @@ namespace Bit.App.Pages
case TwoFactorProviderType.Email: case TwoFactorProviderType.Email:
TotpInstruction = string.Format(AppResources.EnterVerificationCodeEmail, TotpInstruction = string.Format(AppResources.EnterVerificationCodeEmail,
providerData["Email"] as string); providerData["Email"] as string);
if(_authService.TwoFactorProvidersData.Count > 1) if (_authService.TwoFactorProvidersData.Count > 1)
{ {
var emailTask = Task.Run(() => SendEmailAsync(false, false)); var emailTask = Task.Run(() => SendEmailAsync(false, false));
} }
@ -160,11 +160,11 @@ namespace Bit.App.Pages
break; break;
} }
if(!YubikeyMethod) if (!YubikeyMethod)
{ {
_messagingService.Send("listenYubiKeyOTP", false); _messagingService.Send("listenYubiKeyOTP", false);
} }
if(SelectedProviderType == null || DuoMethod) if (SelectedProviderType == null || DuoMethod)
{ {
page.RemoveContinueButton(); page.RemoveContinueButton();
} }
@ -176,24 +176,24 @@ namespace Bit.App.Pages
public async Task SubmitAsync() public async Task SubmitAsync()
{ {
if(SelectedProviderType == null) if (SelectedProviderType == null)
{ {
return; return;
} }
if(Xamarin.Essentials.Connectivity.NetworkAccess == Xamarin.Essentials.NetworkAccess.None) if (Xamarin.Essentials.Connectivity.NetworkAccess == Xamarin.Essentials.NetworkAccess.None)
{ {
await _platformUtilsService.ShowDialogAsync(AppResources.InternetConnectionRequiredMessage, await _platformUtilsService.ShowDialogAsync(AppResources.InternetConnectionRequiredMessage,
AppResources.InternetConnectionRequiredTitle); AppResources.InternetConnectionRequiredTitle);
return; return;
} }
if(string.IsNullOrWhiteSpace(Token)) if (string.IsNullOrWhiteSpace(Token))
{ {
await _platformUtilsService.ShowDialogAsync( await _platformUtilsService.ShowDialogAsync(
string.Format(AppResources.ValidationFieldRequired, AppResources.VerificationCode), string.Format(AppResources.ValidationFieldRequired, AppResources.VerificationCode),
AppResources.AnErrorHasOccurred); AppResources.AnErrorHasOccurred);
return; return;
} }
if(SelectedProviderType == TwoFactorProviderType.Email || if (SelectedProviderType == TwoFactorProviderType.Email ||
SelectedProviderType == TwoFactorProviderType.Authenticator) SelectedProviderType == TwoFactorProviderType.Authenticator)
{ {
Token = Token.Replace(" ", string.Empty).Trim(); Token = Token.Replace(" ", string.Empty).Trim();
@ -211,10 +211,10 @@ namespace Bit.App.Pages
await _stateService.SaveAsync(Constants.DisableFaviconKey, disableFavicon.GetValueOrDefault()); await _stateService.SaveAsync(Constants.DisableFaviconKey, disableFavicon.GetValueOrDefault());
Application.Current.MainPage = new TabsPage(); Application.Current.MainPage = new TabsPage();
} }
catch(ApiException e) catch (ApiException e)
{ {
await _deviceActionService.HideLoadingAsync(); await _deviceActionService.HideLoadingAsync();
if(e?.Error != null) if (e?.Error != null)
{ {
await _platformUtilsService.ShowDialogAsync(e.Error.GetSingleMessage(), await _platformUtilsService.ShowDialogAsync(e.Error.GetSingleMessage(),
AppResources.AnErrorHasOccurred); AppResources.AnErrorHasOccurred);
@ -229,14 +229,14 @@ namespace Bit.App.Pages
options.Add(AppResources.RecoveryCodeTitle); options.Add(AppResources.RecoveryCodeTitle);
var method = await Page.DisplayActionSheet(AppResources.TwoStepLoginOptions, AppResources.Cancel, var method = await Page.DisplayActionSheet(AppResources.TwoStepLoginOptions, AppResources.Cancel,
null, options.ToArray()); null, options.ToArray());
if(method == AppResources.RecoveryCodeTitle) if (method == AppResources.RecoveryCodeTitle)
{ {
_platformUtilsService.LaunchUri("https://help.bitwarden.com/article/lost-two-step-device/"); _platformUtilsService.LaunchUri("https://help.bitwarden.com/article/lost-two-step-device/");
} }
else if(method != AppResources.Cancel) else if (method != AppResources.Cancel)
{ {
var selected = supportedProviders.FirstOrDefault(p => p.Name == method)?.Type; var selected = supportedProviders.FirstOrDefault(p => p.Name == method)?.Type;
if(selected == SelectedProviderType) if (selected == SelectedProviderType)
{ {
// Nothing changed // Nothing changed
return; return;
@ -248,11 +248,11 @@ namespace Bit.App.Pages
public async Task<bool> SendEmailAsync(bool showLoading, bool doToast) public async Task<bool> SendEmailAsync(bool showLoading, bool doToast)
{ {
if(!EmailMethod) if (!EmailMethod)
{ {
return false; return false;
} }
if(Xamarin.Essentials.Connectivity.NetworkAccess == Xamarin.Essentials.NetworkAccess.None) if (Xamarin.Essentials.Connectivity.NetworkAccess == Xamarin.Essentials.NetworkAccess.None)
{ {
await _platformUtilsService.ShowDialogAsync(AppResources.InternetConnectionRequiredMessage, await _platformUtilsService.ShowDialogAsync(AppResources.InternetConnectionRequiredMessage,
AppResources.InternetConnectionRequiredTitle); AppResources.InternetConnectionRequiredTitle);
@ -260,7 +260,7 @@ namespace Bit.App.Pages
} }
try try
{ {
if(showLoading) if (showLoading)
{ {
await _deviceActionService.ShowLoadingAsync(AppResources.Submitting); await _deviceActionService.ShowLoadingAsync(AppResources.Submitting);
} }
@ -270,19 +270,19 @@ namespace Bit.App.Pages
MasterPasswordHash = _authService.MasterPasswordHash MasterPasswordHash = _authService.MasterPasswordHash
}; };
await _apiService.PostTwoFactorEmailAsync(request); await _apiService.PostTwoFactorEmailAsync(request);
if(showLoading) if (showLoading)
{ {
await _deviceActionService.HideLoadingAsync(); await _deviceActionService.HideLoadingAsync();
} }
if(doToast) if (doToast)
{ {
_platformUtilsService.ShowToast("success", null, AppResources.VerificationEmailSent); _platformUtilsService.ShowToast("success", null, AppResources.VerificationEmailSent);
} }
return true; return true;
} }
catch(ApiException) catch (ApiException)
{ {
if(showLoading) if (showLoading)
{ {
await _deviceActionService.HideLoadingAsync(); await _deviceActionService.HideLoadingAsync();
} }

View File

@ -34,7 +34,7 @@ namespace Bit.App.Pages
public bool DoOnce(Action action = null, int milliseconds = 1000) public bool DoOnce(Action action = null, int milliseconds = 1000)
{ {
if(LastPageAction.HasValue && (DateTime.UtcNow - LastPageAction.Value).TotalMilliseconds < milliseconds) if (LastPageAction.HasValue && (DateTime.UtcNow - LastPageAction.Value).TotalMilliseconds < milliseconds)
{ {
// Last action occurred recently. // Last action occurred recently.
return false; return false;
@ -52,7 +52,7 @@ namespace Bit.App.Pages
VerticalOptions = LayoutOptions.CenterAndExpand, VerticalOptions = LayoutOptions.CenterAndExpand,
HorizontalOptions = LayoutOptions.Center HorizontalOptions = LayoutOptions.Center
}; };
if(targetView != null) if (targetView != null)
{ {
targetView.Content = indicator; targetView.Content = indicator;
} }
@ -68,9 +68,9 @@ namespace Bit.App.Pages
async Task DoWorkAsync() async Task DoWorkAsync()
{ {
await workFunction.Invoke(); await workFunction.Invoke();
if(sourceView != null) if (sourceView != null)
{ {
if(targetView != null) if (targetView != null)
{ {
targetView.Content = sourceView; targetView.Content = sourceView;
} }
@ -80,7 +80,7 @@ namespace Bit.App.Pages
} }
} }
} }
if(Device.RuntimePlatform == Device.iOS) if (Device.RuntimePlatform == Device.iOS)
{ {
await DoWorkAsync(); await DoWorkAsync();
return; return;
@ -103,7 +103,7 @@ namespace Bit.App.Pages
private void SetStorageService() private void SetStorageService()
{ {
if(_storageService == null) if (_storageService == null)
{ {
_storageService = ServiceContainer.Resolve<IStorageService>("storageService"); _storageService = ServiceContainer.Resolve<IStorageService>("storageService");
} }

View File

@ -14,7 +14,7 @@ namespace Bit.App.Pages
SetActivityIndicator(); SetActivityIndicator();
_vm = BindingContext as GeneratorHistoryPageViewModel; _vm = BindingContext as GeneratorHistoryPageViewModel;
_vm.Page = this; _vm.Page = this;
if(Device.RuntimePlatform == Device.iOS) if (Device.RuntimePlatform == Device.iOS)
{ {
ToolbarItems.Add(_closeItem); ToolbarItems.Add(_closeItem);
ToolbarItems.Add(_moreItem); ToolbarItems.Add(_moreItem);
@ -40,7 +40,7 @@ namespace Bit.App.Pages
private async void Close_Clicked(object sender, System.EventArgs e) private async void Close_Clicked(object sender, System.EventArgs e)
{ {
if(DoOnce()) if (DoOnce())
{ {
await Navigation.PopModalAsync(); await Navigation.PopModalAsync();
} }
@ -48,13 +48,13 @@ namespace Bit.App.Pages
private async void More_Clicked(object sender, EventArgs e) private async void More_Clicked(object sender, EventArgs e)
{ {
if(!DoOnce()) if (!DoOnce())
{ {
return; return;
} }
var selection = await DisplayActionSheet(AppResources.Options, AppResources.Cancel, var selection = await DisplayActionSheet(AppResources.Options, AppResources.Cancel,
null, AppResources.Clear); null, AppResources.Clear);
if(selection == AppResources.Clear) if (selection == AppResources.Clear)
{ {
await _vm.ClearAsync(); await _vm.ClearAsync();
} }

View File

@ -23,9 +23,9 @@ namespace Bit.App.Pages
_fromTabPage = fromTabPage; _fromTabPage = fromTabPage;
_selectAction = selectAction; _selectAction = selectAction;
var isIos = Device.RuntimePlatform == Device.iOS; var isIos = Device.RuntimePlatform == Device.iOS;
if(selectAction != null) if (selectAction != null)
{ {
if(isIos) if (isIos)
{ {
ToolbarItems.Add(_closeItem); ToolbarItems.Add(_closeItem);
} }
@ -33,7 +33,7 @@ namespace Bit.App.Pages
} }
else else
{ {
if(isIos) if (isIos)
{ {
ToolbarItems.Add(_moreItem); ToolbarItems.Add(_moreItem);
} }
@ -42,7 +42,7 @@ namespace Bit.App.Pages
ToolbarItems.Add(_historyItem); ToolbarItems.Add(_historyItem);
} }
} }
if(isIos) if (isIos)
{ {
_typePicker.On<iOS>().SetUpdateMode(UpdateMode.WhenFinished); _typePicker.On<iOS>().SetUpdateMode(UpdateMode.WhenFinished);
} }
@ -56,7 +56,7 @@ namespace Bit.App.Pages
protected async override void OnAppearing() protected async override void OnAppearing()
{ {
base.OnAppearing(); base.OnAppearing();
if(!_fromTabPage) if (!_fromTabPage)
{ {
await InitAsync(); await InitAsync();
} }
@ -64,7 +64,7 @@ namespace Bit.App.Pages
protected override bool OnBackButtonPressed() protected override bool OnBackButtonPressed()
{ {
if(Device.RuntimePlatform == Device.Android && _tabsPage != null) if (Device.RuntimePlatform == Device.Android && _tabsPage != null)
{ {
_tabsPage.ResetToVaultPage(); _tabsPage.ResetToVaultPage();
return true; return true;
@ -84,13 +84,13 @@ namespace Bit.App.Pages
private async void More_Clicked(object sender, EventArgs e) private async void More_Clicked(object sender, EventArgs e)
{ {
if(!DoOnce()) if (!DoOnce())
{ {
return; return;
} }
var selection = await DisplayActionSheet(AppResources.Options, AppResources.Cancel, var selection = await DisplayActionSheet(AppResources.Options, AppResources.Cancel,
null, AppResources.PasswordHistory); null, AppResources.PasswordHistory);
if(selection == AppResources.PasswordHistory) if (selection == AppResources.PasswordHistory)
{ {
var page = new GeneratorHistoryPage(); var page = new GeneratorHistoryPage();
await Navigation.PushModalAsync(new Xamarin.Forms.NavigationPage(page)); await Navigation.PushModalAsync(new Xamarin.Forms.NavigationPage(page));
@ -115,7 +115,7 @@ namespace Bit.App.Pages
private async void Close_Clicked(object sender, EventArgs e) private async void Close_Clicked(object sender, EventArgs e)
{ {
if(DoOnce()) if (DoOnce())
{ {
await Navigation.PopModalAsync(); await Navigation.PopModalAsync();
} }

View File

@ -67,7 +67,7 @@ namespace Bit.App.Pages
get => _length; get => _length;
set set
{ {
if(SetProperty(ref _length, value)) if (SetProperty(ref _length, value))
{ {
_options.Length = value; _options.Length = value;
var task = SliderInputAsync(); var task = SliderInputAsync();
@ -80,7 +80,7 @@ namespace Bit.App.Pages
get => _uppercase; get => _uppercase;
set set
{ {
if(SetProperty(ref _uppercase, value)) if (SetProperty(ref _uppercase, value))
{ {
_options.Uppercase = value; _options.Uppercase = value;
var task = SaveOptionsAsync(); var task = SaveOptionsAsync();
@ -93,7 +93,7 @@ namespace Bit.App.Pages
get => _lowercase; get => _lowercase;
set set
{ {
if(SetProperty(ref _lowercase, value)) if (SetProperty(ref _lowercase, value))
{ {
_options.Lowercase = value; _options.Lowercase = value;
var task = SaveOptionsAsync(); var task = SaveOptionsAsync();
@ -106,7 +106,7 @@ namespace Bit.App.Pages
get => _number; get => _number;
set set
{ {
if(SetProperty(ref _number, value)) if (SetProperty(ref _number, value))
{ {
_options.Number = value; _options.Number = value;
var task = SaveOptionsAsync(); var task = SaveOptionsAsync();
@ -119,7 +119,7 @@ namespace Bit.App.Pages
get => _special; get => _special;
set set
{ {
if(SetProperty(ref _special, value)) if (SetProperty(ref _special, value))
{ {
_options.Special = value; _options.Special = value;
var task = SaveOptionsAsync(); var task = SaveOptionsAsync();
@ -132,7 +132,7 @@ namespace Bit.App.Pages
get => _avoidAmbiguous; get => _avoidAmbiguous;
set set
{ {
if(SetProperty(ref _avoidAmbiguous, value)) if (SetProperty(ref _avoidAmbiguous, value))
{ {
_options.Ambiguous = !value; _options.Ambiguous = !value;
var task = SaveOptionsAsync(); var task = SaveOptionsAsync();
@ -145,7 +145,7 @@ namespace Bit.App.Pages
get => _minNumber; get => _minNumber;
set set
{ {
if(SetProperty(ref _minNumber, value)) if (SetProperty(ref _minNumber, value))
{ {
_options.MinNumber = value; _options.MinNumber = value;
var task = SaveOptionsAsync(); var task = SaveOptionsAsync();
@ -158,7 +158,7 @@ namespace Bit.App.Pages
get => _minSpecial; get => _minSpecial;
set set
{ {
if(SetProperty(ref _minSpecial, value)) if (SetProperty(ref _minSpecial, value))
{ {
_options.MinSpecial = value; _options.MinSpecial = value;
var task = SaveOptionsAsync(); var task = SaveOptionsAsync();
@ -171,7 +171,7 @@ namespace Bit.App.Pages
get => _numWords; get => _numWords;
set set
{ {
if(SetProperty(ref _numWords, value)) if (SetProperty(ref _numWords, value))
{ {
_options.NumWords = value; _options.NumWords = value;
var task = SaveOptionsAsync(); var task = SaveOptionsAsync();
@ -184,12 +184,12 @@ namespace Bit.App.Pages
get => _wordSeparator; get => _wordSeparator;
set set
{ {
if(value == null) if (value == null)
{ {
return; return;
} }
var val = value.Trim(); var val = value.Trim();
if(SetProperty(ref _wordSeparator, val)) if (SetProperty(ref _wordSeparator, val))
{ {
_options.WordSeparator = val; _options.WordSeparator = val;
var task = SaveOptionsAsync(); var task = SaveOptionsAsync();
@ -202,7 +202,7 @@ namespace Bit.App.Pages
get => _capitalize; get => _capitalize;
set set
{ {
if(SetProperty(ref _capitalize, value)) if (SetProperty(ref _capitalize, value))
{ {
_options.Capitalize = value; _options.Capitalize = value;
var task = SaveOptionsAsync(); var task = SaveOptionsAsync();
@ -215,7 +215,7 @@ namespace Bit.App.Pages
get => _includeNumber; get => _includeNumber;
set set
{ {
if(SetProperty(ref _includeNumber, value)) if (SetProperty(ref _includeNumber, value))
{ {
_options.Number = value; _options.Number = value;
var task = SaveOptionsAsync(); var task = SaveOptionsAsync();
@ -240,7 +240,7 @@ namespace Bit.App.Pages
get => _typeSelectedIndex; get => _typeSelectedIndex;
set set
{ {
if(SetProperty(ref _typeSelectedIndex, value)) if (SetProperty(ref _typeSelectedIndex, value))
{ {
IsPassword = value == 0; IsPassword = value == 0;
var task = SaveOptionsAsync(); var task = SaveOptionsAsync();
@ -264,7 +264,7 @@ namespace Bit.App.Pages
public async Task SaveOptionsAsync(bool regenerate = true) public async Task SaveOptionsAsync(bool regenerate = true)
{ {
if(!_doneIniting) if (!_doneIniting)
{ {
return; return;
} }
@ -272,7 +272,7 @@ namespace Bit.App.Pages
_passwordGenerationService.NormalizeOptions(_options, _enforcedPolicyOptions); _passwordGenerationService.NormalizeOptions(_options, _enforcedPolicyOptions);
await _passwordGenerationService.SaveOptionsAsync(_options); await _passwordGenerationService.SaveOptionsAsync(_options);
LoadFromOptions(); LoadFromOptions();
if(regenerate) if (regenerate)
{ {
await RegenerateAsync(); await RegenerateAsync();
} }

View File

@ -25,7 +25,7 @@ namespace Bit.App.Pages
_timerStarted = DateTime.UtcNow; _timerStarted = DateTime.UtcNow;
Device.StartTimer(new TimeSpan(0, 0, 3), () => Device.StartTimer(new TimeSpan(0, 0, 3), () =>
{ {
if(_timerStarted == null || (DateTime.UtcNow - _timerStarted) > _timerMaxLength) if (_timerStarted == null || (DateTime.UtcNow - _timerStarted) > _timerMaxLength)
{ {
return false; return false;
} }
@ -45,7 +45,7 @@ namespace Bit.App.Pages
private void Settings_Clicked(object sender, EventArgs e) private void Settings_Clicked(object sender, EventArgs e)
{ {
if(DoOnce()) if (DoOnce())
{ {
_vm.OpenSettings(); _vm.OpenSettings();
} }
@ -53,7 +53,7 @@ namespace Bit.App.Pages
private void OverlayPermissionSettings_Clicked(object sender, EventArgs e) private void OverlayPermissionSettings_Clicked(object sender, EventArgs e)
{ {
if(DoOnce()) if (DoOnce())
{ {
_vm.OpenOverlayPermissionSettings(); _vm.OpenOverlayPermissionSettings();
} }

View File

@ -11,7 +11,7 @@ namespace Bit.App.Pages
private void Close_Clicked(object sender, EventArgs e) private void Close_Clicked(object sender, EventArgs e)
{ {
if(DoOnce()) if (DoOnce())
{ {
Navigation.PopModalAsync(); Navigation.PopModalAsync();
} }

View File

@ -24,7 +24,7 @@ namespace Bit.App.Pages
_timerStarted = DateTime.UtcNow; _timerStarted = DateTime.UtcNow;
Device.StartTimer(new TimeSpan(0, 0, 2), () => Device.StartTimer(new TimeSpan(0, 0, 2), () =>
{ {
if(_timerStarted == null || (DateTime.UtcNow - _timerStarted) > _timerMaxLength) if (_timerStarted == null || (DateTime.UtcNow - _timerStarted) > _timerMaxLength)
{ {
return false; return false;
} }
@ -43,7 +43,7 @@ namespace Bit.App.Pages
private void Settings_Clicked(object sender, EventArgs e) private void Settings_Clicked(object sender, EventArgs e)
{ {
if(DoOnce()) if (DoOnce())
{ {
_vm.OpenSettings(); _vm.OpenSettings();
} }

View File

@ -26,12 +26,12 @@ namespace Bit.App.Pages
await _vm.InitAsync(); await _vm.InitAsync();
_broadcasterService.Subscribe(nameof(ExportVaultPage), (message) => _broadcasterService.Subscribe(nameof(ExportVaultPage), (message) =>
{ {
if(message.Command == "selectSaveFileResult") if (message.Command == "selectSaveFileResult")
{ {
Device.BeginInvokeOnMainThread(() => Device.BeginInvokeOnMainThread(() =>
{ {
var data = message.Data as Tuple<string, string>; var data = message.Data as Tuple<string, string>;
if(data == null) if (data == null)
{ {
return; return;
} }
@ -52,7 +52,7 @@ namespace Bit.App.Pages
private async void Close_Clicked(object sender, System.EventArgs e) private async void Close_Clicked(object sender, System.EventArgs e)
{ {
if(DoOnce()) if (DoOnce())
{ {
await Navigation.PopModalAsync(); await Navigation.PopModalAsync();
} }
@ -60,7 +60,7 @@ namespace Bit.App.Pages
private async void ExportVault_Clicked(object sender, EventArgs e) private async void ExportVault_Clicked(object sender, EventArgs e)
{ {
if(DoOnce()) if (DoOnce())
{ {
await _vm.ExportVaultAsync(); await _vm.ExportVaultAsync();
} }

View File

@ -83,7 +83,7 @@ namespace Bit.App.Pages
public async Task ExportVaultAsync() public async Task ExportVaultAsync()
{ {
if(string.IsNullOrEmpty(_masterPassword)) if (string.IsNullOrEmpty(_masterPassword))
{ {
await _platformUtilsService.ShowDialogAsync(_i18nService.T("InvalidMasterPassword")); await _platformUtilsService.ShowDialogAsync(_i18nService.T("InvalidMasterPassword"));
return; return;
@ -93,7 +93,7 @@ namespace Bit.App.Pages
MasterPassword = string.Empty; MasterPassword = string.Empty;
var storedKeyHash = await _cryptoService.GetKeyHashAsync(); var storedKeyHash = await _cryptoService.GetKeyHashAsync();
if(storedKeyHash != null && keyHash != null && storedKeyHash == keyHash) if (storedKeyHash != null && keyHash != null && storedKeyHash == keyHash)
{ {
try try
{ {
@ -102,13 +102,13 @@ namespace Bit.App.Pages
_defaultFilename = _exportService.GetFileName(null, fileFormat); _defaultFilename = _exportService.GetFileName(null, fileFormat);
_exportResult = Encoding.ASCII.GetBytes(data.Result); _exportResult = Encoding.ASCII.GetBytes(data.Result);
if(!_deviceActionService.SaveFile(_exportResult, null, _defaultFilename, null)) if (!_deviceActionService.SaveFile(_exportResult, null, _defaultFilename, null))
{ {
ClearResult(); ClearResult();
await _platformUtilsService.ShowDialogAsync(_i18nService.T("ExportVaultFailure")); await _platformUtilsService.ShowDialogAsync(_i18nService.T("ExportVaultFailure"));
} }
} }
catch(Exception ex) catch (Exception ex)
{ {
ClearResult(); ClearResult();
await _platformUtilsService.ShowDialogAsync(_i18nService.T("ExportVaultFailure")); await _platformUtilsService.ShowDialogAsync(_i18nService.T("ExportVaultFailure"));
@ -123,7 +123,7 @@ namespace Bit.App.Pages
public async void SaveFileSelected(string contentUri, string filename) public async void SaveFileSelected(string contentUri, string filename)
{ {
if(_deviceActionService.SaveFile(_exportResult, null, filename ?? _defaultFilename, contentUri)) if (_deviceActionService.SaveFile(_exportResult, null, filename ?? _defaultFilename, contentUri))
{ {
ClearResult(); ClearResult();
_platformUtilsService.ShowToast("success", null, _i18nService.T("ExportVaultSuccess")); _platformUtilsService.ShowToast("success", null, _i18nService.T("ExportVaultSuccess"));

View File

@ -21,7 +21,7 @@ namespace Bit.App.Pages
private void Show_Clicked(object sender, EventArgs e) private void Show_Clicked(object sender, EventArgs e)
{ {
if(DoOnce()) if (DoOnce())
{ {
_vm.ShowExtension(); _vm.ShowExtension();
} }
@ -29,7 +29,7 @@ namespace Bit.App.Pages
private void Close_Clicked(object sender, EventArgs e) private void Close_Clicked(object sender, EventArgs e)
{ {
if(DoOnce()) if (DoOnce())
{ {
Navigation.PopModalAsync(); Navigation.PopModalAsync();
} }

View File

@ -66,7 +66,7 @@ namespace Bit.App.Pages
public void EnabledExtension(bool enabled) public void EnabledExtension(bool enabled)
{ {
Started = true; Started = true;
if(!Activated && enabled) if (!Activated && enabled)
{ {
Activated = enabled; Activated = enabled;
} }

View File

@ -17,15 +17,15 @@ namespace Bit.App.Pages
_vm.FolderId = folderId; _vm.FolderId = folderId;
_vm.Init(); _vm.Init();
SetActivityIndicator(); SetActivityIndicator();
if(!_vm.EditMode || Device.RuntimePlatform == Device.iOS) if (!_vm.EditMode || Device.RuntimePlatform == Device.iOS)
{ {
ToolbarItems.Remove(_deleteItem); ToolbarItems.Remove(_deleteItem);
} }
if(_vm.EditMode && Device.RuntimePlatform == Device.iOS) if (_vm.EditMode && Device.RuntimePlatform == Device.iOS)
{ {
ToolbarItems.Add(_moreItem); ToolbarItems.Add(_moreItem);
} }
if(Device.RuntimePlatform == Device.Android) if (Device.RuntimePlatform == Device.Android)
{ {
ToolbarItems.RemoveAt(0); ToolbarItems.RemoveAt(0);
} }
@ -37,7 +37,7 @@ namespace Bit.App.Pages
await LoadOnAppearedAsync(_scrollView, true, async () => await LoadOnAppearedAsync(_scrollView, true, async () =>
{ {
await _vm.LoadAsync(); await _vm.LoadAsync();
if(!_vm.EditMode) if (!_vm.EditMode)
{ {
RequestFocus(_nameEntry); RequestFocus(_nameEntry);
} }
@ -46,7 +46,7 @@ namespace Bit.App.Pages
private async void Save_Clicked(object sender, System.EventArgs e) private async void Save_Clicked(object sender, System.EventArgs e)
{ {
if(DoOnce()) if (DoOnce())
{ {
await _vm.SubmitAsync(); await _vm.SubmitAsync();
} }
@ -54,7 +54,7 @@ namespace Bit.App.Pages
private async void Delete_Clicked(object sender, System.EventArgs e) private async void Delete_Clicked(object sender, System.EventArgs e)
{ {
if(DoOnce()) if (DoOnce())
{ {
await _vm.DeleteAsync(); await _vm.DeleteAsync();
} }
@ -62,7 +62,7 @@ namespace Bit.App.Pages
private async void Close_Clicked(object sender, System.EventArgs e) private async void Close_Clicked(object sender, System.EventArgs e)
{ {
if(DoOnce()) if (DoOnce())
{ {
await Navigation.PopModalAsync(); await Navigation.PopModalAsync();
} }
@ -70,14 +70,14 @@ namespace Bit.App.Pages
private async void More_Clicked(object sender, System.EventArgs e) private async void More_Clicked(object sender, System.EventArgs e)
{ {
if(!DoOnce()) if (!DoOnce())
{ {
return; return;
} }
var options = new List<string> { }; var options = new List<string> { };
var selection = await DisplayActionSheet(AppResources.Options, AppResources.Cancel, var selection = await DisplayActionSheet(AppResources.Options, AppResources.Cancel,
_vm.EditMode ? AppResources.Delete : null, options.ToArray()); _vm.EditMode ? AppResources.Delete : null, options.ToArray());
if(selection == AppResources.Delete) if (selection == AppResources.Delete)
{ {
await _vm.DeleteAsync(); await _vm.DeleteAsync();
} }

View File

@ -41,12 +41,12 @@ namespace Bit.App.Pages
public async Task LoadAsync() public async Task LoadAsync()
{ {
if(Folder == null) if (Folder == null)
{ {
if(EditMode) if (EditMode)
{ {
var folder = await _folderService.GetAsync(FolderId); var folder = await _folderService.GetAsync(FolderId);
if(folder != null) if (folder != null)
{ {
Folder = await folder.DecryptAsync(); Folder = await folder.DecryptAsync();
} }
@ -60,17 +60,17 @@ namespace Bit.App.Pages
public async Task<bool> SubmitAsync() public async Task<bool> SubmitAsync()
{ {
if(Folder == null) if (Folder == null)
{ {
return false; return false;
} }
if(Xamarin.Essentials.Connectivity.NetworkAccess == Xamarin.Essentials.NetworkAccess.None) if (Xamarin.Essentials.Connectivity.NetworkAccess == Xamarin.Essentials.NetworkAccess.None)
{ {
await _platformUtilsService.ShowDialogAsync(AppResources.InternetConnectionRequiredMessage, await _platformUtilsService.ShowDialogAsync(AppResources.InternetConnectionRequiredMessage,
AppResources.InternetConnectionRequiredTitle); AppResources.InternetConnectionRequiredTitle);
return false; return false;
} }
if(string.IsNullOrWhiteSpace(Folder.Name)) if (string.IsNullOrWhiteSpace(Folder.Name))
{ {
await Page.DisplayAlert(AppResources.AnErrorHasOccurred, await Page.DisplayAlert(AppResources.AnErrorHasOccurred,
string.Format(AppResources.ValidationFieldRequired, AppResources.Name), string.Format(AppResources.ValidationFieldRequired, AppResources.Name),
@ -90,10 +90,10 @@ namespace Bit.App.Pages
await Page.Navigation.PopModalAsync(); await Page.Navigation.PopModalAsync();
return true; return true;
} }
catch(ApiException e) catch (ApiException e)
{ {
await _deviceActionService.HideLoadingAsync(); await _deviceActionService.HideLoadingAsync();
if(e?.Error != null) if (e?.Error != null)
{ {
await _platformUtilsService.ShowDialogAsync(e.Error.GetSingleMessage(), await _platformUtilsService.ShowDialogAsync(e.Error.GetSingleMessage(),
AppResources.AnErrorHasOccurred); AppResources.AnErrorHasOccurred);
@ -104,11 +104,11 @@ namespace Bit.App.Pages
public async Task<bool> DeleteAsync() public async Task<bool> DeleteAsync()
{ {
if(Folder == null) if (Folder == null)
{ {
return false; return false;
} }
if(Xamarin.Essentials.Connectivity.NetworkAccess == Xamarin.Essentials.NetworkAccess.None) if (Xamarin.Essentials.Connectivity.NetworkAccess == Xamarin.Essentials.NetworkAccess.None)
{ {
await _platformUtilsService.ShowDialogAsync(AppResources.InternetConnectionRequiredMessage, await _platformUtilsService.ShowDialogAsync(AppResources.InternetConnectionRequiredMessage,
AppResources.InternetConnectionRequiredTitle); AppResources.InternetConnectionRequiredTitle);
@ -116,7 +116,7 @@ namespace Bit.App.Pages
} }
var confirmed = await _platformUtilsService.ShowDialogAsync(AppResources.DoYouReallyWantToDelete, var confirmed = await _platformUtilsService.ShowDialogAsync(AppResources.DoYouReallyWantToDelete,
null, AppResources.Yes, AppResources.No); null, AppResources.Yes, AppResources.No);
if(!confirmed) if (!confirmed)
{ {
return false; return false;
} }
@ -129,10 +129,10 @@ namespace Bit.App.Pages
await Page.Navigation.PopModalAsync(); await Page.Navigation.PopModalAsync();
return true; return true;
} }
catch(ApiException e) catch (ApiException e)
{ {
await _deviceActionService.HideLoadingAsync(); await _deviceActionService.HideLoadingAsync();
if(e?.Error != null) if (e?.Error != null)
{ {
await _platformUtilsService.ShowDialogAsync(e.Error.GetSingleMessage(), await _platformUtilsService.ShowDialogAsync(e.Error.GetSingleMessage(),
AppResources.AnErrorHasOccurred); AppResources.AnErrorHasOccurred);

View File

@ -15,7 +15,7 @@ namespace Bit.App.Pages
_vm = BindingContext as FoldersPageViewModel; _vm = BindingContext as FoldersPageViewModel;
_vm.Page = this; _vm.Page = this;
if(Device.RuntimePlatform == Device.iOS) if (Device.RuntimePlatform == Device.iOS)
{ {
_absLayout.Children.Remove(_fab); _absLayout.Children.Remove(_fab);
ToolbarItems.Add(_closeItem); ToolbarItems.Add(_closeItem);
@ -35,11 +35,11 @@ namespace Bit.App.Pages
private async void RowSelected(object sender, SelectedItemChangedEventArgs e) private async void RowSelected(object sender, SelectedItemChangedEventArgs e)
{ {
((ListView)sender).SelectedItem = null; ((ListView)sender).SelectedItem = null;
if(!DoOnce()) if (!DoOnce())
{ {
return; return;
} }
if(!(e.SelectedItem is FolderView folder)) if (!(e.SelectedItem is FolderView folder))
{ {
return; return;
} }
@ -49,7 +49,7 @@ namespace Bit.App.Pages
private async void AddButton_Clicked(object sender, EventArgs e) private async void AddButton_Clicked(object sender, EventArgs e)
{ {
if(DoOnce()) if (DoOnce())
{ {
var page = new FolderAddEditPage(); var page = new FolderAddEditPage();
await Navigation.PushModalAsync(new NavigationPage(page)); await Navigation.PushModalAsync(new NavigationPage(page));
@ -58,7 +58,7 @@ namespace Bit.App.Pages
private async void Close_Clicked(object sender, System.EventArgs e) private async void Close_Clicked(object sender, System.EventArgs e)
{ {
if(DoOnce()) if (DoOnce())
{ {
await Navigation.PopModalAsync(); await Navigation.PopModalAsync();
} }

View File

@ -34,7 +34,7 @@ namespace Bit.App.Pages
{ {
var folders = await _folderService.GetAllDecryptedAsync(); var folders = await _folderService.GetAllDecryptedAsync();
// Remove "No Folder" // Remove "No Folder"
if(folders?.Any() ?? false) if (folders?.Any() ?? false)
{ {
folders = folders.GetRange(0, folders.Count - 1); folders = folders.GetRange(0, folders.Count - 1);
} }

View File

@ -21,7 +21,7 @@ namespace Bit.App.Pages
_themePicker.ItemDisplayBinding = new Binding("Value"); _themePicker.ItemDisplayBinding = new Binding("Value");
_uriMatchPicker.ItemDisplayBinding = new Binding("Value"); _uriMatchPicker.ItemDisplayBinding = new Binding("Value");
_clearClipboardPicker.ItemDisplayBinding = new Binding("Value"); _clearClipboardPicker.ItemDisplayBinding = new Binding("Value");
if(Device.RuntimePlatform == Device.Android) if (Device.RuntimePlatform == Device.Android)
{ {
ToolbarItems.RemoveAt(0); ToolbarItems.RemoveAt(0);
_vm.ShowAndroidAutofillSettings = _deviceActionService.SupportsAutofillService(); _vm.ShowAndroidAutofillSettings = _deviceActionService.SupportsAutofillService();
@ -55,7 +55,7 @@ namespace Bit.App.Pages
private async void Close_Clicked(object sender, System.EventArgs e) private async void Close_Clicked(object sender, System.EventArgs e)
{ {
if(DoOnce()) if (DoOnce())
{ {
await Navigation.PopModalAsync(); await Navigation.PopModalAsync();
} }

View File

@ -52,7 +52,7 @@ namespace Bit.App.Pages
new KeyValuePair<int?, string>(30, AppResources.ThirtySeconds), new KeyValuePair<int?, string>(30, AppResources.ThirtySeconds),
new KeyValuePair<int?, string>(60, AppResources.OneMinute) new KeyValuePair<int?, string>(60, AppResources.OneMinute)
}; };
if(!iosIos) if (!iosIos)
{ {
ClearClipboardOptions.Add(new KeyValuePair<int?, string>(120, AppResources.TwoMinutes)); ClearClipboardOptions.Add(new KeyValuePair<int?, string>(120, AppResources.TwoMinutes));
ClearClipboardOptions.Add(new KeyValuePair<int?, string>(300, AppResources.FiveMinutes)); ClearClipboardOptions.Add(new KeyValuePair<int?, string>(300, AppResources.FiveMinutes));
@ -85,7 +85,7 @@ namespace Bit.App.Pages
get => _clearClipboardSelectedIndex; get => _clearClipboardSelectedIndex;
set set
{ {
if(SetProperty(ref _clearClipboardSelectedIndex, value)) if (SetProperty(ref _clearClipboardSelectedIndex, value))
{ {
var task = SaveClipboardChangedAsync(); var task = SaveClipboardChangedAsync();
} }
@ -97,7 +97,7 @@ namespace Bit.App.Pages
get => _themeSelectedIndex; get => _themeSelectedIndex;
set set
{ {
if(SetProperty(ref _themeSelectedIndex, value)) if (SetProperty(ref _themeSelectedIndex, value))
{ {
var task = SaveThemeAsync(); var task = SaveThemeAsync();
} }
@ -109,7 +109,7 @@ namespace Bit.App.Pages
get => _uriMatchSelectedIndex; get => _uriMatchSelectedIndex;
set set
{ {
if(SetProperty(ref _uriMatchSelectedIndex, value)) if (SetProperty(ref _uriMatchSelectedIndex, value))
{ {
var task = SaveDefaultUriAsync(); var task = SaveDefaultUriAsync();
} }
@ -121,7 +121,7 @@ namespace Bit.App.Pages
get => _disableFavicon; get => _disableFavicon;
set set
{ {
if(SetProperty(ref _disableFavicon, value)) if (SetProperty(ref _disableFavicon, value))
{ {
var task = UpdateDisableFaviconAsync(); var task = UpdateDisableFaviconAsync();
} }
@ -133,7 +133,7 @@ namespace Bit.App.Pages
get => _disableAutoTotpCopy; get => _disableAutoTotpCopy;
set set
{ {
if(SetProperty(ref _disableAutoTotpCopy, value)) if (SetProperty(ref _disableAutoTotpCopy, value))
{ {
var task = UpdateAutoTotpCopyAsync(); var task = UpdateAutoTotpCopyAsync();
} }
@ -145,7 +145,7 @@ namespace Bit.App.Pages
get => _autofillDisableSavePrompt; get => _autofillDisableSavePrompt;
set set
{ {
if(SetProperty(ref _autofillDisableSavePrompt, value)) if (SetProperty(ref _autofillDisableSavePrompt, value))
{ {
var task = UpdateAutofillDisableSavePromptAsync(); var task = UpdateAutofillDisableSavePromptAsync();
} }
@ -185,7 +185,7 @@ namespace Bit.App.Pages
private async Task UpdateAutoTotpCopyAsync() private async Task UpdateAutoTotpCopyAsync()
{ {
if(_inited) if (_inited)
{ {
await _storageService.SaveAsync(Constants.DisableAutoTotpCopyKey, DisableAutoTotpCopy); await _storageService.SaveAsync(Constants.DisableAutoTotpCopyKey, DisableAutoTotpCopy);
} }
@ -193,7 +193,7 @@ namespace Bit.App.Pages
private async Task UpdateDisableFaviconAsync() private async Task UpdateDisableFaviconAsync()
{ {
if(_inited) if (_inited)
{ {
await _storageService.SaveAsync(Constants.DisableFaviconKey, DisableFavicon); await _storageService.SaveAsync(Constants.DisableFaviconKey, DisableFavicon);
await _stateService.SaveAsync(Constants.DisableFaviconKey, DisableFavicon); await _stateService.SaveAsync(Constants.DisableFaviconKey, DisableFavicon);
@ -202,7 +202,7 @@ namespace Bit.App.Pages
private async Task SaveClipboardChangedAsync() private async Task SaveClipboardChangedAsync()
{ {
if(_inited && ClearClipboardSelectedIndex > -1) if (_inited && ClearClipboardSelectedIndex > -1)
{ {
await _storageService.SaveAsync(Constants.ClearClipboardKey, await _storageService.SaveAsync(Constants.ClearClipboardKey,
ClearClipboardOptions[ClearClipboardSelectedIndex].Key); ClearClipboardOptions[ClearClipboardSelectedIndex].Key);
@ -211,17 +211,17 @@ namespace Bit.App.Pages
private async Task SaveThemeAsync() private async Task SaveThemeAsync()
{ {
if(_inited && ThemeSelectedIndex > -1) if (_inited && ThemeSelectedIndex > -1)
{ {
var theme = ThemeOptions[ThemeSelectedIndex].Key; var theme = ThemeOptions[ThemeSelectedIndex].Key;
await _storageService.SaveAsync(Constants.ThemeKey, theme); await _storageService.SaveAsync(Constants.ThemeKey, theme);
if(Device.RuntimePlatform == Device.Android) if (Device.RuntimePlatform == Device.Android)
{ {
await _deviceActionService.ShowLoadingAsync(AppResources.Restarting); await _deviceActionService.ShowLoadingAsync(AppResources.Restarting);
await Task.Delay(1000); await Task.Delay(1000);
} }
_messagingService.Send("updatedTheme", theme); _messagingService.Send("updatedTheme", theme);
if(Device.RuntimePlatform == Device.iOS) if (Device.RuntimePlatform == Device.iOS)
{ {
await Task.Delay(500); await Task.Delay(500);
await _platformUtilsService.ShowDialogAsync(AppResources.ThemeAppliedOnRestart); await _platformUtilsService.ShowDialogAsync(AppResources.ThemeAppliedOnRestart);
@ -231,7 +231,7 @@ namespace Bit.App.Pages
private async Task SaveDefaultUriAsync() private async Task SaveDefaultUriAsync()
{ {
if(_inited && UriMatchSelectedIndex > -1) if (_inited && UriMatchSelectedIndex > -1)
{ {
await _storageService.SaveAsync(Constants.DefaultUriMatch, await _storageService.SaveAsync(Constants.DefaultUriMatch,
(int?)UriMatchOptions[UriMatchSelectedIndex].Key); (int?)UriMatchOptions[UriMatchSelectedIndex].Key);
@ -240,7 +240,7 @@ namespace Bit.App.Pages
private async Task UpdateAutofillDisableSavePromptAsync() private async Task UpdateAutofillDisableSavePromptAsync()
{ {
if(_inited) if (_inited)
{ {
await _storageService.SaveAsync(Constants.AutofillDisableSavePromptKey, AutofillDisableSavePrompt); await _storageService.SaveAsync(Constants.AutofillDisableSavePromptKey, AutofillDisableSavePrompt);
} }
@ -248,9 +248,9 @@ namespace Bit.App.Pages
public async Task UpdateAutofillBlacklistedUris() public async Task UpdateAutofillBlacklistedUris()
{ {
if(_inited) if (_inited)
{ {
if(string.IsNullOrWhiteSpace(AutofillBlacklistedUris)) if (string.IsNullOrWhiteSpace(AutofillBlacklistedUris))
{ {
await _storageService.RemoveAsync(Constants.AutofillBlacklistedUrisKey); await _storageService.RemoveAsync(Constants.AutofillBlacklistedUrisKey);
AutofillBlacklistedUris = null; AutofillBlacklistedUris = null;
@ -260,14 +260,14 @@ namespace Bit.App.Pages
{ {
var csv = AutofillBlacklistedUris; var csv = AutofillBlacklistedUris;
var urisList = new List<string>(); var urisList = new List<string>();
foreach(var uri in csv.Split(',')) foreach (var uri in csv.Split(','))
{ {
if(string.IsNullOrWhiteSpace(uri)) if (string.IsNullOrWhiteSpace(uri))
{ {
continue; continue;
} }
var cleanedUri = uri.Replace(System.Environment.NewLine, string.Empty).Trim(); var cleanedUri = uri.Replace(System.Environment.NewLine, string.Empty).Trim();
if(!cleanedUri.StartsWith("http://") && !cleanedUri.StartsWith("https://") && if (!cleanedUri.StartsWith("http://") && !cleanedUri.StartsWith("https://") &&
!cleanedUri.StartsWith(Constants.AndroidAppProtocol)) !cleanedUri.StartsWith(Constants.AndroidAppProtocol))
{ {
continue; continue;

View File

@ -33,7 +33,7 @@ namespace Bit.App.Pages
protected override bool OnBackButtonPressed() protected override bool OnBackButtonPressed()
{ {
if(Device.RuntimePlatform == Device.Android && _tabsPage != null) if (Device.RuntimePlatform == Device.Android && _tabsPage != null)
{ {
_tabsPage.ResetToVaultPage(); _tabsPage.ResetToVaultPage();
return true; return true;
@ -44,112 +44,112 @@ namespace Bit.App.Pages
private async void RowSelected(object sender, SelectedItemChangedEventArgs e) private async void RowSelected(object sender, SelectedItemChangedEventArgs e)
{ {
((ListView)sender).SelectedItem = null; ((ListView)sender).SelectedItem = null;
if(!DoOnce()) if (!DoOnce())
{ {
return; return;
} }
if(!(e.SelectedItem is SettingsPageListItem item)) if (!(e.SelectedItem is SettingsPageListItem item))
{ {
return; return;
} }
if(item.Name == AppResources.Sync) if (item.Name == AppResources.Sync)
{ {
await Navigation.PushModalAsync(new NavigationPage(new SyncPage())); await Navigation.PushModalAsync(new NavigationPage(new SyncPage()));
} }
else if(item.Name == AppResources.AutofillAccessibilityService) else if (item.Name == AppResources.AutofillAccessibilityService)
{ {
await Navigation.PushModalAsync(new NavigationPage(new AccessibilityServicePage(this))); await Navigation.PushModalAsync(new NavigationPage(new AccessibilityServicePage(this)));
} }
else if(item.Name == AppResources.AutofillService) else if (item.Name == AppResources.AutofillService)
{ {
await Navigation.PushModalAsync(new NavigationPage(new AutofillServicePage(this))); await Navigation.PushModalAsync(new NavigationPage(new AutofillServicePage(this)));
} }
else if(item.Name == AppResources.PasswordAutofill) else if (item.Name == AppResources.PasswordAutofill)
{ {
await Navigation.PushModalAsync(new NavigationPage(new AutofillPage())); await Navigation.PushModalAsync(new NavigationPage(new AutofillPage()));
} }
else if(item.Name == AppResources.AppExtension) else if (item.Name == AppResources.AppExtension)
{ {
await Navigation.PushModalAsync(new NavigationPage(new ExtensionPage())); await Navigation.PushModalAsync(new NavigationPage(new ExtensionPage()));
} }
else if(item.Name == AppResources.Options) else if (item.Name == AppResources.Options)
{ {
await Navigation.PushModalAsync(new NavigationPage(new OptionsPage())); await Navigation.PushModalAsync(new NavigationPage(new OptionsPage()));
} }
else if(item.Name == AppResources.Folders) else if (item.Name == AppResources.Folders)
{ {
await Navigation.PushModalAsync(new NavigationPage(new FoldersPage())); await Navigation.PushModalAsync(new NavigationPage(new FoldersPage()));
} }
else if(item.Name == AppResources.About) else if (item.Name == AppResources.About)
{ {
await _vm.AboutAsync(); await _vm.AboutAsync();
} }
else if(item.Name == AppResources.HelpAndFeedback) else if (item.Name == AppResources.HelpAndFeedback)
{ {
_vm.Help(); _vm.Help();
} }
else if(item.Name == AppResources.FingerprintPhrase) else if (item.Name == AppResources.FingerprintPhrase)
{ {
await _vm.FingerprintAsync(); await _vm.FingerprintAsync();
} }
else if(item.Name == AppResources.RateTheApp) else if (item.Name == AppResources.RateTheApp)
{ {
_vm.Rate(); _vm.Rate();
} }
else if(item.Name == AppResources.ImportItems) else if (item.Name == AppResources.ImportItems)
{ {
_vm.Import(); _vm.Import();
} }
else if(item.Name == AppResources.ExportVault) else if (item.Name == AppResources.ExportVault)
{ {
await Navigation.PushModalAsync(new NavigationPage(new ExportVaultPage())); await Navigation.PushModalAsync(new NavigationPage(new ExportVaultPage()));
} }
else if(item.Name == AppResources.ShareVault) else if (item.Name == AppResources.ShareVault)
{ {
await _vm.ShareAsync(); await _vm.ShareAsync();
} }
else if(item.Name == AppResources.WebVault) else if (item.Name == AppResources.WebVault)
{ {
_vm.WebVault(); _vm.WebVault();
} }
else if(item.Name == AppResources.ChangeMasterPassword) else if (item.Name == AppResources.ChangeMasterPassword)
{ {
await _vm.ChangePasswordAsync(); await _vm.ChangePasswordAsync();
} }
else if(item.Name == AppResources.TwoStepLogin) else if (item.Name == AppResources.TwoStepLogin)
{ {
await _vm.TwoStepAsync(); await _vm.TwoStepAsync();
} }
else if(item.Name == AppResources.LogOut) else if (item.Name == AppResources.LogOut)
{ {
await _vm.LogOutAsync(); await _vm.LogOutAsync();
} }
else if(item.Name == AppResources.LockNow) else if (item.Name == AppResources.LockNow)
{ {
await _vm.LockAsync(); await _vm.LockAsync();
} }
else if(item.Name == AppResources.LockOptions) else if (item.Name == AppResources.LockOptions)
{ {
await _vm.LockOptionsAsync(); await _vm.LockOptionsAsync();
} }
else if(item.Name == AppResources.UnlockWithPIN) else if (item.Name == AppResources.UnlockWithPIN)
{ {
await _vm.UpdatePinAsync(); await _vm.UpdatePinAsync();
} }
else else
{ {
var fingerprintName = AppResources.Fingerprint; var fingerprintName = AppResources.Fingerprint;
if(Device.RuntimePlatform == Device.iOS) if (Device.RuntimePlatform == Device.iOS)
{ {
var supportsFace = await _deviceActionService.SupportsFaceBiometricAsync(); var supportsFace = await _deviceActionService.SupportsFaceBiometricAsync();
fingerprintName = supportsFace ? AppResources.FaceID : AppResources.TouchID; fingerprintName = supportsFace ? AppResources.FaceID : AppResources.TouchID;
} }
else if(Device.RuntimePlatform == Device.Android && _deviceActionService.UseNativeBiometric()) else if (Device.RuntimePlatform == Device.Android && _deviceActionService.UseNativeBiometric())
{ {
fingerprintName = AppResources.Biometrics; fingerprintName = AppResources.Biometrics;
} }
if(item.Name == string.Format(AppResources.UnlockWith, fingerprintName)) if (item.Name == string.Format(AppResources.UnlockWith, fingerprintName))
{ {
await _vm.UpdateFingerprintAsync(); await _vm.UpdateFingerprintAsync();
} }

View File

@ -8,11 +8,11 @@ namespace Bit.App.Pages
bool first = false) bool first = false)
{ {
AddRange(groupItems); AddRange(groupItems);
if(string.IsNullOrWhiteSpace(name)) if (string.IsNullOrWhiteSpace(name))
{ {
Name = "-"; Name = "-";
} }
else if(doUpper) else if (doUpper)
{ {
Name = name.ToUpperInvariant(); Name = name.ToUpperInvariant();
} }

View File

@ -8,7 +8,7 @@ namespace Bit.App.Pages
protected override DataTemplate OnSelectTemplate(object item, BindableObject container) protected override DataTemplate OnSelectTemplate(object item, BindableObject container)
{ {
if(item is SettingsPageListItem listItem) if (item is SettingsPageListItem listItem)
{ {
return RegularTemplate; return RegularTemplate;
} }

View File

@ -64,7 +64,7 @@ namespace Bit.App.Pages
{ {
_supportsFingerprint = await _platformUtilsService.SupportsBiometricAsync(); _supportsFingerprint = await _platformUtilsService.SupportsBiometricAsync();
var lastSync = await _syncService.GetLastSyncAsync(); var lastSync = await _syncService.GetLastSyncAsync();
if(lastSync != null) if (lastSync != null)
{ {
lastSync = lastSync.Value.ToLocalTime(); lastSync = lastSync.Value.ToLocalTime();
_lastSyncDate = string.Format("{0} {1}", lastSync.Value.ToShortDateString(), _lastSyncDate = string.Format("{0} {1}", lastSync.Value.ToShortDateString(),
@ -85,7 +85,7 @@ namespace Bit.App.Pages
var text = string.Format("© Bitwarden Inc. 2015-{0}\n\n{1}", DateTime.Now.Year, debugText); var text = string.Format("© Bitwarden Inc. 2015-{0}\n\n{1}", DateTime.Now.Year, debugText);
var copy = await _platformUtilsService.ShowDialogAsync(text, AppResources.Bitwarden, AppResources.Copy, var copy = await _platformUtilsService.ShowDialogAsync(text, AppResources.Bitwarden, AppResources.Copy,
AppResources.Close); AppResources.Close);
if(copy) if (copy)
{ {
await _platformUtilsService.CopyToClipboardAsync(debugText); await _platformUtilsService.CopyToClipboardAsync(debugText);
} }
@ -103,7 +103,7 @@ namespace Bit.App.Pages
{ {
fingerprint = await _cryptoService.GetFingerprintAsync(await _userService.GetUserIdAsync()); fingerprint = await _cryptoService.GetFingerprintAsync(await _userService.GetUserIdAsync());
} }
catch(Exception e) when(e.Message == "No public key available.") catch (Exception e) when(e.Message == "No public key available.")
{ {
return; return;
} }
@ -111,7 +111,7 @@ namespace Bit.App.Pages
var text = string.Format("{0}:\n\n{1}", AppResources.YourAccountsFingerprint, phrase); var text = string.Format("{0}:\n\n{1}", AppResources.YourAccountsFingerprint, phrase);
var learnMore = await _platformUtilsService.ShowDialogAsync(text, AppResources.FingerprintPhrase, var learnMore = await _platformUtilsService.ShowDialogAsync(text, AppResources.FingerprintPhrase,
AppResources.LearnMore, AppResources.Close); AppResources.LearnMore, AppResources.Close);
if(learnMore) if (learnMore)
{ {
_platformUtilsService.LaunchUri("https://help.bitwarden.com/article/fingerprint-phrase/"); _platformUtilsService.LaunchUri("https://help.bitwarden.com/article/fingerprint-phrase/");
} }
@ -130,7 +130,7 @@ namespace Bit.App.Pages
public void WebVault() public void WebVault()
{ {
var url = _environmentService.GetWebVaultUrl(); var url = _environmentService.GetWebVaultUrl();
if(url == null) if (url == null)
{ {
url = "https://vault.bitwarden.com"; url = "https://vault.bitwarden.com";
} }
@ -141,7 +141,7 @@ namespace Bit.App.Pages
{ {
var confirmed = await _platformUtilsService.ShowDialogAsync(AppResources.ShareVaultConfirmation, var confirmed = await _platformUtilsService.ShowDialogAsync(AppResources.ShareVaultConfirmation,
AppResources.ShareVault, AppResources.Yes, AppResources.Cancel); AppResources.ShareVault, AppResources.Yes, AppResources.Cancel);
if(confirmed) if (confirmed)
{ {
_platformUtilsService.LaunchUri("https://help.bitwarden.com/article/what-is-an-organization/"); _platformUtilsService.LaunchUri("https://help.bitwarden.com/article/what-is-an-organization/");
} }
@ -151,7 +151,7 @@ namespace Bit.App.Pages
{ {
var confirmed = await _platformUtilsService.ShowDialogAsync(AppResources.TwoStepLoginConfirmation, var confirmed = await _platformUtilsService.ShowDialogAsync(AppResources.TwoStepLoginConfirmation,
AppResources.TwoStepLogin, AppResources.Yes, AppResources.Cancel); AppResources.TwoStepLogin, AppResources.Yes, AppResources.Cancel);
if(confirmed) if (confirmed)
{ {
_platformUtilsService.LaunchUri("https://help.bitwarden.com/article/setup-two-step-login/"); _platformUtilsService.LaunchUri("https://help.bitwarden.com/article/setup-two-step-login/");
} }
@ -161,7 +161,7 @@ namespace Bit.App.Pages
{ {
var confirmed = await _platformUtilsService.ShowDialogAsync(AppResources.ChangePasswordConfirmation, var confirmed = await _platformUtilsService.ShowDialogAsync(AppResources.ChangePasswordConfirmation,
AppResources.ChangeMasterPassword, AppResources.Yes, AppResources.Cancel); AppResources.ChangeMasterPassword, AppResources.Yes, AppResources.Cancel);
if(confirmed) if (confirmed)
{ {
_platformUtilsService.LaunchUri("https://help.bitwarden.com/article/change-your-master-password/"); _platformUtilsService.LaunchUri("https://help.bitwarden.com/article/change-your-master-password/");
} }
@ -171,7 +171,7 @@ namespace Bit.App.Pages
{ {
var confirmed = await _platformUtilsService.ShowDialogAsync(AppResources.LogoutConfirmation, var confirmed = await _platformUtilsService.ShowDialogAsync(AppResources.LogoutConfirmation,
AppResources.LogOut, AppResources.Yes, AppResources.Cancel); AppResources.LogOut, AppResources.Yes, AppResources.Cancel);
if(confirmed) if (confirmed)
{ {
_messagingService.Send("logout"); _messagingService.Send("logout");
} }
@ -186,7 +186,7 @@ namespace Bit.App.Pages
{ {
var options = _lockOptions.Select(o => o.Key == _lockOptionValue ? $"✓ {o.Key}" : o.Key).ToArray(); var options = _lockOptions.Select(o => o.Key == _lockOptionValue ? $"✓ {o.Key}" : o.Key).ToArray();
var selection = await Page.DisplayActionSheet(AppResources.LockOptions, AppResources.Cancel, null, options); var selection = await Page.DisplayActionSheet(AppResources.LockOptions, AppResources.Cancel, null, options);
if(selection == null || selection == AppResources.Cancel) if (selection == null || selection == AppResources.Cancel)
{ {
return; return;
} }
@ -200,11 +200,11 @@ namespace Bit.App.Pages
public async Task UpdatePinAsync() public async Task UpdatePinAsync()
{ {
_pin = !_pin; _pin = !_pin;
if(_pin) if (_pin)
{ {
var pin = await _deviceActionService.DisplayPromptAync(AppResources.EnterPIN, var pin = await _deviceActionService.DisplayPromptAync(AppResources.EnterPIN,
AppResources.SetPINDescription, null, AppResources.Submit, AppResources.Cancel, true); AppResources.SetPINDescription, null, AppResources.Submit, AppResources.Cancel, true);
if(!string.IsNullOrWhiteSpace(pin)) if (!string.IsNullOrWhiteSpace(pin))
{ {
var masterPassOnRestart = await _platformUtilsService.ShowDialogAsync( var masterPassOnRestart = await _platformUtilsService.ShowDialogAsync(
AppResources.PINRequireMasterPasswordRestart, AppResources.UnlockWithPIN, AppResources.PINRequireMasterPasswordRestart, AppResources.UnlockWithPIN,
@ -219,7 +219,7 @@ namespace Bit.App.Pages
var key = await _cryptoService.GetKeyAsync(); var key = await _cryptoService.GetKeyAsync();
var pinProtectedKey = await _cryptoService.EncryptAsync(key.Key, pinKey); var pinProtectedKey = await _cryptoService.EncryptAsync(key.Key, pinKey);
if(masterPassOnRestart) if (masterPassOnRestart)
{ {
var encPin = await _cryptoService.EncryptAsync(pin); var encPin = await _cryptoService.EncryptAsync(pin);
await _storageService.SaveAsync(Constants.ProtectedPin, encPin.EncryptedString); await _storageService.SaveAsync(Constants.ProtectedPin, encPin.EncryptedString);
@ -235,7 +235,7 @@ namespace Bit.App.Pages
_pin = false; _pin = false;
} }
} }
if(!_pin) if (!_pin)
{ {
await _cryptoService.ClearPinProtectedKeyAsync(); await _cryptoService.ClearPinProtectedKeyAsync();
await _lockService.ClearAsync(); await _lockService.ClearAsync();
@ -246,20 +246,20 @@ namespace Bit.App.Pages
public async Task UpdateFingerprintAsync() public async Task UpdateFingerprintAsync()
{ {
var current = _fingerprint; var current = _fingerprint;
if(_fingerprint) if (_fingerprint)
{ {
_fingerprint = false; _fingerprint = false;
} }
else if(await _platformUtilsService.SupportsBiometricAsync()) else if (await _platformUtilsService.SupportsBiometricAsync())
{ {
_fingerprint = await _platformUtilsService.AuthenticateBiometricAsync(null, _fingerprint = await _platformUtilsService.AuthenticateBiometricAsync(null,
_deviceActionService.DeviceType == Core.Enums.DeviceType.Android ? "." : null); _deviceActionService.DeviceType == Core.Enums.DeviceType.Android ? "." : null);
} }
if(_fingerprint == current) if (_fingerprint == current)
{ {
return; return;
} }
if(_fingerprint) if (_fingerprint)
{ {
await _storageService.SaveAsync(Constants.FingerprintUnlockKey, true); await _storageService.SaveAsync(Constants.FingerprintUnlockKey, true);
} }
@ -276,9 +276,9 @@ namespace Bit.App.Pages
{ {
var doUpper = Device.RuntimePlatform != Device.Android; var doUpper = Device.RuntimePlatform != Device.Android;
var autofillItems = new List<SettingsPageListItem>(); var autofillItems = new List<SettingsPageListItem>();
if(Device.RuntimePlatform == Device.Android) if (Device.RuntimePlatform == Device.Android)
{ {
if(_deviceActionService.SupportsAutofillService()) if (_deviceActionService.SupportsAutofillService())
{ {
autofillItems.Add(new SettingsPageListItem autofillItems.Add(new SettingsPageListItem
{ {
@ -299,7 +299,7 @@ namespace Bit.App.Pages
} }
else else
{ {
if(_deviceActionService.SystemMajorVersion() >= 12) if (_deviceActionService.SystemMajorVersion() >= 12)
{ {
autofillItems.Add(new SettingsPageListItem { Name = AppResources.PasswordAutofill }); autofillItems.Add(new SettingsPageListItem { Name = AppResources.PasswordAutofill });
} }
@ -321,15 +321,15 @@ namespace Bit.App.Pages
new SettingsPageListItem { Name = AppResources.LockNow }, new SettingsPageListItem { Name = AppResources.LockNow },
new SettingsPageListItem { Name = AppResources.TwoStepLogin } new SettingsPageListItem { Name = AppResources.TwoStepLogin }
}; };
if(_supportsFingerprint || _fingerprint) if (_supportsFingerprint || _fingerprint)
{ {
var fingerprintName = AppResources.Fingerprint; var fingerprintName = AppResources.Fingerprint;
if(Device.RuntimePlatform == Device.iOS) if (Device.RuntimePlatform == Device.iOS)
{ {
fingerprintName = _deviceActionService.SupportsFaceBiometric() ? AppResources.FaceID : fingerprintName = _deviceActionService.SupportsFaceBiometric() ? AppResources.FaceID :
AppResources.TouchID; AppResources.TouchID;
} }
else if(Device.RuntimePlatform == Device.Android && _deviceActionService.UseNativeBiometric()) else if (Device.RuntimePlatform == Device.Android && _deviceActionService.UseNativeBiometric())
{ {
fingerprintName = AppResources.Biometrics; fingerprintName = AppResources.Biometrics;
} }

View File

@ -12,7 +12,7 @@ namespace Bit.App.Pages
InitializeComponent(); InitializeComponent();
_vm = BindingContext as SyncPageViewModel; _vm = BindingContext as SyncPageViewModel;
_vm.Page = this; _vm.Page = this;
if(Device.RuntimePlatform == Device.Android) if (Device.RuntimePlatform == Device.Android)
{ {
ToolbarItems.RemoveAt(0); ToolbarItems.RemoveAt(0);
} }
@ -26,7 +26,7 @@ namespace Bit.App.Pages
private async void Sync_Clicked(object sender, EventArgs e) private async void Sync_Clicked(object sender, EventArgs e)
{ {
if(DoOnce()) if (DoOnce())
{ {
await _vm.SyncAsync(); await _vm.SyncAsync();
} }
@ -34,7 +34,7 @@ namespace Bit.App.Pages
private async void Close_Clicked(object sender, System.EventArgs e) private async void Close_Clicked(object sender, System.EventArgs e)
{ {
if(DoOnce()) if (DoOnce())
{ {
await Navigation.PopModalAsync(); await Navigation.PopModalAsync();
} }

View File

@ -33,7 +33,7 @@ namespace Bit.App.Pages
public async Task SetLastSyncAsync() public async Task SetLastSyncAsync()
{ {
var last = await _syncService.GetLastSyncAsync(); var last = await _syncService.GetLastSyncAsync();
if(last != null) if (last != null)
{ {
var localDate = last.Value.ToLocalTime(); var localDate = last.Value.ToLocalTime();
LastSync = string.Format("{0} {1}", localDate.ToShortDateString(), localDate.ToShortTimeString()); LastSync = string.Format("{0} {1}", localDate.ToShortDateString(), localDate.ToShortTimeString());
@ -46,7 +46,7 @@ namespace Bit.App.Pages
public async Task SyncAsync() public async Task SyncAsync()
{ {
if(Xamarin.Essentials.Connectivity.NetworkAccess == Xamarin.Essentials.NetworkAccess.None) if (Xamarin.Essentials.Connectivity.NetworkAccess == Xamarin.Essentials.NetworkAccess.None)
{ {
await _platformUtilsService.ShowDialogAsync(AppResources.InternetConnectionRequiredMessage, await _platformUtilsService.ShowDialogAsync(AppResources.InternetConnectionRequiredMessage,
AppResources.InternetConnectionRequiredTitle); AppResources.InternetConnectionRequiredTitle);
@ -57,7 +57,7 @@ namespace Bit.App.Pages
await _deviceActionService.ShowLoadingAsync(AppResources.Syncing); await _deviceActionService.ShowLoadingAsync(AppResources.Syncing);
var success = await _syncService.FullSyncAsync(true); var success = await _syncService.FullSyncAsync(true);
await _deviceActionService.HideLoadingAsync(); await _deviceActionService.HideLoadingAsync();
if(success) if (success)
{ {
await SetLastSyncAsync(); await SetLastSyncAsync();
_platformUtilsService.ShowToast("success", null, AppResources.SyncingComplete); _platformUtilsService.ShowToast("success", null, AppResources.SyncingComplete);
@ -67,10 +67,10 @@ namespace Bit.App.Pages
await Page.DisplayAlert(null, AppResources.SyncingFailed, AppResources.Ok); await Page.DisplayAlert(null, AppResources.SyncingFailed, AppResources.Ok);
} }
} }
catch(ApiException e) catch (ApiException e)
{ {
await _deviceActionService.HideLoadingAsync(); await _deviceActionService.HideLoadingAsync();
if(e?.Error != null) if (e?.Error != null)
{ {
await _platformUtilsService.ShowDialogAsync(e.Error.GetSingleMessage(), await _platformUtilsService.ShowDialogAsync(e.Error.GetSingleMessage(),
AppResources.AnErrorHasOccurred); AppResources.AnErrorHasOccurred);

View File

@ -33,7 +33,7 @@ namespace Bit.App.Pages
}; };
Children.Add(settingsPage); Children.Add(settingsPage);
if(Device.RuntimePlatform == Device.Android) if (Device.RuntimePlatform == Device.Android)
{ {
Effects.Add(new TabBarEffect()); Effects.Add(new TabBarEffect());
@ -43,12 +43,12 @@ namespace Bit.App.Pages
Xamarin.Forms.PlatformConfiguration.AndroidSpecific.TabbedPage.SetIsSmoothScrollEnabled(this, false); Xamarin.Forms.PlatformConfiguration.AndroidSpecific.TabbedPage.SetIsSmoothScrollEnabled(this, false);
} }
if(appOptions?.GeneratorTile ?? false) if (appOptions?.GeneratorTile ?? false)
{ {
appOptions.GeneratorTile = false; appOptions.GeneratorTile = false;
ResetToGeneratorPage(); ResetToGeneratorPage();
} }
else if(appOptions?.MyVaultTile ?? false) else if (appOptions?.MyVaultTile ?? false)
{ {
appOptions.MyVaultTile = false; appOptions.MyVaultTile = false;
} }
@ -66,17 +66,17 @@ namespace Bit.App.Pages
protected async override void OnCurrentPageChanged() protected async override void OnCurrentPageChanged()
{ {
if(CurrentPage is NavigationPage navPage) if (CurrentPage is NavigationPage navPage)
{ {
if(navPage.RootPage is GroupingsPage groupingsPage) if (navPage.RootPage is GroupingsPage groupingsPage)
{ {
// Load something? // Load something?
} }
else if(navPage.RootPage is GeneratorPage genPage) else if (navPage.RootPage is GeneratorPage genPage)
{ {
await genPage.InitAsync(); await genPage.InitAsync();
} }
else if(navPage.RootPage is SettingsPage settingsPage) else if (navPage.RootPage is SettingsPage settingsPage)
{ {
await settingsPage.InitAsync(); await settingsPage.InitAsync();
} }

View File

@ -52,15 +52,15 @@ namespace Bit.App.Pages
_vm.ViewPage = viewPage; _vm.ViewPage = viewPage;
_vm.Init(); _vm.Init();
SetActivityIndicator(); SetActivityIndicator();
if(_vm.EditMode && !_vm.CloneMode && Device.RuntimePlatform == Device.Android) if (_vm.EditMode && !_vm.CloneMode && Device.RuntimePlatform == Device.Android)
{ {
ToolbarItems.Add(_attachmentsItem); ToolbarItems.Add(_attachmentsItem);
ToolbarItems.Add(_deleteItem); ToolbarItems.Add(_deleteItem);
} }
if(Device.RuntimePlatform == Device.iOS) if (Device.RuntimePlatform == Device.iOS)
{ {
ToolbarItems.Add(_closeItem); ToolbarItems.Add(_closeItem);
if(_vm.EditMode && !_vm.CloneMode) if (_vm.EditMode && !_vm.CloneMode)
{ {
ToolbarItems.Add(_moreItem); ToolbarItems.Add(_moreItem);
} }
@ -82,11 +82,11 @@ namespace Bit.App.Pages
_nameEntry.ReturnType = ReturnType.Next; _nameEntry.ReturnType = ReturnType.Next;
_nameEntry.ReturnCommand = new Command(() => _nameEntry.ReturnCommand = new Command(() =>
{ {
if(_vm.Cipher.Type == CipherType.Login) if (_vm.Cipher.Type == CipherType.Login)
{ {
_loginUsernameEntry.Focus(); _loginUsernameEntry.Focus();
} }
else if(_vm.Cipher.Type == CipherType.Card) else if (_vm.Cipher.Type == CipherType.Card)
{ {
_cardholderNameEntry.Focus(); _cardholderNameEntry.Focus();
} }
@ -145,14 +145,14 @@ namespace Bit.App.Pages
await LoadOnAppearedAsync(_scrollView, true, async () => await LoadOnAppearedAsync(_scrollView, true, async () =>
{ {
var success = await _vm.LoadAsync(_appOptions); var success = await _vm.LoadAsync(_appOptions);
if(!success) if (!success)
{ {
await Navigation.PopModalAsync(); await Navigation.PopModalAsync();
return; return;
} }
AdjustToolbar(); AdjustToolbar();
await ShowAlertsAsync(); await ShowAlertsAsync();
if(!_vm.EditMode && string.IsNullOrWhiteSpace(_vm.Cipher?.Name)) if (!_vm.EditMode && string.IsNullOrWhiteSpace(_vm.Cipher?.Name))
{ {
RequestFocus(_nameEntry); RequestFocus(_nameEntry);
} }
@ -166,7 +166,7 @@ namespace Bit.App.Pages
protected override bool OnBackButtonPressed() protected override bool OnBackButtonPressed()
{ {
if(FromAutofillFramework) if (FromAutofillFramework)
{ {
Xamarin.Forms.Application.Current.MainPage = new TabsPage(); Xamarin.Forms.Application.Current.MainPage = new TabsPage();
return true; return true;
@ -176,7 +176,7 @@ namespace Bit.App.Pages
private async void PasswordHistory_Tapped(object sender, System.EventArgs e) private async void PasswordHistory_Tapped(object sender, System.EventArgs e)
{ {
if(DoOnce()) if (DoOnce())
{ {
await Navigation.PushModalAsync( await Navigation.PushModalAsync(
new Xamarin.Forms.NavigationPage(new PasswordHistoryPage(_vm.CipherId))); new Xamarin.Forms.NavigationPage(new PasswordHistoryPage(_vm.CipherId)));
@ -185,7 +185,7 @@ namespace Bit.App.Pages
private async void Save_Clicked(object sender, System.EventArgs e) private async void Save_Clicked(object sender, System.EventArgs e)
{ {
if(DoOnce()) if (DoOnce())
{ {
await _vm.SubmitAsync(); await _vm.SubmitAsync();
} }
@ -203,7 +203,7 @@ namespace Bit.App.Pages
private async void Attachments_Clicked(object sender, System.EventArgs e) private async void Attachments_Clicked(object sender, System.EventArgs e)
{ {
if(DoOnce()) if (DoOnce())
{ {
var page = new AttachmentsPage(_vm.CipherId); var page = new AttachmentsPage(_vm.CipherId);
await Navigation.PushModalAsync(new Xamarin.Forms.NavigationPage(page)); await Navigation.PushModalAsync(new Xamarin.Forms.NavigationPage(page));
@ -212,7 +212,7 @@ namespace Bit.App.Pages
private async void Share_Clicked(object sender, System.EventArgs e) private async void Share_Clicked(object sender, System.EventArgs e)
{ {
if(DoOnce()) if (DoOnce())
{ {
var page = new SharePage(_vm.CipherId); var page = new SharePage(_vm.CipherId);
await Navigation.PushModalAsync(new Xamarin.Forms.NavigationPage(page)); await Navigation.PushModalAsync(new Xamarin.Forms.NavigationPage(page));
@ -221,9 +221,9 @@ namespace Bit.App.Pages
private async void Delete_Clicked(object sender, System.EventArgs e) private async void Delete_Clicked(object sender, System.EventArgs e)
{ {
if(DoOnce()) if (DoOnce())
{ {
if(await _vm.DeleteAsync()) if (await _vm.DeleteAsync())
{ {
await Navigation.PopModalAsync(); await Navigation.PopModalAsync();
} }
@ -232,7 +232,7 @@ namespace Bit.App.Pages
private async void Collections_Clicked(object sender, System.EventArgs e) private async void Collections_Clicked(object sender, System.EventArgs e)
{ {
if(DoOnce()) if (DoOnce())
{ {
var page = new CollectionsPage(_vm.CipherId); var page = new CollectionsPage(_vm.CipherId);
await Navigation.PushModalAsync(new Xamarin.Forms.NavigationPage(page)); await Navigation.PushModalAsync(new Xamarin.Forms.NavigationPage(page));
@ -241,7 +241,7 @@ namespace Bit.App.Pages
private async void ScanTotp_Clicked(object sender, System.EventArgs e) private async void ScanTotp_Clicked(object sender, System.EventArgs e)
{ {
if(DoOnce()) if (DoOnce())
{ {
var page = new ScanPage(key => var page = new ScanPage(key =>
{ {
@ -257,35 +257,35 @@ namespace Bit.App.Pages
private async void More_Clicked(object sender, System.EventArgs e) private async void More_Clicked(object sender, System.EventArgs e)
{ {
if(!DoOnce()) if (!DoOnce())
{ {
return; return;
} }
var options = new List<string> { AppResources.Attachments }; var options = new List<string> { AppResources.Attachments };
if(_vm.EditMode) if (_vm.EditMode)
{ {
options.Add(_vm.Cipher.OrganizationId == null ? AppResources.Share : AppResources.Collections); options.Add(_vm.Cipher.OrganizationId == null ? AppResources.Share : AppResources.Collections);
} }
var selection = await DisplayActionSheet(AppResources.Options, AppResources.Cancel, var selection = await DisplayActionSheet(AppResources.Options, AppResources.Cancel,
(_vm.EditMode && !_vm.CloneMode) ? AppResources.Delete : null, options.ToArray()); (_vm.EditMode && !_vm.CloneMode) ? AppResources.Delete : null, options.ToArray());
if(selection == AppResources.Delete) if (selection == AppResources.Delete)
{ {
if(await _vm.DeleteAsync()) if (await _vm.DeleteAsync())
{ {
await Navigation.PopModalAsync(); await Navigation.PopModalAsync();
} }
} }
else if(selection == AppResources.Attachments) else if (selection == AppResources.Attachments)
{ {
var page = new AttachmentsPage(_vm.CipherId); var page = new AttachmentsPage(_vm.CipherId);
await Navigation.PushModalAsync(new Xamarin.Forms.NavigationPage(page)); await Navigation.PushModalAsync(new Xamarin.Forms.NavigationPage(page));
} }
else if(selection == AppResources.Collections) else if (selection == AppResources.Collections)
{ {
var page = new CollectionsPage(_vm.CipherId); var page = new CollectionsPage(_vm.CipherId);
await Navigation.PushModalAsync(new Xamarin.Forms.NavigationPage(page)); await Navigation.PushModalAsync(new Xamarin.Forms.NavigationPage(page));
} }
else if(selection == AppResources.Share) else if (selection == AppResources.Share)
{ {
var page = new SharePage(_vm.CipherId); var page = new SharePage(_vm.CipherId);
await Navigation.PushModalAsync(new Xamarin.Forms.NavigationPage(page)); await Navigation.PushModalAsync(new Xamarin.Forms.NavigationPage(page));
@ -294,7 +294,7 @@ namespace Bit.App.Pages
private async void Close_Clicked(object sender, System.EventArgs e) private async void Close_Clicked(object sender, System.EventArgs e)
{ {
if(DoOnce()) if (DoOnce())
{ {
await Navigation.PopModalAsync(); await Navigation.PopModalAsync();
} }
@ -302,19 +302,19 @@ namespace Bit.App.Pages
private async Task ShowAlertsAsync() private async Task ShowAlertsAsync()
{ {
if(!_vm.EditMode) if (!_vm.EditMode)
{ {
if(_vm.Cipher == null) if (_vm.Cipher == null)
{ {
return; return;
} }
var addLoginShown = await _storageService.GetAsync<bool?>(Constants.AddSitePromptShownKey); var addLoginShown = await _storageService.GetAsync<bool?>(Constants.AddSitePromptShownKey);
if(_vm.Cipher.Type == CipherType.Login && !_fromAutofill && !addLoginShown.GetValueOrDefault()) if (_vm.Cipher.Type == CipherType.Login && !_fromAutofill && !addLoginShown.GetValueOrDefault())
{ {
await _storageService.SaveAsync(Constants.AddSitePromptShownKey, true); await _storageService.SaveAsync(Constants.AddSitePromptShownKey, true);
if(Device.RuntimePlatform == Device.iOS) if (Device.RuntimePlatform == Device.iOS)
{ {
if(_deviceActionService.SystemMajorVersion() < 12) if (_deviceActionService.SystemMajorVersion() < 12)
{ {
await DisplayAlert(AppResources.BitwardenAppExtension, await DisplayAlert(AppResources.BitwardenAppExtension,
AppResources.BitwardenAppExtensionAlert2, AppResources.Ok); AppResources.BitwardenAppExtensionAlert2, AppResources.Ok);
@ -325,7 +325,7 @@ namespace Bit.App.Pages
AppResources.BitwardenAutofillAlert2, AppResources.Ok); AppResources.BitwardenAutofillAlert2, AppResources.Ok);
} }
} }
else if(Device.RuntimePlatform == Device.Android && else if (Device.RuntimePlatform == Device.Android &&
!_deviceActionService.AutofillAccessibilityServiceRunning() && !_deviceActionService.AutofillAccessibilityServiceRunning() &&
!_deviceActionService.AutofillServiceEnabled()) !_deviceActionService.AutofillServiceEnabled())
{ {
@ -338,30 +338,30 @@ namespace Bit.App.Pages
private void AdjustToolbar() private void AdjustToolbar()
{ {
if((_vm.EditMode || _vm.CloneMode) && Device.RuntimePlatform == Device.Android) if ((_vm.EditMode || _vm.CloneMode) && Device.RuntimePlatform == Device.Android)
{ {
if(_vm.Cipher == null) if (_vm.Cipher == null)
{ {
return; return;
} }
if(_vm.Cipher.OrganizationId == null) if (_vm.Cipher.OrganizationId == null)
{ {
if(ToolbarItems.Contains(_collectionsItem)) if (ToolbarItems.Contains(_collectionsItem))
{ {
ToolbarItems.Remove(_collectionsItem); ToolbarItems.Remove(_collectionsItem);
} }
if(!ToolbarItems.Contains(_shareItem) && !_vm.CloneMode) if (!ToolbarItems.Contains(_shareItem) && !_vm.CloneMode)
{ {
ToolbarItems.Insert(2, _shareItem); ToolbarItems.Insert(2, _shareItem);
} }
} }
else else
{ {
if(ToolbarItems.Contains(_shareItem)) if (ToolbarItems.Contains(_shareItem))
{ {
ToolbarItems.Remove(_shareItem); ToolbarItems.Remove(_shareItem);
} }
if(!ToolbarItems.Contains(_collectionsItem)) if (!ToolbarItems.Contains(_collectionsItem))
{ {
ToolbarItems.Insert(2, _collectionsItem); ToolbarItems.Insert(2, _collectionsItem);
} }

View File

@ -163,7 +163,7 @@ namespace Bit.App.Pages
get => _typeSelectedIndex; get => _typeSelectedIndex;
set set
{ {
if(SetProperty(ref _typeSelectedIndex, value)) if (SetProperty(ref _typeSelectedIndex, value))
{ {
TypeChanged(); TypeChanged();
} }
@ -174,7 +174,7 @@ namespace Bit.App.Pages
get => _cardBrandSelectedIndex; get => _cardBrandSelectedIndex;
set set
{ {
if(SetProperty(ref _cardBrandSelectedIndex, value)) if (SetProperty(ref _cardBrandSelectedIndex, value))
{ {
CardBrandChanged(); CardBrandChanged();
} }
@ -185,7 +185,7 @@ namespace Bit.App.Pages
get => _cardExpMonthSelectedIndex; get => _cardExpMonthSelectedIndex;
set set
{ {
if(SetProperty(ref _cardExpMonthSelectedIndex, value)) if (SetProperty(ref _cardExpMonthSelectedIndex, value))
{ {
CardExpMonthChanged(); CardExpMonthChanged();
} }
@ -196,7 +196,7 @@ namespace Bit.App.Pages
get => _identityTitleSelectedIndex; get => _identityTitleSelectedIndex;
set set
{ {
if(SetProperty(ref _identityTitleSelectedIndex, value)) if (SetProperty(ref _identityTitleSelectedIndex, value))
{ {
IdentityTitleChanged(); IdentityTitleChanged();
} }
@ -207,7 +207,7 @@ namespace Bit.App.Pages
get => _folderSelectedIndex; get => _folderSelectedIndex;
set set
{ {
if(SetProperty(ref _folderSelectedIndex, value)) if (SetProperty(ref _folderSelectedIndex, value))
{ {
FolderChanged(); FolderChanged();
} }
@ -218,7 +218,7 @@ namespace Bit.App.Pages
get => _ownershipSelectedIndex; get => _ownershipSelectedIndex;
set set
{ {
if(SetProperty(ref _ownershipSelectedIndex, value)) if (SetProperty(ref _ownershipSelectedIndex, value))
{ {
OrganizationChanged(); OrganizationChanged();
} }
@ -285,9 +285,9 @@ namespace Bit.App.Pages
var myEmail = await _userService.GetEmailAsync(); var myEmail = await _userService.GetEmailAsync();
OwnershipOptions.Add(new KeyValuePair<string, string>(myEmail, null)); OwnershipOptions.Add(new KeyValuePair<string, string>(myEmail, null));
var orgs = await _userService.GetAllOrganizationAsync(); var orgs = await _userService.GetAllOrganizationAsync();
foreach(var org in orgs.OrderBy(o => o.Name)) foreach (var org in orgs.OrderBy(o => o.Name))
{ {
if(org.Enabled && org.Status == OrganizationUserStatusType.Confirmed) if (org.Enabled && org.Status == OrganizationUserStatusType.Confirmed)
{ {
OwnershipOptions.Add(new KeyValuePair<string, string>(org.Name, org.Id)); OwnershipOptions.Add(new KeyValuePair<string, string>(org.Name, org.Id));
} }
@ -295,7 +295,7 @@ namespace Bit.App.Pages
var allCollections = await _collectionService.GetAllDecryptedAsync(); var allCollections = await _collectionService.GetAllDecryptedAsync();
_writeableCollections = allCollections.Where(c => !c.ReadOnly).ToList(); _writeableCollections = allCollections.Where(c => !c.ReadOnly).ToList();
if(CollectionIds?.Any() ?? false) if (CollectionIds?.Any() ?? false)
{ {
var colId = CollectionIds.First(); var colId = CollectionIds.First();
var collection = _writeableCollections.FirstOrDefault(c => c.Id == colId); var collection = _writeableCollections.FirstOrDefault(c => c.Id == colId);
@ -304,17 +304,17 @@ namespace Bit.App.Pages
var folders = await _folderService.GetAllDecryptedAsync(); var folders = await _folderService.GetAllDecryptedAsync();
FolderOptions = folders.Select(f => new KeyValuePair<string, string>(f.Name, f.Id)).ToList(); FolderOptions = folders.Select(f => new KeyValuePair<string, string>(f.Name, f.Id)).ToList();
if(Cipher == null) if (Cipher == null)
{ {
if(EditMode) if (EditMode)
{ {
var cipher = await _cipherService.GetAsync(CipherId); var cipher = await _cipherService.GetAsync(CipherId);
if(cipher == null) if (cipher == null)
{ {
return false; return false;
} }
Cipher = await cipher.DecryptAsync(); Cipher = await cipher.DecryptAsync();
if(CloneMode) if (CloneMode)
{ {
Cipher.Name += " - " + AppResources.Clone; Cipher.Name += " - " + AppResources.Clone;
} }
@ -335,13 +335,13 @@ namespace Bit.App.Pages
Cipher.Login.Uris = new List<LoginUriView> { new LoginUriView { Uri = DefaultUri } }; Cipher.Login.Uris = new List<LoginUriView> { new LoginUriView { Uri = DefaultUri } };
Cipher.SecureNote.Type = SecureNoteType.Generic; Cipher.SecureNote.Type = SecureNoteType.Generic;
if(appOptions != null) if (appOptions != null)
{ {
Cipher.Type = appOptions.SaveType.GetValueOrDefault(Cipher.Type); Cipher.Type = appOptions.SaveType.GetValueOrDefault(Cipher.Type);
Cipher.Login.Username = appOptions.SaveUsername; Cipher.Login.Username = appOptions.SaveUsername;
Cipher.Login.Password = appOptions.SavePassword; Cipher.Login.Password = appOptions.SavePassword;
Cipher.Card.Code = appOptions.SaveCardCode; Cipher.Card.Code = appOptions.SaveCardCode;
if(int.TryParse(appOptions.SaveCardExpMonth, out int month) && month <= 12 && month >= 1) if (int.TryParse(appOptions.SaveCardExpMonth, out int month) && month <= 12 && month >= 1)
{ {
Cipher.Card.ExpMonth = month.ToString(); Cipher.Card.ExpMonth = month.ToString();
} }
@ -363,24 +363,24 @@ namespace Bit.App.Pages
OwnershipSelectedIndex = string.IsNullOrWhiteSpace(Cipher.OrganizationId) ? 0 : OwnershipSelectedIndex = string.IsNullOrWhiteSpace(Cipher.OrganizationId) ? 0 :
OwnershipOptions.FindIndex(k => k.Value == Cipher.OrganizationId); OwnershipOptions.FindIndex(k => k.Value == Cipher.OrganizationId);
if((!EditMode || CloneMode) && (CollectionIds?.Any() ?? false)) if ((!EditMode || CloneMode) && (CollectionIds?.Any() ?? false))
{ {
foreach(var col in Collections) foreach (var col in Collections)
{ {
col.Checked = CollectionIds.Contains(col.Collection.Id); col.Checked = CollectionIds.Contains(col.Collection.Id);
} }
} }
if(Cipher.Login?.Uris != null) if (Cipher.Login?.Uris != null)
{ {
Uris.ResetWithRange(Cipher.Login.Uris); Uris.ResetWithRange(Cipher.Login.Uris);
} }
if(Cipher.Fields != null) if (Cipher.Fields != null)
{ {
Fields.ResetWithRange(Cipher.Fields?.Select(f => new AddEditPageFieldViewModel(Cipher, f))); Fields.ResetWithRange(Cipher.Fields?.Select(f => new AddEditPageFieldViewModel(Cipher, f)));
} }
} }
if(EditMode && _previousCipherId != CipherId) if (EditMode && _previousCipherId != CipherId)
{ {
var task = _eventService.CollectAsync(EventType.Cipher_ClientViewed, CipherId); var task = _eventService.CollectAsync(EventType.Cipher_ClientViewed, CipherId);
} }
@ -391,17 +391,17 @@ namespace Bit.App.Pages
public async Task<bool> SubmitAsync() public async Task<bool> SubmitAsync()
{ {
if(Cipher == null) if (Cipher == null)
{ {
return false; return false;
} }
if(Xamarin.Essentials.Connectivity.NetworkAccess == Xamarin.Essentials.NetworkAccess.None) if (Xamarin.Essentials.Connectivity.NetworkAccess == Xamarin.Essentials.NetworkAccess.None)
{ {
await _platformUtilsService.ShowDialogAsync(AppResources.InternetConnectionRequiredMessage, await _platformUtilsService.ShowDialogAsync(AppResources.InternetConnectionRequiredMessage,
AppResources.InternetConnectionRequiredTitle); AppResources.InternetConnectionRequiredTitle);
return false; return false;
} }
if(string.IsNullOrWhiteSpace(Cipher.Name)) if (string.IsNullOrWhiteSpace(Cipher.Name))
{ {
await Page.DisplayAlert(AppResources.AnErrorHasOccurred, await Page.DisplayAlert(AppResources.AnErrorHasOccurred,
string.Format(AppResources.ValidationFieldRequired, AppResources.Name), string.Format(AppResources.ValidationFieldRequired, AppResources.Name),
@ -411,19 +411,19 @@ namespace Bit.App.Pages
Cipher.Fields = Fields != null && Fields.Any() ? Cipher.Fields = Fields != null && Fields.Any() ?
Fields.Where(f => f != null).Select(f => f.Field).ToList() : null; Fields.Where(f => f != null).Select(f => f.Field).ToList() : null;
if(Cipher.Login != null) if (Cipher.Login != null)
{ {
Cipher.Login.Uris = Uris?.ToList(); Cipher.Login.Uris = Uris?.ToList();
if((!EditMode || CloneMode) && Cipher.Type == CipherType.Login && Cipher.Login.Uris != null && if ((!EditMode || CloneMode) && Cipher.Type == CipherType.Login && Cipher.Login.Uris != null &&
Cipher.Login.Uris.Count == 1 && string.IsNullOrWhiteSpace(Cipher.Login.Uris[0].Uri)) Cipher.Login.Uris.Count == 1 && string.IsNullOrWhiteSpace(Cipher.Login.Uris[0].Uri))
{ {
Cipher.Login.Uris = null; Cipher.Login.Uris = null;
} }
} }
if((!EditMode || CloneMode) && Cipher.OrganizationId != null) if ((!EditMode || CloneMode) && Cipher.OrganizationId != null)
{ {
if(Collections == null || !Collections.Any(c => c != null && c.Checked)) if (Collections == null || !Collections.Any(c => c != null && c.Checked))
{ {
await Page.DisplayAlert(AppResources.AnErrorHasOccurred, AppResources.SelectOneCollection, await Page.DisplayAlert(AppResources.AnErrorHasOccurred, AppResources.SelectOneCollection,
AppResources.Ok); AppResources.Ok);
@ -435,12 +435,12 @@ namespace Bit.App.Pages
.Select(c => c.Collection.Id)) : null; .Select(c => c.Collection.Id)) : null;
} }
if(CloneMode) if (CloneMode)
{ {
Cipher.Id = null; Cipher.Id = null;
} }
var cipher = await _cipherService.EncryptAsync(Cipher); var cipher = await _cipherService.EncryptAsync(Cipher);
if(cipher == null) if (cipher == null)
{ {
return false; return false;
} }
@ -454,14 +454,14 @@ namespace Bit.App.Pages
EditMode && !CloneMode ? AppResources.ItemUpdated : AppResources.NewItemCreated); EditMode && !CloneMode ? AppResources.ItemUpdated : AppResources.NewItemCreated);
_messagingService.Send(EditMode && !CloneMode ? "editedCipher" : "addedCipher", Cipher.Id); _messagingService.Send(EditMode && !CloneMode ? "editedCipher" : "addedCipher", Cipher.Id);
if(Page is AddEditPage page && page.FromAutofillFramework) if (Page is AddEditPage page && page.FromAutofillFramework)
{ {
// Close and go back to app // Close and go back to app
_deviceActionService.CloseAutofill(); _deviceActionService.CloseAutofill();
} }
else else
{ {
if(CloneMode) if (CloneMode)
{ {
ViewPage?.UpdateCipherId(this.Cipher.Id); ViewPage?.UpdateCipherId(this.Cipher.Id);
} }
@ -469,10 +469,10 @@ namespace Bit.App.Pages
} }
return true; return true;
} }
catch(ApiException e) catch (ApiException e)
{ {
await _deviceActionService.HideLoadingAsync(); await _deviceActionService.HideLoadingAsync();
if(e?.Error != null) if (e?.Error != null)
{ {
await _platformUtilsService.ShowDialogAsync(e.Error.GetSingleMessage(), await _platformUtilsService.ShowDialogAsync(e.Error.GetSingleMessage(),
AppResources.AnErrorHasOccurred); AppResources.AnErrorHasOccurred);
@ -483,7 +483,7 @@ namespace Bit.App.Pages
public async Task<bool> DeleteAsync() public async Task<bool> DeleteAsync()
{ {
if(Xamarin.Essentials.Connectivity.NetworkAccess == Xamarin.Essentials.NetworkAccess.None) if (Xamarin.Essentials.Connectivity.NetworkAccess == Xamarin.Essentials.NetworkAccess.None)
{ {
await _platformUtilsService.ShowDialogAsync(AppResources.InternetConnectionRequiredMessage, await _platformUtilsService.ShowDialogAsync(AppResources.InternetConnectionRequiredMessage,
AppResources.InternetConnectionRequiredTitle); AppResources.InternetConnectionRequiredTitle);
@ -491,7 +491,7 @@ namespace Bit.App.Pages
} }
var confirmed = await _platformUtilsService.ShowDialogAsync(AppResources.DoYouReallyWantToDelete, var confirmed = await _platformUtilsService.ShowDialogAsync(AppResources.DoYouReallyWantToDelete,
null, AppResources.Yes, AppResources.Cancel); null, AppResources.Yes, AppResources.Cancel);
if(!confirmed) if (!confirmed)
{ {
return false; return false;
} }
@ -504,10 +504,10 @@ namespace Bit.App.Pages
_messagingService.Send("deletedCipher", Cipher); _messagingService.Send("deletedCipher", Cipher);
return true; return true;
} }
catch(ApiException e) catch (ApiException e)
{ {
await _deviceActionService.HideLoadingAsync(); await _deviceActionService.HideLoadingAsync();
if(e?.Error != null) if (e?.Error != null)
{ {
await _platformUtilsService.ShowDialogAsync(e.Error.GetSingleMessage(), await _platformUtilsService.ShowDialogAsync(e.Error.GetSingleMessage(),
AppResources.AnErrorHasOccurred); AppResources.AnErrorHasOccurred);
@ -518,11 +518,11 @@ namespace Bit.App.Pages
public async void GeneratePassword() public async void GeneratePassword()
{ {
if(!string.IsNullOrWhiteSpace(Cipher?.Login?.Password)) if (!string.IsNullOrWhiteSpace(Cipher?.Login?.Password))
{ {
var confirmed = await _platformUtilsService.ShowDialogAsync(AppResources.PasswordOverrideAlert, var confirmed = await _platformUtilsService.ShowDialogAsync(AppResources.PasswordOverrideAlert,
null, AppResources.Yes, AppResources.No); null, AppResources.Yes, AppResources.No);
if(!confirmed) if (!confirmed)
{ {
return; return;
} }
@ -538,22 +538,22 @@ namespace Bit.App.Pages
public async void UriOptions(LoginUriView uri) public async void UriOptions(LoginUriView uri)
{ {
if(!(Page as AddEditPage).DoOnce()) if (!(Page as AddEditPage).DoOnce())
{ {
return; return;
} }
var selection = await Page.DisplayActionSheet(AppResources.Options, AppResources.Cancel, null, var selection = await Page.DisplayActionSheet(AppResources.Options, AppResources.Cancel, null,
AppResources.MatchDetection, AppResources.Remove); AppResources.MatchDetection, AppResources.Remove);
if(selection == AppResources.Remove) if (selection == AppResources.Remove)
{ {
Uris.Remove(uri); Uris.Remove(uri);
} }
else if(selection == AppResources.MatchDetection) else if (selection == AppResources.MatchDetection)
{ {
var options = _matchDetectionOptions.Select(o => o.Key == uri.Match ? $"✓ {o.Value}" : o.Value); var options = _matchDetectionOptions.Select(o => o.Key == uri.Match ? $"✓ {o.Value}" : o.Value);
var matchSelection = await Page.DisplayActionSheet(AppResources.URIMatchDetection, var matchSelection = await Page.DisplayActionSheet(AppResources.URIMatchDetection,
AppResources.Cancel, null, options.ToArray()); AppResources.Cancel, null, options.ToArray());
if(matchSelection != null && matchSelection != AppResources.Cancel) if (matchSelection != null && matchSelection != AppResources.Cancel)
{ {
var matchSelectionClean = matchSelection.Replace("✓ ", string.Empty); var matchSelectionClean = matchSelection.Replace("✓ ", string.Empty);
uri.Match = _matchDetectionOptions.FirstOrDefault(o => o.Value == matchSelectionClean).Key; uri.Match = _matchDetectionOptions.FirstOrDefault(o => o.Value == matchSelectionClean).Key;
@ -563,11 +563,11 @@ namespace Bit.App.Pages
public void AddUri() public void AddUri()
{ {
if(Cipher.Type != CipherType.Login) if (Cipher.Type != CipherType.Login)
{ {
return; return;
} }
if(Uris == null) if (Uris == null)
{ {
Uris = new ExtendedObservableCollection<LoginUriView>(); Uris = new ExtendedObservableCollection<LoginUriView>();
} }
@ -576,35 +576,35 @@ namespace Bit.App.Pages
public async void FieldOptions(AddEditPageFieldViewModel field) public async void FieldOptions(AddEditPageFieldViewModel field)
{ {
if(!(Page as AddEditPage).DoOnce()) if (!(Page as AddEditPage).DoOnce())
{ {
return; return;
} }
var selection = await Page.DisplayActionSheet(AppResources.Options, AppResources.Cancel, null, var selection = await Page.DisplayActionSheet(AppResources.Options, AppResources.Cancel, null,
AppResources.Edit, AppResources.MoveUp, AppResources.MoveDown, AppResources.Remove); AppResources.Edit, AppResources.MoveUp, AppResources.MoveDown, AppResources.Remove);
if(selection == AppResources.Remove) if (selection == AppResources.Remove)
{ {
Fields.Remove(field); Fields.Remove(field);
} }
else if(selection == AppResources.Edit) else if (selection == AppResources.Edit)
{ {
var name = await _deviceActionService.DisplayPromptAync(AppResources.CustomFieldName, var name = await _deviceActionService.DisplayPromptAync(AppResources.CustomFieldName,
null, field.Field.Name); null, field.Field.Name);
field.Field.Name = name ?? field.Field.Name; field.Field.Name = name ?? field.Field.Name;
field.TriggerFieldChanged(); field.TriggerFieldChanged();
} }
else if(selection == AppResources.MoveUp) else if (selection == AppResources.MoveUp)
{ {
var currentIndex = Fields.IndexOf(field); var currentIndex = Fields.IndexOf(field);
if(currentIndex > 0) if (currentIndex > 0)
{ {
Fields.Move(currentIndex, currentIndex - 1); Fields.Move(currentIndex, currentIndex - 1);
} }
} }
else if(selection == AppResources.MoveDown) else if (selection == AppResources.MoveDown)
{ {
var currentIndex = Fields.IndexOf(field); var currentIndex = Fields.IndexOf(field);
if(currentIndex < Fields.Count - 1) if (currentIndex < Fields.Count - 1)
{ {
Fields.Move(currentIndex, currentIndex + 1); Fields.Move(currentIndex, currentIndex + 1);
} }
@ -615,14 +615,14 @@ namespace Bit.App.Pages
{ {
var typeSelection = await Page.DisplayActionSheet(AppResources.SelectTypeField, AppResources.Cancel, null, var typeSelection = await Page.DisplayActionSheet(AppResources.SelectTypeField, AppResources.Cancel, null,
_fieldTypeOptions.Select(f => f.Value).ToArray()); _fieldTypeOptions.Select(f => f.Value).ToArray());
if(typeSelection != null && typeSelection != AppResources.Cancel) if (typeSelection != null && typeSelection != AppResources.Cancel)
{ {
var name = await _deviceActionService.DisplayPromptAync(AppResources.CustomFieldName); var name = await _deviceActionService.DisplayPromptAync(AppResources.CustomFieldName);
if(name == null) if (name == null)
{ {
return; return;
} }
if(Fields == null) if (Fields == null)
{ {
Fields = new ExtendedObservableCollection<AddEditPageFieldViewModel>(); Fields = new ExtendedObservableCollection<AddEditPageFieldViewModel>();
} }
@ -638,7 +638,7 @@ namespace Bit.App.Pages
public void TogglePassword() public void TogglePassword()
{ {
ShowPassword = !ShowPassword; ShowPassword = !ShowPassword;
if(EditMode && ShowPassword) if (EditMode && ShowPassword)
{ {
var task = _eventService.CollectAsync(EventType.Cipher_ClientToggledPasswordVisible, CipherId); var task = _eventService.CollectAsync(EventType.Cipher_ClientToggledPasswordVisible, CipherId);
} }
@ -647,7 +647,7 @@ namespace Bit.App.Pages
public void ToggleCardCode() public void ToggleCardCode()
{ {
ShowCardCode = !ShowCardCode; ShowCardCode = !ShowCardCode;
if(EditMode && ShowCardCode) if (EditMode && ShowCardCode)
{ {
var task = _eventService.CollectAsync(EventType.Cipher_ClientToggledCardCodeVisible, CipherId); var task = _eventService.CollectAsync(EventType.Cipher_ClientToggledCardCodeVisible, CipherId);
} }
@ -655,9 +655,9 @@ namespace Bit.App.Pages
public async Task UpdateTotpKeyAsync(string key) public async Task UpdateTotpKeyAsync(string key)
{ {
if(Cipher?.Login != null) if (Cipher?.Login != null)
{ {
if(!string.IsNullOrWhiteSpace(key)) if (!string.IsNullOrWhiteSpace(key))
{ {
Cipher.Login.Totp = key; Cipher.Login.Totp = key;
TriggerCipherChanged(); TriggerCipherChanged();
@ -672,7 +672,7 @@ namespace Bit.App.Pages
private void TypeChanged() private void TypeChanged()
{ {
if(Cipher != null && TypeSelectedIndex > -1) if (Cipher != null && TypeSelectedIndex > -1)
{ {
Cipher.Type = TypeOptions[TypeSelectedIndex].Value; Cipher.Type = TypeOptions[TypeSelectedIndex].Value;
TriggerCipherChanged(); TriggerCipherChanged();
@ -681,7 +681,7 @@ namespace Bit.App.Pages
private void CardBrandChanged() private void CardBrandChanged()
{ {
if(Cipher?.Card != null && CardBrandSelectedIndex > -1) if (Cipher?.Card != null && CardBrandSelectedIndex > -1)
{ {
Cipher.Card.Brand = CardBrandOptions[CardBrandSelectedIndex].Value; Cipher.Card.Brand = CardBrandOptions[CardBrandSelectedIndex].Value;
} }
@ -689,7 +689,7 @@ namespace Bit.App.Pages
private void CardExpMonthChanged() private void CardExpMonthChanged()
{ {
if(Cipher?.Card != null && CardExpMonthSelectedIndex > -1) if (Cipher?.Card != null && CardExpMonthSelectedIndex > -1)
{ {
Cipher.Card.ExpMonth = CardExpMonthOptions[CardExpMonthSelectedIndex].Value; Cipher.Card.ExpMonth = CardExpMonthOptions[CardExpMonthSelectedIndex].Value;
} }
@ -697,7 +697,7 @@ namespace Bit.App.Pages
private void IdentityTitleChanged() private void IdentityTitleChanged()
{ {
if(Cipher?.Identity != null && IdentityTitleSelectedIndex > -1) if (Cipher?.Identity != null && IdentityTitleSelectedIndex > -1)
{ {
Cipher.Identity.Title = IdentityTitleOptions[IdentityTitleSelectedIndex].Value; Cipher.Identity.Title = IdentityTitleOptions[IdentityTitleSelectedIndex].Value;
} }
@ -705,7 +705,7 @@ namespace Bit.App.Pages
private void FolderChanged() private void FolderChanged()
{ {
if(Cipher != null && FolderSelectedIndex > -1) if (Cipher != null && FolderSelectedIndex > -1)
{ {
Cipher.FolderId = FolderOptions[FolderSelectedIndex].Value; Cipher.FolderId = FolderOptions[FolderSelectedIndex].Value;
} }
@ -713,12 +713,12 @@ namespace Bit.App.Pages
private void OrganizationChanged() private void OrganizationChanged()
{ {
if(Cipher != null && OwnershipSelectedIndex > -1) if (Cipher != null && OwnershipSelectedIndex > -1)
{ {
Cipher.OrganizationId = OwnershipOptions[OwnershipSelectedIndex].Value; Cipher.OrganizationId = OwnershipOptions[OwnershipSelectedIndex].Value;
TriggerCipherChanged(); TriggerCipherChanged();
} }
if(Cipher.OrganizationId != null) if (Cipher.OrganizationId != null)
{ {
var cols = _writeableCollections.Where(c => c.OrganizationId == Cipher.OrganizationId) var cols = _writeableCollections.Where(c => c.OrganizationId == Cipher.OrganizationId)
.Select(c => new CollectionViewModel { Collection = c }).ToList(); .Select(c => new CollectionViewModel { Collection = c }).ToList();
@ -738,18 +738,18 @@ namespace Bit.App.Pages
private async void CheckPasswordAsync() private async void CheckPasswordAsync()
{ {
if(!(Page as BaseContentPage).DoOnce()) if (!(Page as BaseContentPage).DoOnce())
{ {
return; return;
} }
if(string.IsNullOrWhiteSpace(Cipher.Login?.Password)) if (string.IsNullOrWhiteSpace(Cipher.Login?.Password))
{ {
return; return;
} }
await _deviceActionService.ShowLoadingAsync(AppResources.CheckingPassword); await _deviceActionService.ShowLoadingAsync(AppResources.CheckingPassword);
var matches = await _auditService.PasswordLeakedAsync(Cipher.Login.Password); var matches = await _auditService.PasswordLeakedAsync(Cipher.Login.Password);
await _deviceActionService.HideLoadingAsync(); await _deviceActionService.HideLoadingAsync();
if(matches > 0) if (matches > 0)
{ {
await _platformUtilsService.ShowDialogAsync(string.Format(AppResources.PasswordExposed, await _platformUtilsService.ShowDialogAsync(string.Format(AppResources.PasswordExposed,
matches.ToString("N0"))); matches.ToString("N0")));
@ -804,7 +804,7 @@ namespace Bit.App.Pages
set set
{ {
SetProperty(ref _booleanValue, value); SetProperty(ref _booleanValue, value);
if(IsBooleanType) if (IsBooleanType)
{ {
Field.Value = value ? "true" : "false"; Field.Value = value ? "true" : "false";
} }
@ -821,7 +821,7 @@ namespace Bit.App.Pages
public void ToggleHiddenValue() public void ToggleHiddenValue()
{ {
ShowHiddenValue = !ShowHiddenValue; ShowHiddenValue = !ShowHiddenValue;
if(ShowHiddenValue && _cipher?.Id != null) if (ShowHiddenValue && _cipher?.Id != null)
{ {
var eventService = ServiceContainer.Resolve<IEventService>("eventService"); var eventService = ServiceContainer.Resolve<IEventService>("eventService");
var task = eventService.CollectAsync(EventType.Cipher_ClientToggledHiddenFieldVisible, _cipher.Id); var task = eventService.CollectAsync(EventType.Cipher_ClientToggledHiddenFieldVisible, _cipher.Id);

View File

@ -18,7 +18,7 @@ namespace Bit.App.Pages
_vm.Page = this; _vm.Page = this;
_vm.CipherId = cipherId; _vm.CipherId = cipherId;
SetActivityIndicator(); SetActivityIndicator();
if(Device.RuntimePlatform == Device.Android) if (Device.RuntimePlatform == Device.Android)
{ {
ToolbarItems.RemoveAt(0); ToolbarItems.RemoveAt(0);
} }
@ -29,7 +29,7 @@ namespace Bit.App.Pages
base.OnAppearing(); base.OnAppearing();
_broadcasterService.Subscribe(nameof(AttachmentsPage), (message) => _broadcasterService.Subscribe(nameof(AttachmentsPage), (message) =>
{ {
if(message.Command == "selectFileResult") if (message.Command == "selectFileResult")
{ {
Device.BeginInvokeOnMainThread(() => Device.BeginInvokeOnMainThread(() =>
{ {
@ -45,7 +45,7 @@ namespace Bit.App.Pages
protected override void OnDisappearing() protected override void OnDisappearing()
{ {
base.OnDisappearing(); base.OnDisappearing();
if(Device.RuntimePlatform != Device.iOS) if (Device.RuntimePlatform != Device.iOS)
{ {
_broadcasterService.Unsubscribe(nameof(AttachmentsPage)); _broadcasterService.Unsubscribe(nameof(AttachmentsPage));
} }
@ -53,7 +53,7 @@ namespace Bit.App.Pages
private async void Save_Clicked(object sender, EventArgs e) private async void Save_Clicked(object sender, EventArgs e)
{ {
if(DoOnce()) if (DoOnce())
{ {
await _vm.SubmitAsync(); await _vm.SubmitAsync();
} }
@ -61,7 +61,7 @@ namespace Bit.App.Pages
private async void ChooseFile_Clicked(object sender, EventArgs e) private async void ChooseFile_Clicked(object sender, EventArgs e)
{ {
if(DoOnce()) if (DoOnce())
{ {
await _vm.ChooseFileAsync(); await _vm.ChooseFileAsync();
} }
@ -69,7 +69,7 @@ namespace Bit.App.Pages
private async void Close_Clicked(object sender, System.EventArgs e) private async void Close_Clicked(object sender, System.EventArgs e)
{ {
if(DoOnce()) if (DoOnce())
{ {
await Navigation.PopModalAsync(); await Navigation.PopModalAsync();
} }

View File

@ -66,15 +66,15 @@ namespace Bit.App.Pages
_hasUpdatedKey = await _cryptoService.HasEncKeyAsync(); _hasUpdatedKey = await _cryptoService.HasEncKeyAsync();
var canAccessPremium = await _userService.CanAccessPremiumAsync(); var canAccessPremium = await _userService.CanAccessPremiumAsync();
_canAccessAttachments = canAccessPremium || Cipher.OrganizationId != null; _canAccessAttachments = canAccessPremium || Cipher.OrganizationId != null;
if(!_canAccessAttachments) if (!_canAccessAttachments)
{ {
await _platformUtilsService.ShowDialogAsync(AppResources.PremiumRequired); await _platformUtilsService.ShowDialogAsync(AppResources.PremiumRequired);
} }
else if(!_hasUpdatedKey) else if (!_hasUpdatedKey)
{ {
var confirmed = await _platformUtilsService.ShowDialogAsync(AppResources.UpdateKey, var confirmed = await _platformUtilsService.ShowDialogAsync(AppResources.UpdateKey,
AppResources.FeatureUnavailable, AppResources.LearnMore, AppResources.Cancel); AppResources.FeatureUnavailable, AppResources.LearnMore, AppResources.Cancel);
if(confirmed) if (confirmed)
{ {
_platformUtilsService.LaunchUri("https://help.bitwarden.com/article/update-encryption-key/"); _platformUtilsService.LaunchUri("https://help.bitwarden.com/article/update-encryption-key/");
} }
@ -83,26 +83,26 @@ namespace Bit.App.Pages
public async Task<bool> SubmitAsync() public async Task<bool> SubmitAsync()
{ {
if(Xamarin.Essentials.Connectivity.NetworkAccess == Xamarin.Essentials.NetworkAccess.None) if (Xamarin.Essentials.Connectivity.NetworkAccess == Xamarin.Essentials.NetworkAccess.None)
{ {
await _platformUtilsService.ShowDialogAsync(AppResources.InternetConnectionRequiredMessage, await _platformUtilsService.ShowDialogAsync(AppResources.InternetConnectionRequiredMessage,
AppResources.InternetConnectionRequiredTitle); AppResources.InternetConnectionRequiredTitle);
return false; return false;
} }
if(!_hasUpdatedKey) if (!_hasUpdatedKey)
{ {
await _platformUtilsService.ShowDialogAsync(AppResources.UpdateKey, await _platformUtilsService.ShowDialogAsync(AppResources.UpdateKey,
AppResources.AnErrorHasOccurred); AppResources.AnErrorHasOccurred);
return false; return false;
} }
if(FileData == null) if (FileData == null)
{ {
await _platformUtilsService.ShowDialogAsync( await _platformUtilsService.ShowDialogAsync(
string.Format(AppResources.ValidationFieldRequired, AppResources.File), string.Format(AppResources.ValidationFieldRequired, AppResources.File),
AppResources.AnErrorHasOccurred); AppResources.AnErrorHasOccurred);
return false; return false;
} }
if(FileData.Length > 104857600) // 100 MB if (FileData.Length > 104857600) // 100 MB
{ {
await _platformUtilsService.ShowDialogAsync(AppResources.MaxFileSize, await _platformUtilsService.ShowDialogAsync(AppResources.MaxFileSize,
AppResources.AnErrorHasOccurred); AppResources.AnErrorHasOccurred);
@ -121,10 +121,10 @@ namespace Bit.App.Pages
FileName = null; FileName = null;
return true; return true;
} }
catch(ApiException e) catch (ApiException e)
{ {
await _deviceActionService.HideLoadingAsync(); await _deviceActionService.HideLoadingAsync();
if(e?.Error != null) if (e?.Error != null)
{ {
await _platformUtilsService.ShowDialogAsync(e.Error.GetSingleMessage(), await _platformUtilsService.ShowDialogAsync(e.Error.GetSingleMessage(),
AppResources.AnErrorHasOccurred); AppResources.AnErrorHasOccurred);
@ -140,7 +140,7 @@ namespace Bit.App.Pages
private async void DeleteAsync(AttachmentView attachment) private async void DeleteAsync(AttachmentView attachment)
{ {
if(Xamarin.Essentials.Connectivity.NetworkAccess == Xamarin.Essentials.NetworkAccess.None) if (Xamarin.Essentials.Connectivity.NetworkAccess == Xamarin.Essentials.NetworkAccess.None)
{ {
await _platformUtilsService.ShowDialogAsync(AppResources.InternetConnectionRequiredMessage, await _platformUtilsService.ShowDialogAsync(AppResources.InternetConnectionRequiredMessage,
AppResources.InternetConnectionRequiredTitle); AppResources.InternetConnectionRequiredTitle);
@ -148,7 +148,7 @@ namespace Bit.App.Pages
} }
var confirmed = await _platformUtilsService.ShowDialogAsync(AppResources.DoYouReallyWantToDelete, var confirmed = await _platformUtilsService.ShowDialogAsync(AppResources.DoYouReallyWantToDelete,
null, AppResources.Yes, AppResources.No); null, AppResources.Yes, AppResources.No);
if(!confirmed) if (!confirmed)
{ {
return; return;
} }
@ -159,16 +159,16 @@ namespace Bit.App.Pages
await _deviceActionService.HideLoadingAsync(); await _deviceActionService.HideLoadingAsync();
_platformUtilsService.ShowToast("success", null, AppResources.AttachmentDeleted); _platformUtilsService.ShowToast("success", null, AppResources.AttachmentDeleted);
var attachmentToRemove = Cipher.Attachments.FirstOrDefault(a => a.Id == attachment.Id); var attachmentToRemove = Cipher.Attachments.FirstOrDefault(a => a.Id == attachment.Id);
if(attachmentToRemove != null) if (attachmentToRemove != null)
{ {
Cipher.Attachments.Remove(attachmentToRemove); Cipher.Attachments.Remove(attachmentToRemove);
LoadAttachments(); LoadAttachments();
} }
} }
catch(ApiException e) catch (ApiException e)
{ {
await _deviceActionService.HideLoadingAsync(); await _deviceActionService.HideLoadingAsync();
if(e?.Error != null) if (e?.Error != null)
{ {
await _platformUtilsService.ShowDialogAsync(e.Error.GetSingleMessage(), await _platformUtilsService.ShowDialogAsync(e.Error.GetSingleMessage(),
AppResources.AnErrorHasOccurred); AppResources.AnErrorHasOccurred);

View File

@ -36,7 +36,7 @@ namespace Bit.App.Pages
{ {
await _vm.LoadAsync(); await _vm.LoadAsync();
} }
catch(Exception e) when(e.Message.Contains("No key.")) catch (Exception e) when(e.Message.Contains("No key."))
{ {
await Task.Delay(1000); await Task.Delay(1000);
await _vm.LoadAsync(); await _vm.LoadAsync();
@ -47,11 +47,11 @@ namespace Bit.App.Pages
private async void RowSelected(object sender, SelectedItemChangedEventArgs e) private async void RowSelected(object sender, SelectedItemChangedEventArgs e)
{ {
((ListView)sender).SelectedItem = null; ((ListView)sender).SelectedItem = null;
if(!DoOnce()) if (!DoOnce())
{ {
return; return;
} }
if(e.SelectedItem is GroupingsPageListItem item && item.Cipher != null) if (e.SelectedItem is GroupingsPageListItem item && item.Cipher != null)
{ {
await _vm.SelectCipherAsync(item.Cipher, item.FuzzyAutofill); await _vm.SelectCipherAsync(item.Cipher, item.FuzzyAutofill);
} }
@ -59,11 +59,11 @@ namespace Bit.App.Pages
private async void AddButton_Clicked(object sender, System.EventArgs e) private async void AddButton_Clicked(object sender, System.EventArgs e)
{ {
if(!DoOnce()) if (!DoOnce())
{ {
return; return;
} }
if(_appOptions.FillType.HasValue && _appOptions.FillType != CipherType.Login) if (_appOptions.FillType.HasValue && _appOptions.FillType != CipherType.Login)
{ {
var pageForOther = new AddEditPage(type: _appOptions.FillType, fromAutofill: true); var pageForOther = new AddEditPage(type: _appOptions.FillType, fromAutofill: true);
await Navigation.PushModalAsync(new NavigationPage(pageForOther)); await Navigation.PushModalAsync(new NavigationPage(pageForOther));

View File

@ -67,7 +67,7 @@ namespace Bit.App.Pages
_appOptions = appOptions; _appOptions = appOptions;
Uri = appOptions.Uri; Uri = appOptions.Uri;
string name = null; string name = null;
if(Uri.StartsWith(Constants.AndroidAppProtocol)) if (Uri.StartsWith(Constants.AndroidAppProtocol))
{ {
name = Uri.Substring(Constants.AndroidAppProtocol.Length); name = Uri.Substring(Constants.AndroidAppProtocol.Length);
} }
@ -75,7 +75,7 @@ namespace Bit.App.Pages
{ {
name = CoreHelpers.GetDomain(Uri); name = CoreHelpers.GetDomain(Uri);
} }
if(string.IsNullOrWhiteSpace(name)) if (string.IsNullOrWhiteSpace(name))
{ {
name = "--"; name = "--";
} }
@ -93,14 +93,14 @@ namespace Bit.App.Pages
var ciphers = await _cipherService.GetAllDecryptedByUrlAsync(Uri, null); var ciphers = await _cipherService.GetAllDecryptedByUrlAsync(Uri, null);
var matching = ciphers.Item1?.Select(c => new GroupingsPageListItem { Cipher = c }).ToList(); var matching = ciphers.Item1?.Select(c => new GroupingsPageListItem { Cipher = c }).ToList();
var hasMatching = matching?.Any() ?? false; var hasMatching = matching?.Any() ?? false;
if(matching?.Any() ?? false) if (matching?.Any() ?? false)
{ {
groupedItems.Add( groupedItems.Add(
new GroupingsPageListGroup(matching, AppResources.MatchingItems, matching.Count, false, true)); new GroupingsPageListGroup(matching, AppResources.MatchingItems, matching.Count, false, true));
} }
var fuzzy = ciphers.Item2?.Select(c => var fuzzy = ciphers.Item2?.Select(c =>
new GroupingsPageListItem { Cipher = c, FuzzyAutofill = true }).ToList(); new GroupingsPageListItem { Cipher = c, FuzzyAutofill = true }).ToList();
if(fuzzy?.Any() ?? false) if (fuzzy?.Any() ?? false)
{ {
groupedItems.Add( groupedItems.Add(
new GroupingsPageListGroup(fuzzy, AppResources.PossibleMatchingItems, fuzzy.Count, false, new GroupingsPageListGroup(fuzzy, AppResources.PossibleMatchingItems, fuzzy.Count, false,
@ -112,21 +112,21 @@ namespace Bit.App.Pages
public async Task SelectCipherAsync(CipherView cipher, bool fuzzy) public async Task SelectCipherAsync(CipherView cipher, bool fuzzy)
{ {
if(cipher == null) if (cipher == null)
{ {
return; return;
} }
if(_deviceActionService.SystemMajorVersion() < 21) if (_deviceActionService.SystemMajorVersion() < 21)
{ {
await AppHelpers.CipherListOptions(Page, cipher); await AppHelpers.CipherListOptions(Page, cipher);
} }
else else
{ {
var autofillResponse = AppResources.Yes; var autofillResponse = AppResources.Yes;
if(fuzzy) if (fuzzy)
{ {
var options = new List<string> { AppResources.Yes }; var options = new List<string> { AppResources.Yes };
if(cipher.Type == CipherType.Login && if (cipher.Type == CipherType.Login &&
Xamarin.Essentials.Connectivity.NetworkAccess != Xamarin.Essentials.NetworkAccess.None) Xamarin.Essentials.Connectivity.NetworkAccess != Xamarin.Essentials.NetworkAccess.None)
{ {
options.Add(AppResources.YesAndSave); options.Add(AppResources.YesAndSave);
@ -135,10 +135,10 @@ namespace Bit.App.Pages
string.Format(AppResources.BitwardenAutofillServiceMatchConfirm, Name), AppResources.No, string.Format(AppResources.BitwardenAutofillServiceMatchConfirm, Name), AppResources.No,
options.ToArray()); options.ToArray());
} }
if(autofillResponse == AppResources.YesAndSave && cipher.Type == CipherType.Login) if (autofillResponse == AppResources.YesAndSave && cipher.Type == CipherType.Login)
{ {
var uris = cipher.Login?.Uris?.ToList(); var uris = cipher.Login?.Uris?.ToList();
if(uris == null) if (uris == null)
{ {
uris = new List<LoginUriView>(); uris = new List<LoginUriView>();
} }
@ -154,17 +154,17 @@ namespace Bit.App.Pages
await _cipherService.SaveWithServerAsync(await _cipherService.EncryptAsync(cipher)); await _cipherService.SaveWithServerAsync(await _cipherService.EncryptAsync(cipher));
await _deviceActionService.HideLoadingAsync(); await _deviceActionService.HideLoadingAsync();
} }
catch(ApiException e) catch (ApiException e)
{ {
await _deviceActionService.HideLoadingAsync(); await _deviceActionService.HideLoadingAsync();
if(e?.Error != null) if (e?.Error != null)
{ {
await _platformUtilsService.ShowDialogAsync(e.Error.GetSingleMessage(), await _platformUtilsService.ShowDialogAsync(e.Error.GetSingleMessage(),
AppResources.AnErrorHasOccurred); AppResources.AnErrorHasOccurred);
} }
} }
} }
if(autofillResponse == AppResources.Yes || autofillResponse == AppResources.YesAndSave) if (autofillResponse == AppResources.Yes || autofillResponse == AppResources.YesAndSave)
{ {
_deviceActionService.Autofill(cipher); _deviceActionService.Autofill(cipher);
} }
@ -173,7 +173,7 @@ namespace Bit.App.Pages
private async void CipherOptionsAsync(CipherView cipher) private async void CipherOptionsAsync(CipherView cipher)
{ {
if((Page as BaseContentPage).DoOnce()) if ((Page as BaseContentPage).DoOnce())
{ {
await AppHelpers.CipherListOptions(Page, cipher); await AppHelpers.CipherListOptions(Page, cipher);
} }

View File

@ -23,15 +23,15 @@ namespace Bit.App.Pages
_vm.Page = this; _vm.Page = this;
_vm.Filter = filter; _vm.Filter = filter;
_vm.AutofillUrl = _autofillUrl = autofillUrl; _vm.AutofillUrl = _autofillUrl = autofillUrl;
if(folder) if (folder)
{ {
_vm.PageTitle = AppResources.SearchFolder; _vm.PageTitle = AppResources.SearchFolder;
} }
else if(collection) else if (collection)
{ {
_vm.PageTitle = AppResources.SearchCollection; _vm.PageTitle = AppResources.SearchCollection;
} }
else if(type) else if (type)
{ {
_vm.PageTitle = AppResources.SearchType; _vm.PageTitle = AppResources.SearchType;
} }
@ -40,7 +40,7 @@ namespace Bit.App.Pages
_vm.PageTitle = AppResources.SearchVault; _vm.PageTitle = AppResources.SearchVault;
} }
if(Device.RuntimePlatform == Device.iOS) if (Device.RuntimePlatform == Device.iOS)
{ {
ToolbarItems.Add(_closeItem); ToolbarItems.Add(_closeItem);
_searchBar.Placeholder = AppResources.Search; _searchBar.Placeholder = AppResources.Search;
@ -60,7 +60,7 @@ namespace Bit.App.Pages
{ {
base.OnAppearing(); base.OnAppearing();
await _vm.InitAsync(); await _vm.InitAsync();
if(!_hasFocused) if (!_hasFocused)
{ {
_hasFocused = true; _hasFocused = true;
RequestFocus(_searchBar); RequestFocus(_searchBar);
@ -71,7 +71,7 @@ namespace Bit.App.Pages
{ {
var oldLength = e.OldTextValue?.Length ?? 0; var oldLength = e.OldTextValue?.Length ?? 0;
var newLength = e.NewTextValue?.Length ?? 0; var newLength = e.NewTextValue?.Length ?? 0;
if(oldLength < 2 && newLength < 2 && oldLength < newLength) if (oldLength < 2 && newLength < 2 && oldLength < newLength)
{ {
return; return;
} }
@ -90,7 +90,7 @@ namespace Bit.App.Pages
protected override bool OnBackButtonPressed() protected override bool OnBackButtonPressed()
{ {
if(string.IsNullOrWhiteSpace(_autofillUrl)) if (string.IsNullOrWhiteSpace(_autofillUrl))
{ {
return false; return false;
} }
@ -100,11 +100,11 @@ namespace Bit.App.Pages
private void GoBack() private void GoBack()
{ {
if(!DoOnce()) if (!DoOnce())
{ {
return; return;
} }
if(string.IsNullOrWhiteSpace(_autofillUrl)) if (string.IsNullOrWhiteSpace(_autofillUrl))
{ {
Navigation.PopModalAsync(false); Navigation.PopModalAsync(false);
} }
@ -117,12 +117,12 @@ namespace Bit.App.Pages
private async void RowSelected(object sender, SelectedItemChangedEventArgs e) private async void RowSelected(object sender, SelectedItemChangedEventArgs e)
{ {
((ListView)sender).SelectedItem = null; ((ListView)sender).SelectedItem = null;
if(!DoOnce()) if (!DoOnce())
{ {
return; return;
} }
if(e.SelectedItem is CipherView cipher) if (e.SelectedItem is CipherView cipher)
{ {
await _vm.SelectCipherAsync(cipher); await _vm.SelectCipherAsync(cipher);
} }

View File

@ -75,7 +75,7 @@ namespace Bit.App.Pages
{ {
WebsiteIconsEnabled = !(await _stateService.GetAsync<bool?>(Constants.DisableFaviconKey)) WebsiteIconsEnabled = !(await _stateService.GetAsync<bool?>(Constants.DisableFaviconKey))
.GetValueOrDefault(); .GetValueOrDefault();
if(!string.IsNullOrWhiteSpace((Page as CiphersPage).SearchBar.Text)) if (!string.IsNullOrWhiteSpace((Page as CiphersPage).SearchBar.Text))
{ {
Search((Page as CiphersPage).SearchBar.Text, 200); Search((Page as CiphersPage).SearchBar.Text, 200);
} }
@ -89,13 +89,13 @@ namespace Bit.App.Pages
{ {
List<CipherView> ciphers = null; List<CipherView> ciphers = null;
var searchable = !string.IsNullOrWhiteSpace(searchText) && searchText.Length > 1; var searchable = !string.IsNullOrWhiteSpace(searchText) && searchText.Length > 1;
if(searchable) if (searchable)
{ {
if(timeout != null) if (timeout != null)
{ {
await Task.Delay(timeout.Value); await Task.Delay(timeout.Value);
} }
if(searchText != (Page as CiphersPage).SearchBar.Text) if (searchText != (Page as CiphersPage).SearchBar.Text)
{ {
return; return;
} }
@ -108,12 +108,12 @@ namespace Bit.App.Pages
ciphers = await _searchService.SearchCiphersAsync(searchText, Filter, null, cts.Token); ciphers = await _searchService.SearchCiphersAsync(searchText, Filter, null, cts.Token);
cts.Token.ThrowIfCancellationRequested(); cts.Token.ThrowIfCancellationRequested();
} }
catch(OperationCanceledException) catch (OperationCanceledException)
{ {
return; return;
} }
} }
if(ciphers == null) if (ciphers == null)
{ {
ciphers = new List<CipherView>(); ciphers = new List<CipherView>();
} }
@ -130,10 +130,10 @@ namespace Bit.App.Pages
public async Task SelectCipherAsync(CipherView cipher) public async Task SelectCipherAsync(CipherView cipher)
{ {
string selection = null; string selection = null;
if(!string.IsNullOrWhiteSpace(AutofillUrl)) if (!string.IsNullOrWhiteSpace(AutofillUrl))
{ {
var options = new List<string> { AppResources.Autofill }; var options = new List<string> { AppResources.Autofill };
if(cipher.Type == CipherType.Login && if (cipher.Type == CipherType.Login &&
Xamarin.Essentials.Connectivity.NetworkAccess != Xamarin.Essentials.NetworkAccess.None) Xamarin.Essentials.Connectivity.NetworkAccess != Xamarin.Essentials.NetworkAccess.None)
{ {
options.Add(AppResources.AutofillAndSave); options.Add(AppResources.AutofillAndSave);
@ -142,17 +142,17 @@ namespace Bit.App.Pages
selection = await Page.DisplayActionSheet(AppResources.AutofillOrView, AppResources.Cancel, null, selection = await Page.DisplayActionSheet(AppResources.AutofillOrView, AppResources.Cancel, null,
options.ToArray()); options.ToArray());
} }
if(selection == AppResources.View || string.IsNullOrWhiteSpace(AutofillUrl)) if (selection == AppResources.View || string.IsNullOrWhiteSpace(AutofillUrl))
{ {
var page = new ViewPage(cipher.Id); var page = new ViewPage(cipher.Id);
await Page.Navigation.PushModalAsync(new NavigationPage(page)); await Page.Navigation.PushModalAsync(new NavigationPage(page));
} }
else if(selection == AppResources.Autofill || selection == AppResources.AutofillAndSave) else if (selection == AppResources.Autofill || selection == AppResources.AutofillAndSave)
{ {
if(selection == AppResources.AutofillAndSave) if (selection == AppResources.AutofillAndSave)
{ {
var uris = cipher.Login?.Uris?.ToList(); var uris = cipher.Login?.Uris?.ToList();
if(uris == null) if (uris == null)
{ {
uris = new List<LoginUriView>(); uris = new List<LoginUriView>();
} }
@ -168,17 +168,17 @@ namespace Bit.App.Pages
await _cipherService.SaveWithServerAsync(await _cipherService.EncryptAsync(cipher)); await _cipherService.SaveWithServerAsync(await _cipherService.EncryptAsync(cipher));
await _deviceActionService.HideLoadingAsync(); await _deviceActionService.HideLoadingAsync();
} }
catch(ApiException e) catch (ApiException e)
{ {
await _deviceActionService.HideLoadingAsync(); await _deviceActionService.HideLoadingAsync();
if(e?.Error != null) if (e?.Error != null)
{ {
await _platformUtilsService.ShowDialogAsync(e.Error.GetSingleMessage(), await _platformUtilsService.ShowDialogAsync(e.Error.GetSingleMessage(),
AppResources.AnErrorHasOccurred); AppResources.AnErrorHasOccurred);
} }
} }
} }
if(_deviceActionService.SystemMajorVersion() < 21) if (_deviceActionService.SystemMajorVersion() < 21)
{ {
await Utilities.AppHelpers.CipherListOptions(Page, cipher); await Utilities.AppHelpers.CipherListOptions(Page, cipher);
} }
@ -191,7 +191,7 @@ namespace Bit.App.Pages
private async void CipherOptionsAsync(CipherView cipher) private async void CipherOptionsAsync(CipherView cipher)
{ {
if((Page as BaseContentPage).DoOnce()) if ((Page as BaseContentPage).DoOnce())
{ {
await Utilities.AppHelpers.CipherListOptions(Page, cipher); await Utilities.AppHelpers.CipherListOptions(Page, cipher);
} }

View File

@ -13,7 +13,7 @@ namespace Bit.App.Pages
_vm.Page = this; _vm.Page = this;
_vm.CipherId = cipherId; _vm.CipherId = cipherId;
SetActivityIndicator(); SetActivityIndicator();
if(Device.RuntimePlatform == Device.Android) if (Device.RuntimePlatform == Device.Android)
{ {
ToolbarItems.RemoveAt(0); ToolbarItems.RemoveAt(0);
} }
@ -32,7 +32,7 @@ namespace Bit.App.Pages
private async void Save_Clicked(object sender, System.EventArgs e) private async void Save_Clicked(object sender, System.EventArgs e)
{ {
if(DoOnce()) if (DoOnce())
{ {
await _vm.SubmitAsync(); await _vm.SubmitAsync();
} }
@ -40,7 +40,7 @@ namespace Bit.App.Pages
private async void Close_Clicked(object sender, System.EventArgs e) private async void Close_Clicked(object sender, System.EventArgs e)
{ {
if(DoOnce()) if (DoOnce())
{ {
await Navigation.PopModalAsync(); await Navigation.PopModalAsync();
} }

View File

@ -59,13 +59,13 @@ namespace Bit.App.Pages
public async Task<bool> SubmitAsync() public async Task<bool> SubmitAsync()
{ {
var selectedCollectionIds = Collections?.Where(c => c.Checked).Select(c => c.Collection.Id); var selectedCollectionIds = Collections?.Where(c => c.Checked).Select(c => c.Collection.Id);
if(!selectedCollectionIds?.Any() ?? true) if (!selectedCollectionIds?.Any() ?? true)
{ {
await Page.DisplayAlert(AppResources.AnErrorHasOccurred, AppResources.SelectOneCollection, await Page.DisplayAlert(AppResources.AnErrorHasOccurred, AppResources.SelectOneCollection,
AppResources.Ok); AppResources.Ok);
return false; return false;
} }
if(Xamarin.Essentials.Connectivity.NetworkAccess == Xamarin.Essentials.NetworkAccess.None) if (Xamarin.Essentials.Connectivity.NetworkAccess == Xamarin.Essentials.NetworkAccess.None)
{ {
await _platformUtilsService.ShowDialogAsync(AppResources.InternetConnectionRequiredMessage, await _platformUtilsService.ShowDialogAsync(AppResources.InternetConnectionRequiredMessage,
AppResources.InternetConnectionRequiredTitle); AppResources.InternetConnectionRequiredTitle);
@ -82,10 +82,10 @@ namespace Bit.App.Pages
await Page.Navigation.PopModalAsync(); await Page.Navigation.PopModalAsync();
return true; return true;
} }
catch(ApiException e) catch (ApiException e)
{ {
await _deviceActionService.HideLoadingAsync(); await _deviceActionService.HideLoadingAsync();
if(e?.Error != null) if (e?.Error != null)
{ {
await _platformUtilsService.ShowDialogAsync(e.Error.GetSingleMessage(), await _platformUtilsService.ShowDialogAsync(e.Error.GetSingleMessage(),
AppResources.AnErrorHasOccurred); AppResources.AnErrorHasOccurred);

View File

@ -48,12 +48,12 @@ namespace Bit.App.Pages
_vm.FolderId = folderId; _vm.FolderId = folderId;
_vm.CollectionId = collectionId; _vm.CollectionId = collectionId;
_previousPage = previousPage; _previousPage = previousPage;
if(pageTitle != null) if (pageTitle != null)
{ {
_vm.PageTitle = pageTitle; _vm.PageTitle = pageTitle;
} }
if(Device.RuntimePlatform == Device.iOS) if (Device.RuntimePlatform == Device.iOS)
{ {
_absLayout.Children.Remove(_fab); _absLayout.Children.Remove(_fab);
ToolbarItems.Add(_addItem); ToolbarItems.Add(_addItem);
@ -71,24 +71,24 @@ namespace Bit.App.Pages
protected async override void OnAppearing() protected async override void OnAppearing()
{ {
base.OnAppearing(); base.OnAppearing();
if(_syncService.SyncInProgress) if (_syncService.SyncInProgress)
{ {
IsBusy = true; IsBusy = true;
} }
_broadcasterService.Subscribe(_pageName, async (message) => _broadcasterService.Subscribe(_pageName, async (message) =>
{ {
if(message.Command == "syncStarted") if (message.Command == "syncStarted")
{ {
Device.BeginInvokeOnMainThread(() => IsBusy = true); Device.BeginInvokeOnMainThread(() => IsBusy = true);
} }
else if(message.Command == "syncCompleted") else if (message.Command == "syncCompleted")
{ {
await Task.Delay(500); await Task.Delay(500);
Device.BeginInvokeOnMainThread(() => Device.BeginInvokeOnMainThread(() =>
{ {
IsBusy = false; IsBusy = false;
if(_vm.LoadedOnce) if (_vm.LoadedOnce)
{ {
var task = _vm.LoadAsync(); var task = _vm.LoadAsync();
} }
@ -99,13 +99,13 @@ namespace Bit.App.Pages
var migratedFromV1 = await _storageService.GetAsync<bool?>(Constants.MigratedFromV1); var migratedFromV1 = await _storageService.GetAsync<bool?>(Constants.MigratedFromV1);
await LoadOnAppearedAsync(_mainLayout, false, async () => await LoadOnAppearedAsync(_mainLayout, false, async () =>
{ {
if(!_syncService.SyncInProgress || (await _cipherService.GetAllAsync()).Any()) if (!_syncService.SyncInProgress || (await _cipherService.GetAllAsync()).Any())
{ {
try try
{ {
await _vm.LoadAsync(); await _vm.LoadAsync();
} }
catch(Exception e) when(e.Message.Contains("No key.")) catch (Exception e) when(e.Message.Contains("No key."))
{ {
await Task.Delay(1000); await Task.Delay(1000);
await _vm.LoadAsync(); await _vm.LoadAsync();
@ -114,18 +114,18 @@ namespace Bit.App.Pages
else else
{ {
await Task.Delay(5000); await Task.Delay(5000);
if(!_vm.Loaded) if (!_vm.Loaded)
{ {
await _vm.LoadAsync(); await _vm.LoadAsync();
} }
} }
// Forced sync if for some reason we have no data after a v1 migration // Forced sync if for some reason we have no data after a v1 migration
if(_vm.MainPage && !_syncService.SyncInProgress && migratedFromV1.GetValueOrDefault() && if (_vm.MainPage && !_syncService.SyncInProgress && migratedFromV1.GetValueOrDefault() &&
!_vm.HasCiphers && !_vm.HasCiphers &&
Xamarin.Essentials.Connectivity.NetworkAccess != Xamarin.Essentials.NetworkAccess.None) Xamarin.Essentials.Connectivity.NetworkAccess != Xamarin.Essentials.NetworkAccess.None)
{ {
var triedV1ReSync = await _storageService.GetAsync<bool?>(Constants.TriedV1Resync); var triedV1ReSync = await _storageService.GetAsync<bool?>(Constants.TriedV1Resync);
if(!triedV1ReSync.GetValueOrDefault()) if (!triedV1ReSync.GetValueOrDefault())
{ {
await _storageService.SaveAsync(Constants.TriedV1Resync, true); await _storageService.SaveAsync(Constants.TriedV1Resync, true);
await _syncService.FullSyncAsync(true); await _syncService.FullSyncAsync(true);
@ -134,7 +134,7 @@ namespace Bit.App.Pages
await ShowPreviousPageAsync(); await ShowPreviousPageAsync();
}, _mainContent); }, _mainContent);
if(!_vm.MainPage) if (!_vm.MainPage)
{ {
return; return;
} }
@ -142,35 +142,35 @@ namespace Bit.App.Pages
// Push registration // Push registration
var lastPushRegistration = await _storageService.GetAsync<DateTime?>(Constants.PushLastRegistrationDateKey); var lastPushRegistration = await _storageService.GetAsync<DateTime?>(Constants.PushLastRegistrationDateKey);
lastPushRegistration = lastPushRegistration.GetValueOrDefault(DateTime.MinValue); lastPushRegistration = lastPushRegistration.GetValueOrDefault(DateTime.MinValue);
if(Device.RuntimePlatform == Device.iOS) if (Device.RuntimePlatform == Device.iOS)
{ {
var pushPromptShow = await _storageService.GetAsync<bool?>(Constants.PushInitialPromptShownKey); var pushPromptShow = await _storageService.GetAsync<bool?>(Constants.PushInitialPromptShownKey);
if(!pushPromptShow.GetValueOrDefault(false)) if (!pushPromptShow.GetValueOrDefault(false))
{ {
await _storageService.SaveAsync(Constants.PushInitialPromptShownKey, true); await _storageService.SaveAsync(Constants.PushInitialPromptShownKey, true);
await DisplayAlert(AppResources.EnableAutomaticSyncing, AppResources.PushNotificationAlert, await DisplayAlert(AppResources.EnableAutomaticSyncing, AppResources.PushNotificationAlert,
AppResources.OkGotIt); AppResources.OkGotIt);
} }
if(!pushPromptShow.GetValueOrDefault(false) || if (!pushPromptShow.GetValueOrDefault(false) ||
DateTime.UtcNow - lastPushRegistration > TimeSpan.FromDays(1)) DateTime.UtcNow - lastPushRegistration > TimeSpan.FromDays(1))
{ {
await _pushNotificationService.RegisterAsync(); await _pushNotificationService.RegisterAsync();
} }
} }
else if(Device.RuntimePlatform == Device.Android) else if (Device.RuntimePlatform == Device.Android)
{ {
if(DateTime.UtcNow - lastPushRegistration > TimeSpan.FromDays(1)) if (DateTime.UtcNow - lastPushRegistration > TimeSpan.FromDays(1))
{ {
await _pushNotificationService.RegisterAsync(); await _pushNotificationService.RegisterAsync();
} }
if(!_deviceActionService.AutofillAccessibilityServiceRunning() if (!_deviceActionService.AutofillAccessibilityServiceRunning()
&& !_deviceActionService.AutofillServiceEnabled()) && !_deviceActionService.AutofillServiceEnabled())
{ {
if(migratedFromV1.GetValueOrDefault()) if (migratedFromV1.GetValueOrDefault())
{ {
var migratedFromV1AutofillPromptShown = await _storageService.GetAsync<bool?>( var migratedFromV1AutofillPromptShown = await _storageService.GetAsync<bool?>(
Constants.MigratedFromV1AutofillPromptShown); Constants.MigratedFromV1AutofillPromptShown);
if(!migratedFromV1AutofillPromptShown.GetValueOrDefault()) if (!migratedFromV1AutofillPromptShown.GetValueOrDefault())
{ {
await DisplayAlert(AppResources.Autofill, await DisplayAlert(AppResources.Autofill,
AppResources.AutofillServiceNotEnabled, AppResources.Ok); AppResources.AutofillServiceNotEnabled, AppResources.Ok);
@ -191,28 +191,28 @@ namespace Bit.App.Pages
private async void RowSelected(object sender, SelectedItemChangedEventArgs e) private async void RowSelected(object sender, SelectedItemChangedEventArgs e)
{ {
((ListView)sender).SelectedItem = null; ((ListView)sender).SelectedItem = null;
if(!DoOnce()) if (!DoOnce())
{ {
return; return;
} }
if(!(e.SelectedItem is GroupingsPageListItem item)) if (!(e.SelectedItem is GroupingsPageListItem item))
{ {
return; return;
} }
if(item.Cipher != null) if (item.Cipher != null)
{ {
await _vm.SelectCipherAsync(item.Cipher); await _vm.SelectCipherAsync(item.Cipher);
} }
else if(item.Folder != null) else if (item.Folder != null)
{ {
await _vm.SelectFolderAsync(item.Folder); await _vm.SelectFolderAsync(item.Folder);
} }
else if(item.Collection != null) else if (item.Collection != null)
{ {
await _vm.SelectCollectionAsync(item.Collection); await _vm.SelectCollectionAsync(item.Collection);
} }
else if(item.Type != null) else if (item.Type != null)
{ {
await _vm.SelectTypeAsync(item.Type.Value); await _vm.SelectTypeAsync(item.Type.Value);
} }
@ -220,7 +220,7 @@ namespace Bit.App.Pages
private async void Search_Clicked(object sender, EventArgs e) private async void Search_Clicked(object sender, EventArgs e)
{ {
if(DoOnce()) if (DoOnce())
{ {
var page = new CiphersPage(_vm.Filter, _vm.FolderId != null, _vm.CollectionId != null, var page = new CiphersPage(_vm.Filter, _vm.FolderId != null, _vm.CollectionId != null,
_vm.Type != null); _vm.Type != null);
@ -245,7 +245,7 @@ namespace Bit.App.Pages
private async void AddButton_Clicked(object sender, EventArgs e) private async void AddButton_Clicked(object sender, EventArgs e)
{ {
if(DoOnce()) if (DoOnce())
{ {
var page = new AddEditPage(null, _vm.Type, _vm.FolderId, _vm.CollectionId); var page = new AddEditPage(null, _vm.Type, _vm.FolderId, _vm.CollectionId);
await Navigation.PushModalAsync(new NavigationPage(page)); await Navigation.PushModalAsync(new NavigationPage(page));
@ -254,15 +254,15 @@ namespace Bit.App.Pages
private async Task ShowPreviousPageAsync() private async Task ShowPreviousPageAsync()
{ {
if(_previousPage == null) if (_previousPage == null)
{ {
return; return;
} }
if(_previousPage.Page == "view" && !string.IsNullOrWhiteSpace(_previousPage.CipherId)) if (_previousPage.Page == "view" && !string.IsNullOrWhiteSpace(_previousPage.CipherId))
{ {
await Navigation.PushModalAsync(new NavigationPage(new ViewPage(_previousPage.CipherId))); await Navigation.PushModalAsync(new NavigationPage(new ViewPage(_previousPage.CipherId)));
} }
else if(_previousPage.Page == "edit" && !string.IsNullOrWhiteSpace(_previousPage.CipherId)) else if (_previousPage.Page == "edit" && !string.IsNullOrWhiteSpace(_previousPage.CipherId))
{ {
await Navigation.PushModalAsync(new NavigationPage(new AddEditPage(_previousPage.CipherId))); await Navigation.PushModalAsync(new NavigationPage(new AddEditPage(_previousPage.CipherId)));
} }

View File

@ -12,11 +12,11 @@ namespace Bit.App.Pages
bool doUpper = true, bool first = false) bool doUpper = true, bool first = false)
{ {
AddRange(groupItems); AddRange(groupItems);
if(string.IsNullOrWhiteSpace(name)) if (string.IsNullOrWhiteSpace(name))
{ {
Name = "-"; Name = "-";
} }
else if(doUpper) else if (doUpper)
{ {
Name = name.ToUpperInvariant(); Name = name.ToUpperInvariant();
} }

View File

@ -20,21 +20,21 @@ namespace Bit.App.Pages
{ {
get get
{ {
if(_name != null) if (_name != null)
{ {
return _name; return _name;
} }
if(Folder != null) if (Folder != null)
{ {
_name = Folder.Name; _name = Folder.Name;
} }
else if(Collection != null) else if (Collection != null)
{ {
_name = Collection.Name; _name = Collection.Name;
} }
else if(Type != null) else if (Type != null)
{ {
switch(Type.Value) switch (Type.Value)
{ {
case CipherType.Login: case CipherType.Login:
_name = AppResources.TypeLogin; _name = AppResources.TypeLogin;
@ -60,21 +60,21 @@ namespace Bit.App.Pages
{ {
get get
{ {
if(_icon != null) if (_icon != null)
{ {
return _icon; return _icon;
} }
if(Folder != null) if (Folder != null)
{ {
_icon = Folder.Id == null ? "" : ""; _icon = Folder.Id == null ? "" : "";
} }
else if(Collection != null) else if (Collection != null)
{ {
_icon = ""; _icon = "";
} }
else if(Type != null) else if (Type != null)
{ {
switch(Type.Value) switch (Type.Value)
{ {
case CipherType.Login: case CipherType.Login:
_icon = ""; _icon = "";

View File

@ -9,7 +9,7 @@ namespace Bit.App.Pages
protected override DataTemplate OnSelectTemplate(object item, BindableObject container) protected override DataTemplate OnSelectTemplate(object item, BindableObject container)
{ {
if(item is GroupingsPageListItem listItem) if (item is GroupingsPageListItem listItem)
{ {
return listItem.Cipher != null ? CipherTemplate : GroupTemplate; return listItem.Cipher != null ? CipherTemplate : GroupTemplate;
} }

View File

@ -134,16 +134,16 @@ namespace Bit.App.Pages
public async Task LoadAsync() public async Task LoadAsync()
{ {
if(_doingLoad) if (_doingLoad)
{ {
return; return;
} }
var authed = await _userService.IsAuthenticatedAsync(); var authed = await _userService.IsAuthenticatedAsync();
if(!authed) if (!authed)
{ {
return; return;
} }
if(await _lockService.IsLockedAsync()) if (await _lockService.IsLockedAsync())
{ {
return; return;
} }
@ -161,7 +161,7 @@ namespace Bit.App.Pages
try try
{ {
await LoadDataAsync(); await LoadDataAsync();
if(ShowNoFolderCiphers && (NestedFolders?.Any() ?? false)) if (ShowNoFolderCiphers && (NestedFolders?.Any() ?? false))
{ {
// Remove "No Folder" from folder listing // Remove "No Folder" from folder listing
NestedFolders = NestedFolders.GetRange(0, NestedFolders.Count - 1); NestedFolders = NestedFolders.GetRange(0, NestedFolders.Count - 1);
@ -169,13 +169,13 @@ namespace Bit.App.Pages
var uppercaseGroupNames = _deviceActionService.DeviceType == DeviceType.iOS; var uppercaseGroupNames = _deviceActionService.DeviceType == DeviceType.iOS;
var hasFavorites = FavoriteCiphers?.Any() ?? false; var hasFavorites = FavoriteCiphers?.Any() ?? false;
if(hasFavorites) if (hasFavorites)
{ {
var favListItems = FavoriteCiphers.Select(c => new GroupingsPageListItem { Cipher = c }).ToList(); var favListItems = FavoriteCiphers.Select(c => new GroupingsPageListItem { Cipher = c }).ToList();
groupedItems.Add(new GroupingsPageListGroup(favListItems, AppResources.Favorites, groupedItems.Add(new GroupingsPageListGroup(favListItems, AppResources.Favorites,
favListItems.Count, uppercaseGroupNames, true)); favListItems.Count, uppercaseGroupNames, true));
} }
if(MainPage) if (MainPage)
{ {
groupedItems.Add(new GroupingsPageListGroup( groupedItems.Add(new GroupingsPageListGroup(
AppResources.Types, 4, uppercaseGroupNames, !hasFavorites) AppResources.Types, 4, uppercaseGroupNames, !hasFavorites)
@ -206,7 +206,7 @@ namespace Bit.App.Pages
}, },
}); });
} }
if(NestedFolders?.Any() ?? false) if (NestedFolders?.Any() ?? false)
{ {
var folderListItems = NestedFolders.Select(f => var folderListItems = NestedFolders.Select(f =>
{ {
@ -220,7 +220,7 @@ namespace Bit.App.Pages
groupedItems.Add(new GroupingsPageListGroup(folderListItems, AppResources.Folders, groupedItems.Add(new GroupingsPageListGroup(folderListItems, AppResources.Folders,
folderListItems.Count, uppercaseGroupNames, !MainPage)); folderListItems.Count, uppercaseGroupNames, !MainPage));
} }
if(NestedCollections?.Any() ?? false) if (NestedCollections?.Any() ?? false)
{ {
var collectionListItems = NestedCollections.Select(c => new GroupingsPageListItem var collectionListItems = NestedCollections.Select(c => new GroupingsPageListItem
{ {
@ -231,13 +231,13 @@ namespace Bit.App.Pages
groupedItems.Add(new GroupingsPageListGroup(collectionListItems, AppResources.Collections, groupedItems.Add(new GroupingsPageListGroup(collectionListItems, AppResources.Collections,
collectionListItems.Count, uppercaseGroupNames, !MainPage)); collectionListItems.Count, uppercaseGroupNames, !MainPage));
} }
if(Ciphers?.Any() ?? false) if (Ciphers?.Any() ?? false)
{ {
var ciphersListItems = Ciphers.Select(c => new GroupingsPageListItem { Cipher = c }).ToList(); var ciphersListItems = Ciphers.Select(c => new GroupingsPageListItem { Cipher = c }).ToList();
groupedItems.Add(new GroupingsPageListGroup(ciphersListItems, AppResources.Items, groupedItems.Add(new GroupingsPageListGroup(ciphersListItems, AppResources.Items,
ciphersListItems.Count, uppercaseGroupNames, !MainPage && !groupedItems.Any())); ciphersListItems.Count, uppercaseGroupNames, !MainPage && !groupedItems.Any()));
} }
if(ShowNoFolderCiphers) if (ShowNoFolderCiphers)
{ {
var noFolderCiphersListItems = NoFolderCiphers.Select( var noFolderCiphersListItems = NoFolderCiphers.Select(
c => new GroupingsPageListItem { Cipher = c }).ToList(); c => new GroupingsPageListItem { Cipher = c }).ToList();
@ -266,7 +266,7 @@ namespace Bit.App.Pages
public async Task SelectTypeAsync(CipherType type) public async Task SelectTypeAsync(CipherType type)
{ {
string title = null; string title = null;
switch(type) switch (type)
{ {
case CipherType.Login: case CipherType.Login:
title = AppResources.Logins; title = AppResources.Logins;
@ -303,7 +303,7 @@ namespace Bit.App.Pages
{ {
var confirmed = await _platformUtilsService.ShowDialogAsync(AppResources.ExitConfirmation, var confirmed = await _platformUtilsService.ShowDialogAsync(AppResources.ExitConfirmation,
AppResources.Exit, AppResources.Yes, AppResources.Cancel); AppResources.Exit, AppResources.Yes, AppResources.Cancel);
if(confirmed) if (confirmed)
{ {
_messagingService.Send("exit"); _messagingService.Send("exit");
} }
@ -311,7 +311,7 @@ namespace Bit.App.Pages
public async Task SyncAsync() public async Task SyncAsync()
{ {
if(Xamarin.Essentials.Connectivity.NetworkAccess == Xamarin.Essentials.NetworkAccess.None) if (Xamarin.Essentials.Connectivity.NetworkAccess == Xamarin.Essentials.NetworkAccess.None)
{ {
await _platformUtilsService.ShowDialogAsync(AppResources.InternetConnectionRequiredMessage, await _platformUtilsService.ShowDialogAsync(AppResources.InternetConnectionRequiredMessage,
AppResources.InternetConnectionRequiredTitle); AppResources.InternetConnectionRequiredTitle);
@ -345,7 +345,7 @@ namespace Bit.App.Pages
HasCollections = false; HasCollections = false;
Filter = null; Filter = null;
if(MainPage) if (MainPage)
{ {
Folders = await _folderService.GetAllDecryptedAsync(); Folders = await _folderService.GetAllDecryptedAsync();
NestedFolders = await _folderService.GetAllNestedAsync(); NestedFolders = await _folderService.GetAllNestedAsync();
@ -356,18 +356,18 @@ namespace Bit.App.Pages
} }
else else
{ {
if(Type != null) if (Type != null)
{ {
Filter = c => c.Type == Type.Value; Filter = c => c.Type == Type.Value;
} }
else if(FolderId != null) else if (FolderId != null)
{ {
NoDataText = AppResources.NoItemsFolder; NoDataText = AppResources.NoItemsFolder;
var folderId = FolderId == "none" ? null : FolderId; var folderId = FolderId == "none" ? null : FolderId;
if(folderId != null) if (folderId != null)
{ {
var folderNode = await _folderService.GetNestedAsync(folderId); var folderNode = await _folderService.GetNestedAsync(folderId);
if(folderNode?.Node != null) if (folderNode?.Node != null)
{ {
PageTitle = folderNode.Node.Name; PageTitle = folderNode.Node.Name;
NestedFolders = (folderNode.Children?.Count ?? 0) > 0 ? folderNode.Children : null; NestedFolders = (folderNode.Children?.Count ?? 0) > 0 ? folderNode.Children : null;
@ -379,12 +379,12 @@ namespace Bit.App.Pages
} }
Filter = c => c.FolderId == folderId; Filter = c => c.FolderId == folderId;
} }
else if(CollectionId != null) else if (CollectionId != null)
{ {
ShowAddCipherButton = false; ShowAddCipherButton = false;
NoDataText = AppResources.NoItemsCollection; NoDataText = AppResources.NoItemsCollection;
var collectionNode = await _collectionService.GetNestedAsync(CollectionId); var collectionNode = await _collectionService.GetNestedAsync(CollectionId);
if(collectionNode?.Node != null) if (collectionNode?.Node != null)
{ {
PageTitle = collectionNode.Node.Name; PageTitle = collectionNode.Node.Name;
NestedCollections = (collectionNode.Children?.Count ?? 0) > 0 ? collectionNode.Children : null; NestedCollections = (collectionNode.Children?.Count ?? 0) > 0 ? collectionNode.Children : null;
@ -398,28 +398,28 @@ namespace Bit.App.Pages
Ciphers = Filter != null ? _allCiphers.Where(Filter).ToList() : _allCiphers; Ciphers = Filter != null ? _allCiphers.Where(Filter).ToList() : _allCiphers;
} }
foreach(var c in _allCiphers) foreach (var c in _allCiphers)
{ {
if(MainPage) if (MainPage)
{ {
if(c.Favorite) if (c.Favorite)
{ {
if(FavoriteCiphers == null) if (FavoriteCiphers == null)
{ {
FavoriteCiphers = new List<CipherView>(); FavoriteCiphers = new List<CipherView>();
} }
FavoriteCiphers.Add(c); FavoriteCiphers.Add(c);
} }
if(c.FolderId == null) if (c.FolderId == null)
{ {
if(NoFolderCiphers == null) if (NoFolderCiphers == null)
{ {
NoFolderCiphers = new List<CipherView>(); NoFolderCiphers = new List<CipherView>();
} }
NoFolderCiphers.Add(c); NoFolderCiphers.Add(c);
} }
if(_typeCounts.ContainsKey(c.Type)) if (_typeCounts.ContainsKey(c.Type))
{ {
_typeCounts[c.Type] = _typeCounts[c.Type] + 1; _typeCounts[c.Type] = _typeCounts[c.Type] + 1;
} }
@ -430,7 +430,7 @@ namespace Bit.App.Pages
} }
var fId = c.FolderId ?? "none"; var fId = c.FolderId ?? "none";
if(_folderCounts.ContainsKey(fId)) if (_folderCounts.ContainsKey(fId))
{ {
_folderCounts[fId] = _folderCounts[fId] + 1; _folderCounts[fId] = _folderCounts[fId] + 1;
} }
@ -439,11 +439,11 @@ namespace Bit.App.Pages
_folderCounts.Add(fId, 1); _folderCounts.Add(fId, 1);
} }
if(c.CollectionIds != null) if (c.CollectionIds != null)
{ {
foreach(var colId in c.CollectionIds) foreach (var colId in c.CollectionIds)
{ {
if(_collectionCounts.ContainsKey(colId)) if (_collectionCounts.ContainsKey(colId))
{ {
_collectionCounts[colId] = _collectionCounts[colId] + 1; _collectionCounts[colId] = _collectionCounts[colId] + 1;
} }
@ -458,7 +458,7 @@ namespace Bit.App.Pages
private async void CipherOptionsAsync(CipherView cipher) private async void CipherOptionsAsync(CipherView cipher)
{ {
if((Page as BaseContentPage).DoOnce()) if ((Page as BaseContentPage).DoOnce())
{ {
await AppHelpers.CipherListOptions(Page, cipher); await AppHelpers.CipherListOptions(Page, cipher);
} }

View File

@ -14,7 +14,7 @@ namespace Bit.App.Pages
_vm = BindingContext as PasswordHistoryPageViewModel; _vm = BindingContext as PasswordHistoryPageViewModel;
_vm.Page = this; _vm.Page = this;
_vm.CipherId = cipherId; _vm.CipherId = cipherId;
if(Device.RuntimePlatform == Device.Android) if (Device.RuntimePlatform == Device.Android)
{ {
ToolbarItems.RemoveAt(0); ToolbarItems.RemoveAt(0);
} }
@ -30,7 +30,7 @@ namespace Bit.App.Pages
private async void Close_Clicked(object sender, System.EventArgs e) private async void Close_Clicked(object sender, System.EventArgs e)
{ {
if(DoOnce()) if (DoOnce())
{ {
await Navigation.PopModalAsync(); await Navigation.PopModalAsync();
} }

View File

@ -22,7 +22,7 @@ namespace Bit.App.Pages
AutoRotate = false, AutoRotate = false,
TryInverted = true TryInverted = true
}; };
if(Device.RuntimePlatform == Device.Android) if (Device.RuntimePlatform == Device.Android)
{ {
ToolbarItems.RemoveAt(0); ToolbarItems.RemoveAt(0);
} }
@ -35,7 +35,7 @@ namespace Bit.App.Pages
_timerStarted = DateTime.Now; _timerStarted = DateTime.Now;
Device.StartTimer(new TimeSpan(0, 0, 2), () => Device.StartTimer(new TimeSpan(0, 0, 2), () =>
{ {
if(_timerStarted == null || (DateTime.Now - _timerStarted) > _timerMaxLength) if (_timerStarted == null || (DateTime.Now - _timerStarted) > _timerMaxLength)
{ {
return false; return false;
} }
@ -57,20 +57,20 @@ namespace Bit.App.Pages
_zxing.IsAnalyzing = false; _zxing.IsAnalyzing = false;
_zxing.IsScanning = false; _zxing.IsScanning = false;
var text = result?.Text; var text = result?.Text;
if(!string.IsNullOrWhiteSpace(text)) if (!string.IsNullOrWhiteSpace(text))
{ {
if(text.StartsWith("otpauth://totp")) if (text.StartsWith("otpauth://totp"))
{ {
_callback(text); _callback(text);
return; return;
} }
else if(Uri.TryCreate(text, UriKind.Absolute, out Uri uri) && else if (Uri.TryCreate(text, UriKind.Absolute, out Uri uri) &&
!string.IsNullOrWhiteSpace(uri?.Query)) !string.IsNullOrWhiteSpace(uri?.Query))
{ {
var queryParts = uri.Query.Substring(1).ToLowerInvariant().Split('&'); var queryParts = uri.Query.Substring(1).ToLowerInvariant().Split('&');
foreach(var part in queryParts) foreach (var part in queryParts)
{ {
if(part.StartsWith("secret=")) if (part.StartsWith("secret="))
{ {
_callback(part.Substring(7)?.ToUpperInvariant()); _callback(part.Substring(7)?.ToUpperInvariant());
return; return;
@ -83,7 +83,7 @@ namespace Bit.App.Pages
private async void Close_Clicked(object sender, System.EventArgs e) private async void Close_Clicked(object sender, System.EventArgs e)
{ {
if(DoOnce()) if (DoOnce())
{ {
await Navigation.PopModalAsync(); await Navigation.PopModalAsync();
} }

Some files were not shown because too many files have changed in this diff Show More