diff --git a/src/Android/Accessibility/AccessibilityActivity.cs b/src/Android/Accessibility/AccessibilityActivity.cs index f6ea4aedf..f0e8d0e15 100644 --- a/src/Android/Accessibility/AccessibilityActivity.cs +++ b/src/Android/Accessibility/AccessibilityActivity.cs @@ -35,7 +35,7 @@ namespace Bit.Droid.Accessibility protected override void OnResume() { base.OnResume(); - if(!Intent.HasExtra("uri")) + if (!Intent.HasExtra("uri")) { Finish(); return; @@ -46,7 +46,7 @@ namespace Bit.Droid.Accessibility protected override void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data) { base.OnActivityResult(requestCode, resultCode, data); - if(data == null) + if (data == null) { AccessibilityHelpers.LastCredentials = null; } @@ -54,7 +54,7 @@ namespace Bit.Droid.Accessibility { try { - if(data.GetStringExtra("canceled") != null) + if (data.GetStringExtra("canceled") != null) { AccessibilityHelpers.LastCredentials = null; } @@ -82,7 +82,7 @@ namespace Bit.Droid.Accessibility private void HandleIntent(Intent callingIntent, int requestCode) { - if(callingIntent?.GetBooleanExtra("autofillTileClicked", false) ?? false) + if (callingIntent?.GetBooleanExtra("autofillTileClicked", false) ?? false) { Intent.RemoveExtra("autofillTileClicked"); var messagingService = ServiceContainer.Resolve("messagingService"); @@ -98,20 +98,20 @@ namespace Bit.Droid.Accessibility private void LaunchMainActivity(Intent callingIntent, int requestCode) { _lastQueriedUri = callingIntent?.GetStringExtra("uri"); - if(_lastQueriedUri == null) + if (_lastQueriedUri == null) { Finish(); return; } var now = DateTime.UtcNow; - if(_lastLaunch.HasValue && (now - _lastLaunch.Value) <= TimeSpan.FromSeconds(2)) + if (_lastLaunch.HasValue && (now - _lastLaunch.Value) <= TimeSpan.FromSeconds(2)) { return; } _lastLaunch = now; var intent = new Intent(this, typeof(MainActivity)); - if(!callingIntent.Flags.HasFlag(ActivityFlags.LaunchedFromHistory)) + if (!callingIntent.Flags.HasFlag(ActivityFlags.LaunchedFromHistory)) { intent.PutExtra("uri", _lastQueriedUri); } diff --git a/src/Android/Accessibility/AccessibilityHelpers.cs b/src/Android/Accessibility/AccessibilityHelpers.cs index c4639059e..fc17557af 100644 --- a/src/Android/Accessibility/AccessibilityHelpers.cs +++ b/src/Android/Accessibility/AccessibilityHelpers.cs @@ -105,7 +105,7 @@ namespace Bit.Droid.Accessibility { 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 }); - foreach(var node in testNodesData) + foreach (var node in testNodesData) { 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) { var uri = string.Concat(Constants.AndroidAppProtocol, root.PackageName); - if(SupportedBrowsers.ContainsKey(root.PackageName)) + if (SupportedBrowsers.ContainsKey(root.PackageName)) { var browser = SupportedBrowsers[root.PackageName]; AccessibilityNodeInfo addressNode = null; - foreach(var uriViewId in browser.UriViewId.Split(",")) + foreach (var uriViewId in browser.UriViewId.Split(",")) { addressNode = root.FindAccessibilityNodeInfosByViewId( $"{root.PackageName}:id/{uriViewId}").FirstOrDefault(); - if(addressNode != null) + if (addressNode != null) { break; } } - if(addressNode != null) + if (addressNode != null) { uri = ExtractUri(uri, addressNode, browser); addressNode.Recycle(); @@ -145,28 +145,28 @@ namespace Bit.Droid.Accessibility public static string ExtractUri(string uri, AccessibilityNodeInfo addressNode, Browser browser) { - if(addressNode?.Text == null) + if (addressNode?.Text == null) { return uri; } - if(addressNode.Text == null) + if (addressNode.Text == null) { return uri; } 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); } - else if(Build.VERSION.SdkInt <= BuildVersionCodes.KitkatWatch) + else if (Build.VERSION.SdkInt <= BuildVersionCodes.KitkatWatch) { var parts = uri.Split(new string[] { ". " }, StringSplitOptions.None); - if(parts.Length > 1) + if (parts.Length > 1) { var urlPart = parts.FirstOrDefault(p => p.StartsWith("http")); - if(urlPart != null) + if (urlPart != null) { uri = urlPart.Trim(); } @@ -181,11 +181,11 @@ namespace Bit.Droid.Accessibility /// public static bool NeedToAutofill(Credentials credentials, string currentUriString) { - if(credentials == null) + if (credentials == null) { 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)) { return lastUri.Host == currentUri.Host; @@ -202,7 +202,7 @@ namespace Bit.Droid.Accessibility IEnumerable passwordNodes) { FillEditText(usernameNode, LastCredentials?.Username); - foreach(var n in passwordNodes) + foreach (var n in passwordNodes) { FillEditText(n, LastCredentials?.Password); } @@ -210,7 +210,7 @@ namespace Bit.Droid.Accessibility public static void FillEditText(AccessibilityNodeInfo editTextNode, string value) { - if(editTextNode == null || value == null) + if (editTextNode == null || value == null) { return; } @@ -223,35 +223,35 @@ namespace Bit.Droid.Accessibility Func condition, bool disposeIfUnused, NodeList nodes = null, int recursionDepth = 0) { - if(nodes == null) + if (nodes == null) { nodes = new NodeList(); } var dispose = disposeIfUnused; - if(n != null && recursionDepth < 100) + if (n != null && recursionDepth < 100) { var add = n.WindowId == e.WindowId && !(n.ViewIdResourceName?.StartsWith(SystemUiPackage) ?? false) && condition(n); - if(add) + if (add) { dispose = false; nodes.Add(n); } - for(var i = 0; i < n.ChildCount; i++) + for (var i = 0; i < n.ChildCount; i++) { var childNode = n.GetChild(i); - if(childNode == null) + if (childNode == null) { continue; } - else if(i > 100) + else if (i > 100) { Android.Util.Log.Info(BitwardenTag, "Too many child iterations."); 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."); } @@ -261,7 +261,7 @@ namespace Bit.Droid.Accessibility } } } - if(dispose) + if (dispose) { n?.Recycle(); n?.Dispose(); @@ -283,9 +283,9 @@ namespace Bit.Droid.Accessibility IEnumerable allEditTexts) { AccessibilityNodeInfo previousEditText = null; - foreach(var editText in allEditTexts) + foreach (var editText in allEditTexts) { - if(editText.Password) + if (editText.Password) { return previousEditText; } @@ -300,7 +300,7 @@ namespace Bit.Droid.Accessibility var usernameEditText = GetUsernameEditTextIfPasswordExists(allEditTexts); var isUsernameEditText = false; - if(usernameEditText != null) + if (usernameEditText != null) { isUsernameEditText = IsSameNode(usernameEditText, e.Source); } @@ -311,7 +311,7 @@ namespace Bit.Droid.Accessibility 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(); } @@ -320,7 +320,7 @@ namespace Bit.Droid.Accessibility public static bool OverlayPermitted() { - if(Build.VERSION.SdkInt >= BuildVersionCodes.M) + if (Build.VERSION.SdkInt >= BuildVersionCodes.M) { return Settings.CanDrawOverlays(Android.App.Application.Context); } @@ -347,7 +347,7 @@ namespace Bit.Droid.Accessibility public static WindowManagerLayoutParams GetOverlayLayoutParams() { WindowManagerTypes windowManagerType; - if(Build.VERSION.SdkInt >= BuildVersionCodes.O) + if (Build.VERSION.SdkInt >= BuildVersionCodes.O) { windowManagerType = WindowManagerTypes.ApplicationOverlay; } @@ -376,7 +376,7 @@ namespace Bit.Droid.Accessibility var anchorViewY = isOverlayAboveAnchor ? anchorViewRect.Top : anchorViewRect.Bottom; anchorViewRect.Dispose(); - if(isOverlayAboveAnchor) + if (isOverlayAboveAnchor) { anchorViewY -= overlayViewHeight; } @@ -389,15 +389,15 @@ namespace Bit.Droid.Accessibility IEnumerable windows, int overlayViewHeight, bool isOverlayAboveAnchor) { Point point = null; - if(anchorNode != null) + if (anchorNode != null) { // Update node's info since this is still a reference from an older event anchorNode.Refresh(); - if(!anchorNode.VisibleToUser) + if (!anchorNode.VisibleToUser) { return new Point(-1, -1); } - if(!anchorNode.Focused) + if (!anchorNode.Focused) { return null; } @@ -406,9 +406,9 @@ namespace Bit.Droid.Accessibility // of visibility var minY = 0; int maxY; - if(windows != null) + if (windows != null) { - if(IsStatusBarExpanded(windows)) + if (IsStatusBarExpanded(windows)) { return new Point(-1, -1); } @@ -417,7 +417,7 @@ namespace Bit.Droid.Accessibility else { var rootNodeHeight = GetNodeHeight(root); - if(rootNodeHeight == -1) + if (rootNodeHeight == -1) { return null; } @@ -425,9 +425,9 @@ namespace Bit.Droid.Accessibility } point = GetOverlayAnchorPosition(anchorNode, overlayViewHeight, isOverlayAboveAnchor); - if(point.Y < minY) + if (point.Y < minY) { - if(isOverlayAboveAnchor) + if (isOverlayAboveAnchor) { // view nearing bounds, anchor to bottom point.X = -1; @@ -440,9 +440,9 @@ namespace Bit.Droid.Accessibility point.Y = -1; } } - else if(point.Y > maxY) + else if (point.Y > maxY) { - if(isOverlayAboveAnchor) + if (isOverlayAboveAnchor) { // view out of bounds, hide overlay point.X = -1; @@ -455,7 +455,7 @@ namespace Bit.Droid.Accessibility 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 // 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 windows) { - if(windows != null && windows.Any()) + if (windows != null && windows.Any()) { 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; break; @@ -489,13 +489,13 @@ namespace Bit.Droid.Accessibility { var appWindowHeight = 0; var nonAppWindowHeight = 0; - if(windows != null) + if (windows != null) { - foreach(var window in windows) + foreach (var window in windows) { var windowRect = new Rect(); window.GetBoundsInScreen(windowRect); - if(window.Type == AccessibilityWindowType.Application) + if (window.Type == AccessibilityWindowType.Application) { appWindowHeight += windowRect.Height(); } @@ -510,7 +510,7 @@ namespace Bit.Droid.Accessibility public static int GetNodeHeight(AccessibilityNodeInfo node) { - if(node == null) + if (node == null) { return -1; } @@ -536,7 +536,7 @@ namespace Bit.Droid.Accessibility var activity = (MainActivity)CrossCurrentActivity.Current.Activity; var barHeight = 0; var resourceId = activity.Resources.GetIdentifier(resName, "dimen", "android"); - if(resourceId > 0) + if (resourceId > 0) { barHeight = activity.Resources.GetDimensionPixelSize(resourceId); } diff --git a/src/Android/Accessibility/AccessibilityService.cs b/src/Android/Accessibility/AccessibilityService.cs index 498bf767c..66d957fd3 100644 --- a/src/Android/Accessibility/AccessibilityService.cs +++ b/src/Android/Accessibility/AccessibilityService.cs @@ -56,7 +56,7 @@ namespace Bit.Droid.Accessibility var settingsTask = LoadSettingsAsync(); _broadcasterService.Subscribe(nameof(AccessibilityService), (message) => { - if(message.Command == "OnAutofillTileClick") + if (message.Command == "OnAutofillTileClick") { var runnable = new Java.Lang.Runnable(OnAutofillTileClick); _handler.PostDelayed(runnable, 250); @@ -76,18 +76,18 @@ namespace Bit.Droid.Accessibility try { var powerManager = GetSystemService(PowerService) as PowerManager; - if(Build.VERSION.SdkInt > BuildVersionCodes.KitkatWatch && !powerManager.IsInteractive) + if (Build.VERSION.SdkInt > BuildVersionCodes.KitkatWatch && !powerManager.IsInteractive) { return; } - else if(Build.VERSION.SdkInt < BuildVersionCodes.Lollipop && !powerManager.IsScreenOn) + else if (Build.VERSION.SdkInt < BuildVersionCodes.Lollipop && !powerManager.IsScreenOn) { return; } - if(SkipPackage(e?.PackageName)) + if (SkipPackage(e?.PackageName)) { - if(e?.PackageName != "com.android.systemui") + if (e?.PackageName != "com.android.systemui") { CancelOverlayPrompt(); } @@ -100,28 +100,28 @@ namespace Bit.Droid.Accessibility var settingsTask = LoadSettingsAsync(); AccessibilityNodeInfo root = null; - switch(e.EventType) + switch (e.EventType) { case EventTypes.ViewFocused: case EventTypes.ViewClicked: - if(e.Source == null || e.PackageName == BitwardenPackage) + if (e.Source == null || e.PackageName == BitwardenPackage) { CancelOverlayPrompt(); break; } root = RootInActiveWindow; - if(root == null || root.PackageName != e.PackageName) + if (root == null || root.PackageName != e.PackageName) { break; } - if(!(e.Source?.Password ?? false) && !AccessibilityHelpers.IsUsernameEditText(root, e)) + if (!(e.Source?.Password ?? false) && !AccessibilityHelpers.IsUsernameEditText(root, e)) { CancelOverlayPrompt(); break; } - if(ScanAndAutofill(root, e)) + if (ScanAndAutofill(root, e)) { CancelOverlayPrompt(); } @@ -132,22 +132,22 @@ namespace Bit.Droid.Accessibility break; case EventTypes.WindowContentChanged: case EventTypes.WindowStateChanged: - if(AccessibilityHelpers.LastCredentials == null) + if (AccessibilityHelpers.LastCredentials == null) { break; } - if(e.PackageName == BitwardenPackage) + if (e.PackageName == BitwardenPackage) { CancelOverlayPrompt(); break; } root = RootInActiveWindow; - if(root == null || root.PackageName != e.PackageName) + if (root == null || root.PackageName != e.PackageName) { break; } - if(ScanAndAutofill(root, e)) + if (ScanAndAutofill(root, e)) { CancelOverlayPrompt(); } @@ -157,7 +157,7 @@ namespace Bit.Droid.Accessibility } } // Suppress exceptions so that service doesn't crash. - catch(Exception ex) + catch (Exception ex) { System.Diagnostics.Debug.WriteLine(">>> {0}: {1}", ex.GetType(), ex.StackTrace); } @@ -172,12 +172,12 @@ namespace Bit.Droid.Accessibility { var filled = false; var passwordNodes = AccessibilityHelpers.GetWindowNodes(root, e, n => n.Password, false); - if(passwordNodes.Count > 0) + if (passwordNodes.Count > 0) { 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); filled = true; @@ -186,7 +186,7 @@ namespace Bit.Droid.Accessibility } AccessibilityHelpers.LastCredentials = null; } - else if(AccessibilityHelpers.LastCredentials != null) + else if (AccessibilityHelpers.LastCredentials != null) { Task.Run(async () => { @@ -203,12 +203,12 @@ namespace Bit.Droid.Accessibility CancelOverlayPrompt(); var root = RootInActiveWindow; - if(root != null && root.PackageName != BitwardenPackage && + if (root != null && root.PackageName != BitwardenPackage && root.PackageName != AccessibilityHelpers.SystemUiPackage && !SkipPackage(root.PackageName)) { var uri = AccessibilityHelpers.GetUri(root); - if(!string.IsNullOrWhiteSpace(uri)) + if (!string.IsNullOrWhiteSpace(uri)) { var intent = new Intent(this, typeof(AccessibilityActivity)); intent.PutExtra("uri", uri); @@ -225,7 +225,7 @@ namespace Bit.Droid.Accessibility { _overlayAnchorObserverRunning = false; - if(_windowManager != null && _overlayView != null) + if (_windowManager != null && _overlayView != null) { try { @@ -240,7 +240,7 @@ namespace Bit.Droid.Accessibility _lastAnchorY = 0; _isOverlayAboveAnchor = false; - if(_anchorNode != null) + if (_anchorNode != null) { _anchorNode.Recycle(); _anchorNode = null; @@ -249,9 +249,9 @@ namespace Bit.Droid.Accessibility 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 // disabled, so only show this toast if they're using accessibility without overlay permission and @@ -262,23 +262,23 @@ namespace Bit.Droid.Accessibility return; } - if(_overlayView != null || _anchorNode != null || _overlayAnchorObserverRunning) + if (_overlayView != null || _anchorNode != null || _overlayAnchorObserverRunning) { CancelOverlayPrompt(); } - if(Java.Lang.JavaSystem.CurrentTimeMillis() - _lastAutoFillTime < 1000) + if (Java.Lang.JavaSystem.CurrentTimeMillis() - _lastAutoFillTime < 1000) { return; } var uri = AccessibilityHelpers.GetUri(root); 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( string.Format("{0}://{1}", parsedUri.Scheme, parsedUri.Host)); @@ -289,7 +289,7 @@ namespace Bit.Droid.Accessibility } } } - if(!fillable) + if (!fillable) { return; } @@ -314,7 +314,7 @@ namespace Bit.Droid.Accessibility layoutParams.X = anchorPosition.X; layoutParams.Y = anchorPosition.Y; - if(_windowManager == null) + if (_windowManager == null) { _windowManager = GetSystemService(WindowService).JavaCast(); } @@ -333,7 +333,7 @@ namespace Bit.Droid.Accessibility private void StartOverlayAnchorObserver() { - if(_overlayAnchorObserverRunning) + if (_overlayAnchorObserverRunning) { return; } @@ -341,7 +341,7 @@ namespace Bit.Droid.Accessibility _overlayAnchorObserverRunning = true; _overlayAnchorObserverRunnable = new Java.Lang.Runnable(() => { - if(_overlayAnchorObserverRunning) + if (_overlayAnchorObserverRunning) { AdjustOverlayForScroll(); _handler.PostDelayed(_overlayAnchorObserverRunnable, 250); @@ -353,7 +353,7 @@ namespace Bit.Droid.Accessibility private void AdjustOverlayForScroll() { - if(_overlayView == null || _anchorNode == null) + if (_overlayView == null || _anchorNode == null) { CancelOverlayPrompt(); return; @@ -361,42 +361,42 @@ namespace Bit.Droid.Accessibility var root = RootInActiveWindow; IEnumerable windows = null; - if(Build.VERSION.SdkInt > BuildVersionCodes.Kitkat) + if (Build.VERSION.SdkInt > BuildVersionCodes.Kitkat) { windows = Windows; } var anchorPosition = AccessibilityHelpers.GetOverlayAnchorPosition(_anchorNode, root, windows, _overlayViewHeight, _isOverlayAboveAnchor); - if(anchorPosition == null) + if (anchorPosition == null) { CancelOverlayPrompt(); 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; System.Diagnostics.Debug.WriteLine(">>> Accessibility Overlay View Hidden"); } return; } - else if(anchorPosition.X == -1) + else if (anchorPosition.X == -1) { _isOverlayAboveAnchor = false; System.Diagnostics.Debug.WriteLine(">>> Accessibility Overlay View Below Anchor"); return; } - else if(anchorPosition.Y == -1) + else if (anchorPosition.Y == -1) { _isOverlayAboveAnchor = true; System.Diagnostics.Debug.WriteLine(">>> Accessibility Overlay View Above Anchor"); 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; } @@ -412,7 +412,7 @@ namespace Bit.Droid.Accessibility _windowManager.UpdateViewLayout(_overlayView, layoutParams); - if(_overlayView.Visibility != ViewStates.Visible) + if (_overlayView.Visibility != ViewStates.Visible) { _overlayView.Visibility = ViewStates.Visible; } @@ -423,13 +423,13 @@ namespace Bit.Droid.Accessibility private bool SkipPackage(string eventPackageName) { - if(string.IsNullOrWhiteSpace(eventPackageName) || + if (string.IsNullOrWhiteSpace(eventPackageName) || AccessibilityHelpers.FilteredPackageNames.Contains(eventPackageName) || eventPackageName.Contains("launcher")) { return true; } - if(_launcherPackageNames == null || _lastLauncherSetBuilt == null || + if (_launcherPackageNames == null || _lastLauncherSetBuilt == null || (DateTime.Now - _lastLauncherSetBuilt.Value) > _rebuildLauncherSpan) { // refresh launcher list every now and then @@ -444,11 +444,11 @@ namespace Bit.Droid.Accessibility private void LoadServices() { - if(_storageService == null) + if (_storageService == null) { _storageService = ServiceContainer.Resolve("storageService"); } - if(_broadcasterService == null) + if (_broadcasterService == null) { _broadcasterService = ServiceContainer.Resolve("broadcasterService"); } @@ -457,11 +457,11 @@ namespace Bit.Droid.Accessibility private async Task LoadSettingsAsync() { var now = DateTime.UtcNow; - if(_lastSettingsReload == null || (now - _lastSettingsReload.Value) > _settingsReloadSpan) + if (_lastSettingsReload == null || (now - _lastSettingsReload.Value) > _settingsReloadSpan) { _lastSettingsReload = now; var uris = await _storageService.GetAsync>(Constants.AutofillBlacklistedUrisKey); - if(uris != null) + if (uris != null) { _blacklistedUris = new HashSet(uris); } diff --git a/src/Android/Accessibility/NodeList.cs b/src/Android/Accessibility/NodeList.cs index 13a1fbc83..631b7502a 100644 --- a/src/Android/Accessibility/NodeList.cs +++ b/src/Android/Accessibility/NodeList.cs @@ -8,7 +8,7 @@ namespace Bit.Droid.Accessibility { public void Dispose() { - foreach(var item in this) + foreach (var item in this) { item.Recycle(); item.Dispose(); diff --git a/src/Android/Autofill/AutofillHelpers.cs b/src/Android/Autofill/AutofillHelpers.cs index fff8708bd..3deb5f4f2 100644 --- a/src/Android/Autofill/AutofillHelpers.cs +++ b/src/Android/Autofill/AutofillHelpers.cs @@ -75,17 +75,17 @@ namespace Bit.Droid.Autofill public static async Task> GetFillItemsAsync(Parser parser, ICipherService cipherService) { - if(parser.FieldCollection.FillableForLogin) + if (parser.FieldCollection.FillableForLogin) { 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(); allCiphers.AddRange(ciphers.Item2.ToList()); return allCiphers.Select(c => new FilledItem(c)).ToList(); } } - else if(parser.FieldCollection.FillableForCard) + else if (parser.FieldCollection.FillableForCard) { var ciphers = await cipherService.GetAllDecryptedAsync(); 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 items, bool locked) { 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); - if(dataset != null) + if (dataset != null) { responseBuilder.AddDataset(dataset); } @@ -118,7 +118,7 @@ namespace Bit.Droid.Autofill { var datasetBuilder = new Dataset.Builder( BuildListView(filledItem.Name, filledItem.Subtitle, filledItem.Icon, context)); - if(filledItem.ApplyToFields(fields, datasetBuilder)) + if (filledItem.ApplyToFields(fields, datasetBuilder)) { return datasetBuilder.Build(); } @@ -129,15 +129,15 @@ namespace Bit.Droid.Autofill { var intent = new Intent(context, typeof(MainActivity)); intent.PutExtra("autofillFramework", true); - if(fields.FillableForLogin) + if (fields.FillableForLogin) { intent.PutExtra("autofillFrameworkFillType", (int)CipherType.Login); } - else if(fields.FillableForCard) + else if (fields.FillableForCard) { intent.PutExtra("autofillFrameworkFillType", (int)CipherType.Card); } - else if(fields.FillableForIdentity) + else if (fields.FillableForIdentity) { intent.PutExtra("autofillFrameworkFillType", (int)CipherType.Identity); } @@ -159,7 +159,7 @@ namespace Bit.Droid.Autofill datasetBuilder.SetAuthentication(pendingIntent.IntentSender); // 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")); } @@ -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 // masked values. var compatBrowser = CompatBrowsers.Contains(parser.PackageName); - if(compatBrowser && fields.SaveType == SaveDataType.Password) + if (compatBrowser && fields.SaveType == SaveDataType.Password) { return; } var requiredIds = fields.GetRequiredSaveFields(); - if(fields.SaveType == SaveDataType.Generic || requiredIds.Length == 0) + if (fields.SaveType == SaveDataType.Generic || requiredIds.Length == 0) { return; } var saveBuilder = new SaveInfo.Builder(fields.SaveType, requiredIds); var optionalIds = fields.GetOptionalSaveIds(); - if(optionalIds.Length > 0) + if (optionalIds.Length > 0) { saveBuilder.SetOptionalIds(optionalIds); } - if(compatBrowser) + if (compatBrowser) { saveBuilder.SetFlags(SaveFlags.SaveOnAllViewsInvisible); } diff --git a/src/Android/Autofill/AutofillService.cs b/src/Android/Autofill/AutofillService.cs index 893e22314..1062c2274 100644 --- a/src/Android/Autofill/AutofillService.cs +++ b/src/Android/Autofill/AutofillService.cs @@ -28,7 +28,7 @@ namespace Bit.Droid.Autofill FillCallback callback) { var structure = request.FillContexts?.LastOrDefault()?.Structure; - if(structure == null) + if (structure == null) { return; } @@ -36,27 +36,27 @@ namespace Bit.Droid.Autofill var parser = new Parser(structure, ApplicationContext); parser.Parse(); - if(_storageService == null) + if (_storageService == null) { _storageService = ServiceContainer.Resolve("storageService"); } var shouldAutofill = await parser.ShouldAutofillAsync(_storageService); - if(!shouldAutofill) + if (!shouldAutofill) { return; } - if(_lockService == null) + if (_lockService == null) { _lockService = ServiceContainer.Resolve("lockService"); } List items = null; var locked = await _lockService.IsLockedAsync(); - if(!locked) + if (!locked) { - if(_cipherService == null) + if (_cipherService == null) { _cipherService = ServiceContainer.Resolve("cipherService"); } @@ -71,18 +71,18 @@ namespace Bit.Droid.Autofill public async override void OnSaveRequest(SaveRequest request, SaveCallback callback) { var structure = request.FillContexts?.LastOrDefault()?.Structure; - if(structure == null) + if (structure == null) { return; } - if(_storageService == null) + if (_storageService == null) { _storageService = ServiceContainer.Resolve("storageService"); } var disableSavePrompt = await _storageService.GetAsync(Constants.AutofillDisableSavePromptKey); - if(disableSavePrompt.GetValueOrDefault()) + if (disableSavePrompt.GetValueOrDefault()) { return; } @@ -91,7 +91,7 @@ namespace Bit.Droid.Autofill parser.Parse(); var savedItem = parser.FieldCollection.GetSavedItem(); - if(savedItem == null) + if (savedItem == null) { Toast.MakeText(this, "Unable to save this form.", ToastLength.Short).Show(); return; @@ -102,7 +102,7 @@ namespace Bit.Droid.Autofill intent.PutExtra("autofillFramework", true); intent.PutExtra("autofillFrameworkSave", true); intent.PutExtra("autofillFrameworkType", (int)savedItem.Type); - switch(savedItem.Type) + switch (savedItem.Type) { case CipherType.Login: intent.PutExtra("autofillFrameworkName", parser.Uri diff --git a/src/Android/Autofill/Field.cs b/src/Android/Autofill/Field.cs index 34a6d664c..1ea906e48 100644 --- a/src/Android/Autofill/Field.cs +++ b/src/Android/Autofill/Field.cs @@ -31,26 +31,26 @@ namespace Bit.Droid.Autofill HtmlInfo = node.HtmlInfo; Node = node; - if(node.AutofillValue != null) + if (node.AutofillValue != null) { - if(node.AutofillValue.IsList) + if (node.AutofillValue.IsList) { var autofillOptions = node.GetAutofillOptions(); - if(autofillOptions != null && autofillOptions.Length > 0) + if (autofillOptions != null && autofillOptions.Length > 0) { ListValue = node.AutofillValue.ListValue; TextValue = autofillOptions[node.AutofillValue.ListValue]; } } - else if(node.AutofillValue.IsDate) + else if (node.AutofillValue.IsDate) { DateValue = node.AutofillValue.DateValue; } - else if(node.AutofillValue.IsText) + else if (node.AutofillValue.IsText) { TextValue = node.AutofillValue.TextValue; } - else if(node.AutofillValue.IsToggle) + else if (node.AutofillValue.IsToggle) { ToggleValue = node.AutofillValue.ToggleValue; } @@ -93,20 +93,20 @@ namespace Bit.Droid.Autofill public override bool Equals(object obj) { - if(this == obj) + if (this == obj) { return true; } - if(obj == null || GetType() != obj.GetType()) + if (obj == null || GetType() != obj.GetType()) { return false; } 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; } - if(DateValue != null ? !DateValue.Equals(field.DateValue) : field.DateValue != null) + if (DateValue != null ? !DateValue.Equals(field.DateValue) : field.DateValue != null) { return false; } @@ -128,7 +128,7 @@ namespace Bit.Droid.Autofill private static bool IsValidHint(string hint) { - switch(hint) + switch (hint) { case View.AutofillHintCreditCardExpirationDate: case View.AutofillHintCreditCardExpirationDay: @@ -152,14 +152,14 @@ namespace Bit.Droid.Autofill private void UpdateSaveTypeFromHints() { SaveType = SaveDataType.Generic; - if(_hints == null) + if (_hints == null) { return; } - foreach(var hint in _hints) + foreach (var hint in _hints) { - switch(hint) + switch (hint) { case View.AutofillHintCreditCardExpirationDate: case View.AutofillHintCreditCardExpirationDay: diff --git a/src/Android/Autofill/FieldCollection.cs b/src/Android/Autofill/FieldCollection.cs index 84e6f48db..3c2e35358 100644 --- a/src/Android/Autofill/FieldCollection.cs +++ b/src/Android/Autofill/FieldCollection.cs @@ -19,11 +19,11 @@ namespace Bit.Droid.Autofill { get { - if(FillableForLogin) + if (FillableForLogin) { return SaveDataType.Password; } - else if(FillableForCard) + else if (FillableForCard) { return SaveDataType.CreditCard; } @@ -43,14 +43,14 @@ namespace Bit.Droid.Autofill { get { - if(_passwordFields != null) + if (_passwordFields != null) { return _passwordFields; } - if(Hints.Any()) + if (Hints.Any()) { _passwordFields = new List(); - if(HintToFieldsMap.ContainsKey(View.AutofillHintPassword)) + if (HintToFieldsMap.ContainsKey(View.AutofillHintPassword)) { _passwordFields.AddRange(HintToFieldsMap[View.AutofillHintPassword]); } @@ -58,7 +58,7 @@ namespace Bit.Droid.Autofill else { _passwordFields = Fields.Where(f => FieldIsPassword(f)).ToList(); - if(!_passwordFields.Any()) + if (!_passwordFields.Any()) { _passwordFields = Fields.Where(f => FieldHasPasswordTerms(f)).ToList(); } @@ -71,29 +71,29 @@ namespace Bit.Droid.Autofill { get { - if(_usernameFields != null) + if (_usernameFields != null) { return _usernameFields; } _usernameFields = new List(); - if(Hints.Any()) + if (Hints.Any()) { - if(HintToFieldsMap.ContainsKey(View.AutofillHintEmailAddress)) + if (HintToFieldsMap.ContainsKey(View.AutofillHintEmailAddress)) { _usernameFields.AddRange(HintToFieldsMap[View.AutofillHintEmailAddress]); } - if(HintToFieldsMap.ContainsKey(View.AutofillHintUsername)) + if (HintToFieldsMap.ContainsKey(View.AutofillHintUsername)) { _usernameFields.AddRange(HintToFieldsMap[View.AutofillHintUsername]); } } else { - foreach(var passwordField in PasswordFields) + foreach (var passwordField in PasswordFields) { var usernameField = Fields.TakeWhile(f => f.AutofillId != passwordField.AutofillId) .LastOrDefault(); - if(usernameField != null) + if (usernameField != null) { _usernameFields.Add(usernameField); } @@ -127,7 +127,7 @@ namespace Bit.Droid.Autofill public void Add(Field field) { - if(field == null || FieldTrackingIds.Contains(field.TrackingId)) + if (field == null || FieldTrackingIds.Contains(field.TrackingId)) { return; } @@ -137,16 +137,16 @@ namespace Bit.Droid.Autofill Fields.Add(field); 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); - if(field.Focused) + if (field.Focused) { FocusedHints.Add(hint); } - if(!HintToFieldsMap.ContainsKey(hint)) + if (!HintToFieldsMap.ContainsKey(hint)) { HintToFieldsMap.Add(hint, new List()); } @@ -157,10 +157,10 @@ namespace Bit.Droid.Autofill public SavedItem GetSavedItem() { - if(SaveType == SaveDataType.Password) + if (SaveType == SaveDataType.Password) { var passwordField = PasswordFields.FirstOrDefault(f => !string.IsNullOrWhiteSpace(f.TextValue)); - if(passwordField == null) + if (passwordField == null) { return null; } @@ -178,7 +178,7 @@ namespace Bit.Droid.Autofill savedItem.Login.Username = GetFieldValue(usernameField); return savedItem; } - else if(SaveType == SaveDataType.CreditCard) + else if (SaveType == SaveDataType.CreditCard) { var savedItem = new SavedItem { @@ -199,26 +199,26 @@ namespace Bit.Droid.Autofill public AutofillId[] GetOptionalSaveIds() { - if(SaveType == SaveDataType.Password) + if (SaveType == SaveDataType.Password) { return UsernameFields.Select(f => f.AutofillId).ToArray(); } - else if(SaveType == SaveDataType.CreditCard) + else if (SaveType == SaveDataType.CreditCard) { var fieldList = new List(); - if(HintToFieldsMap.ContainsKey(View.AutofillHintCreditCardSecurityCode)) + if (HintToFieldsMap.ContainsKey(View.AutofillHintCreditCardSecurityCode)) { fieldList.AddRange(HintToFieldsMap[View.AutofillHintCreditCardSecurityCode]); } - if(HintToFieldsMap.ContainsKey(View.AutofillHintCreditCardExpirationYear)) + if (HintToFieldsMap.ContainsKey(View.AutofillHintCreditCardExpirationYear)) { fieldList.AddRange(HintToFieldsMap[View.AutofillHintCreditCardExpirationYear]); } - if(HintToFieldsMap.ContainsKey(View.AutofillHintCreditCardExpirationMonth)) + if (HintToFieldsMap.ContainsKey(View.AutofillHintCreditCardExpirationMonth)) { fieldList.AddRange(HintToFieldsMap[View.AutofillHintCreditCardExpirationMonth]); } - if(HintToFieldsMap.ContainsKey(View.AutofillHintName)) + if (HintToFieldsMap.ContainsKey(View.AutofillHintName)) { fieldList.AddRange(HintToFieldsMap[View.AutofillHintName]); } @@ -229,11 +229,11 @@ namespace Bit.Droid.Autofill public AutofillId[] GetRequiredSaveFields() { - if(SaveType == SaveDataType.Password) + if (SaveType == SaveDataType.Password) { 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(); } @@ -247,12 +247,12 @@ namespace Bit.Droid.Autofill 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); - if(!string.IsNullOrWhiteSpace(val)) + if (!string.IsNullOrWhiteSpace(val)) { return val; } @@ -263,30 +263,30 @@ namespace Bit.Droid.Autofill private string GetFieldValue(Field field, bool monthValue = false) { - if(field == null) + if (field == 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(); } - else if(field.AutofillOptions.Count == 12) + else if (field.AutofillOptions.Count == 12) { return (field.ListValue + 1).ToString(); } } return field.TextValue; } - else if(field.DateValue.HasValue) + else if (field.DateValue.HasValue) { return field.DateValue.Value.ToString(); } - else if(field.ToggleValue.HasValue) + else if (field.ToggleValue.HasValue) { return field.ToggleValue.Value.ToString(); } @@ -300,20 +300,20 @@ namespace Bit.Droid.Autofill f.InputType.HasFlag(InputTypes.TextVariationWebPassword); // 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)) { 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)) { - foreach(var a in f.HtmlInfo.Attributes) + foreach (var a in f.HtmlInfo.Attributes) { var key = a.First 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; } @@ -331,7 +331,7 @@ namespace Bit.Droid.Autofill private bool ValueContainsAnyTerms(string value, HashSet terms) { - if(string.IsNullOrWhiteSpace(value)) + if (string.IsNullOrWhiteSpace(value)) { return false; } diff --git a/src/Android/Autofill/FilledItem.cs b/src/Android/Autofill/FilledItem.cs index ce2aa2671..d4414fa65 100644 --- a/src/Android/Autofill/FilledItem.cs +++ b/src/Android/Autofill/FilledItem.cs @@ -27,7 +27,7 @@ namespace Bit.Droid.Autofill Type = cipher.Type; Subtitle = cipher.SubTitle; - switch(Type) + switch (Type) { case CipherType.Login: Icon = Resource.Drawable.login; @@ -62,32 +62,32 @@ namespace Bit.Droid.Autofill public bool ApplyToFields(FieldCollection fieldCollection, Dataset.Builder datasetBuilder) { - if(!fieldCollection?.Fields.Any() ?? true) + if (!fieldCollection?.Fields.Any() ?? true) { return 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); - if(val != null) + if (val != null) { setValues = true; 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); - if(val != null) + if (val != null) { setValues = true; 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)) { setValues = true; } - if(ApplyValue(datasetBuilder, fieldCollection, Android.Views.View.AutofillHintCreditCardSecurityCode, + if (ApplyValue(datasetBuilder, fieldCollection, Android.Views.View.AutofillHintCreditCardSecurityCode, _cardCode)) { setValues = true; } - if(ApplyValue(datasetBuilder, fieldCollection, + if (ApplyValue(datasetBuilder, fieldCollection, Android.Views.View.AutofillHintCreditCardExpirationMonth, _cardExpMonth, true)) { setValues = true; } - if(ApplyValue(datasetBuilder, fieldCollection, Android.Views.View.AutofillHintCreditCardExpirationYear, + if (ApplyValue(datasetBuilder, fieldCollection, Android.Views.View.AutofillHintCreditCardExpirationYear, _cardExpYear)) { setValues = true; } - if(ApplyValue(datasetBuilder, fieldCollection, Android.Views.View.AutofillHintName, _cardName)) + if (ApplyValue(datasetBuilder, fieldCollection, Android.Views.View.AutofillHintName, _cardName)) { 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; } - if(ApplyValue(datasetBuilder, fieldCollection, Android.Views.View.AutofillHintEmailAddress, _idEmail)) + if (ApplyValue(datasetBuilder, fieldCollection, Android.Views.View.AutofillHintEmailAddress, _idEmail)) { setValues = true; } - if(ApplyValue(datasetBuilder, fieldCollection, Android.Views.View.AutofillHintUsername, + if (ApplyValue(datasetBuilder, fieldCollection, Android.Views.View.AutofillHintUsername, _idUsername)) { setValues = true; } - if(ApplyValue(datasetBuilder, fieldCollection, Android.Views.View.AutofillHintPostalAddress, + if (ApplyValue(datasetBuilder, fieldCollection, Android.Views.View.AutofillHintPostalAddress, _idAddress)) { setValues = true; } - if(ApplyValue(datasetBuilder, fieldCollection, Android.Views.View.AutofillHintPostalCode, + if (ApplyValue(datasetBuilder, fieldCollection, Android.Views.View.AutofillHintPostalCode, _idPostalCode)) { setValues = true; } - if(ApplyValue(datasetBuilder, fieldCollection, Android.Views.View.AutofillHintName, Subtitle)) + if (ApplyValue(datasetBuilder, fieldCollection, Android.Views.View.AutofillHintName, Subtitle)) { setValues = true; } @@ -159,12 +159,12 @@ namespace Bit.Droid.Autofill string hint, string value, bool monthValue = 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); - if(val != null) + if (val != null) { setValues = true; builder.SetValue(f.AutofillId, val); @@ -176,31 +176,31 @@ namespace Bit.Droid.Autofill private static AutofillValue ApplyValue(Field field, string value, bool monthValue = false) { - switch(field.AutofillType) + switch (field.AutofillType) { case AutofillType.Date: - if(long.TryParse(value, out long dateValue)) + if (long.TryParse(value, out long dateValue)) { return AutofillValue.ForDate(dateValue); } break; 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); } - else if(field.AutofillOptions.Count >= monthIndex) + else if (field.AutofillOptions.Count >= monthIndex) { 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); } @@ -210,7 +210,7 @@ namespace Bit.Droid.Autofill case AutofillType.Text: return AutofillValue.ForText(value); case AutofillType.Toggle: - if(bool.TryParse(value, out bool toggleValue)) + if (bool.TryParse(value, out bool toggleValue)) { return AutofillValue.ForToggle(toggleValue); } diff --git a/src/Android/Autofill/Parser.cs b/src/Android/Autofill/Parser.cs index f46758184..d097d4d1f 100644 --- a/src/Android/Autofill/Parser.cs +++ b/src/Android/Autofill/Parser.cs @@ -33,16 +33,16 @@ namespace Bit.Droid.Autofill { get { - if(!string.IsNullOrWhiteSpace(_uri)) + if (!string.IsNullOrWhiteSpace(_uri)) { return _uri; } var websiteNull = string.IsNullOrWhiteSpace(Website); - if(websiteNull && string.IsNullOrWhiteSpace(PackageName)) + if (websiteNull && string.IsNullOrWhiteSpace(PackageName)) { _uri = null; } - else if(!websiteNull) + else if (!websiteNull) { _uri = Website; } @@ -59,7 +59,7 @@ namespace Bit.Droid.Autofill get => _packageName; set { - if(string.IsNullOrWhiteSpace(value)) + if (string.IsNullOrWhiteSpace(value)) { _packageName = _uri = null; } @@ -72,7 +72,7 @@ namespace Bit.Droid.Autofill get => _website; set { - if(string.IsNullOrWhiteSpace(value)) + if (string.IsNullOrWhiteSpace(value)) { _website = _uri = null; } @@ -84,10 +84,10 @@ namespace Bit.Droid.Autofill { var fillable = !string.IsNullOrWhiteSpace(Uri) && !AutofillHelpers.BlacklistedUris.Contains(Uri) && FieldCollection != null && FieldCollection.Fillable; - if(fillable) + if (fillable) { var blacklistedUris = await storageService.GetAsync>(Constants.AutofillBlacklistedUrisKey); - if(blacklistedUris != null && blacklistedUris.Count > 0) + if (blacklistedUris != null && blacklistedUris.Count > 0) { fillable = !new HashSet(blacklistedUris).Contains(Uri); } @@ -98,20 +98,20 @@ namespace Bit.Droid.Autofill public void Parse() { string titlePackageId = null; - for(var i = 0; i < _structure.WindowNodeCount; i++) + for (var i = 0; i < _structure.WindowNodeCount; i++) { var node = _structure.GetWindowNodeAt(i); - if(i == 0) + if (i == 0) { titlePackageId = GetTitlePackageId(node); } ParseNode(node.RootViewNode); } - if(string.IsNullOrWhiteSpace(PackageName) && string.IsNullOrWhiteSpace(Website)) + if (string.IsNullOrWhiteSpace(PackageName) && string.IsNullOrWhiteSpace(Website)) { PackageName = titlePackageId; } - if(!AutofillHelpers.TrustedBrowsers.Contains(PackageName) && + if (!AutofillHelpers.TrustedBrowsers.Contains(PackageName) && !AutofillHelpers.CompatBrowsers.Contains(PackageName)) { Website = null; @@ -123,7 +123,7 @@ namespace Bit.Droid.Autofill SetPackageAndDomain(node); var hints = node.GetAutofillHints(); 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)); } @@ -132,7 +132,7 @@ namespace Bit.Droid.Autofill 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)); } @@ -140,15 +140,15 @@ namespace Bit.Droid.Autofill 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)) { PackageName = node.IdPackage; } - if(string.IsNullOrWhiteSpace(Website) && !string.IsNullOrWhiteSpace(node.WebDomain)) + if (string.IsNullOrWhiteSpace(Website) && !string.IsNullOrWhiteSpace(node.WebDomain)) { var scheme = "http"; - if((int)Build.VERSION.SdkInt >= 28) + if ((int)Build.VERSION.SdkInt >= 28) { scheme = node.WebScheme; } @@ -158,13 +158,13 @@ namespace Bit.Droid.Autofill private string GetTitlePackageId(WindowNode node) { - if(node != null && !string.IsNullOrWhiteSpace(node.Title)) + if (node != null && !string.IsNullOrWhiteSpace(node.Title)) { var slashPosition = node.Title.IndexOf('/'); - if(slashPosition > -1) + if (slashPosition > -1) { var packageId = node.Title.Substring(0, slashPosition); - if(packageId.Contains(".")) + if (packageId.Contains(".")) { return packageId; } diff --git a/src/Android/Effects/FabShadowEffect.cs b/src/Android/Effects/FabShadowEffect.cs index 83ce27c63..ad0083d37 100644 --- a/src/Android/Effects/FabShadowEffect.cs +++ b/src/Android/Effects/FabShadowEffect.cs @@ -10,7 +10,7 @@ namespace Bit.Droid.Effects { protected override void OnAttached () { - if(Control is Android.Widget.Button button) + if (Control is Android.Widget.Button button) { var gd = new GradientDrawable(); gd.SetColor(((Color)Application.Current.Resources["FabColor"]).ToAndroid()); diff --git a/src/Android/Effects/FixedSizeEffect.cs b/src/Android/Effects/FixedSizeEffect.cs index 0143d2dd3..98c997e18 100644 --- a/src/Android/Effects/FixedSizeEffect.cs +++ b/src/Android/Effects/FixedSizeEffect.cs @@ -10,7 +10,7 @@ namespace Bit.Droid.Effects { 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); } diff --git a/src/Android/Effects/SelectableLabelEffect.cs b/src/Android/Effects/SelectableLabelEffect.cs index ded6eedd3..e14a39526 100644 --- a/src/Android/Effects/SelectableLabelEffect.cs +++ b/src/Android/Effects/SelectableLabelEffect.cs @@ -10,7 +10,7 @@ namespace Bit.Droid.Effects { protected override void OnAttached() { - if(Control is TextView textView) + if (Control is TextView textView) { textView.SetTextIsSelectable(true); } diff --git a/src/Android/Effects/TabBarEffect.cs b/src/Android/Effects/TabBarEffect.cs index c2e0a7f4f..e684ef452 100644 --- a/src/Android/Effects/TabBarEffect.cs +++ b/src/Android/Effects/TabBarEffect.cs @@ -12,11 +12,11 @@ namespace Bit.Droid.Effects { protected override void OnAttached() { - if(!(Container.GetChildAt(0) is ViewGroup layout)) + if (!(Container.GetChildAt(0) is ViewGroup layout)) { return; } - if(!(layout.GetChildAt(1) is BottomNavigationView bottomNavigationView)) + if (!(layout.GetChildAt(1) is BottomNavigationView bottomNavigationView)) { return; } diff --git a/src/Android/MainActivity.cs b/src/Android/MainActivity.cs index d30cc0988..0553443b4 100644 --- a/src/Android/MainActivity.cs +++ b/src/Android/MainActivity.cs @@ -73,7 +73,7 @@ namespace Bit.Droid UpdateTheme(ThemeManager.GetTheme(true)); base.OnCreate(savedInstanceState); - if(!CoreHelpers.InDebugMode()) + if (!CoreHelpers.InDebugMode()) { Window.AddFlags(Android.Views.WindowManagerFlags.Secure); } @@ -90,7 +90,7 @@ namespace Bit.Droid _broadcasterService.Subscribe(_activityKey, (message) => { - if(message.Command == "scheduleLockTimer") + if (message.Command == "scheduleLockTimer") { var alarmManager = GetSystemService(AlarmService) as AlarmManager; var lockOptionMinutes = (int)message.Data; @@ -98,36 +98,36 @@ namespace Bit.Droid var triggerMs = Java.Lang.JavaSystem.CurrentTimeMillis() + lockOptionMs + 10; alarmManager.Set(AlarmType.RtcWakeup, triggerMs, _lockAlarmPendingIntent); } - else if(message.Command == "cancelLockTimer") + else if (message.Command == "cancelLockTimer") { var alarmManager = GetSystemService(AlarmService) as AlarmManager; alarmManager.Cancel(_lockAlarmPendingIntent); } - else if(message.Command == "startEventTimer") + else if (message.Command == "startEventTimer") { StartEventAlarm(); } - else if(message.Command == "stopEventTimer") + else if (message.Command == "stopEventTimer") { var task = StopEventAlarmAsync(); } - else if(message.Command == "finishMainActivity") + else if (message.Command == "finishMainActivity") { Xamarin.Forms.Device.BeginInvokeOnMainThread(() => Finish()); } - else if(message.Command == "listenYubiKeyOTP") + else if (message.Command == "listenYubiKeyOTP") { ListenYubiKey((bool)message.Data); } - else if(message.Command == "updatedTheme") + else if (message.Command == "updatedTheme") { RestartApp(); } - else if(message.Command == "exit") + else if (message.Command == "exit") { ExitApp(); } - else if(message.Command == "copiedToClipboard") + else if (message.Command == "copiedToClipboard") { var task = ClearClipboardAlarmAsync(message.Data as Tuple); } @@ -143,7 +143,7 @@ namespace Bit.Droid protected override void OnResume() { base.OnResume(); - if(_deviceActionService.SupportsNfc()) + if (_deviceActionService.SupportsNfc()) { try { @@ -157,18 +157,18 @@ namespace Bit.Droid protected override void OnNewIntent(Intent intent) { base.OnNewIntent(intent); - if(intent.GetBooleanExtra("generatorTile", false)) + if (intent.GetBooleanExtra("generatorTile", false)) { _messagingService.Send("popAllAndGoToTabGenerator"); - if(_appOptions != null) + if (_appOptions != null) { _appOptions.GeneratorTile = true; } } - if(intent.GetBooleanExtra("myVaultTile", false)) + if (intent.GetBooleanExtra("myVaultTile", false)) { _messagingService.Send("popAllAndGoToTabMyVault"); - if(_appOptions != null) + if (_appOptions != null) { _appOptions.MyVaultTile = true; } @@ -182,9 +182,9 @@ namespace Bit.Droid public async override void OnRequestPermissionsResult(int requestCode, string[] permissions, [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"); } @@ -201,12 +201,12 @@ namespace Bit.Droid protected override void OnActivityResult(int requestCode, Result resultCode, Intent data) { - if(resultCode == Result.Ok && + if (resultCode == Result.Ok && (requestCode == Constants.SelectFileRequestCode || requestCode == Constants.SaveFileRequestCode)) { Android.Net.Uri uri = null; string fileName = null; - if(data != null && data.Data != null) + if (data != null && data.Data != null) { uri = data.Data; fileName = AndroidHelpers.GetFileName(ApplicationContext, uri); @@ -219,12 +219,12 @@ namespace Bit.Droid fileName = $"photo_{DateTime.UtcNow.ToString("yyyyMMddHHmmss")}.jpg"; } - if(uri == null) + if (uri == null) { return; } - if(requestCode == Constants.SaveFileRequestCode) + if (requestCode == Constants.SaveFileRequestCode) { _messagingService.Send("selectSaveFileResult", new Tuple(uri.ToString(), fileName)); @@ -233,15 +233,15 @@ namespace Bit.Droid try { - using(var stream = ContentResolver.OpenInputStream(uri)) - using(var memoryStream = new MemoryStream()) + using (var stream = ContentResolver.OpenInputStream(uri)) + using (var memoryStream = new MemoryStream()) { stream.CopyTo(memoryStream); _messagingService.Send("selectFileResult", new Tuple(memoryStream.ToArray(), fileName ?? "unknown_file_name")); } } - catch(Java.IO.FileNotFoundException) + catch (Java.IO.FileNotFoundException) { return; } @@ -256,12 +256,12 @@ namespace Bit.Droid private void ListenYubiKey(bool listen) { - if(!_deviceActionService.SupportsNfc()) + if (!_deviceActionService.SupportsNfc()) { return; } var adapter = NfcAdapter.GetDefaultAdapter(this); - if(listen) + if (listen) { var intent = new Intent(this, Class); intent.AddFlags(ActivityFlags.SingleTop); @@ -298,11 +298,11 @@ namespace Bit.Droid FromAutofillFramework = Intent.GetBooleanExtra("autofillFramework", false) }; var fillType = Intent.GetIntExtra("autofillFrameworkFillType", 0); - if(fillType > 0) + if (fillType > 0) { options.FillType = (CipherType)fillType; } - if(Intent.GetBooleanExtra("autofillFrameworkSave", false)) + if (Intent.GetBooleanExtra("autofillFrameworkSave", false)) { options.SaveType = (CipherType)Intent.GetIntExtra("autofillFrameworkType", 0); options.SaveName = Intent.GetStringExtra("autofillFrameworkName"); @@ -319,12 +319,12 @@ namespace Bit.Droid private void ParseYubiKey(string data) { - if(data == null) + if (data == null) { return; } var otpMatch = _otpPattern.Matcher(data); - if(otpMatch.Matches()) + if (otpMatch.Matches()) { var otp = otpMatch.Group(1); _messagingService.Send("gotYubiKeyOTP", otp); @@ -333,15 +333,15 @@ namespace Bit.Droid private void UpdateTheme(string theme) { - if(theme == "dark") + if (theme == "dark") { SetTheme(Resource.Style.DarkTheme); } - else if(theme == "black") + else if (theme == "black") { SetTheme(Resource.Style.BlackTheme); } - else if(theme == "nord") + else if (theme == "nord") { SetTheme(Resource.Style.NordTheme); } @@ -369,20 +369,20 @@ namespace Bit.Droid private async Task ClearClipboardAlarmAsync(Tuple data) { - if(data.Item3) + if (data.Item3) { return; } var clearMs = data.Item2; - if(clearMs == null) + if (clearMs == null) { var clearSeconds = await _storageService.GetAsync(Constants.ClearClipboardKey); - if(clearSeconds != null) + if (clearSeconds != null) { clearMs = clearSeconds.Value * 1000; } } - if(clearMs == null) + if (clearMs == null) { return; } diff --git a/src/Android/MainApplication.cs b/src/Android/MainApplication.cs index ee0ee3b3b..358d8ed1e 100644 --- a/src/Android/MainApplication.cs +++ b/src/Android/MainApplication.cs @@ -37,14 +37,14 @@ namespace Bit.Droid public MainApplication(IntPtr handle, JniHandleOwnership transer) : base(handle, transer) { - if(ServiceContainer.RegisteredServices.Count == 0) + if (ServiceContainer.RegisteredServices.Count == 0) { RegisterLocalServices(); var deviceActionService = ServiceContainer.Resolve("deviceActionService"); ServiceContainer.Init(deviceActionService.DeviceUserAgent); } #if !FDROID - if(Build.VERSION.SdkInt <= BuildVersionCodes.Kitkat) + if (Build.VERSION.SdkInt <= BuildVersionCodes.Kitkat) { ProviderInstaller.InstallIfNeededAsync(ApplicationContext, this); } diff --git a/src/Android/Push/FirebaseMessagingService.cs b/src/Android/Push/FirebaseMessagingService.cs index 101a04370..a7be046bb 100644 --- a/src/Android/Push/FirebaseMessagingService.cs +++ b/src/Android/Push/FirebaseMessagingService.cs @@ -16,12 +16,12 @@ namespace Bit.Droid.Push { public async override void OnMessageReceived(RemoteMessage message) { - if(message?.Data == null) + if (message?.Data == null) { return; } var data = message.Data.ContainsKey("data") ? message.Data["data"] : null; - if(data == null) + if (data == null) { return; } @@ -32,7 +32,7 @@ namespace Bit.Droid.Push "pushNotificationListenerService"); await listener.OnMessageAsync(obj, Device.Android); } - catch(JsonReaderException ex) + catch (JsonReaderException ex) { System.Diagnostics.Debug.WriteLine(ex.ToString()); } diff --git a/src/Android/Receivers/ClearClipboardAlarmReceiver.cs b/src/Android/Receivers/ClearClipboardAlarmReceiver.cs index 4085cf69b..31420ba16 100644 --- a/src/Android/Receivers/ClearClipboardAlarmReceiver.cs +++ b/src/Android/Receivers/ClearClipboardAlarmReceiver.cs @@ -12,7 +12,7 @@ namespace Bit.Droid.Receivers public override void OnReceive(Context context, Intent intent) { 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; } diff --git a/src/Android/Receivers/RestrictionsChangedReceiver.cs b/src/Android/Receivers/RestrictionsChangedReceiver.cs index 156dc7c1f..4c81bf03c 100644 --- a/src/Android/Receivers/RestrictionsChangedReceiver.cs +++ b/src/Android/Receivers/RestrictionsChangedReceiver.cs @@ -14,7 +14,7 @@ namespace Bit.Droid.Receivers { public async override void OnReceive(Context context, Intent intent) { - if(intent.Action == Intent.ActionApplicationRestrictionsChanged) + if (intent.Action == Intent.ActionApplicationRestrictionsChanged) { await AndroidHelpers.SetPreconfiguredRestrictionSettingsAsync(context); } diff --git a/src/Android/Renderers/CipherViewCellRenderer.cs b/src/Android/Renderers/CipherViewCellRenderer.cs index 774fd40dc..0d4811cb1 100644 --- a/src/Android/Renderers/CipherViewCellRenderer.cs +++ b/src/Android/Renderers/CipherViewCellRenderer.cs @@ -32,25 +32,25 @@ namespace Bit.Droid.Renderers protected override Android.Views.View GetCellCore(Cell item, Android.Views.View convertView, ViewGroup parent, Context context) { - if(_faTypeface == null) + if (_faTypeface == null) { _faTypeface = Typeface.CreateFromAsset(context.Assets, "FontAwesome.ttf"); } - if(_miTypeface == null) + if (_miTypeface == null) { _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"]) .ToAndroid(); } - if(_mutedColor == default(Android.Graphics.Color)) + if (_mutedColor == default(Android.Graphics.Color)) { _mutedColor = ((Xamarin.Forms.Color)Xamarin.Forms.Application.Current.Resources["MutedColor"]) .ToAndroid(); } - if(_disabledIconColor == default(Android.Graphics.Color)) + if (_disabledIconColor == default(Android.Graphics.Color)) { _disabledIconColor = ((Xamarin.Forms.Color)Xamarin.Forms.Application.Current.Resources["DisabledIconColor"]) @@ -59,7 +59,7 @@ namespace Bit.Droid.Renderers var cipherCell = item as CipherViewCell; _cell = convertView as AndroidCipherCell; - if(_cell == null) + if (_cell == null) { _cell = new AndroidCipherCell(context, cipherCell, _faTypeface, _miTypeface); } @@ -77,11 +77,11 @@ namespace Bit.Droid.Renderers { var cipherCell = sender as CipherViewCell; _cell.CipherViewCell = cipherCell; - if(e.PropertyName == CipherViewCell.CipherProperty.PropertyName) + if (e.PropertyName == CipherViewCell.CipherProperty.PropertyName) { _cell.UpdateCell(cipherCell); } - else if(e.PropertyName == CipherViewCell.WebsiteIconsEnabledProperty.PropertyName) + else if (e.PropertyName == CipherViewCell.WebsiteIconsEnabledProperty.PropertyName) { _cell.UpdateIconImage(cipherCell); } @@ -145,7 +145,7 @@ namespace Bit.Droid.Renderers var cipher = cipherCell.Cipher; Name.Text = cipher.Name; - if(!string.IsNullOrWhiteSpace(cipher.SubTitle)) + if (!string.IsNullOrWhiteSpace(cipher.SubTitle)) { SubTitle.Text = cipher.SubTitle; SubTitle.Visibility = ViewStates.Visible; @@ -160,7 +160,7 @@ namespace Bit.Droid.Renderers public void UpdateIconImage(CipherViewCell cipherCell) { - if(_currentTask != null && !_currentTask.IsCancelled && !_currentTask.IsCompleted) + if (_currentTask != null && !_currentTask.IsCancelled && !_currentTask.IsCompleted) { _currentTask.Cancel(); } @@ -168,7 +168,7 @@ namespace Bit.Droid.Renderers var cipher = cipherCell.Cipher; var iconImage = cipherCell.GetIconImage(cipher); - if(iconImage.Item2 != null) + if (iconImage.Item2 != null) { IconImage.SetImageResource(Resource.Drawable.login); IconImage.Visibility = ViewStates.Visible; @@ -197,7 +197,7 @@ namespace Bit.Droid.Renderers 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); } @@ -205,7 +205,7 @@ namespace Bit.Droid.Renderers protected override void Dispose(bool disposing) { - if(disposing) + if (disposing) { MoreButton.Click -= MoreButton_Click; } diff --git a/src/Android/Renderers/CustomEditorRenderer.cs b/src/Android/Renderers/CustomEditorRenderer.cs index ed5ba203e..6cb593513 100644 --- a/src/Android/Renderers/CustomEditorRenderer.cs +++ b/src/Android/Renderers/CustomEditorRenderer.cs @@ -16,7 +16,7 @@ namespace Bit.Droid.Renderers protected override void OnElementChanged(ElementChangedEventArgs 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.PaddingBottom + 20); diff --git a/src/Android/Renderers/CustomEntryRenderer.cs b/src/Android/Renderers/CustomEntryRenderer.cs index 001767913..046ceb7c8 100644 --- a/src/Android/Renderers/CustomEntryRenderer.cs +++ b/src/Android/Renderers/CustomEntryRenderer.cs @@ -16,7 +16,7 @@ namespace Bit.Droid.Renderers protected override void OnElementChanged(ElementChangedEventArgs 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.PaddingBottom + 20); diff --git a/src/Android/Renderers/CustomPickerRenderer.cs b/src/Android/Renderers/CustomPickerRenderer.cs index f9cf9912a..2327072d4 100644 --- a/src/Android/Renderers/CustomPickerRenderer.cs +++ b/src/Android/Renderers/CustomPickerRenderer.cs @@ -15,7 +15,7 @@ namespace Bit.Droid.Renderers protected override void OnElementChanged(ElementChangedEventArgs 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.PaddingBottom + 20); diff --git a/src/Android/Renderers/CustomSearchBarRenderer.cs b/src/Android/Renderers/CustomSearchBarRenderer.cs index 4bf0f6f2c..c48c078cc 100644 --- a/src/Android/Renderers/CustomSearchBarRenderer.cs +++ b/src/Android/Renderers/CustomSearchBarRenderer.cs @@ -16,7 +16,7 @@ namespace Bit.Droid.Renderers protected override void OnElementChanged(ElementChangedEventArgs e) { base.OnElementChanged(e); - if(Control != null && e.NewElement != null) + if (Control != null && e.NewElement != null) { try { diff --git a/src/Android/Renderers/ExtendedListViewRenderer.cs b/src/Android/Renderers/ExtendedListViewRenderer.cs index 8ce796f8a..963239825 100644 --- a/src/Android/Renderers/ExtendedListViewRenderer.cs +++ b/src/Android/Renderers/ExtendedListViewRenderer.cs @@ -17,7 +17,7 @@ namespace Bit.Droid.Renderers protected override void OnElementChanged(ElementChangedEventArgs 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 Control.SetPadding(0, 0, 0, 170); diff --git a/src/Android/Renderers/ExtendedSliderRenderer.cs b/src/Android/Renderers/ExtendedSliderRenderer.cs index 344d887fb..aee0ffc63 100644 --- a/src/Android/Renderers/ExtendedSliderRenderer.cs +++ b/src/Android/Renderers/ExtendedSliderRenderer.cs @@ -18,12 +18,12 @@ namespace Bit.Droid.Renderers protected override void OnElementChanged(ElementChangedEventArgs 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); - 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()); } diff --git a/src/Android/Renderers/HybridWebViewRenderer.cs b/src/Android/Renderers/HybridWebViewRenderer.cs index 93c15562e..eff5e1276 100644 --- a/src/Android/Renderers/HybridWebViewRenderer.cs +++ b/src/Android/Renderers/HybridWebViewRenderer.cs @@ -28,20 +28,20 @@ namespace Bit.Droid.Renderers { base.OnElementChanged(e); - if(Control == null) + if (Control == null) { var webView = new AWebkit.WebView(_context); webView.Settings.JavaScriptEnabled = true; webView.SetWebViewClient(new JSWebViewClient(string.Format("javascript: {0}", JSFunction))); SetNativeControl(webView); } - if(e.OldElement != null) + if (e.OldElement != null) { Control.RemoveJavascriptInterface("jsBridge"); var hybridWebView = e.OldElement as HybridWebView; hybridWebView.Cleanup(); } - if(e.NewElement != null) + if (e.NewElement != null) { Control.AddJavascriptInterface(new JSBridge(this), "jsBridge"); Control.LoadUrl(Element.Uri); @@ -51,7 +51,7 @@ namespace Bit.Droid.Renderers protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e) { base.OnElementPropertyChanged(sender, e); - if(e.PropertyName == HybridWebView.UriProperty.PropertyName) + if (e.PropertyName == HybridWebView.UriProperty.PropertyName) { Control.LoadUrl(Element.Uri); } @@ -70,7 +70,7 @@ namespace Bit.Droid.Renderers [Export("invokeAction")] public void InvokeAction(string data) { - if(_hybridWebViewRenderer != null && + if (_hybridWebViewRenderer != null && _hybridWebViewRenderer.TryGetTarget(out HybridWebViewRenderer hybridRenderer)) { hybridRenderer.Element.InvokeAction(data); diff --git a/src/Android/Services/AndroidPushNotificationService.cs b/src/Android/Services/AndroidPushNotificationService.cs index 5b536c5cd..975cbd2db 100644 --- a/src/Android/Services/AndroidPushNotificationService.cs +++ b/src/Android/Services/AndroidPushNotificationService.cs @@ -30,7 +30,7 @@ namespace Bit.Droid.Services { var registeredToken = await _storageService.GetAsync(Constants.PushRegisteredTokenKey); var currentToken = await GetTokenAsync(); - if(!string.IsNullOrWhiteSpace(registeredToken) && registeredToken != currentToken) + if (!string.IsNullOrWhiteSpace(registeredToken) && registeredToken != currentToken) { await _pushNotificationListenerService.OnRegisteredAsync(registeredToken, Device.Android); } diff --git a/src/Android/Services/CryptoPrimitiveService.cs b/src/Android/Services/CryptoPrimitiveService.cs index e00e370c3..bdb19cfa5 100644 --- a/src/Android/Services/CryptoPrimitiveService.cs +++ b/src/Android/Services/CryptoPrimitiveService.cs @@ -14,12 +14,12 @@ namespace Bit.Droid.Services { int keySize = 256; IDigest digest = null; - if(algorithm == CryptoHashAlgorithm.Sha256) + if (algorithm == CryptoHashAlgorithm.Sha256) { keySize = 256; digest = new Sha256Digest(); } - else if(algorithm == CryptoHashAlgorithm.Sha512) + else if (algorithm == CryptoHashAlgorithm.Sha512) { keySize = 512; digest = new Sha512Digest(); diff --git a/src/Android/Services/DeviceActionService.cs b/src/Android/Services/DeviceActionService.cs index e4760c5e3..0715fb42b 100644 --- a/src/Android/Services/DeviceActionService.cs +++ b/src/Android/Services/DeviceActionService.cs @@ -59,7 +59,7 @@ namespace Bit.Droid.Services _broadcasterService.Subscribe(nameof(DeviceActionService), (message) => { - if(message.Command == "selectFileCameraPermissionDenied") + if (message.Command == "selectFileCameraPermissionDenied") { _cameraPermissionsDenied = true; } @@ -70,7 +70,7 @@ namespace Bit.Droid.Services { get { - if(string.IsNullOrWhiteSpace(_userAgent)) + if (string.IsNullOrWhiteSpace(_userAgent)) { _userAgent = $"Bitwarden_Mobile/{Xamarin.Essentials.AppInfo.VersionString} " + $"(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) { - if(_toast != null) + if (_toast != null) { _toast.Cancel(); _toast.Dispose(); @@ -99,7 +99,7 @@ namespace Bit.Droid.Services var activity = CrossCurrentActivity.Current.Activity; appName = appName.Replace("androidapp://", string.Empty); var launchIntent = activity.PackageManager.GetLaunchIntentForPackage(appName); - if(launchIntent != null) + if (launchIntent != null) { activity.StartActivity(launchIntent); } @@ -108,7 +108,7 @@ namespace Bit.Droid.Services public async Task ShowLoadingAsync(string text) { - if(_progressDialog != null) + if (_progressDialog != null) { await HideLoadingAsync(); } @@ -121,7 +121,7 @@ namespace Bit.Droid.Services public Task HideLoadingAsync() { - if(_progressDialog != null) + if (_progressDialog != null) { _progressDialog.Dismiss(); _progressDialog.Dispose(); @@ -136,7 +136,7 @@ namespace Bit.Droid.Services { var activity = (MainActivity)CrossCurrentActivity.Current.Activity; var intent = BuildOpenFileIntent(fileData, fileName); - if(intent == null) + if (intent == null) { return false; } @@ -153,7 +153,7 @@ namespace Bit.Droid.Services { var activity = (MainActivity)CrossCurrentActivity.Current.Activity; var intent = BuildOpenFileIntent(new byte[0], string.Concat("opentest_", fileName)); - if(intent == null) + if (intent == null) { return false; } @@ -168,12 +168,12 @@ namespace Bit.Droid.Services private Intent BuildOpenFileIntent(byte[] fileData, string fileName) { var extension = MimeTypeMap.GetFileExtensionFromUrl(fileName.Replace(' ', '_').ToLower()); - if(extension == null) + if (extension == null) { return null; } var mimeType = MimeTypeMap.Singleton.GetMimeTypeFromExtension(extension); - if(mimeType == null) + if (mimeType == null) { return null; } @@ -183,7 +183,7 @@ namespace Bit.Droid.Services var filePath = Path.Combine(cachePath.Path, fileName); File.WriteAllBytes(filePath, fileData); var file = new Java.IO.File(cachePath, fileName); - if(!file.IsFile) + if (!file.IsFile) { return null; } @@ -207,7 +207,7 @@ namespace Bit.Droid.Services { var activity = (MainActivity)CrossCurrentActivity.Current.Activity; - if(contentUri != null) + if (contentUri != null) { var uri = Android.Net.Uri.Parse(contentUri); var stream = activity.ContentResolver.OpenOutputStream(uri); @@ -222,13 +222,13 @@ namespace Bit.Droid.Services // Prompt for location to save file var extension = MimeTypeMap.GetFileExtensionFromUrl(fileName.Replace(' ', '_').ToLower()); - if(extension == null) + if (extension == null) { return false; } string mimeType = MimeTypeMap.Singleton.GetMimeTypeFromExtension(extension); - if(mimeType == null) + if (mimeType == null) { // Unable to identify so fall back to generic "any" type mimeType = "*/*"; @@ -242,7 +242,7 @@ namespace Bit.Droid.Services activity.StartActivityForResult(intent, Constants.SaveFileRequestCode); return true; } - catch(Exception ex) + catch (Exception ex) { System.Diagnostics.Debug.WriteLine(">>> {0}: {1}", ex.GetType(), ex.StackTrace); } @@ -256,7 +256,7 @@ namespace Bit.Droid.Services DeleteDir(CrossCurrentActivity.Current.Activity.CacheDir); await _storageService.SaveAsync(Constants.LastFileCacheClearKey, DateTime.UtcNow); } - catch(Exception) { } + catch (Exception) { } } public Task SelectFileAsync() @@ -265,25 +265,25 @@ namespace Bit.Droid.Services var hasStorageWritePermission = !_cameraPermissionsDenied && HasPermission(Manifest.Permission.WriteExternalStorage); var additionalIntents = new List(); - if(activity.PackageManager.HasSystemFeature(PackageManager.FeatureCamera)) + if (activity.PackageManager.HasSystemFeature(PackageManager.FeatureCamera)) { var hasCameraPermission = !_cameraPermissionsDenied && HasPermission(Manifest.Permission.Camera); - if(!_cameraPermissionsDenied && !hasStorageWritePermission) + if (!_cameraPermissionsDenied && !hasStorageWritePermission) { AskPermission(Manifest.Permission.WriteExternalStorage); return Task.FromResult(0); } - if(!_cameraPermissionsDenied && !hasCameraPermission) + if (!_cameraPermissionsDenied && !hasCameraPermission) { AskPermission(Manifest.Permission.Camera); return Task.FromResult(0); } - if(!_cameraPermissionsDenied && hasCameraPermission && hasStorageWritePermission) + if (!_cameraPermissionsDenied && hasCameraPermission && hasStorageWritePermission) { try { var file = new Java.IO.File(activity.FilesDir, "temp_camera_photo.jpg"); - if(!file.Exists()) + if (!file.Exists()) { file.ParentFile.Mkdirs(); file.CreateNewFile(); @@ -292,7 +292,7 @@ namespace Bit.Droid.Services "com.x8bit.bitwarden.fileprovider", file); 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.SetType("*/*"); var chooserIntent = Intent.CreateChooser(docIntent, AppResources.FileSource); - if(additionalIntents.Count > 0) + if (additionalIntents.Count > 0) { chooserIntent.PutExtra(Intent.ExtraInitialIntents, additionalIntents.ToArray()); } @@ -313,7 +313,7 @@ namespace Bit.Droid.Services bool numericKeyboard = false, bool autofocus = true) { var activity = (MainActivity)CrossCurrentActivity.Current.Activity; - if(activity == null) + if (activity == null) { return Task.FromResult(null); } @@ -325,11 +325,11 @@ namespace Bit.Droid.Services { InputType = InputTypes.ClassText }; - if(text == null) + if (text == null) { text = string.Empty; } - if(numericKeyboard) + if (numericKeyboard) { input.InputType = InputTypes.ClassNumber | InputTypes.NumberFlagDecimal | InputTypes.NumberFlagSigned; #pragma warning disable CS0618 // Type or member is obsolete @@ -359,7 +359,7 @@ namespace Bit.Droid.Services var alert = alertBuilder.Create(); alert.Window.SetSoftInputMode(Android.Views.SoftInput.StateVisible); alert.Show(); - if(autofocus) + if (autofocus) { input.RequestFocus(); } @@ -374,7 +374,7 @@ namespace Bit.Droid.Services var rateIntent = RateIntentForUrl("market://details", activity); activity.StartActivity(rateIntent); } - catch(ActivityNotFoundException) + catch (ActivityNotFoundException) { var rateIntent = RateIntentForUrl("https://play.google.com/store/apps/details", activity); activity.StartActivity(rateIntent); @@ -399,7 +399,7 @@ namespace Bit.Droid.Services public async Task BiometricAvailableAsync() { - if(UseNativeBiometric()) + if (UseNativeBiometric()) { var activity = (MainActivity)CrossCurrentActivity.Current.Activity; var manager = activity.GetSystemService(Context.BiometricService) as BiometricManager; @@ -425,13 +425,13 @@ namespace Bit.Droid.Services public Task AuthenticateBiometricAsync(string text = null) { - if(string.IsNullOrWhiteSpace(text)) + if (string.IsNullOrWhiteSpace(text)) { text = AppResources.BiometricsDirection; } var activity = (MainActivity)CrossCurrentActivity.Current.Activity; - using(var builder = new BiometricPrompt.Builder(activity)) + using (var builder = new BiometricPrompt.Builder(activity)) { builder.SetTitle(text); builder.SetConfirmationRequired(false); @@ -468,7 +468,7 @@ namespace Bit.Droid.Services public bool SupportsAutofillService() { - if(Build.VERSION.SdkInt < BuildVersionCodes.O) + if (Build.VERSION.SdkInt < BuildVersionCodes.O) { return false; } @@ -498,7 +498,7 @@ namespace Bit.Droid.Services public Task DisplayAlertAsync(string title, string message, string cancel, params string[] buttons) { var activity = (MainActivity)CrossCurrentActivity.Current.Activity; - if(activity == null) + if (activity == null) { return Task.FromResult(null); } @@ -507,11 +507,11 @@ namespace Bit.Droid.Services var alertBuilder = new AlertDialog.Builder(activity); 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}"); } @@ -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) => { @@ -537,14 +537,14 @@ namespace Bit.Droid.Services } else { - if(buttons.Length > 0) + if (buttons.Length > 0) { alertBuilder.SetPositiveButton(buttons[0], (sender, args) => { result.TrySetResult(buttons[0]); }); } - if(buttons.Length > 1) + if (buttons.Length > 1) { 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) => { @@ -571,13 +571,13 @@ namespace Bit.Droid.Services public void Autofill(CipherView cipher) { var activity = (MainActivity)CrossCurrentActivity.Current.Activity; - if(activity == null) + if (activity == null) { return; } - if(activity.Intent.GetBooleanExtra("autofillFramework", false)) + if (activity.Intent.GetBooleanExtra("autofillFramework", false)) { - if(cipher == null) + if (cipher == null) { activity.SetResult(Result.Canceled); activity.Finish(); @@ -585,7 +585,7 @@ namespace Bit.Droid.Services } var structure = activity.Intent.GetParcelableExtra( AutofillManager.ExtraAssistStructure) as AssistStructure; - if(structure == null) + if (structure == null) { activity.SetResult(Result.Canceled); activity.Finish(); @@ -593,7 +593,7 @@ namespace Bit.Droid.Services } var parser = new Parser(structure, activity.ApplicationContext); 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.Finish(); @@ -610,7 +610,7 @@ namespace Bit.Droid.Services else { var data = new Intent(); - if(cipher == null) + if (cipher == null) { data.PutExtra("canceled", "true"); } @@ -621,7 +621,7 @@ namespace Bit.Droid.Services data.PutExtra("username", cipher.Login.Username); data.PutExtra("password", cipher.Login.Password); } - if(activity.Parent == null) + if (activity.Parent == null) { activity.SetResult(Result.Ok, data); } @@ -631,7 +631,7 @@ namespace Bit.Droid.Services } activity.Finish(); _messagingService.Send("finishMainActivity"); - if(cipher != null) + if (cipher != null) { var eventTask = _eventServiceFunc().CollectAsync(EventType.Cipher_ClientAutofilled, cipher.Id); } @@ -646,7 +646,7 @@ namespace Bit.Droid.Services public void Background() { var activity = (MainActivity)CrossCurrentActivity.Current.Activity; - if(activity.Intent.GetBooleanExtra("autofillFramework", false)) + if (activity.Intent.GetBooleanExtra("autofillFramework", false)) { activity.SetResult(Result.Canceled); activity.Finish(); @@ -687,7 +687,7 @@ namespace Bit.Droid.Services intent.SetData(Android.Net.Uri.Parse("package:com.x8bit.bitwarden")); activity.StartActivity(intent); } - catch(ActivityNotFoundException) + catch (ActivityNotFoundException) { // can't open overlay permission management, fall back to app settings var intent = new Intent(Settings.ActionApplicationDetailsSettings); @@ -709,7 +709,7 @@ namespace Bit.Droid.Services public bool AutofillServiceEnabled() { - if(Build.VERSION.SdkInt < BuildVersionCodes.O) + if (Build.VERSION.SdkInt < BuildVersionCodes.O) { return false; } @@ -746,7 +746,7 @@ namespace Bit.Droid.Services intent.SetData(Android.Net.Uri.Parse("package:com.x8bit.bitwarden")); activity.StartActivity(intent); } - catch(ActivityNotFoundException) + catch (ActivityNotFoundException) { var alertBuilder = new AlertDialog.Builder(activity); alertBuilder.SetMessage(AppResources.BitwardenAutofillGoToSettings); @@ -766,20 +766,20 @@ namespace Bit.Droid.Services private bool DeleteDir(Java.IO.File dir) { - if(dir != null && dir.IsDirectory) + if (dir != null && dir.IsDirectory) { 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])); - if(!success) + if (!success) { return false; } } return dir.Delete(); } - else if(dir != null && dir.IsFile) + else if (dir != null && dir.IsFile) { return dir.Delete(); } @@ -807,7 +807,7 @@ namespace Bit.Droid.Services var pm = CrossCurrentActivity.Current.Activity.PackageManager; var captureIntent = new Intent(MediaStore.ActionImageCapture); var listCam = pm.QueryIntentActivities(captureIntent, 0); - foreach(var res in listCam) + foreach (var res in listCam) { var packageName = res.ActivityInfo.PackageName; 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 flags = ActivityFlags.NoHistory | ActivityFlags.MultipleTask; - if((int)Build.VERSION.SdkInt >= 21) + if ((int)Build.VERSION.SdkInt >= 21) { flags |= ActivityFlags.NewDocument; } @@ -838,16 +838,16 @@ namespace Bit.Droid.Services private async Task CopyTotpAsync(CipherView cipher) { - if(!string.IsNullOrWhiteSpace(cipher?.Login?.Totp)) + if (!string.IsNullOrWhiteSpace(cipher?.Login?.Totp)) { var userService = ServiceContainer.Resolve("userService"); var autoCopyDisabled = await _storageService.GetAsync(Constants.DisableAutoTotpCopyKey); var canAccessPremium = await userService.CanAccessPremiumAsync(); - if((canAccessPremium || cipher.OrganizationUseTotp) && !autoCopyDisabled.GetValueOrDefault()) + if ((canAccessPremium || cipher.OrganizationUseTotp) && !autoCopyDisabled.GetValueOrDefault()) { var totpService = ServiceContainer.Resolve("totpService"); var totp = await totpService.GetCodeAsync(cipher.Login.Totp); - if(totp != null) + if (totp != null) { CopyToClipboard(totp); } diff --git a/src/Android/Services/LocalizeService.cs b/src/Android/Services/LocalizeService.cs index 24c82c4ee..bafcbacd2 100644 --- a/src/Android/Services/LocalizeService.cs +++ b/src/Android/Services/LocalizeService.cs @@ -18,7 +18,7 @@ namespace Bit.Droid.Services { ci = new CultureInfo(netLanguage); } - catch(CultureNotFoundException e1) + catch (CultureNotFoundException e1) { // iOS locale not valid .NET culture (eg. "en-ES" : English in Spain) // fallback to first characters, in this case "en" @@ -28,7 +28,7 @@ namespace Bit.Droid.Services Console.WriteLine(netLanguage + " failed, trying " + fallback + " (" + e1.Message + ")"); ci = new CultureInfo(fallback); } - catch(CultureNotFoundException e2) + catch (CultureNotFoundException e2) { // iOS language not valid .NET culture, falling back to English Console.WriteLine(netLanguage + " couldn't be set, using 'en' (" + e2.Message + ")"); @@ -42,9 +42,9 @@ namespace Bit.Droid.Services { Console.WriteLine("Android Language:" + 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")) { netLanguage = "zh-Hant"; @@ -54,7 +54,7 @@ namespace Bit.Droid.Services netLanguage = "zh-Hans"; } } - else if(androidLanguage.StartsWith("iw")) + else if (androidLanguage.StartsWith("iw")) { // Uncomment when we support RTL // netLanguage = "he"; @@ -62,7 +62,7 @@ namespace Bit.Droid.Services else { // Certain languages need to be converted to CultureInfo equivalent - switch(androidLanguage) + switch (androidLanguage) { case "ms-BN": // "Malaysian (Brunei)" 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); var netLanguage = platCulture.LanguageCode; // use the first part of the identifier (two chars, usually); - switch(platCulture.LanguageCode) + switch (platCulture.LanguageCode) { case "gsw": netLanguage = "de-CH"; // equivalent to German (Switzerland) for this app diff --git a/src/Android/Tiles/AutofillTileService.cs b/src/Android/Tiles/AutofillTileService.cs index 39f75c07a..71db23805 100644 --- a/src/Android/Tiles/AutofillTileService.cs +++ b/src/Android/Tiles/AutofillTileService.cs @@ -46,7 +46,7 @@ namespace Bit.Droid.Tile { base.OnClick(); - if(IsLocked) + if (IsLocked) { UnlockAndRun(new Runnable(ScanAndFill)); } @@ -59,7 +59,7 @@ namespace Bit.Droid.Tile private void SetTileAdded(bool isAdded) { AccessibilityHelpers.IsAutofillTileAdded = isAdded; - if(_storageService == null) + if (_storageService == null) { _storageService = ServiceContainer.Resolve("storageService"); } @@ -68,7 +68,7 @@ namespace Bit.Droid.Tile private void ScanAndFill() { - if(!AccessibilityHelpers.IsAccessibilityBroadcastReady) + if (!AccessibilityHelpers.IsAccessibilityBroadcastReady) { ShowConfigErrorDialog(); return; diff --git a/src/Android/Tiles/GeneratorTileService.cs b/src/Android/Tiles/GeneratorTileService.cs index ce03d1f31..e32691ca3 100644 --- a/src/Android/Tiles/GeneratorTileService.cs +++ b/src/Android/Tiles/GeneratorTileService.cs @@ -44,7 +44,7 @@ namespace Bit.Droid.Tile { base.OnClick(); - if(IsLocked) + if (IsLocked) { UnlockAndRun(new Runnable(() => { diff --git a/src/Android/Tiles/MyVaultTileService.cs b/src/Android/Tiles/MyVaultTileService.cs index bef831100..5b35f6024 100644 --- a/src/Android/Tiles/MyVaultTileService.cs +++ b/src/Android/Tiles/MyVaultTileService.cs @@ -44,7 +44,7 @@ namespace Bit.Droid.Tile { base.OnClick(); - if(IsLocked) + if (IsLocked) { UnlockAndRun(new Runnable(() => { diff --git a/src/Android/Utilities/AndroidHelpers.cs b/src/Android/Utilities/AndroidHelpers.cs index a36869998..b2ba7a8dd 100644 --- a/src/Android/Utilities/AndroidHelpers.cs +++ b/src/Android/Utilities/AndroidHelpers.cs @@ -15,11 +15,11 @@ namespace Bit.Droid.Utilities string name = null; string[] projection = { MediaStore.MediaColumns.DisplayName }; var metaCursor = context.ContentResolver.Query(uri, projection, null, null, null); - if(metaCursor != null) + if (metaCursor != null) { try { - if(metaCursor.MoveToFirst()) + if (metaCursor.MoveToFirst()) { name = metaCursor.GetString(0); } @@ -37,12 +37,12 @@ namespace Bit.Droid.Utilities var restrictionsManager = (RestrictionsManager)context.GetSystemService(Context.RestrictionsService); var restrictions = restrictionsManager.ApplicationRestrictions; var dict = new Dictionary(); - if(restrictions.ContainsKey(BaseEnvironmentUrlRestrictionKey)) + if (restrictions.ContainsKey(BaseEnvironmentUrlRestrictionKey)) { dict.Add(BaseEnvironmentUrlRestrictionKey, restrictions.GetString(BaseEnvironmentUrlRestrictionKey)); } - if(dict.Count > 0) + if (dict.Count > 0) { await AppHelpers.SetPreconfiguredSettingsAsync(dict); } diff --git a/src/Android/Utilities/HockeyAppCrashManagerListener.cs b/src/Android/Utilities/HockeyAppCrashManagerListener.cs index e7b490f2e..b039839ef 100644 --- a/src/Android/Utilities/HockeyAppCrashManagerListener.cs +++ b/src/Android/Utilities/HockeyAppCrashManagerListener.cs @@ -45,7 +45,7 @@ namespace Bit.Droid.Utilities { get { - if(_userId != null && _appId != null) + if (_userId != null && _appId != null) { return JsonConvert.SerializeObject(new { diff --git a/src/App/App.xaml.cs b/src/App/App.xaml.cs index b5f66da1c..303f31908 100644 --- a/src/App/App.xaml.cs +++ b/src/App/App.xaml.cs @@ -69,7 +69,7 @@ namespace Bit.App Bootstrap(); _broadcasterService.Subscribe(nameof(App), async (message) => { - if(message.Command == "showDialog") + if (message.Command == "showDialog") { var details = message.Data as DialogDetails; var confirmed = true; @@ -77,7 +77,7 @@ namespace Bit.App AppResources.Ok : details.ConfirmText; Device.BeginInvokeOnMainThread(async () => { - if(!string.IsNullOrWhiteSpace(details.CancelText)) + if (!string.IsNullOrWhiteSpace(details.CancelText)) { confirmed = await Current.MainPage.DisplayAlert(details.Title, details.Text, confirmText, details.CancelText); @@ -89,55 +89,55 @@ namespace Bit.App _messagingService.Send("showDialogResolve", new Tuple(details.DialogId, confirmed)); }); } - else if(message.Command == "locked") + else if (message.Command == "locked") { await LockedAsync(!(message.Data as bool?).GetValueOrDefault()); } - else if(message.Command == "lockVault") + else if (message.Command == "lockVault") { await _lockService.LockAsync(true); } - else if(message.Command == "logout") + else if (message.Command == "logout") { Device.BeginInvokeOnMainThread(async () => 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. 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(); } } - else if(message.Command == "slept") + else if (message.Command == "slept") { - if(Device.RuntimePlatform == Device.iOS) + if (Device.RuntimePlatform == Device.iOS) { await SleptAsync(); } } - else if(message.Command == "migrated") + else if (message.Command == "migrated") { await Task.Delay(1000); await SetMainPageAsync(); } - else if(message.Command == "popAllAndGoToTabGenerator" || + else if (message.Command == "popAllAndGoToTabGenerator" || message.Command == "popAllAndGoToTabMyVault") { 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); } - if(message.Command == "popAllAndGoToTabMyVault") + if (message.Command == "popAllAndGoToTabMyVault") { _appOptions.MyVaultTile = false; tabsPage.ResetToVaultPage(); @@ -161,13 +161,13 @@ namespace Bit.App var maxTimeInMillis = 5000; var count = 0; - while(!_isResumed) + while (!_isResumed) { Task.Delay(checkFrequencyInMillis).Wait(); count += checkFrequencyInMillis; // don't let this run forever - if(count >= maxTimeInMillis) + if (count >= maxTimeInMillis) { break; } @@ -180,11 +180,11 @@ namespace Bit.App await ClearCacheIfNeededAsync(); await TryClearCiphersCacheAsync(); Prime(); - if(string.IsNullOrWhiteSpace(_appOptions.Uri)) + if (string.IsNullOrWhiteSpace(_appOptions.Uri)) { var updated = await AppHelpers.PerformUpdateTasksAsync(_syncService, _deviceActionService, _storageService); - if(!updated) + if (!updated) { SyncIfNeeded(); } @@ -196,10 +196,10 @@ namespace Bit.App { System.Diagnostics.Debug.WriteLine("XF App: OnSleep"); _isResumed = false; - if(Device.RuntimePlatform == Device.Android) + if (Device.RuntimePlatform == Device.Android) { var isLocked = await _lockService.IsLockedAsync(); - if(!isLocked) + if (!isLocked) { await _storageService.SaveAsync(Constants.LastActiveKey, DateTime.UtcNow); } @@ -212,7 +212,7 @@ namespace Bit.App { System.Diagnostics.Debug.WriteLine("XF App: OnResume"); _isResumed = true; - if(Device.RuntimePlatform == Device.Android) + if (Device.RuntimePlatform == Device.Android) { ResumedAsync(); } @@ -232,9 +232,9 @@ namespace Bit.App await TryClearCiphersCacheAsync(); Prime(); 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 await Task.Delay(100); @@ -273,7 +273,7 @@ namespace Bit.App _authService.LogOut(() => { Current.MainPage = new HomePage(); - if(expired) + if (expired) { _platformUtilsService.ShowToast("warning", null, AppResources.LoginExpired); } @@ -283,17 +283,17 @@ namespace Bit.App private async Task SetMainPageAsync() { var authed = await _userService.IsAuthenticatedAsync(); - if(authed) + if (authed) { - if(await _lockService.IsLockedAsync()) + if (await _lockService.IsLockedAsync()) { 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)); } - else if(_appOptions.Uri != null) + else if (_appOptions.Uri != null) { Current.MainPage = new NavigationPage(new AutofillCiphersPage(_appOptions)); } @@ -310,26 +310,26 @@ namespace Bit.App private async Task HandleLockingAsync() { - if(await _lockService.IsLockedAsync()) + if (await _lockService.IsLockedAsync()) { return; } var authed = await _userService.IsAuthenticatedAsync(); - if(!authed) + if (!authed) { return; } var lockOption = _platformUtilsService.LockTimeout(); - if(lockOption == null) + if (lockOption == null) { lockOption = await _storageService.GetAsync(Constants.LockOptionKey); } lockOption = lockOption.GetValueOrDefault(-1); - if(lockOption > 0) + if (lockOption > 0) { _messagingService.Send("scheduleLockTimer", lockOption.Value); } - else if(lockOption == 0) + else if (lockOption == 0) { await _lockService.LockAsync(true); } @@ -338,7 +338,7 @@ namespace Bit.App private async Task ClearCacheIfNeededAsync() { var lastClear = await _storageService.GetAsync(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()); } @@ -346,7 +346,7 @@ namespace Bit.App 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) { Task.Run(() => @@ -354,7 +354,7 @@ namespace Bit.App Device.BeginInvokeOnMainThread(() => { _appOptions.Uri = null; - if(isLocked) + if (isLocked) { Current.MainPage = new NavigationPage(new LockPage()); } @@ -388,14 +388,14 @@ namespace Bit.App private void SyncIfNeeded() { - if(Xamarin.Essentials.Connectivity.NetworkAccess == Xamarin.Essentials.NetworkAccess.None) + if (Xamarin.Essentials.Connectivity.NetworkAccess == Xamarin.Essentials.NetworkAccess.None) { return; } Task.Run(async () => { 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 _syncService.FullSyncAsync(false); @@ -405,12 +405,12 @@ namespace Bit.App private async Task TryClearCiphersCacheAsync() { - if(Device.RuntimePlatform != Device.iOS) + if (Device.RuntimePlatform != Device.iOS) { return; } var clearCache = await _storageService.GetAsync(Constants.ClearCiphersCacheKey); - if(clearCache.GetValueOrDefault()) + if (clearCache.GetValueOrDefault()) { _cipherService.ClearCache(); await _storageService.RemoveAsync(Constants.ClearCiphersCacheKey); @@ -420,26 +420,26 @@ namespace Bit.App private async Task LockedAsync(bool autoPromptFingerprint) { await _stateService.PurgeAsync(); - if(autoPromptFingerprint && Device.RuntimePlatform == Device.iOS) + if (autoPromptFingerprint && Device.RuntimePlatform == Device.iOS) { var lockOptions = await _storageService.GetAsync(Constants.LockOptionKey); - if(lockOptions == 0) + if (lockOptions == 0) { autoPromptFingerprint = false; } } - else if(autoPromptFingerprint && Device.RuntimePlatform == Device.Android && + else if (autoPromptFingerprint && Device.RuntimePlatform == Device.Android && _deviceActionService.UseNativeBiometric()) { autoPromptFingerprint = false; } 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]; - 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 { @@ -447,7 +447,7 @@ namespace Bit.App 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 { diff --git a/src/App/Controls/CipherViewCell/CipherViewCell.xaml.cs b/src/App/Controls/CipherViewCell/CipherViewCell.xaml.cs index 20f8c520e..85be2f34b 100644 --- a/src/App/Controls/CipherViewCell/CipherViewCell.xaml.cs +++ b/src/App/Controls/CipherViewCell/CipherViewCell.xaml.cs @@ -28,7 +28,7 @@ namespace Bit.App.Controls public CipherViewCell() { _environmentService = ServiceContainer.Resolve("environmentService"); - if(Device.RuntimePlatform == Device.iOS) + if (Device.RuntimePlatform == Device.iOS) { InitializeComponent(); _viewModel = _grid.BindingContext as CipherViewCellViewModel; @@ -60,11 +60,11 @@ namespace Bit.App.Controls protected override void OnPropertyChanged(string propertyName = null) { base.OnPropertyChanged(propertyName); - if(_usingNativeCell) + if (_usingNativeCell) { return; } - if(propertyName == CipherProperty.PropertyName) + if (propertyName == CipherProperty.PropertyName) { _viewModel.Cipher = Cipher; } @@ -73,25 +73,25 @@ namespace Bit.App.Controls protected override void OnBindingContextChanged() { base.OnBindingContextChanged(); - if(_usingNativeCell) + if (_usingNativeCell) { return; } _image.Source = null; CipherView cipher = null; - if(BindingContext is GroupingsPageListItem groupingsPageListItem) + if (BindingContext is GroupingsPageListItem groupingsPageListItem) { cipher = groupingsPageListItem.Cipher; } - else if(BindingContext is CipherView cv) + else if (BindingContext is CipherView cv) { cipher = cv; } - if(cipher != null) + if (cipher != null) { var iconImage = GetIconImage(cipher); - if(iconImage.Item2 != null) + if (iconImage.Item2 != null) { _image.IsVisible = true; _icon.IsVisible = false; @@ -111,7 +111,7 @@ namespace Bit.App.Controls { string icon = null; string image = null; - switch(cipher.Type) + switch (cipher.Type) { case CipherType.Login: var loginIconImage = GetLoginIconImage(cipher); @@ -137,36 +137,36 @@ namespace Bit.App.Controls { string icon = ""; string image = null; - if(cipher.Login.Uri != null) + if (cipher.Login.Uri != null) { var hostnameUri = cipher.Login.Uri; var isWebsite = false; - if(hostnameUri.StartsWith(Constants.AndroidAppProtocol)) + if (hostnameUri.StartsWith(Constants.AndroidAppProtocol)) { icon = ""; } - else if(hostnameUri.StartsWith(Constants.iOSAppProtocol)) + else if (hostnameUri.StartsWith(Constants.iOSAppProtocol)) { icon = ""; } - else if(WebsiteIconsEnabled && !hostnameUri.Contains("://") && hostnameUri.Contains(".")) + else if (WebsiteIconsEnabled && !hostnameUri.Contains("://") && hostnameUri.Contains(".")) { hostnameUri = string.Concat("http://", hostnameUri); isWebsite = true; } - else if(WebsiteIconsEnabled) + else if (WebsiteIconsEnabled) { isWebsite = hostnameUri.StartsWith("http") && hostnameUri.Contains("."); } - if(WebsiteIconsEnabled && isWebsite) + if (WebsiteIconsEnabled && isWebsite) { var hostname = CoreHelpers.GetHostname(hostnameUri); 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); } diff --git a/src/App/Controls/ExtendedSearchBar.cs b/src/App/Controls/ExtendedSearchBar.cs index c93861d94..4e52a354e 100644 --- a/src/App/Controls/ExtendedSearchBar.cs +++ b/src/App/Controls/ExtendedSearchBar.cs @@ -8,10 +8,10 @@ namespace Bit.App.Controls { public ExtendedSearchBar() { - if(Device.RuntimePlatform == Device.iOS) + if (Device.RuntimePlatform == Device.iOS) { var deviceActionService = ServiceContainer.Resolve("deviceActionService", true); - if(!deviceActionService?.UsingDarkTheme() ?? false) + if (!deviceActionService?.UsingDarkTheme() ?? false) { TextColor = Color.Black; } diff --git a/src/App/Controls/FaButton.cs b/src/App/Controls/FaButton.cs index 88289616b..f6528fd9c 100644 --- a/src/App/Controls/FaButton.cs +++ b/src/App/Controls/FaButton.cs @@ -7,7 +7,7 @@ namespace Bit.App.Controls public FaButton() { Padding = 0; - switch(Device.RuntimePlatform) + switch (Device.RuntimePlatform) { case Device.iOS: FontFamily = "FontAwesome"; diff --git a/src/App/Controls/FaLabel.cs b/src/App/Controls/FaLabel.cs index 23839fc95..146b7b017 100644 --- a/src/App/Controls/FaLabel.cs +++ b/src/App/Controls/FaLabel.cs @@ -6,7 +6,7 @@ namespace Bit.App.Controls { public FaLabel() { - switch(Device.RuntimePlatform) + switch (Device.RuntimePlatform) { case Device.iOS: FontFamily = "FontAwesome"; diff --git a/src/App/Controls/MiButton.cs b/src/App/Controls/MiButton.cs index 9e902f201..1146f1317 100644 --- a/src/App/Controls/MiButton.cs +++ b/src/App/Controls/MiButton.cs @@ -7,7 +7,7 @@ namespace Bit.App.Controls public MiButton() { Padding = 0; - switch(Device.RuntimePlatform) + switch (Device.RuntimePlatform) { case Device.iOS: FontFamily = "Material Icons"; diff --git a/src/App/Controls/MiLabel.cs b/src/App/Controls/MiLabel.cs index 0a30eb0bd..7ed7edeaa 100644 --- a/src/App/Controls/MiLabel.cs +++ b/src/App/Controls/MiLabel.cs @@ -6,7 +6,7 @@ namespace Bit.App.Controls { public MiLabel() { - switch(Device.RuntimePlatform) + switch (Device.RuntimePlatform) { case Device.iOS: FontFamily = "Material Icons"; diff --git a/src/App/Controls/MonoEntry.cs b/src/App/Controls/MonoEntry.cs index 117d8abdd..9fa23ef5e 100644 --- a/src/App/Controls/MonoEntry.cs +++ b/src/App/Controls/MonoEntry.cs @@ -6,7 +6,7 @@ namespace Bit.App.Controls { public MonoEntry() { - switch(Device.RuntimePlatform) + switch (Device.RuntimePlatform) { case Device.iOS: FontFamily = "Menlo-Regular"; diff --git a/src/App/Controls/MonoLabel.cs b/src/App/Controls/MonoLabel.cs index 7209fc8ee..71c43050b 100644 --- a/src/App/Controls/MonoLabel.cs +++ b/src/App/Controls/MonoLabel.cs @@ -6,7 +6,7 @@ namespace Bit.App.Controls { public MonoLabel() { - switch(Device.RuntimePlatform) + switch (Device.RuntimePlatform) { case Device.iOS: FontFamily = "Menlo-Regular"; diff --git a/src/App/Controls/RepeaterView.cs b/src/App/Controls/RepeaterView.cs index 7e58ab918..e5928e3e6 100644 --- a/src/App/Controls/RepeaterView.cs +++ b/src/App/Controls/RepeaterView.cs @@ -39,7 +39,7 @@ namespace Bit.App.Controls protected override void OnPropertyChanged(string propertyName = null) { base.OnPropertyChanged(propertyName); - if(propertyName == ItemTemplateProperty.PropertyName || propertyName == ItemsSourceProperty.PropertyName) + if (propertyName == ItemTemplateProperty.PropertyName || propertyName == ItemsSourceProperty.PropertyName) { Populate(); } @@ -55,9 +55,9 @@ namespace Bit.App.Controls { View view = null; var template = ItemTemplate; - if(template != null) + if (template != null) { - if(template is DataTemplateSelector selector) + if (template is DataTemplateSelector selector) { template = selector.SelectTemplate(item, this); } @@ -70,10 +70,10 @@ namespace Bit.App.Controls private void Populate() { - if(ItemsSource != null) + if (ItemsSource != null) { Children.Clear(); - foreach(var item in ItemsSource) + foreach (var item in ItemsSource) { Children.Add(ViewFor(item)); } @@ -82,11 +82,11 @@ namespace Bit.App.Controls 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; } - if(newValue != null && newValue is INotifyCollectionChanged nv) + if (newValue != null && newValue is INotifyCollectionChanged nv) { nv.CollectionChanged += (bindable as RepeaterView).OnCollectionChanged; } diff --git a/src/App/Models/PlatformCulture.cs b/src/App/Models/PlatformCulture.cs index 2b1dc671d..ec9f0b1d5 100644 --- a/src/App/Models/PlatformCulture.cs +++ b/src/App/Models/PlatformCulture.cs @@ -6,7 +6,7 @@ namespace Bit.App.Models { public PlatformCulture(string platformCultureString) { - if(string.IsNullOrWhiteSpace(platformCultureString)) + if (string.IsNullOrWhiteSpace(platformCultureString)) { throw new ArgumentException("Expected culture identifier.", nameof(platformCultureString)); } @@ -14,7 +14,7 @@ namespace Bit.App.Models // .NET expects dash, not underscore PlatformString = platformCultureString.Replace("_", "-"); var dashIndex = PlatformString.IndexOf("-", StringComparison.Ordinal); - if(dashIndex > 0) + if (dashIndex > 0) { var parts = PlatformString.Split('-'); LanguageCode = parts[0]; diff --git a/src/App/Pages/Accounts/EnvironmentPage.xaml.cs b/src/App/Pages/Accounts/EnvironmentPage.xaml.cs index 3e6e7b209..f5fc51531 100644 --- a/src/App/Pages/Accounts/EnvironmentPage.xaml.cs +++ b/src/App/Pages/Accounts/EnvironmentPage.xaml.cs @@ -17,7 +17,7 @@ namespace Bit.App.Pages InitializeComponent(); _vm = BindingContext as EnvironmentPageViewModel; _vm.Page = this; - if(Device.RuntimePlatform == Device.Android) + if (Device.RuntimePlatform == Device.Android) { ToolbarItems.RemoveAt(0); } @@ -32,7 +32,7 @@ namespace Bit.App.Pages private async void Submit_Clicked(object sender, EventArgs e) { - if(DoOnce()) + if (DoOnce()) { await _vm.SubmitAsync(); } @@ -40,7 +40,7 @@ namespace Bit.App.Pages private async void Close_Clicked(object sender, EventArgs e) { - if(DoOnce()) + if (DoOnce()) { _messagingService.Send("showStatusBar", false); await Navigation.PopModalAsync(); diff --git a/src/App/Pages/Accounts/HintPage.xaml.cs b/src/App/Pages/Accounts/HintPage.xaml.cs index 5eb5c09f5..178ad5db1 100644 --- a/src/App/Pages/Accounts/HintPage.xaml.cs +++ b/src/App/Pages/Accounts/HintPage.xaml.cs @@ -12,7 +12,7 @@ namespace Bit.App.Pages InitializeComponent(); _vm = BindingContext as HintPageViewModel; _vm.Page = this; - if(Device.RuntimePlatform == Device.Android) + if (Device.RuntimePlatform == Device.Android) { ToolbarItems.RemoveAt(0); } @@ -26,7 +26,7 @@ namespace Bit.App.Pages private async void Submit_Clicked(object sender, EventArgs e) { - if(DoOnce()) + if (DoOnce()) { await _vm.SubmitAsync(); } @@ -34,7 +34,7 @@ namespace Bit.App.Pages private async void Close_Clicked(object sender, System.EventArgs e) { - if(DoOnce()) + if (DoOnce()) { await Navigation.PopModalAsync(); } diff --git a/src/App/Pages/Accounts/HintPageViewModel.cs b/src/App/Pages/Accounts/HintPageViewModel.cs index cb36d1ce7..cb316759f 100644 --- a/src/App/Pages/Accounts/HintPageViewModel.cs +++ b/src/App/Pages/Accounts/HintPageViewModel.cs @@ -29,20 +29,20 @@ namespace Bit.App.Pages 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, AppResources.InternetConnectionRequiredTitle); return; } - if(string.IsNullOrWhiteSpace(Email)) + if (string.IsNullOrWhiteSpace(Email)) { await Page.DisplayAlert(AppResources.AnErrorHasOccurred, string.Format(AppResources.ValidationFieldRequired, AppResources.EmailAddress), AppResources.Ok); return; } - if(!Email.Contains("@")) + if (!Email.Contains("@")) { await Page.DisplayAlert(AppResources.AnErrorHasOccurred, AppResources.InvalidEmail, AppResources.Ok); return; @@ -57,10 +57,10 @@ namespace Bit.App.Pages await Page.DisplayAlert(null, AppResources.PasswordHintAlert, AppResources.Ok); await Page.Navigation.PopModalAsync(); } - catch(ApiException e) + catch (ApiException e) { await _deviceActionService.HideLoadingAsync(); - if(e?.Error != null) + if (e?.Error != null) { await _platformUtilsService.ShowDialogAsync(e.Error.GetSingleMessage(), AppResources.AnErrorHasOccurred); diff --git a/src/App/Pages/Accounts/HomePage.xaml.cs b/src/App/Pages/Accounts/HomePage.xaml.cs index 60ab8bbad..ce072c963 100644 --- a/src/App/Pages/Accounts/HomePage.xaml.cs +++ b/src/App/Pages/Accounts/HomePage.xaml.cs @@ -33,7 +33,7 @@ namespace Bit.App.Pages private void LogIn_Clicked(object sender, EventArgs e) { - if(DoOnce()) + if (DoOnce()) { Navigation.PushModalAsync(new NavigationPage(new LoginPage())); } @@ -41,7 +41,7 @@ namespace Bit.App.Pages private void Register_Clicked(object sender, EventArgs e) { - if(DoOnce()) + if (DoOnce()) { Navigation.PushModalAsync(new NavigationPage(new RegisterPage(this))); } @@ -49,7 +49,7 @@ namespace Bit.App.Pages private void Settings_Clicked(object sender, EventArgs e) { - if(DoOnce()) + if (DoOnce()) { Navigation.PushModalAsync(new NavigationPage(new EnvironmentPage())); } diff --git a/src/App/Pages/Accounts/LockPage.xaml.cs b/src/App/Pages/Accounts/LockPage.xaml.cs index 9e1fe7442..040a24a62 100644 --- a/src/App/Pages/Accounts/LockPage.xaml.cs +++ b/src/App/Pages/Accounts/LockPage.xaml.cs @@ -36,10 +36,10 @@ namespace Bit.App.Pages public async Task PromptFingerprintAfterResumeAsync() { - if(_vm.FingerprintLock) + if (_vm.FingerprintLock) { await Task.Delay(500); - if(!_promptedAfterResume) + if (!_promptedAfterResume) { _promptedAfterResume = true; await _vm?.PromptFingerprintAsync(); @@ -50,15 +50,15 @@ namespace Bit.App.Pages protected override async void OnAppearing() { base.OnAppearing(); - if(_appeared) + if (_appeared) { return; } _appeared = true; await _vm.InitAsync(_autoPromptFingerprint); - if(!_vm.FingerprintLock) + if (!_vm.FingerprintLock) { - if(_vm.PinLock) + if (_vm.PinLock) { RequestFocus(PinEntry); } @@ -71,7 +71,7 @@ namespace Bit.App.Pages private void Unlock_Clicked(object sender, EventArgs e) { - if(DoOnce()) + if (DoOnce()) { var tasks = Task.Run(async () => { @@ -83,7 +83,7 @@ namespace Bit.App.Pages private async void LogOut_Clicked(object sender, EventArgs e) { - if(DoOnce()) + if (DoOnce()) { await _vm.LogOutAsync(); } @@ -91,7 +91,7 @@ namespace Bit.App.Pages private async void Fingerprint_Clicked(object sender, EventArgs e) { - if(DoOnce()) + if (DoOnce()) { await _vm.PromptFingerprintAsync(); } @@ -99,21 +99,21 @@ namespace Bit.App.Pages 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)); return; } - else if(_appOptions.Uri != null) + else if (_appOptions.Uri != null) { Application.Current.MainPage = new NavigationPage(new AutofillCiphersPage(_appOptions)); return; } } var previousPage = await _storageService.GetAsync(Constants.PreviousPageKey); - if(previousPage != null) + if (previousPage != null) { await _storageService.RemoveAsync(Constants.PreviousPageKey); } diff --git a/src/App/Pages/Accounts/LockPageViewModel.cs b/src/App/Pages/Accounts/LockPageViewModel.cs index c92b8b336..6d5dce8f7 100644 --- a/src/App/Pages/Accounts/LockPageViewModel.cs +++ b/src/App/Pages/Accounts/LockPageViewModel.cs @@ -107,13 +107,13 @@ namespace Bit.App.Pages FingerprintLock = await _lockService.IsFingerprintLockSetAsync(); _email = await _userService.GetEmailAsync(); var webVault = _environmentService.GetWebVaultUrl(); - if(string.IsNullOrWhiteSpace(webVault)) + if (string.IsNullOrWhiteSpace(webVault)) { webVault = "https://bitwarden.com"; } var webVaultHostname = CoreHelpers.GetHostname(webVault); LoggedInAsText = string.Format(AppResources.LoggedInAsOn, _email, webVaultHostname); - if(PinLock) + if (PinLock) { PageTitle = AppResources.VerifyPIN; LockedVerifyText = AppResources.VaultLockedPIN; @@ -124,14 +124,14 @@ namespace Bit.App.Pages LockedVerifyText = AppResources.VaultLockedMasterPassword; } - if(FingerprintLock) + if (FingerprintLock) { var supportsFace = await _deviceActionService.SupportsFaceBiometricAsync(); - if(Device.RuntimePlatform == Device.iOS && supportsFace) + if (Device.RuntimePlatform == Device.iOS && supportsFace) { FingerprintButtonText = AppResources.UseFaceIDToUnlock; } - else if(Device.RuntimePlatform == Device.Android && _deviceActionService.UseNativeBiometric()) + else if (Device.RuntimePlatform == Device.Android && _deviceActionService.UseNativeBiometric()) { FingerprintButtonText = AppResources.UseBiometricsToUnlock; } @@ -139,7 +139,7 @@ namespace Bit.App.Pages { FingerprintButtonText = AppResources.UseFingerprintToUnlock; } - if(autoPromptFingerprint) + if (autoPromptFingerprint) { var tasks = Task.Run(async () => { @@ -152,14 +152,14 @@ namespace Bit.App.Pages public async Task SubmitAsync() { - if(PinLock && string.IsNullOrWhiteSpace(Pin)) + if (PinLock && string.IsNullOrWhiteSpace(Pin)) { await Page.DisplayAlert(AppResources.AnErrorHasOccurred, string.Format(AppResources.ValidationFieldRequired, AppResources.PIN), AppResources.Ok); return; } - if(!PinLock && string.IsNullOrWhiteSpace(MasterPassword)) + if (!PinLock && string.IsNullOrWhiteSpace(MasterPassword)) { await Page.DisplayAlert(AppResources.AnErrorHasOccurred, string.Format(AppResources.ValidationFieldRequired, AppResources.MasterPassword), @@ -171,12 +171,12 @@ namespace Bit.App.Pages var kdf = await _userService.GetKdfAsync(); var kdfIterations = await _userService.GetKdfIterationsAsync(); - if(PinLock) + if (PinLock) { var failed = true; try { - if(_pinSet.Item1) + if (_pinSet.Item1) { var key = await _cryptoService.MakeKeyFromPinAsync(Pin, _email, kdf.GetValueOrDefault(KdfType.PBKDF2_SHA256), kdfIterations.GetValueOrDefault(5000), @@ -185,7 +185,7 @@ namespace Bit.App.Pages var protectedPin = await _storageService.GetAsync(Constants.ProtectedPin); var decPin = await _cryptoService.DecryptToUtf8Async(new CipherString(protectedPin), encKey); failed = decPin != Pin; - if(!failed) + if (!failed) { Pin = string.Empty; await SetKeyAndContinueAsync(key); @@ -204,10 +204,10 @@ namespace Bit.App.Pages { failed = true; } - if(failed) + if (failed) { _invalidPinAttempts++; - if(_invalidPinAttempts >= 5) + if (_invalidPinAttempts >= 5) { _messagingService.Send("logout"); return; @@ -221,19 +221,19 @@ namespace Bit.App.Pages var key = await _cryptoService.MakeKeyAsync(MasterPassword, _email, kdf, kdfIterations); var keyHash = await _cryptoService.HashPasswordAsync(MasterPassword, key); var storedKeyHash = await _cryptoService.GetKeyHashAsync(); - if(storedKeyHash == null) + if (storedKeyHash == null) { var oldKey = await _secureStorageService.GetAsync("oldKey"); - if(key.KeyB64 == oldKey) + if (key.KeyB64 == oldKey) { await _secureStorageService.RemoveAsync("oldKey"); await _cryptoService.SetKeyHashAsync(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(Constants.ProtectedPin); var encKey = await _cryptoService.GetEncKeyAsync(key); @@ -257,7 +257,7 @@ namespace Bit.App.Pages { var confirmed = await _platformUtilsService.ShowDialogAsync(AppResources.LogoutConfirmation, AppResources.LogOut, AppResources.Yes, AppResources.Cancel); - if(confirmed) + if (confirmed) { _messagingService.Send("logout"); } @@ -273,7 +273,7 @@ namespace Bit.App.Pages public async Task PromptFingerprintAsync() { - if(!FingerprintLock) + if (!FingerprintLock) { return; } @@ -281,7 +281,7 @@ namespace Bit.App.Pages PinLock ? AppResources.PIN : AppResources.MasterPassword, () => { var page = Page as LockPage; - if(PinLock) + if (PinLock) { page.PinEntry.Focus(); } @@ -291,7 +291,7 @@ namespace Bit.App.Pages } }); _lockService.FingerprintLocked = !success; - if(success) + if (success) { await DoContinueAsync(); } @@ -300,7 +300,7 @@ namespace Bit.App.Pages private async Task SetKeyAndContinueAsync(SymmetricCryptoKey key) { var hasKey = await _cryptoService.HasKeyAsync(); - if(!hasKey) + if (!hasKey) { await _cryptoService.SetKeyAsync(key); } diff --git a/src/App/Pages/Accounts/LoginPage.xaml.cs b/src/App/Pages/Accounts/LoginPage.xaml.cs index 0a26702d4..aa6c623b5 100644 --- a/src/App/Pages/Accounts/LoginPage.xaml.cs +++ b/src/App/Pages/Accounts/LoginPage.xaml.cs @@ -19,7 +19,7 @@ namespace Bit.App.Pages _vm.Page = this; _vm.Email = email; MasterPasswordEntry = _masterPassword; - if(Device.RuntimePlatform == Device.Android) + if (Device.RuntimePlatform == Device.Android) { ToolbarItems.RemoveAt(0); } @@ -34,7 +34,7 @@ namespace Bit.App.Pages { base.OnAppearing(); await _vm.InitAsync(); - if(string.IsNullOrWhiteSpace(_vm.Email)) + if (string.IsNullOrWhiteSpace(_vm.Email)) { RequestFocus(_email); } @@ -46,7 +46,7 @@ namespace Bit.App.Pages private async void LogIn_Clicked(object sender, EventArgs e) { - if(DoOnce()) + if (DoOnce()) { await _vm.LogInAsync(); } @@ -54,7 +54,7 @@ namespace Bit.App.Pages private void Hint_Clicked(object sender, EventArgs e) { - if(DoOnce()) + if (DoOnce()) { Navigation.PushModalAsync(new NavigationPage(new HintPage())); } @@ -62,7 +62,7 @@ namespace Bit.App.Pages private async void Close_Clicked(object sender, EventArgs e) { - if(DoOnce()) + if (DoOnce()) { _messagingService.Send("showStatusBar", false); await Navigation.PopModalAsync(); diff --git a/src/App/Pages/Accounts/LoginPageViewModel.cs b/src/App/Pages/Accounts/LoginPageViewModel.cs index 2c7fad603..d6c8893fc 100644 --- a/src/App/Pages/Accounts/LoginPageViewModel.cs +++ b/src/App/Pages/Accounts/LoginPageViewModel.cs @@ -68,7 +68,7 @@ namespace Bit.App.Pages public async Task InitAsync() { - if(string.IsNullOrWhiteSpace(Email)) + if (string.IsNullOrWhiteSpace(Email)) { Email = await _storageService.GetAsync(Keys_RememberedEmail); } @@ -78,25 +78,25 @@ namespace Bit.App.Pages 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, AppResources.InternetConnectionRequiredTitle); return; } - if(string.IsNullOrWhiteSpace(Email)) + if (string.IsNullOrWhiteSpace(Email)) { await Page.DisplayAlert(AppResources.AnErrorHasOccurred, string.Format(AppResources.ValidationFieldRequired, AppResources.EmailAddress), AppResources.Ok); return; } - if(!Email.Contains("@")) + if (!Email.Contains("@")) { await Page.DisplayAlert(AppResources.AnErrorHasOccurred, AppResources.InvalidEmail, AppResources.Ok); return; } - if(string.IsNullOrWhiteSpace(MasterPassword)) + if (string.IsNullOrWhiteSpace(MasterPassword)) { await Page.DisplayAlert(AppResources.AnErrorHasOccurred, string.Format(AppResources.ValidationFieldRequired, AppResources.MasterPassword), @@ -110,7 +110,7 @@ namespace Bit.App.Pages await _deviceActionService.ShowLoadingAsync(AppResources.LoggingIn); var response = await _authService.LogInAsync(Email, MasterPassword); MasterPassword = string.Empty; - if(RememberEmail) + if (RememberEmail) { await _storageService.SaveAsync(Keys_RememberedEmail, Email); } @@ -119,7 +119,7 @@ namespace Bit.App.Pages await _storageService.RemoveAsync(Keys_RememberedEmail); } await _deviceActionService.HideLoadingAsync(); - if(response.TwoFactor) + if (response.TwoFactor) { var page = new TwoFactorPage(); await Page.Navigation.PushModalAsync(new NavigationPage(page)); @@ -132,10 +132,10 @@ namespace Bit.App.Pages Application.Current.MainPage = new TabsPage(); } } - catch(ApiException e) + catch (ApiException e) { await _deviceActionService.HideLoadingAsync(); - if(e?.Error != null) + if (e?.Error != null) { await _platformUtilsService.ShowDialogAsync(e.Error.GetSingleMessage(), AppResources.AnErrorHasOccurred); diff --git a/src/App/Pages/Accounts/RegisterPage.xaml.cs b/src/App/Pages/Accounts/RegisterPage.xaml.cs index 8254b9ad9..0966bc78b 100644 --- a/src/App/Pages/Accounts/RegisterPage.xaml.cs +++ b/src/App/Pages/Accounts/RegisterPage.xaml.cs @@ -19,14 +19,14 @@ namespace Bit.App.Pages _vm.Page = this; _vm.RegistrationSuccess = async () => { - if(homePage != null) + if (homePage != null) { await homePage.DismissRegisterPageAndLogInAsync(_vm.Email); } }; MasterPasswordEntry = _masterPassword; ConfirmMasterPasswordEntry = _confirmMasterPassword; - if(Device.RuntimePlatform == Device.Android) + if (Device.RuntimePlatform == Device.Android) { ToolbarItems.RemoveAt(0); } @@ -50,7 +50,7 @@ namespace Bit.App.Pages private async void Submit_Clicked(object sender, EventArgs e) { - if(DoOnce()) + if (DoOnce()) { await _vm.SubmitAsync(); } @@ -58,7 +58,7 @@ namespace Bit.App.Pages private async void Close_Clicked(object sender, EventArgs e) { - if(DoOnce()) + if (DoOnce()) { _messagingService.Send("showStatusBar", false); await Navigation.PopModalAsync(); diff --git a/src/App/Pages/Accounts/RegisterPageViewModel.cs b/src/App/Pages/Accounts/RegisterPageViewModel.cs index 2648ef976..0f771a36f 100644 --- a/src/App/Pages/Accounts/RegisterPageViewModel.cs +++ b/src/App/Pages/Accounts/RegisterPageViewModel.cs @@ -55,38 +55,38 @@ namespace Bit.App.Pages 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, AppResources.InternetConnectionRequiredTitle); return; } - if(string.IsNullOrWhiteSpace(Email)) + if (string.IsNullOrWhiteSpace(Email)) { await Page.DisplayAlert(AppResources.AnErrorHasOccurred, string.Format(AppResources.ValidationFieldRequired, AppResources.EmailAddress), AppResources.Ok); return; } - if(!Email.Contains("@")) + if (!Email.Contains("@")) { await Page.DisplayAlert(AppResources.AnErrorHasOccurred, AppResources.InvalidEmail, AppResources.Ok); return; } - if(string.IsNullOrWhiteSpace(MasterPassword)) + if (string.IsNullOrWhiteSpace(MasterPassword)) { await Page.DisplayAlert(AppResources.AnErrorHasOccurred, string.Format(AppResources.ValidationFieldRequired, AppResources.MasterPassword), AppResources.Ok); return; } - if(MasterPassword.Length < 8) + if (MasterPassword.Length < 8) { await Page.DisplayAlert(AppResources.AnErrorHasOccurred, AppResources.MasterPasswordLengthValMessage, AppResources.Ok); return; } - if(MasterPassword != ConfirmMasterPassword) + if (MasterPassword != ConfirmMasterPassword) { await Page.DisplayAlert(AppResources.AnErrorHasOccurred, AppResources.MasterPasswordConfirmationValMessage, AppResources.Ok); @@ -132,10 +132,10 @@ namespace Bit.App.Pages }); RegistrationSuccess?.Invoke(); } - catch(ApiException e) + catch (ApiException e) { await _deviceActionService.HideLoadingAsync(); - if(e?.Error != null) + if (e?.Error != null) { await _platformUtilsService.ShowDialogAsync(e.Error.GetSingleMessage(), AppResources.AnErrorHasOccurred); diff --git a/src/App/Pages/Accounts/TwoFactorPage.xaml.cs b/src/App/Pages/Accounts/TwoFactorPage.xaml.cs index e3fae6c8d..50db79f1c 100644 --- a/src/App/Pages/Accounts/TwoFactorPage.xaml.cs +++ b/src/App/Pages/Accounts/TwoFactorPage.xaml.cs @@ -24,7 +24,7 @@ namespace Bit.App.Pages _vm = BindingContext as TwoFactorPageViewModel; _vm.Page = this; DuoWebView = _duoWebView; - if(Device.RuntimePlatform == Device.Android) + if (Device.RuntimePlatform == Device.Android) { ToolbarItems.Remove(_cancelItem); } @@ -34,7 +34,7 @@ namespace Bit.App.Pages public void AddContinueButton() { - if(!ToolbarItems.Contains(_continueItem)) + if (!ToolbarItems.Contains(_continueItem)) { ToolbarItems.Add(_continueItem); } @@ -42,7 +42,7 @@ namespace Bit.App.Pages public void RemoveContinueButton() { - if(ToolbarItems.Contains(_continueItem)) + if (ToolbarItems.Contains(_continueItem)) { ToolbarItems.Remove(_continueItem); } @@ -53,10 +53,10 @@ namespace Bit.App.Pages base.OnAppearing(); _broadcasterService.Subscribe(nameof(TwoFactorPage), (message) => { - if(message.Command == "gotYubiKeyOTP") + if (message.Command == "gotYubiKeyOTP") { var token = (string)message.Data; - if(_vm.YubikeyMethod && !string.IsNullOrWhiteSpace(token) && + if (_vm.YubikeyMethod && !string.IsNullOrWhiteSpace(token) && token.Length == 44 && !token.Contains(" ")) { 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); } } }); - if(!_inited) + if (!_inited) { _inited = true; await LoadOnAppearedAsync(_scrollView, true, () => { _vm.Init(); - if(_vm.TotpMethod) + if (_vm.TotpMethod) { RequestFocus(_totpEntry); } @@ -93,7 +93,7 @@ namespace Bit.App.Pages protected override void OnDisappearing() { base.OnDisappearing(); - if(!_vm.YubikeyMethod) + if (!_vm.YubikeyMethod) { _messagingService.Send("listenYubiKeyOTP", false); _broadcasterService.Unsubscribe(nameof(TwoFactorPage)); @@ -101,7 +101,7 @@ namespace Bit.App.Pages } protected override bool OnBackButtonPressed() { - if(_vm.YubikeyMethod) + if (_vm.YubikeyMethod) { _messagingService.Send("listenYubiKeyOTP", false); _broadcasterService.Unsubscribe(nameof(TwoFactorPage)); @@ -111,7 +111,7 @@ namespace Bit.App.Pages private async void Continue_Clicked(object sender, EventArgs e) { - if(DoOnce()) + if (DoOnce()) { await _vm.SubmitAsync(); } @@ -119,7 +119,7 @@ namespace Bit.App.Pages private async void Methods_Clicked(object sender, EventArgs e) { - if(DoOnce()) + if (DoOnce()) { await _vm.AnotherMethodAsync(); } @@ -127,7 +127,7 @@ namespace Bit.App.Pages private async void ResendEmail_Clicked(object sender, EventArgs e) { - if(DoOnce()) + if (DoOnce()) { await _vm.SendEmailAsync(true, true); } @@ -135,7 +135,7 @@ namespace Bit.App.Pages private async void Close_Clicked(object sender, System.EventArgs e) { - if(DoOnce()) + if (DoOnce()) { await Navigation.PopModalAsync(); } @@ -143,9 +143,9 @@ namespace Bit.App.Pages private void TryAgain_Clicked(object sender, EventArgs e) { - if(DoOnce()) + if (DoOnce()) { - if(_vm.YubikeyMethod) + if (_vm.YubikeyMethod) { _messagingService.Send("listenYubiKeyOTP", true); } diff --git a/src/App/Pages/Accounts/TwoFactorPageViewModel.cs b/src/App/Pages/Accounts/TwoFactorPageViewModel.cs index 2e5171d85..61ba7b5a7 100644 --- a/src/App/Pages/Accounts/TwoFactorPageViewModel.cs +++ b/src/App/Pages/Accounts/TwoFactorPageViewModel.cs @@ -91,7 +91,7 @@ namespace Bit.App.Pages public void Init() { - if(string.IsNullOrWhiteSpace(_authService.Email) || + if (string.IsNullOrWhiteSpace(_authService.Email) || string.IsNullOrWhiteSpace(_authService.MasterPasswordHash) || _authService.TwoFactorProvidersData == null) { @@ -99,11 +99,11 @@ namespace Bit.App.Pages return; } - if(!string.IsNullOrWhiteSpace(_environmentService.BaseUrl)) + if (!string.IsNullOrWhiteSpace(_environmentService.BaseUrl)) { _webVaultUrl = _environmentService.BaseUrl; } - else if(!string.IsNullOrWhiteSpace(_environmentService.WebVaultUrl)) + else if (!string.IsNullOrWhiteSpace(_environmentService.WebVaultUrl)) { _webVaultUrl = _environmentService.WebVaultUrl; } @@ -117,7 +117,7 @@ namespace Bit.App.Pages public void Load() { - if(SelectedProviderType == null) + if (SelectedProviderType == null) { PageTitle = AppResources.LoginUnavailable; return; @@ -125,7 +125,7 @@ namespace Bit.App.Pages var page = Page as TwoFactorPage; PageTitle = _authService.TwoFactorProviders[SelectedProviderType.Value].Name; var providerData = _authService.TwoFactorProvidersData[SelectedProviderType.Value]; - switch(SelectedProviderType.Value) + switch (SelectedProviderType.Value) { case TwoFactorProviderType.U2f: // TODO @@ -148,7 +148,7 @@ namespace Bit.App.Pages case TwoFactorProviderType.Email: TotpInstruction = string.Format(AppResources.EnterVerificationCodeEmail, providerData["Email"] as string); - if(_authService.TwoFactorProvidersData.Count > 1) + if (_authService.TwoFactorProvidersData.Count > 1) { var emailTask = Task.Run(() => SendEmailAsync(false, false)); } @@ -160,11 +160,11 @@ namespace Bit.App.Pages break; } - if(!YubikeyMethod) + if (!YubikeyMethod) { _messagingService.Send("listenYubiKeyOTP", false); } - if(SelectedProviderType == null || DuoMethod) + if (SelectedProviderType == null || DuoMethod) { page.RemoveContinueButton(); } @@ -176,24 +176,24 @@ namespace Bit.App.Pages public async Task SubmitAsync() { - if(SelectedProviderType == null) + if (SelectedProviderType == null) { return; } - if(Xamarin.Essentials.Connectivity.NetworkAccess == Xamarin.Essentials.NetworkAccess.None) + if (Xamarin.Essentials.Connectivity.NetworkAccess == Xamarin.Essentials.NetworkAccess.None) { await _platformUtilsService.ShowDialogAsync(AppResources.InternetConnectionRequiredMessage, AppResources.InternetConnectionRequiredTitle); return; } - if(string.IsNullOrWhiteSpace(Token)) + if (string.IsNullOrWhiteSpace(Token)) { await _platformUtilsService.ShowDialogAsync( string.Format(AppResources.ValidationFieldRequired, AppResources.VerificationCode), AppResources.AnErrorHasOccurred); return; } - if(SelectedProviderType == TwoFactorProviderType.Email || + if (SelectedProviderType == TwoFactorProviderType.Email || SelectedProviderType == TwoFactorProviderType.Authenticator) { Token = Token.Replace(" ", string.Empty).Trim(); @@ -211,10 +211,10 @@ namespace Bit.App.Pages await _stateService.SaveAsync(Constants.DisableFaviconKey, disableFavicon.GetValueOrDefault()); Application.Current.MainPage = new TabsPage(); } - catch(ApiException e) + catch (ApiException e) { await _deviceActionService.HideLoadingAsync(); - if(e?.Error != null) + if (e?.Error != null) { await _platformUtilsService.ShowDialogAsync(e.Error.GetSingleMessage(), AppResources.AnErrorHasOccurred); @@ -229,14 +229,14 @@ namespace Bit.App.Pages options.Add(AppResources.RecoveryCodeTitle); var method = await Page.DisplayActionSheet(AppResources.TwoStepLoginOptions, AppResources.Cancel, null, options.ToArray()); - if(method == AppResources.RecoveryCodeTitle) + if (method == AppResources.RecoveryCodeTitle) { _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; - if(selected == SelectedProviderType) + if (selected == SelectedProviderType) { // Nothing changed return; @@ -248,11 +248,11 @@ namespace Bit.App.Pages public async Task SendEmailAsync(bool showLoading, bool doToast) { - if(!EmailMethod) + if (!EmailMethod) { 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, AppResources.InternetConnectionRequiredTitle); @@ -260,7 +260,7 @@ namespace Bit.App.Pages } try { - if(showLoading) + if (showLoading) { await _deviceActionService.ShowLoadingAsync(AppResources.Submitting); } @@ -270,19 +270,19 @@ namespace Bit.App.Pages MasterPasswordHash = _authService.MasterPasswordHash }; await _apiService.PostTwoFactorEmailAsync(request); - if(showLoading) + if (showLoading) { await _deviceActionService.HideLoadingAsync(); } - if(doToast) + if (doToast) { _platformUtilsService.ShowToast("success", null, AppResources.VerificationEmailSent); } return true; } - catch(ApiException) + catch (ApiException) { - if(showLoading) + if (showLoading) { await _deviceActionService.HideLoadingAsync(); } diff --git a/src/App/Pages/BaseContentPage.cs b/src/App/Pages/BaseContentPage.cs index e4f59de48..4d7d8b803 100644 --- a/src/App/Pages/BaseContentPage.cs +++ b/src/App/Pages/BaseContentPage.cs @@ -34,7 +34,7 @@ namespace Bit.App.Pages 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. return false; @@ -52,7 +52,7 @@ namespace Bit.App.Pages VerticalOptions = LayoutOptions.CenterAndExpand, HorizontalOptions = LayoutOptions.Center }; - if(targetView != null) + if (targetView != null) { targetView.Content = indicator; } @@ -68,9 +68,9 @@ namespace Bit.App.Pages async Task DoWorkAsync() { await workFunction.Invoke(); - if(sourceView != null) + if (sourceView != null) { - if(targetView != null) + if (targetView != null) { targetView.Content = sourceView; } @@ -80,7 +80,7 @@ namespace Bit.App.Pages } } } - if(Device.RuntimePlatform == Device.iOS) + if (Device.RuntimePlatform == Device.iOS) { await DoWorkAsync(); return; @@ -103,7 +103,7 @@ namespace Bit.App.Pages private void SetStorageService() { - if(_storageService == null) + if (_storageService == null) { _storageService = ServiceContainer.Resolve("storageService"); } diff --git a/src/App/Pages/Generator/GeneratorHistoryPage.xaml.cs b/src/App/Pages/Generator/GeneratorHistoryPage.xaml.cs index 48479dd17..d40ba0d50 100644 --- a/src/App/Pages/Generator/GeneratorHistoryPage.xaml.cs +++ b/src/App/Pages/Generator/GeneratorHistoryPage.xaml.cs @@ -14,7 +14,7 @@ namespace Bit.App.Pages SetActivityIndicator(); _vm = BindingContext as GeneratorHistoryPageViewModel; _vm.Page = this; - if(Device.RuntimePlatform == Device.iOS) + if (Device.RuntimePlatform == Device.iOS) { ToolbarItems.Add(_closeItem); ToolbarItems.Add(_moreItem); @@ -40,7 +40,7 @@ namespace Bit.App.Pages private async void Close_Clicked(object sender, System.EventArgs e) { - if(DoOnce()) + if (DoOnce()) { await Navigation.PopModalAsync(); } @@ -48,13 +48,13 @@ namespace Bit.App.Pages private async void More_Clicked(object sender, EventArgs e) { - if(!DoOnce()) + if (!DoOnce()) { return; } var selection = await DisplayActionSheet(AppResources.Options, AppResources.Cancel, null, AppResources.Clear); - if(selection == AppResources.Clear) + if (selection == AppResources.Clear) { await _vm.ClearAsync(); } diff --git a/src/App/Pages/Generator/GeneratorPage.xaml.cs b/src/App/Pages/Generator/GeneratorPage.xaml.cs index 724f513df..dddf7bddc 100644 --- a/src/App/Pages/Generator/GeneratorPage.xaml.cs +++ b/src/App/Pages/Generator/GeneratorPage.xaml.cs @@ -23,9 +23,9 @@ namespace Bit.App.Pages _fromTabPage = fromTabPage; _selectAction = selectAction; var isIos = Device.RuntimePlatform == Device.iOS; - if(selectAction != null) + if (selectAction != null) { - if(isIos) + if (isIos) { ToolbarItems.Add(_closeItem); } @@ -33,7 +33,7 @@ namespace Bit.App.Pages } else { - if(isIos) + if (isIos) { ToolbarItems.Add(_moreItem); } @@ -42,7 +42,7 @@ namespace Bit.App.Pages ToolbarItems.Add(_historyItem); } } - if(isIos) + if (isIos) { _typePicker.On().SetUpdateMode(UpdateMode.WhenFinished); } @@ -56,7 +56,7 @@ namespace Bit.App.Pages protected async override void OnAppearing() { base.OnAppearing(); - if(!_fromTabPage) + if (!_fromTabPage) { await InitAsync(); } @@ -64,7 +64,7 @@ namespace Bit.App.Pages protected override bool OnBackButtonPressed() { - if(Device.RuntimePlatform == Device.Android && _tabsPage != null) + if (Device.RuntimePlatform == Device.Android && _tabsPage != null) { _tabsPage.ResetToVaultPage(); return true; @@ -84,13 +84,13 @@ namespace Bit.App.Pages private async void More_Clicked(object sender, EventArgs e) { - if(!DoOnce()) + if (!DoOnce()) { return; } var selection = await DisplayActionSheet(AppResources.Options, AppResources.Cancel, null, AppResources.PasswordHistory); - if(selection == AppResources.PasswordHistory) + if (selection == AppResources.PasswordHistory) { var page = new GeneratorHistoryPage(); 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) { - if(DoOnce()) + if (DoOnce()) { await Navigation.PopModalAsync(); } diff --git a/src/App/Pages/Generator/GeneratorPageViewModel.cs b/src/App/Pages/Generator/GeneratorPageViewModel.cs index 2b3db6f18..fcf99fb26 100644 --- a/src/App/Pages/Generator/GeneratorPageViewModel.cs +++ b/src/App/Pages/Generator/GeneratorPageViewModel.cs @@ -67,7 +67,7 @@ namespace Bit.App.Pages get => _length; set { - if(SetProperty(ref _length, value)) + if (SetProperty(ref _length, value)) { _options.Length = value; var task = SliderInputAsync(); @@ -80,7 +80,7 @@ namespace Bit.App.Pages get => _uppercase; set { - if(SetProperty(ref _uppercase, value)) + if (SetProperty(ref _uppercase, value)) { _options.Uppercase = value; var task = SaveOptionsAsync(); @@ -93,7 +93,7 @@ namespace Bit.App.Pages get => _lowercase; set { - if(SetProperty(ref _lowercase, value)) + if (SetProperty(ref _lowercase, value)) { _options.Lowercase = value; var task = SaveOptionsAsync(); @@ -106,7 +106,7 @@ namespace Bit.App.Pages get => _number; set { - if(SetProperty(ref _number, value)) + if (SetProperty(ref _number, value)) { _options.Number = value; var task = SaveOptionsAsync(); @@ -119,7 +119,7 @@ namespace Bit.App.Pages get => _special; set { - if(SetProperty(ref _special, value)) + if (SetProperty(ref _special, value)) { _options.Special = value; var task = SaveOptionsAsync(); @@ -132,7 +132,7 @@ namespace Bit.App.Pages get => _avoidAmbiguous; set { - if(SetProperty(ref _avoidAmbiguous, value)) + if (SetProperty(ref _avoidAmbiguous, value)) { _options.Ambiguous = !value; var task = SaveOptionsAsync(); @@ -145,7 +145,7 @@ namespace Bit.App.Pages get => _minNumber; set { - if(SetProperty(ref _minNumber, value)) + if (SetProperty(ref _minNumber, value)) { _options.MinNumber = value; var task = SaveOptionsAsync(); @@ -158,7 +158,7 @@ namespace Bit.App.Pages get => _minSpecial; set { - if(SetProperty(ref _minSpecial, value)) + if (SetProperty(ref _minSpecial, value)) { _options.MinSpecial = value; var task = SaveOptionsAsync(); @@ -171,7 +171,7 @@ namespace Bit.App.Pages get => _numWords; set { - if(SetProperty(ref _numWords, value)) + if (SetProperty(ref _numWords, value)) { _options.NumWords = value; var task = SaveOptionsAsync(); @@ -184,12 +184,12 @@ namespace Bit.App.Pages get => _wordSeparator; set { - if(value == null) + if (value == null) { return; } var val = value.Trim(); - if(SetProperty(ref _wordSeparator, val)) + if (SetProperty(ref _wordSeparator, val)) { _options.WordSeparator = val; var task = SaveOptionsAsync(); @@ -202,7 +202,7 @@ namespace Bit.App.Pages get => _capitalize; set { - if(SetProperty(ref _capitalize, value)) + if (SetProperty(ref _capitalize, value)) { _options.Capitalize = value; var task = SaveOptionsAsync(); @@ -215,7 +215,7 @@ namespace Bit.App.Pages get => _includeNumber; set { - if(SetProperty(ref _includeNumber, value)) + if (SetProperty(ref _includeNumber, value)) { _options.Number = value; var task = SaveOptionsAsync(); @@ -240,7 +240,7 @@ namespace Bit.App.Pages get => _typeSelectedIndex; set { - if(SetProperty(ref _typeSelectedIndex, value)) + if (SetProperty(ref _typeSelectedIndex, value)) { IsPassword = value == 0; var task = SaveOptionsAsync(); @@ -264,7 +264,7 @@ namespace Bit.App.Pages public async Task SaveOptionsAsync(bool regenerate = true) { - if(!_doneIniting) + if (!_doneIniting) { return; } @@ -272,7 +272,7 @@ namespace Bit.App.Pages _passwordGenerationService.NormalizeOptions(_options, _enforcedPolicyOptions); await _passwordGenerationService.SaveOptionsAsync(_options); LoadFromOptions(); - if(regenerate) + if (regenerate) { await RegenerateAsync(); } diff --git a/src/App/Pages/Settings/AccessibilityServicePage.xaml.cs b/src/App/Pages/Settings/AccessibilityServicePage.xaml.cs index d39360295..93dc5ed32 100644 --- a/src/App/Pages/Settings/AccessibilityServicePage.xaml.cs +++ b/src/App/Pages/Settings/AccessibilityServicePage.xaml.cs @@ -25,7 +25,7 @@ namespace Bit.App.Pages _timerStarted = DateTime.UtcNow; Device.StartTimer(new TimeSpan(0, 0, 3), () => { - if(_timerStarted == null || (DateTime.UtcNow - _timerStarted) > _timerMaxLength) + if (_timerStarted == null || (DateTime.UtcNow - _timerStarted) > _timerMaxLength) { return false; } @@ -45,7 +45,7 @@ namespace Bit.App.Pages private void Settings_Clicked(object sender, EventArgs e) { - if(DoOnce()) + if (DoOnce()) { _vm.OpenSettings(); } @@ -53,7 +53,7 @@ namespace Bit.App.Pages private void OverlayPermissionSettings_Clicked(object sender, EventArgs e) { - if(DoOnce()) + if (DoOnce()) { _vm.OpenOverlayPermissionSettings(); } diff --git a/src/App/Pages/Settings/AutofillPage.xaml.cs b/src/App/Pages/Settings/AutofillPage.xaml.cs index b3c7efb59..b52146856 100644 --- a/src/App/Pages/Settings/AutofillPage.xaml.cs +++ b/src/App/Pages/Settings/AutofillPage.xaml.cs @@ -11,7 +11,7 @@ namespace Bit.App.Pages private void Close_Clicked(object sender, EventArgs e) { - if(DoOnce()) + if (DoOnce()) { Navigation.PopModalAsync(); } diff --git a/src/App/Pages/Settings/AutofillServicePage.xaml.cs b/src/App/Pages/Settings/AutofillServicePage.xaml.cs index 053e929ec..14f3ad54f 100644 --- a/src/App/Pages/Settings/AutofillServicePage.xaml.cs +++ b/src/App/Pages/Settings/AutofillServicePage.xaml.cs @@ -24,7 +24,7 @@ namespace Bit.App.Pages _timerStarted = DateTime.UtcNow; Device.StartTimer(new TimeSpan(0, 0, 2), () => { - if(_timerStarted == null || (DateTime.UtcNow - _timerStarted) > _timerMaxLength) + if (_timerStarted == null || (DateTime.UtcNow - _timerStarted) > _timerMaxLength) { return false; } @@ -43,7 +43,7 @@ namespace Bit.App.Pages private void Settings_Clicked(object sender, EventArgs e) { - if(DoOnce()) + if (DoOnce()) { _vm.OpenSettings(); } diff --git a/src/App/Pages/Settings/ExportVaultPage.xaml.cs b/src/App/Pages/Settings/ExportVaultPage.xaml.cs index a1578d8d9..1f16be450 100644 --- a/src/App/Pages/Settings/ExportVaultPage.xaml.cs +++ b/src/App/Pages/Settings/ExportVaultPage.xaml.cs @@ -26,12 +26,12 @@ namespace Bit.App.Pages await _vm.InitAsync(); _broadcasterService.Subscribe(nameof(ExportVaultPage), (message) => { - if(message.Command == "selectSaveFileResult") + if (message.Command == "selectSaveFileResult") { Device.BeginInvokeOnMainThread(() => { var data = message.Data as Tuple; - if(data == null) + if (data == null) { return; } @@ -52,7 +52,7 @@ namespace Bit.App.Pages private async void Close_Clicked(object sender, System.EventArgs e) { - if(DoOnce()) + if (DoOnce()) { await Navigation.PopModalAsync(); } @@ -60,7 +60,7 @@ namespace Bit.App.Pages private async void ExportVault_Clicked(object sender, EventArgs e) { - if(DoOnce()) + if (DoOnce()) { await _vm.ExportVaultAsync(); } diff --git a/src/App/Pages/Settings/ExportVaultPageViewModel.cs b/src/App/Pages/Settings/ExportVaultPageViewModel.cs index c7db767c5..72d6e727c 100644 --- a/src/App/Pages/Settings/ExportVaultPageViewModel.cs +++ b/src/App/Pages/Settings/ExportVaultPageViewModel.cs @@ -83,7 +83,7 @@ namespace Bit.App.Pages public async Task ExportVaultAsync() { - if(string.IsNullOrEmpty(_masterPassword)) + if (string.IsNullOrEmpty(_masterPassword)) { await _platformUtilsService.ShowDialogAsync(_i18nService.T("InvalidMasterPassword")); return; @@ -93,7 +93,7 @@ namespace Bit.App.Pages MasterPassword = string.Empty; var storedKeyHash = await _cryptoService.GetKeyHashAsync(); - if(storedKeyHash != null && keyHash != null && storedKeyHash == keyHash) + if (storedKeyHash != null && keyHash != null && storedKeyHash == keyHash) { try { @@ -102,13 +102,13 @@ namespace Bit.App.Pages _defaultFilename = _exportService.GetFileName(null, fileFormat); _exportResult = Encoding.ASCII.GetBytes(data.Result); - if(!_deviceActionService.SaveFile(_exportResult, null, _defaultFilename, null)) + if (!_deviceActionService.SaveFile(_exportResult, null, _defaultFilename, null)) { ClearResult(); await _platformUtilsService.ShowDialogAsync(_i18nService.T("ExportVaultFailure")); } } - catch(Exception ex) + catch (Exception ex) { ClearResult(); await _platformUtilsService.ShowDialogAsync(_i18nService.T("ExportVaultFailure")); @@ -123,7 +123,7 @@ namespace Bit.App.Pages 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(); _platformUtilsService.ShowToast("success", null, _i18nService.T("ExportVaultSuccess")); diff --git a/src/App/Pages/Settings/ExtensionPage.xaml.cs b/src/App/Pages/Settings/ExtensionPage.xaml.cs index b4deb8bc4..aa2219d09 100644 --- a/src/App/Pages/Settings/ExtensionPage.xaml.cs +++ b/src/App/Pages/Settings/ExtensionPage.xaml.cs @@ -21,7 +21,7 @@ namespace Bit.App.Pages private void Show_Clicked(object sender, EventArgs e) { - if(DoOnce()) + if (DoOnce()) { _vm.ShowExtension(); } @@ -29,7 +29,7 @@ namespace Bit.App.Pages private void Close_Clicked(object sender, EventArgs e) { - if(DoOnce()) + if (DoOnce()) { Navigation.PopModalAsync(); } diff --git a/src/App/Pages/Settings/ExtensionPageViewModel.cs b/src/App/Pages/Settings/ExtensionPageViewModel.cs index adddc549e..e513e380d 100644 --- a/src/App/Pages/Settings/ExtensionPageViewModel.cs +++ b/src/App/Pages/Settings/ExtensionPageViewModel.cs @@ -66,7 +66,7 @@ namespace Bit.App.Pages public void EnabledExtension(bool enabled) { Started = true; - if(!Activated && enabled) + if (!Activated && enabled) { Activated = enabled; } diff --git a/src/App/Pages/Settings/FolderAddEditPage.xaml.cs b/src/App/Pages/Settings/FolderAddEditPage.xaml.cs index f835e64c7..958756e54 100644 --- a/src/App/Pages/Settings/FolderAddEditPage.xaml.cs +++ b/src/App/Pages/Settings/FolderAddEditPage.xaml.cs @@ -17,15 +17,15 @@ namespace Bit.App.Pages _vm.FolderId = folderId; _vm.Init(); SetActivityIndicator(); - if(!_vm.EditMode || Device.RuntimePlatform == Device.iOS) + if (!_vm.EditMode || Device.RuntimePlatform == Device.iOS) { ToolbarItems.Remove(_deleteItem); } - if(_vm.EditMode && Device.RuntimePlatform == Device.iOS) + if (_vm.EditMode && Device.RuntimePlatform == Device.iOS) { ToolbarItems.Add(_moreItem); } - if(Device.RuntimePlatform == Device.Android) + if (Device.RuntimePlatform == Device.Android) { ToolbarItems.RemoveAt(0); } @@ -37,7 +37,7 @@ namespace Bit.App.Pages await LoadOnAppearedAsync(_scrollView, true, async () => { await _vm.LoadAsync(); - if(!_vm.EditMode) + if (!_vm.EditMode) { RequestFocus(_nameEntry); } @@ -46,7 +46,7 @@ namespace Bit.App.Pages private async void Save_Clicked(object sender, System.EventArgs e) { - if(DoOnce()) + if (DoOnce()) { await _vm.SubmitAsync(); } @@ -54,7 +54,7 @@ namespace Bit.App.Pages private async void Delete_Clicked(object sender, System.EventArgs e) { - if(DoOnce()) + if (DoOnce()) { await _vm.DeleteAsync(); } @@ -62,7 +62,7 @@ namespace Bit.App.Pages private async void Close_Clicked(object sender, System.EventArgs e) { - if(DoOnce()) + if (DoOnce()) { await Navigation.PopModalAsync(); } @@ -70,14 +70,14 @@ namespace Bit.App.Pages private async void More_Clicked(object sender, System.EventArgs e) { - if(!DoOnce()) + if (!DoOnce()) { return; } var options = new List { }; var selection = await DisplayActionSheet(AppResources.Options, AppResources.Cancel, _vm.EditMode ? AppResources.Delete : null, options.ToArray()); - if(selection == AppResources.Delete) + if (selection == AppResources.Delete) { await _vm.DeleteAsync(); } diff --git a/src/App/Pages/Settings/FolderAddEditPageViewModel.cs b/src/App/Pages/Settings/FolderAddEditPageViewModel.cs index 76124b962..33479ae68 100644 --- a/src/App/Pages/Settings/FolderAddEditPageViewModel.cs +++ b/src/App/Pages/Settings/FolderAddEditPageViewModel.cs @@ -41,12 +41,12 @@ namespace Bit.App.Pages public async Task LoadAsync() { - if(Folder == null) + if (Folder == null) { - if(EditMode) + if (EditMode) { var folder = await _folderService.GetAsync(FolderId); - if(folder != null) + if (folder != null) { Folder = await folder.DecryptAsync(); } @@ -60,17 +60,17 @@ namespace Bit.App.Pages public async Task SubmitAsync() { - if(Folder == null) + if (Folder == null) { 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, AppResources.InternetConnectionRequiredTitle); return false; } - if(string.IsNullOrWhiteSpace(Folder.Name)) + if (string.IsNullOrWhiteSpace(Folder.Name)) { await Page.DisplayAlert(AppResources.AnErrorHasOccurred, string.Format(AppResources.ValidationFieldRequired, AppResources.Name), @@ -90,10 +90,10 @@ namespace Bit.App.Pages await Page.Navigation.PopModalAsync(); return true; } - catch(ApiException e) + catch (ApiException e) { await _deviceActionService.HideLoadingAsync(); - if(e?.Error != null) + if (e?.Error != null) { await _platformUtilsService.ShowDialogAsync(e.Error.GetSingleMessage(), AppResources.AnErrorHasOccurred); @@ -104,11 +104,11 @@ namespace Bit.App.Pages public async Task DeleteAsync() { - if(Folder == null) + if (Folder == null) { 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, AppResources.InternetConnectionRequiredTitle); @@ -116,7 +116,7 @@ namespace Bit.App.Pages } var confirmed = await _platformUtilsService.ShowDialogAsync(AppResources.DoYouReallyWantToDelete, null, AppResources.Yes, AppResources.No); - if(!confirmed) + if (!confirmed) { return false; } @@ -129,10 +129,10 @@ namespace Bit.App.Pages await Page.Navigation.PopModalAsync(); return true; } - catch(ApiException e) + catch (ApiException e) { await _deviceActionService.HideLoadingAsync(); - if(e?.Error != null) + if (e?.Error != null) { await _platformUtilsService.ShowDialogAsync(e.Error.GetSingleMessage(), AppResources.AnErrorHasOccurred); diff --git a/src/App/Pages/Settings/FoldersPage.xaml.cs b/src/App/Pages/Settings/FoldersPage.xaml.cs index 90b64b8f4..58f948e39 100644 --- a/src/App/Pages/Settings/FoldersPage.xaml.cs +++ b/src/App/Pages/Settings/FoldersPage.xaml.cs @@ -15,7 +15,7 @@ namespace Bit.App.Pages _vm = BindingContext as FoldersPageViewModel; _vm.Page = this; - if(Device.RuntimePlatform == Device.iOS) + if (Device.RuntimePlatform == Device.iOS) { _absLayout.Children.Remove(_fab); ToolbarItems.Add(_closeItem); @@ -35,11 +35,11 @@ namespace Bit.App.Pages private async void RowSelected(object sender, SelectedItemChangedEventArgs e) { ((ListView)sender).SelectedItem = null; - if(!DoOnce()) + if (!DoOnce()) { return; } - if(!(e.SelectedItem is FolderView folder)) + if (!(e.SelectedItem is FolderView folder)) { return; } @@ -49,7 +49,7 @@ namespace Bit.App.Pages private async void AddButton_Clicked(object sender, EventArgs e) { - if(DoOnce()) + if (DoOnce()) { var page = new FolderAddEditPage(); await Navigation.PushModalAsync(new NavigationPage(page)); @@ -58,7 +58,7 @@ namespace Bit.App.Pages private async void Close_Clicked(object sender, System.EventArgs e) { - if(DoOnce()) + if (DoOnce()) { await Navigation.PopModalAsync(); } diff --git a/src/App/Pages/Settings/FoldersPageViewModel.cs b/src/App/Pages/Settings/FoldersPageViewModel.cs index 7f6a75182..8bdb8004f 100644 --- a/src/App/Pages/Settings/FoldersPageViewModel.cs +++ b/src/App/Pages/Settings/FoldersPageViewModel.cs @@ -34,7 +34,7 @@ namespace Bit.App.Pages { var folders = await _folderService.GetAllDecryptedAsync(); // Remove "No Folder" - if(folders?.Any() ?? false) + if (folders?.Any() ?? false) { folders = folders.GetRange(0, folders.Count - 1); } diff --git a/src/App/Pages/Settings/OptionsPage.xaml.cs b/src/App/Pages/Settings/OptionsPage.xaml.cs index 7133dca12..ceba05548 100644 --- a/src/App/Pages/Settings/OptionsPage.xaml.cs +++ b/src/App/Pages/Settings/OptionsPage.xaml.cs @@ -21,7 +21,7 @@ namespace Bit.App.Pages _themePicker.ItemDisplayBinding = new Binding("Value"); _uriMatchPicker.ItemDisplayBinding = new Binding("Value"); _clearClipboardPicker.ItemDisplayBinding = new Binding("Value"); - if(Device.RuntimePlatform == Device.Android) + if (Device.RuntimePlatform == Device.Android) { ToolbarItems.RemoveAt(0); _vm.ShowAndroidAutofillSettings = _deviceActionService.SupportsAutofillService(); @@ -55,7 +55,7 @@ namespace Bit.App.Pages private async void Close_Clicked(object sender, System.EventArgs e) { - if(DoOnce()) + if (DoOnce()) { await Navigation.PopModalAsync(); } diff --git a/src/App/Pages/Settings/OptionsPageViewModel.cs b/src/App/Pages/Settings/OptionsPageViewModel.cs index 5e13328a2..b0f5ba96f 100644 --- a/src/App/Pages/Settings/OptionsPageViewModel.cs +++ b/src/App/Pages/Settings/OptionsPageViewModel.cs @@ -52,7 +52,7 @@ namespace Bit.App.Pages new KeyValuePair(30, AppResources.ThirtySeconds), new KeyValuePair(60, AppResources.OneMinute) }; - if(!iosIos) + if (!iosIos) { ClearClipboardOptions.Add(new KeyValuePair(120, AppResources.TwoMinutes)); ClearClipboardOptions.Add(new KeyValuePair(300, AppResources.FiveMinutes)); @@ -85,7 +85,7 @@ namespace Bit.App.Pages get => _clearClipboardSelectedIndex; set { - if(SetProperty(ref _clearClipboardSelectedIndex, value)) + if (SetProperty(ref _clearClipboardSelectedIndex, value)) { var task = SaveClipboardChangedAsync(); } @@ -97,7 +97,7 @@ namespace Bit.App.Pages get => _themeSelectedIndex; set { - if(SetProperty(ref _themeSelectedIndex, value)) + if (SetProperty(ref _themeSelectedIndex, value)) { var task = SaveThemeAsync(); } @@ -109,7 +109,7 @@ namespace Bit.App.Pages get => _uriMatchSelectedIndex; set { - if(SetProperty(ref _uriMatchSelectedIndex, value)) + if (SetProperty(ref _uriMatchSelectedIndex, value)) { var task = SaveDefaultUriAsync(); } @@ -121,7 +121,7 @@ namespace Bit.App.Pages get => _disableFavicon; set { - if(SetProperty(ref _disableFavicon, value)) + if (SetProperty(ref _disableFavicon, value)) { var task = UpdateDisableFaviconAsync(); } @@ -133,7 +133,7 @@ namespace Bit.App.Pages get => _disableAutoTotpCopy; set { - if(SetProperty(ref _disableAutoTotpCopy, value)) + if (SetProperty(ref _disableAutoTotpCopy, value)) { var task = UpdateAutoTotpCopyAsync(); } @@ -145,7 +145,7 @@ namespace Bit.App.Pages get => _autofillDisableSavePrompt; set { - if(SetProperty(ref _autofillDisableSavePrompt, value)) + if (SetProperty(ref _autofillDisableSavePrompt, value)) { var task = UpdateAutofillDisableSavePromptAsync(); } @@ -185,7 +185,7 @@ namespace Bit.App.Pages private async Task UpdateAutoTotpCopyAsync() { - if(_inited) + if (_inited) { await _storageService.SaveAsync(Constants.DisableAutoTotpCopyKey, DisableAutoTotpCopy); } @@ -193,7 +193,7 @@ namespace Bit.App.Pages private async Task UpdateDisableFaviconAsync() { - if(_inited) + if (_inited) { await _storageService.SaveAsync(Constants.DisableFaviconKey, DisableFavicon); await _stateService.SaveAsync(Constants.DisableFaviconKey, DisableFavicon); @@ -202,7 +202,7 @@ namespace Bit.App.Pages private async Task SaveClipboardChangedAsync() { - if(_inited && ClearClipboardSelectedIndex > -1) + if (_inited && ClearClipboardSelectedIndex > -1) { await _storageService.SaveAsync(Constants.ClearClipboardKey, ClearClipboardOptions[ClearClipboardSelectedIndex].Key); @@ -211,17 +211,17 @@ namespace Bit.App.Pages private async Task SaveThemeAsync() { - if(_inited && ThemeSelectedIndex > -1) + if (_inited && ThemeSelectedIndex > -1) { var theme = ThemeOptions[ThemeSelectedIndex].Key; await _storageService.SaveAsync(Constants.ThemeKey, theme); - if(Device.RuntimePlatform == Device.Android) + if (Device.RuntimePlatform == Device.Android) { await _deviceActionService.ShowLoadingAsync(AppResources.Restarting); await Task.Delay(1000); } _messagingService.Send("updatedTheme", theme); - if(Device.RuntimePlatform == Device.iOS) + if (Device.RuntimePlatform == Device.iOS) { await Task.Delay(500); await _platformUtilsService.ShowDialogAsync(AppResources.ThemeAppliedOnRestart); @@ -231,7 +231,7 @@ namespace Bit.App.Pages private async Task SaveDefaultUriAsync() { - if(_inited && UriMatchSelectedIndex > -1) + if (_inited && UriMatchSelectedIndex > -1) { await _storageService.SaveAsync(Constants.DefaultUriMatch, (int?)UriMatchOptions[UriMatchSelectedIndex].Key); @@ -240,7 +240,7 @@ namespace Bit.App.Pages private async Task UpdateAutofillDisableSavePromptAsync() { - if(_inited) + if (_inited) { await _storageService.SaveAsync(Constants.AutofillDisableSavePromptKey, AutofillDisableSavePrompt); } @@ -248,9 +248,9 @@ namespace Bit.App.Pages public async Task UpdateAutofillBlacklistedUris() { - if(_inited) + if (_inited) { - if(string.IsNullOrWhiteSpace(AutofillBlacklistedUris)) + if (string.IsNullOrWhiteSpace(AutofillBlacklistedUris)) { await _storageService.RemoveAsync(Constants.AutofillBlacklistedUrisKey); AutofillBlacklistedUris = null; @@ -260,14 +260,14 @@ namespace Bit.App.Pages { var csv = AutofillBlacklistedUris; var urisList = new List(); - foreach(var uri in csv.Split(',')) + foreach (var uri in csv.Split(',')) { - if(string.IsNullOrWhiteSpace(uri)) + if (string.IsNullOrWhiteSpace(uri)) { continue; } 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)) { continue; diff --git a/src/App/Pages/Settings/SettingsPage/SettingsPage.xaml.cs b/src/App/Pages/Settings/SettingsPage/SettingsPage.xaml.cs index 22e00fadb..a4e75cffe 100644 --- a/src/App/Pages/Settings/SettingsPage/SettingsPage.xaml.cs +++ b/src/App/Pages/Settings/SettingsPage/SettingsPage.xaml.cs @@ -33,7 +33,7 @@ namespace Bit.App.Pages protected override bool OnBackButtonPressed() { - if(Device.RuntimePlatform == Device.Android && _tabsPage != null) + if (Device.RuntimePlatform == Device.Android && _tabsPage != null) { _tabsPage.ResetToVaultPage(); return true; @@ -44,112 +44,112 @@ namespace Bit.App.Pages private async void RowSelected(object sender, SelectedItemChangedEventArgs e) { ((ListView)sender).SelectedItem = null; - if(!DoOnce()) + if (!DoOnce()) { return; } - if(!(e.SelectedItem is SettingsPageListItem item)) + if (!(e.SelectedItem is SettingsPageListItem item)) { return; } - if(item.Name == AppResources.Sync) + if (item.Name == AppResources.Sync) { 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))); } - else if(item.Name == AppResources.AutofillService) + else if (item.Name == AppResources.AutofillService) { 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())); } - else if(item.Name == AppResources.AppExtension) + else if (item.Name == AppResources.AppExtension) { 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())); } - else if(item.Name == AppResources.Folders) + else if (item.Name == AppResources.Folders) { await Navigation.PushModalAsync(new NavigationPage(new FoldersPage())); } - else if(item.Name == AppResources.About) + else if (item.Name == AppResources.About) { await _vm.AboutAsync(); } - else if(item.Name == AppResources.HelpAndFeedback) + else if (item.Name == AppResources.HelpAndFeedback) { _vm.Help(); } - else if(item.Name == AppResources.FingerprintPhrase) + else if (item.Name == AppResources.FingerprintPhrase) { await _vm.FingerprintAsync(); } - else if(item.Name == AppResources.RateTheApp) + else if (item.Name == AppResources.RateTheApp) { _vm.Rate(); } - else if(item.Name == AppResources.ImportItems) + else if (item.Name == AppResources.ImportItems) { _vm.Import(); } - else if(item.Name == AppResources.ExportVault) + else if (item.Name == AppResources.ExportVault) { await Navigation.PushModalAsync(new NavigationPage(new ExportVaultPage())); } - else if(item.Name == AppResources.ShareVault) + else if (item.Name == AppResources.ShareVault) { await _vm.ShareAsync(); } - else if(item.Name == AppResources.WebVault) + else if (item.Name == AppResources.WebVault) { _vm.WebVault(); } - else if(item.Name == AppResources.ChangeMasterPassword) + else if (item.Name == AppResources.ChangeMasterPassword) { await _vm.ChangePasswordAsync(); } - else if(item.Name == AppResources.TwoStepLogin) + else if (item.Name == AppResources.TwoStepLogin) { await _vm.TwoStepAsync(); } - else if(item.Name == AppResources.LogOut) + else if (item.Name == AppResources.LogOut) { await _vm.LogOutAsync(); } - else if(item.Name == AppResources.LockNow) + else if (item.Name == AppResources.LockNow) { await _vm.LockAsync(); } - else if(item.Name == AppResources.LockOptions) + else if (item.Name == AppResources.LockOptions) { await _vm.LockOptionsAsync(); } - else if(item.Name == AppResources.UnlockWithPIN) + else if (item.Name == AppResources.UnlockWithPIN) { await _vm.UpdatePinAsync(); } else { var fingerprintName = AppResources.Fingerprint; - if(Device.RuntimePlatform == Device.iOS) + if (Device.RuntimePlatform == Device.iOS) { var supportsFace = await _deviceActionService.SupportsFaceBiometricAsync(); 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; } - if(item.Name == string.Format(AppResources.UnlockWith, fingerprintName)) + if (item.Name == string.Format(AppResources.UnlockWith, fingerprintName)) { await _vm.UpdateFingerprintAsync(); } diff --git a/src/App/Pages/Settings/SettingsPage/SettingsPageListGroup.cs b/src/App/Pages/Settings/SettingsPage/SettingsPageListGroup.cs index a57118667..319e3e773 100644 --- a/src/App/Pages/Settings/SettingsPage/SettingsPageListGroup.cs +++ b/src/App/Pages/Settings/SettingsPage/SettingsPageListGroup.cs @@ -8,11 +8,11 @@ namespace Bit.App.Pages bool first = false) { AddRange(groupItems); - if(string.IsNullOrWhiteSpace(name)) + if (string.IsNullOrWhiteSpace(name)) { Name = "-"; } - else if(doUpper) + else if (doUpper) { Name = name.ToUpperInvariant(); } diff --git a/src/App/Pages/Settings/SettingsPage/SettingsPageListItemSelector.cs b/src/App/Pages/Settings/SettingsPage/SettingsPageListItemSelector.cs index c58e7723f..feb562453 100644 --- a/src/App/Pages/Settings/SettingsPage/SettingsPageListItemSelector.cs +++ b/src/App/Pages/Settings/SettingsPage/SettingsPageListItemSelector.cs @@ -8,7 +8,7 @@ namespace Bit.App.Pages protected override DataTemplate OnSelectTemplate(object item, BindableObject container) { - if(item is SettingsPageListItem listItem) + if (item is SettingsPageListItem listItem) { return RegularTemplate; } diff --git a/src/App/Pages/Settings/SettingsPage/SettingsPageViewModel.cs b/src/App/Pages/Settings/SettingsPage/SettingsPageViewModel.cs index 375f57897..3f9dda815 100644 --- a/src/App/Pages/Settings/SettingsPage/SettingsPageViewModel.cs +++ b/src/App/Pages/Settings/SettingsPage/SettingsPageViewModel.cs @@ -64,7 +64,7 @@ namespace Bit.App.Pages { _supportsFingerprint = await _platformUtilsService.SupportsBiometricAsync(); var lastSync = await _syncService.GetLastSyncAsync(); - if(lastSync != null) + if (lastSync != null) { lastSync = lastSync.Value.ToLocalTime(); _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 copy = await _platformUtilsService.ShowDialogAsync(text, AppResources.Bitwarden, AppResources.Copy, AppResources.Close); - if(copy) + if (copy) { await _platformUtilsService.CopyToClipboardAsync(debugText); } @@ -103,7 +103,7 @@ namespace Bit.App.Pages { 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; } @@ -111,7 +111,7 @@ namespace Bit.App.Pages var text = string.Format("{0}:\n\n{1}", AppResources.YourAccountsFingerprint, phrase); var learnMore = await _platformUtilsService.ShowDialogAsync(text, AppResources.FingerprintPhrase, AppResources.LearnMore, AppResources.Close); - if(learnMore) + if (learnMore) { _platformUtilsService.LaunchUri("https://help.bitwarden.com/article/fingerprint-phrase/"); } @@ -130,7 +130,7 @@ namespace Bit.App.Pages public void WebVault() { var url = _environmentService.GetWebVaultUrl(); - if(url == null) + if (url == null) { url = "https://vault.bitwarden.com"; } @@ -141,7 +141,7 @@ namespace Bit.App.Pages { var confirmed = await _platformUtilsService.ShowDialogAsync(AppResources.ShareVaultConfirmation, AppResources.ShareVault, AppResources.Yes, AppResources.Cancel); - if(confirmed) + if (confirmed) { _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, AppResources.TwoStepLogin, AppResources.Yes, AppResources.Cancel); - if(confirmed) + if (confirmed) { _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, AppResources.ChangeMasterPassword, AppResources.Yes, AppResources.Cancel); - if(confirmed) + if (confirmed) { _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, AppResources.LogOut, AppResources.Yes, AppResources.Cancel); - if(confirmed) + if (confirmed) { _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 selection = await Page.DisplayActionSheet(AppResources.LockOptions, AppResources.Cancel, null, options); - if(selection == null || selection == AppResources.Cancel) + if (selection == null || selection == AppResources.Cancel) { return; } @@ -200,11 +200,11 @@ namespace Bit.App.Pages public async Task UpdatePinAsync() { _pin = !_pin; - if(_pin) + if (_pin) { var pin = await _deviceActionService.DisplayPromptAync(AppResources.EnterPIN, AppResources.SetPINDescription, null, AppResources.Submit, AppResources.Cancel, true); - if(!string.IsNullOrWhiteSpace(pin)) + if (!string.IsNullOrWhiteSpace(pin)) { var masterPassOnRestart = await _platformUtilsService.ShowDialogAsync( AppResources.PINRequireMasterPasswordRestart, AppResources.UnlockWithPIN, @@ -219,7 +219,7 @@ namespace Bit.App.Pages var key = await _cryptoService.GetKeyAsync(); var pinProtectedKey = await _cryptoService.EncryptAsync(key.Key, pinKey); - if(masterPassOnRestart) + if (masterPassOnRestart) { var encPin = await _cryptoService.EncryptAsync(pin); await _storageService.SaveAsync(Constants.ProtectedPin, encPin.EncryptedString); @@ -235,7 +235,7 @@ namespace Bit.App.Pages _pin = false; } } - if(!_pin) + if (!_pin) { await _cryptoService.ClearPinProtectedKeyAsync(); await _lockService.ClearAsync(); @@ -246,20 +246,20 @@ namespace Bit.App.Pages public async Task UpdateFingerprintAsync() { var current = _fingerprint; - if(_fingerprint) + if (_fingerprint) { _fingerprint = false; } - else if(await _platformUtilsService.SupportsBiometricAsync()) + else if (await _platformUtilsService.SupportsBiometricAsync()) { _fingerprint = await _platformUtilsService.AuthenticateBiometricAsync(null, _deviceActionService.DeviceType == Core.Enums.DeviceType.Android ? "." : null); } - if(_fingerprint == current) + if (_fingerprint == current) { return; } - if(_fingerprint) + if (_fingerprint) { await _storageService.SaveAsync(Constants.FingerprintUnlockKey, true); } @@ -276,9 +276,9 @@ namespace Bit.App.Pages { var doUpper = Device.RuntimePlatform != Device.Android; var autofillItems = new List(); - if(Device.RuntimePlatform == Device.Android) + if (Device.RuntimePlatform == Device.Android) { - if(_deviceActionService.SupportsAutofillService()) + if (_deviceActionService.SupportsAutofillService()) { autofillItems.Add(new SettingsPageListItem { @@ -299,7 +299,7 @@ namespace Bit.App.Pages } else { - if(_deviceActionService.SystemMajorVersion() >= 12) + if (_deviceActionService.SystemMajorVersion() >= 12) { autofillItems.Add(new SettingsPageListItem { Name = AppResources.PasswordAutofill }); } @@ -321,15 +321,15 @@ namespace Bit.App.Pages new SettingsPageListItem { Name = AppResources.LockNow }, new SettingsPageListItem { Name = AppResources.TwoStepLogin } }; - if(_supportsFingerprint || _fingerprint) + if (_supportsFingerprint || _fingerprint) { var fingerprintName = AppResources.Fingerprint; - if(Device.RuntimePlatform == Device.iOS) + if (Device.RuntimePlatform == Device.iOS) { fingerprintName = _deviceActionService.SupportsFaceBiometric() ? AppResources.FaceID : AppResources.TouchID; } - else if(Device.RuntimePlatform == Device.Android && _deviceActionService.UseNativeBiometric()) + else if (Device.RuntimePlatform == Device.Android && _deviceActionService.UseNativeBiometric()) { fingerprintName = AppResources.Biometrics; } diff --git a/src/App/Pages/Settings/SyncPage.xaml.cs b/src/App/Pages/Settings/SyncPage.xaml.cs index c9ee70c6a..f90538683 100644 --- a/src/App/Pages/Settings/SyncPage.xaml.cs +++ b/src/App/Pages/Settings/SyncPage.xaml.cs @@ -12,7 +12,7 @@ namespace Bit.App.Pages InitializeComponent(); _vm = BindingContext as SyncPageViewModel; _vm.Page = this; - if(Device.RuntimePlatform == Device.Android) + if (Device.RuntimePlatform == Device.Android) { ToolbarItems.RemoveAt(0); } @@ -26,7 +26,7 @@ namespace Bit.App.Pages private async void Sync_Clicked(object sender, EventArgs e) { - if(DoOnce()) + if (DoOnce()) { await _vm.SyncAsync(); } @@ -34,7 +34,7 @@ namespace Bit.App.Pages private async void Close_Clicked(object sender, System.EventArgs e) { - if(DoOnce()) + if (DoOnce()) { await Navigation.PopModalAsync(); } diff --git a/src/App/Pages/Settings/SyncPageViewModel.cs b/src/App/Pages/Settings/SyncPageViewModel.cs index ad9e75028..7983ac149 100644 --- a/src/App/Pages/Settings/SyncPageViewModel.cs +++ b/src/App/Pages/Settings/SyncPageViewModel.cs @@ -33,7 +33,7 @@ namespace Bit.App.Pages public async Task SetLastSyncAsync() { var last = await _syncService.GetLastSyncAsync(); - if(last != null) + if (last != null) { var localDate = last.Value.ToLocalTime(); LastSync = string.Format("{0} {1}", localDate.ToShortDateString(), localDate.ToShortTimeString()); @@ -46,7 +46,7 @@ namespace Bit.App.Pages 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, AppResources.InternetConnectionRequiredTitle); @@ -57,7 +57,7 @@ namespace Bit.App.Pages await _deviceActionService.ShowLoadingAsync(AppResources.Syncing); var success = await _syncService.FullSyncAsync(true); await _deviceActionService.HideLoadingAsync(); - if(success) + if (success) { await SetLastSyncAsync(); _platformUtilsService.ShowToast("success", null, AppResources.SyncingComplete); @@ -67,10 +67,10 @@ namespace Bit.App.Pages await Page.DisplayAlert(null, AppResources.SyncingFailed, AppResources.Ok); } } - catch(ApiException e) + catch (ApiException e) { await _deviceActionService.HideLoadingAsync(); - if(e?.Error != null) + if (e?.Error != null) { await _platformUtilsService.ShowDialogAsync(e.Error.GetSingleMessage(), AppResources.AnErrorHasOccurred); diff --git a/src/App/Pages/TabsPage.cs b/src/App/Pages/TabsPage.cs index a2961bd30..37f0fb08c 100644 --- a/src/App/Pages/TabsPage.cs +++ b/src/App/Pages/TabsPage.cs @@ -33,7 +33,7 @@ namespace Bit.App.Pages }; Children.Add(settingsPage); - if(Device.RuntimePlatform == Device.Android) + if (Device.RuntimePlatform == Device.Android) { Effects.Add(new TabBarEffect()); @@ -43,12 +43,12 @@ namespace Bit.App.Pages Xamarin.Forms.PlatformConfiguration.AndroidSpecific.TabbedPage.SetIsSmoothScrollEnabled(this, false); } - if(appOptions?.GeneratorTile ?? false) + if (appOptions?.GeneratorTile ?? false) { appOptions.GeneratorTile = false; ResetToGeneratorPage(); } - else if(appOptions?.MyVaultTile ?? false) + else if (appOptions?.MyVaultTile ?? false) { appOptions.MyVaultTile = false; } @@ -66,17 +66,17 @@ namespace Bit.App.Pages 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? } - else if(navPage.RootPage is GeneratorPage genPage) + else if (navPage.RootPage is GeneratorPage genPage) { await genPage.InitAsync(); } - else if(navPage.RootPage is SettingsPage settingsPage) + else if (navPage.RootPage is SettingsPage settingsPage) { await settingsPage.InitAsync(); } diff --git a/src/App/Pages/Vault/AddEditPage.xaml.cs b/src/App/Pages/Vault/AddEditPage.xaml.cs index 77faf3f92..654159c40 100644 --- a/src/App/Pages/Vault/AddEditPage.xaml.cs +++ b/src/App/Pages/Vault/AddEditPage.xaml.cs @@ -52,15 +52,15 @@ namespace Bit.App.Pages _vm.ViewPage = viewPage; _vm.Init(); SetActivityIndicator(); - if(_vm.EditMode && !_vm.CloneMode && Device.RuntimePlatform == Device.Android) + if (_vm.EditMode && !_vm.CloneMode && Device.RuntimePlatform == Device.Android) { ToolbarItems.Add(_attachmentsItem); ToolbarItems.Add(_deleteItem); } - if(Device.RuntimePlatform == Device.iOS) + if (Device.RuntimePlatform == Device.iOS) { ToolbarItems.Add(_closeItem); - if(_vm.EditMode && !_vm.CloneMode) + if (_vm.EditMode && !_vm.CloneMode) { ToolbarItems.Add(_moreItem); } @@ -82,11 +82,11 @@ namespace Bit.App.Pages _nameEntry.ReturnType = ReturnType.Next; _nameEntry.ReturnCommand = new Command(() => { - if(_vm.Cipher.Type == CipherType.Login) + if (_vm.Cipher.Type == CipherType.Login) { _loginUsernameEntry.Focus(); } - else if(_vm.Cipher.Type == CipherType.Card) + else if (_vm.Cipher.Type == CipherType.Card) { _cardholderNameEntry.Focus(); } @@ -145,14 +145,14 @@ namespace Bit.App.Pages await LoadOnAppearedAsync(_scrollView, true, async () => { var success = await _vm.LoadAsync(_appOptions); - if(!success) + if (!success) { await Navigation.PopModalAsync(); return; } AdjustToolbar(); await ShowAlertsAsync(); - if(!_vm.EditMode && string.IsNullOrWhiteSpace(_vm.Cipher?.Name)) + if (!_vm.EditMode && string.IsNullOrWhiteSpace(_vm.Cipher?.Name)) { RequestFocus(_nameEntry); } @@ -166,7 +166,7 @@ namespace Bit.App.Pages protected override bool OnBackButtonPressed() { - if(FromAutofillFramework) + if (FromAutofillFramework) { Xamarin.Forms.Application.Current.MainPage = new TabsPage(); return true; @@ -176,7 +176,7 @@ namespace Bit.App.Pages private async void PasswordHistory_Tapped(object sender, System.EventArgs e) { - if(DoOnce()) + if (DoOnce()) { await Navigation.PushModalAsync( 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) { - if(DoOnce()) + if (DoOnce()) { await _vm.SubmitAsync(); } @@ -203,7 +203,7 @@ namespace Bit.App.Pages private async void Attachments_Clicked(object sender, System.EventArgs e) { - if(DoOnce()) + if (DoOnce()) { var page = new AttachmentsPage(_vm.CipherId); 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) { - if(DoOnce()) + if (DoOnce()) { var page = new SharePage(_vm.CipherId); 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) { - if(DoOnce()) + if (DoOnce()) { - if(await _vm.DeleteAsync()) + if (await _vm.DeleteAsync()) { await Navigation.PopModalAsync(); } @@ -232,7 +232,7 @@ namespace Bit.App.Pages private async void Collections_Clicked(object sender, System.EventArgs e) { - if(DoOnce()) + if (DoOnce()) { var page = new CollectionsPage(_vm.CipherId); 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) { - if(DoOnce()) + if (DoOnce()) { var page = new ScanPage(key => { @@ -257,35 +257,35 @@ namespace Bit.App.Pages private async void More_Clicked(object sender, System.EventArgs e) { - if(!DoOnce()) + if (!DoOnce()) { return; } var options = new List { AppResources.Attachments }; - if(_vm.EditMode) + if (_vm.EditMode) { options.Add(_vm.Cipher.OrganizationId == null ? AppResources.Share : AppResources.Collections); } var selection = await DisplayActionSheet(AppResources.Options, AppResources.Cancel, (_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(); } } - else if(selection == AppResources.Attachments) + else if (selection == AppResources.Attachments) { var page = new AttachmentsPage(_vm.CipherId); await Navigation.PushModalAsync(new Xamarin.Forms.NavigationPage(page)); } - else if(selection == AppResources.Collections) + else if (selection == AppResources.Collections) { var page = new CollectionsPage(_vm.CipherId); await Navigation.PushModalAsync(new Xamarin.Forms.NavigationPage(page)); } - else if(selection == AppResources.Share) + else if (selection == AppResources.Share) { var page = new SharePage(_vm.CipherId); 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) { - if(DoOnce()) + if (DoOnce()) { await Navigation.PopModalAsync(); } @@ -302,19 +302,19 @@ namespace Bit.App.Pages private async Task ShowAlertsAsync() { - if(!_vm.EditMode) + if (!_vm.EditMode) { - if(_vm.Cipher == null) + if (_vm.Cipher == null) { return; } var addLoginShown = await _storageService.GetAsync(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); - if(Device.RuntimePlatform == Device.iOS) + if (Device.RuntimePlatform == Device.iOS) { - if(_deviceActionService.SystemMajorVersion() < 12) + if (_deviceActionService.SystemMajorVersion() < 12) { await DisplayAlert(AppResources.BitwardenAppExtension, AppResources.BitwardenAppExtensionAlert2, AppResources.Ok); @@ -325,7 +325,7 @@ namespace Bit.App.Pages AppResources.BitwardenAutofillAlert2, AppResources.Ok); } } - else if(Device.RuntimePlatform == Device.Android && + else if (Device.RuntimePlatform == Device.Android && !_deviceActionService.AutofillAccessibilityServiceRunning() && !_deviceActionService.AutofillServiceEnabled()) { @@ -338,30 +338,30 @@ namespace Bit.App.Pages 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; } - if(_vm.Cipher.OrganizationId == null) + if (_vm.Cipher.OrganizationId == null) { - if(ToolbarItems.Contains(_collectionsItem)) + if (ToolbarItems.Contains(_collectionsItem)) { ToolbarItems.Remove(_collectionsItem); } - if(!ToolbarItems.Contains(_shareItem) && !_vm.CloneMode) + if (!ToolbarItems.Contains(_shareItem) && !_vm.CloneMode) { ToolbarItems.Insert(2, _shareItem); } } else { - if(ToolbarItems.Contains(_shareItem)) + if (ToolbarItems.Contains(_shareItem)) { ToolbarItems.Remove(_shareItem); } - if(!ToolbarItems.Contains(_collectionsItem)) + if (!ToolbarItems.Contains(_collectionsItem)) { ToolbarItems.Insert(2, _collectionsItem); } diff --git a/src/App/Pages/Vault/AddEditPageViewModel.cs b/src/App/Pages/Vault/AddEditPageViewModel.cs index eca05ce6c..92d3fd55f 100644 --- a/src/App/Pages/Vault/AddEditPageViewModel.cs +++ b/src/App/Pages/Vault/AddEditPageViewModel.cs @@ -163,7 +163,7 @@ namespace Bit.App.Pages get => _typeSelectedIndex; set { - if(SetProperty(ref _typeSelectedIndex, value)) + if (SetProperty(ref _typeSelectedIndex, value)) { TypeChanged(); } @@ -174,7 +174,7 @@ namespace Bit.App.Pages get => _cardBrandSelectedIndex; set { - if(SetProperty(ref _cardBrandSelectedIndex, value)) + if (SetProperty(ref _cardBrandSelectedIndex, value)) { CardBrandChanged(); } @@ -185,7 +185,7 @@ namespace Bit.App.Pages get => _cardExpMonthSelectedIndex; set { - if(SetProperty(ref _cardExpMonthSelectedIndex, value)) + if (SetProperty(ref _cardExpMonthSelectedIndex, value)) { CardExpMonthChanged(); } @@ -196,7 +196,7 @@ namespace Bit.App.Pages get => _identityTitleSelectedIndex; set { - if(SetProperty(ref _identityTitleSelectedIndex, value)) + if (SetProperty(ref _identityTitleSelectedIndex, value)) { IdentityTitleChanged(); } @@ -207,7 +207,7 @@ namespace Bit.App.Pages get => _folderSelectedIndex; set { - if(SetProperty(ref _folderSelectedIndex, value)) + if (SetProperty(ref _folderSelectedIndex, value)) { FolderChanged(); } @@ -218,7 +218,7 @@ namespace Bit.App.Pages get => _ownershipSelectedIndex; set { - if(SetProperty(ref _ownershipSelectedIndex, value)) + if (SetProperty(ref _ownershipSelectedIndex, value)) { OrganizationChanged(); } @@ -285,9 +285,9 @@ namespace Bit.App.Pages var myEmail = await _userService.GetEmailAsync(); OwnershipOptions.Add(new KeyValuePair(myEmail, null)); 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(org.Name, org.Id)); } @@ -295,7 +295,7 @@ namespace Bit.App.Pages var allCollections = await _collectionService.GetAllDecryptedAsync(); _writeableCollections = allCollections.Where(c => !c.ReadOnly).ToList(); - if(CollectionIds?.Any() ?? false) + if (CollectionIds?.Any() ?? false) { var colId = CollectionIds.First(); var collection = _writeableCollections.FirstOrDefault(c => c.Id == colId); @@ -304,17 +304,17 @@ namespace Bit.App.Pages var folders = await _folderService.GetAllDecryptedAsync(); FolderOptions = folders.Select(f => new KeyValuePair(f.Name, f.Id)).ToList(); - if(Cipher == null) + if (Cipher == null) { - if(EditMode) + if (EditMode) { var cipher = await _cipherService.GetAsync(CipherId); - if(cipher == null) + if (cipher == null) { return false; } Cipher = await cipher.DecryptAsync(); - if(CloneMode) + if (CloneMode) { Cipher.Name += " - " + AppResources.Clone; } @@ -335,13 +335,13 @@ namespace Bit.App.Pages Cipher.Login.Uris = new List { new LoginUriView { Uri = DefaultUri } }; Cipher.SecureNote.Type = SecureNoteType.Generic; - if(appOptions != null) + if (appOptions != null) { Cipher.Type = appOptions.SaveType.GetValueOrDefault(Cipher.Type); Cipher.Login.Username = appOptions.SaveUsername; Cipher.Login.Password = appOptions.SavePassword; 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(); } @@ -363,24 +363,24 @@ namespace Bit.App.Pages OwnershipSelectedIndex = string.IsNullOrWhiteSpace(Cipher.OrganizationId) ? 0 : 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); } } - if(Cipher.Login?.Uris != null) + if (Cipher.Login?.Uris != null) { Uris.ResetWithRange(Cipher.Login.Uris); } - if(Cipher.Fields != null) + if (Cipher.Fields != null) { 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); } @@ -391,17 +391,17 @@ namespace Bit.App.Pages public async Task SubmitAsync() { - if(Cipher == null) + if (Cipher == null) { 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, AppResources.InternetConnectionRequiredTitle); return false; } - if(string.IsNullOrWhiteSpace(Cipher.Name)) + if (string.IsNullOrWhiteSpace(Cipher.Name)) { await Page.DisplayAlert(AppResources.AnErrorHasOccurred, string.Format(AppResources.ValidationFieldRequired, AppResources.Name), @@ -411,19 +411,19 @@ namespace Bit.App.Pages Cipher.Fields = Fields != null && Fields.Any() ? Fields.Where(f => f != null).Select(f => f.Field).ToList() : null; - if(Cipher.Login != null) + if (Cipher.Login != null) { 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 = 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, AppResources.Ok); @@ -435,12 +435,12 @@ namespace Bit.App.Pages .Select(c => c.Collection.Id)) : null; } - if(CloneMode) + if (CloneMode) { Cipher.Id = null; } var cipher = await _cipherService.EncryptAsync(Cipher); - if(cipher == null) + if (cipher == null) { return false; } @@ -454,14 +454,14 @@ namespace Bit.App.Pages EditMode && !CloneMode ? AppResources.ItemUpdated : AppResources.NewItemCreated); _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 _deviceActionService.CloseAutofill(); } else { - if(CloneMode) + if (CloneMode) { ViewPage?.UpdateCipherId(this.Cipher.Id); } @@ -469,10 +469,10 @@ namespace Bit.App.Pages } return true; } - catch(ApiException e) + catch (ApiException e) { await _deviceActionService.HideLoadingAsync(); - if(e?.Error != null) + if (e?.Error != null) { await _platformUtilsService.ShowDialogAsync(e.Error.GetSingleMessage(), AppResources.AnErrorHasOccurred); @@ -483,7 +483,7 @@ namespace Bit.App.Pages public async Task DeleteAsync() { - if(Xamarin.Essentials.Connectivity.NetworkAccess == Xamarin.Essentials.NetworkAccess.None) + if (Xamarin.Essentials.Connectivity.NetworkAccess == Xamarin.Essentials.NetworkAccess.None) { await _platformUtilsService.ShowDialogAsync(AppResources.InternetConnectionRequiredMessage, AppResources.InternetConnectionRequiredTitle); @@ -491,7 +491,7 @@ namespace Bit.App.Pages } var confirmed = await _platformUtilsService.ShowDialogAsync(AppResources.DoYouReallyWantToDelete, null, AppResources.Yes, AppResources.Cancel); - if(!confirmed) + if (!confirmed) { return false; } @@ -504,10 +504,10 @@ namespace Bit.App.Pages _messagingService.Send("deletedCipher", Cipher); return true; } - catch(ApiException e) + catch (ApiException e) { await _deviceActionService.HideLoadingAsync(); - if(e?.Error != null) + if (e?.Error != null) { await _platformUtilsService.ShowDialogAsync(e.Error.GetSingleMessage(), AppResources.AnErrorHasOccurred); @@ -518,11 +518,11 @@ namespace Bit.App.Pages public async void GeneratePassword() { - if(!string.IsNullOrWhiteSpace(Cipher?.Login?.Password)) + if (!string.IsNullOrWhiteSpace(Cipher?.Login?.Password)) { var confirmed = await _platformUtilsService.ShowDialogAsync(AppResources.PasswordOverrideAlert, null, AppResources.Yes, AppResources.No); - if(!confirmed) + if (!confirmed) { return; } @@ -538,22 +538,22 @@ namespace Bit.App.Pages public async void UriOptions(LoginUriView uri) { - if(!(Page as AddEditPage).DoOnce()) + if (!(Page as AddEditPage).DoOnce()) { return; } var selection = await Page.DisplayActionSheet(AppResources.Options, AppResources.Cancel, null, AppResources.MatchDetection, AppResources.Remove); - if(selection == AppResources.Remove) + if (selection == AppResources.Remove) { 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 matchSelection = await Page.DisplayActionSheet(AppResources.URIMatchDetection, AppResources.Cancel, null, options.ToArray()); - if(matchSelection != null && matchSelection != AppResources.Cancel) + if (matchSelection != null && matchSelection != AppResources.Cancel) { var matchSelectionClean = matchSelection.Replace("✓ ", string.Empty); uri.Match = _matchDetectionOptions.FirstOrDefault(o => o.Value == matchSelectionClean).Key; @@ -563,11 +563,11 @@ namespace Bit.App.Pages public void AddUri() { - if(Cipher.Type != CipherType.Login) + if (Cipher.Type != CipherType.Login) { return; } - if(Uris == null) + if (Uris == null) { Uris = new ExtendedObservableCollection(); } @@ -576,35 +576,35 @@ namespace Bit.App.Pages public async void FieldOptions(AddEditPageFieldViewModel field) { - if(!(Page as AddEditPage).DoOnce()) + if (!(Page as AddEditPage).DoOnce()) { return; } var selection = await Page.DisplayActionSheet(AppResources.Options, AppResources.Cancel, null, AppResources.Edit, AppResources.MoveUp, AppResources.MoveDown, AppResources.Remove); - if(selection == AppResources.Remove) + if (selection == AppResources.Remove) { Fields.Remove(field); } - else if(selection == AppResources.Edit) + else if (selection == AppResources.Edit) { var name = await _deviceActionService.DisplayPromptAync(AppResources.CustomFieldName, null, field.Field.Name); field.Field.Name = name ?? field.Field.Name; field.TriggerFieldChanged(); } - else if(selection == AppResources.MoveUp) + else if (selection == AppResources.MoveUp) { var currentIndex = Fields.IndexOf(field); - if(currentIndex > 0) + if (currentIndex > 0) { Fields.Move(currentIndex, currentIndex - 1); } } - else if(selection == AppResources.MoveDown) + else if (selection == AppResources.MoveDown) { var currentIndex = Fields.IndexOf(field); - if(currentIndex < Fields.Count - 1) + if (currentIndex < Fields.Count - 1) { Fields.Move(currentIndex, currentIndex + 1); } @@ -615,14 +615,14 @@ namespace Bit.App.Pages { var typeSelection = await Page.DisplayActionSheet(AppResources.SelectTypeField, AppResources.Cancel, null, _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); - if(name == null) + if (name == null) { return; } - if(Fields == null) + if (Fields == null) { Fields = new ExtendedObservableCollection(); } @@ -638,7 +638,7 @@ namespace Bit.App.Pages public void TogglePassword() { ShowPassword = !ShowPassword; - if(EditMode && ShowPassword) + if (EditMode && ShowPassword) { var task = _eventService.CollectAsync(EventType.Cipher_ClientToggledPasswordVisible, CipherId); } @@ -647,7 +647,7 @@ namespace Bit.App.Pages public void ToggleCardCode() { ShowCardCode = !ShowCardCode; - if(EditMode && ShowCardCode) + if (EditMode && ShowCardCode) { var task = _eventService.CollectAsync(EventType.Cipher_ClientToggledCardCodeVisible, CipherId); } @@ -655,9 +655,9 @@ namespace Bit.App.Pages 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; TriggerCipherChanged(); @@ -672,7 +672,7 @@ namespace Bit.App.Pages private void TypeChanged() { - if(Cipher != null && TypeSelectedIndex > -1) + if (Cipher != null && TypeSelectedIndex > -1) { Cipher.Type = TypeOptions[TypeSelectedIndex].Value; TriggerCipherChanged(); @@ -681,7 +681,7 @@ namespace Bit.App.Pages private void CardBrandChanged() { - if(Cipher?.Card != null && CardBrandSelectedIndex > -1) + if (Cipher?.Card != null && CardBrandSelectedIndex > -1) { Cipher.Card.Brand = CardBrandOptions[CardBrandSelectedIndex].Value; } @@ -689,7 +689,7 @@ namespace Bit.App.Pages private void CardExpMonthChanged() { - if(Cipher?.Card != null && CardExpMonthSelectedIndex > -1) + if (Cipher?.Card != null && CardExpMonthSelectedIndex > -1) { Cipher.Card.ExpMonth = CardExpMonthOptions[CardExpMonthSelectedIndex].Value; } @@ -697,7 +697,7 @@ namespace Bit.App.Pages private void IdentityTitleChanged() { - if(Cipher?.Identity != null && IdentityTitleSelectedIndex > -1) + if (Cipher?.Identity != null && IdentityTitleSelectedIndex > -1) { Cipher.Identity.Title = IdentityTitleOptions[IdentityTitleSelectedIndex].Value; } @@ -705,7 +705,7 @@ namespace Bit.App.Pages private void FolderChanged() { - if(Cipher != null && FolderSelectedIndex > -1) + if (Cipher != null && FolderSelectedIndex > -1) { Cipher.FolderId = FolderOptions[FolderSelectedIndex].Value; } @@ -713,12 +713,12 @@ namespace Bit.App.Pages private void OrganizationChanged() { - if(Cipher != null && OwnershipSelectedIndex > -1) + if (Cipher != null && OwnershipSelectedIndex > -1) { Cipher.OrganizationId = OwnershipOptions[OwnershipSelectedIndex].Value; TriggerCipherChanged(); } - if(Cipher.OrganizationId != null) + if (Cipher.OrganizationId != null) { var cols = _writeableCollections.Where(c => c.OrganizationId == Cipher.OrganizationId) .Select(c => new CollectionViewModel { Collection = c }).ToList(); @@ -738,18 +738,18 @@ namespace Bit.App.Pages private async void CheckPasswordAsync() { - if(!(Page as BaseContentPage).DoOnce()) + if (!(Page as BaseContentPage).DoOnce()) { return; } - if(string.IsNullOrWhiteSpace(Cipher.Login?.Password)) + if (string.IsNullOrWhiteSpace(Cipher.Login?.Password)) { return; } await _deviceActionService.ShowLoadingAsync(AppResources.CheckingPassword); var matches = await _auditService.PasswordLeakedAsync(Cipher.Login.Password); await _deviceActionService.HideLoadingAsync(); - if(matches > 0) + if (matches > 0) { await _platformUtilsService.ShowDialogAsync(string.Format(AppResources.PasswordExposed, matches.ToString("N0"))); @@ -804,7 +804,7 @@ namespace Bit.App.Pages set { SetProperty(ref _booleanValue, value); - if(IsBooleanType) + if (IsBooleanType) { Field.Value = value ? "true" : "false"; } @@ -821,7 +821,7 @@ namespace Bit.App.Pages public void ToggleHiddenValue() { ShowHiddenValue = !ShowHiddenValue; - if(ShowHiddenValue && _cipher?.Id != null) + if (ShowHiddenValue && _cipher?.Id != null) { var eventService = ServiceContainer.Resolve("eventService"); var task = eventService.CollectAsync(EventType.Cipher_ClientToggledHiddenFieldVisible, _cipher.Id); diff --git a/src/App/Pages/Vault/AttachmentsPage.xaml.cs b/src/App/Pages/Vault/AttachmentsPage.xaml.cs index f6ff3faab..4af1b9148 100644 --- a/src/App/Pages/Vault/AttachmentsPage.xaml.cs +++ b/src/App/Pages/Vault/AttachmentsPage.xaml.cs @@ -18,7 +18,7 @@ namespace Bit.App.Pages _vm.Page = this; _vm.CipherId = cipherId; SetActivityIndicator(); - if(Device.RuntimePlatform == Device.Android) + if (Device.RuntimePlatform == Device.Android) { ToolbarItems.RemoveAt(0); } @@ -29,7 +29,7 @@ namespace Bit.App.Pages base.OnAppearing(); _broadcasterService.Subscribe(nameof(AttachmentsPage), (message) => { - if(message.Command == "selectFileResult") + if (message.Command == "selectFileResult") { Device.BeginInvokeOnMainThread(() => { @@ -45,7 +45,7 @@ namespace Bit.App.Pages protected override void OnDisappearing() { base.OnDisappearing(); - if(Device.RuntimePlatform != Device.iOS) + if (Device.RuntimePlatform != Device.iOS) { _broadcasterService.Unsubscribe(nameof(AttachmentsPage)); } @@ -53,7 +53,7 @@ namespace Bit.App.Pages private async void Save_Clicked(object sender, EventArgs e) { - if(DoOnce()) + if (DoOnce()) { await _vm.SubmitAsync(); } @@ -61,7 +61,7 @@ namespace Bit.App.Pages private async void ChooseFile_Clicked(object sender, EventArgs e) { - if(DoOnce()) + if (DoOnce()) { await _vm.ChooseFileAsync(); } @@ -69,7 +69,7 @@ namespace Bit.App.Pages private async void Close_Clicked(object sender, System.EventArgs e) { - if(DoOnce()) + if (DoOnce()) { await Navigation.PopModalAsync(); } diff --git a/src/App/Pages/Vault/AttachmentsPageViewModel.cs b/src/App/Pages/Vault/AttachmentsPageViewModel.cs index afb6de84a..bed4ecf85 100644 --- a/src/App/Pages/Vault/AttachmentsPageViewModel.cs +++ b/src/App/Pages/Vault/AttachmentsPageViewModel.cs @@ -66,15 +66,15 @@ namespace Bit.App.Pages _hasUpdatedKey = await _cryptoService.HasEncKeyAsync(); var canAccessPremium = await _userService.CanAccessPremiumAsync(); _canAccessAttachments = canAccessPremium || Cipher.OrganizationId != null; - if(!_canAccessAttachments) + if (!_canAccessAttachments) { await _platformUtilsService.ShowDialogAsync(AppResources.PremiumRequired); } - else if(!_hasUpdatedKey) + else if (!_hasUpdatedKey) { var confirmed = await _platformUtilsService.ShowDialogAsync(AppResources.UpdateKey, AppResources.FeatureUnavailable, AppResources.LearnMore, AppResources.Cancel); - if(confirmed) + if (confirmed) { _platformUtilsService.LaunchUri("https://help.bitwarden.com/article/update-encryption-key/"); } @@ -83,26 +83,26 @@ namespace Bit.App.Pages 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, AppResources.InternetConnectionRequiredTitle); return false; } - if(!_hasUpdatedKey) + if (!_hasUpdatedKey) { await _platformUtilsService.ShowDialogAsync(AppResources.UpdateKey, AppResources.AnErrorHasOccurred); return false; } - if(FileData == null) + if (FileData == null) { await _platformUtilsService.ShowDialogAsync( string.Format(AppResources.ValidationFieldRequired, AppResources.File), AppResources.AnErrorHasOccurred); return false; } - if(FileData.Length > 104857600) // 100 MB + if (FileData.Length > 104857600) // 100 MB { await _platformUtilsService.ShowDialogAsync(AppResources.MaxFileSize, AppResources.AnErrorHasOccurred); @@ -121,10 +121,10 @@ namespace Bit.App.Pages FileName = null; return true; } - catch(ApiException e) + catch (ApiException e) { await _deviceActionService.HideLoadingAsync(); - if(e?.Error != null) + if (e?.Error != null) { await _platformUtilsService.ShowDialogAsync(e.Error.GetSingleMessage(), AppResources.AnErrorHasOccurred); @@ -140,7 +140,7 @@ namespace Bit.App.Pages 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, AppResources.InternetConnectionRequiredTitle); @@ -148,7 +148,7 @@ namespace Bit.App.Pages } var confirmed = await _platformUtilsService.ShowDialogAsync(AppResources.DoYouReallyWantToDelete, null, AppResources.Yes, AppResources.No); - if(!confirmed) + if (!confirmed) { return; } @@ -159,16 +159,16 @@ namespace Bit.App.Pages await _deviceActionService.HideLoadingAsync(); _platformUtilsService.ShowToast("success", null, AppResources.AttachmentDeleted); var attachmentToRemove = Cipher.Attachments.FirstOrDefault(a => a.Id == attachment.Id); - if(attachmentToRemove != null) + if (attachmentToRemove != null) { Cipher.Attachments.Remove(attachmentToRemove); LoadAttachments(); } } - catch(ApiException e) + catch (ApiException e) { await _deviceActionService.HideLoadingAsync(); - if(e?.Error != null) + if (e?.Error != null) { await _platformUtilsService.ShowDialogAsync(e.Error.GetSingleMessage(), AppResources.AnErrorHasOccurred); diff --git a/src/App/Pages/Vault/AutofillCiphersPage.xaml.cs b/src/App/Pages/Vault/AutofillCiphersPage.xaml.cs index 5589c9777..3fcfef52e 100644 --- a/src/App/Pages/Vault/AutofillCiphersPage.xaml.cs +++ b/src/App/Pages/Vault/AutofillCiphersPage.xaml.cs @@ -36,7 +36,7 @@ namespace Bit.App.Pages { 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 _vm.LoadAsync(); @@ -47,11 +47,11 @@ namespace Bit.App.Pages private async void RowSelected(object sender, SelectedItemChangedEventArgs e) { ((ListView)sender).SelectedItem = null; - if(!DoOnce()) + if (!DoOnce()) { 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); } @@ -59,11 +59,11 @@ namespace Bit.App.Pages private async void AddButton_Clicked(object sender, System.EventArgs e) { - if(!DoOnce()) + if (!DoOnce()) { 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); await Navigation.PushModalAsync(new NavigationPage(pageForOther)); diff --git a/src/App/Pages/Vault/AutofillCiphersPageViewModel.cs b/src/App/Pages/Vault/AutofillCiphersPageViewModel.cs index e328500fc..4c5b86aa2 100644 --- a/src/App/Pages/Vault/AutofillCiphersPageViewModel.cs +++ b/src/App/Pages/Vault/AutofillCiphersPageViewModel.cs @@ -67,7 +67,7 @@ namespace Bit.App.Pages _appOptions = appOptions; Uri = appOptions.Uri; string name = null; - if(Uri.StartsWith(Constants.AndroidAppProtocol)) + if (Uri.StartsWith(Constants.AndroidAppProtocol)) { name = Uri.Substring(Constants.AndroidAppProtocol.Length); } @@ -75,7 +75,7 @@ namespace Bit.App.Pages { name = CoreHelpers.GetDomain(Uri); } - if(string.IsNullOrWhiteSpace(name)) + if (string.IsNullOrWhiteSpace(name)) { name = "--"; } @@ -93,14 +93,14 @@ namespace Bit.App.Pages var ciphers = await _cipherService.GetAllDecryptedByUrlAsync(Uri, null); var matching = ciphers.Item1?.Select(c => new GroupingsPageListItem { Cipher = c }).ToList(); var hasMatching = matching?.Any() ?? false; - if(matching?.Any() ?? false) + if (matching?.Any() ?? false) { groupedItems.Add( new GroupingsPageListGroup(matching, AppResources.MatchingItems, matching.Count, false, true)); } var fuzzy = ciphers.Item2?.Select(c => new GroupingsPageListItem { Cipher = c, FuzzyAutofill = true }).ToList(); - if(fuzzy?.Any() ?? false) + if (fuzzy?.Any() ?? false) { groupedItems.Add( new GroupingsPageListGroup(fuzzy, AppResources.PossibleMatchingItems, fuzzy.Count, false, @@ -112,21 +112,21 @@ namespace Bit.App.Pages public async Task SelectCipherAsync(CipherView cipher, bool fuzzy) { - if(cipher == null) + if (cipher == null) { return; } - if(_deviceActionService.SystemMajorVersion() < 21) + if (_deviceActionService.SystemMajorVersion() < 21) { await AppHelpers.CipherListOptions(Page, cipher); } else { var autofillResponse = AppResources.Yes; - if(fuzzy) + if (fuzzy) { var options = new List { AppResources.Yes }; - if(cipher.Type == CipherType.Login && + if (cipher.Type == CipherType.Login && Xamarin.Essentials.Connectivity.NetworkAccess != Xamarin.Essentials.NetworkAccess.None) { options.Add(AppResources.YesAndSave); @@ -135,10 +135,10 @@ namespace Bit.App.Pages string.Format(AppResources.BitwardenAutofillServiceMatchConfirm, Name), AppResources.No, options.ToArray()); } - if(autofillResponse == AppResources.YesAndSave && cipher.Type == CipherType.Login) + if (autofillResponse == AppResources.YesAndSave && cipher.Type == CipherType.Login) { var uris = cipher.Login?.Uris?.ToList(); - if(uris == null) + if (uris == null) { uris = new List(); } @@ -154,17 +154,17 @@ namespace Bit.App.Pages await _cipherService.SaveWithServerAsync(await _cipherService.EncryptAsync(cipher)); await _deviceActionService.HideLoadingAsync(); } - catch(ApiException e) + catch (ApiException e) { await _deviceActionService.HideLoadingAsync(); - if(e?.Error != null) + if (e?.Error != null) { await _platformUtilsService.ShowDialogAsync(e.Error.GetSingleMessage(), AppResources.AnErrorHasOccurred); } } } - if(autofillResponse == AppResources.Yes || autofillResponse == AppResources.YesAndSave) + if (autofillResponse == AppResources.Yes || autofillResponse == AppResources.YesAndSave) { _deviceActionService.Autofill(cipher); } @@ -173,7 +173,7 @@ namespace Bit.App.Pages private async void CipherOptionsAsync(CipherView cipher) { - if((Page as BaseContentPage).DoOnce()) + if ((Page as BaseContentPage).DoOnce()) { await AppHelpers.CipherListOptions(Page, cipher); } diff --git a/src/App/Pages/Vault/CiphersPage.xaml.cs b/src/App/Pages/Vault/CiphersPage.xaml.cs index efe0c9605..ee7253187 100644 --- a/src/App/Pages/Vault/CiphersPage.xaml.cs +++ b/src/App/Pages/Vault/CiphersPage.xaml.cs @@ -23,15 +23,15 @@ namespace Bit.App.Pages _vm.Page = this; _vm.Filter = filter; _vm.AutofillUrl = _autofillUrl = autofillUrl; - if(folder) + if (folder) { _vm.PageTitle = AppResources.SearchFolder; } - else if(collection) + else if (collection) { _vm.PageTitle = AppResources.SearchCollection; } - else if(type) + else if (type) { _vm.PageTitle = AppResources.SearchType; } @@ -40,7 +40,7 @@ namespace Bit.App.Pages _vm.PageTitle = AppResources.SearchVault; } - if(Device.RuntimePlatform == Device.iOS) + if (Device.RuntimePlatform == Device.iOS) { ToolbarItems.Add(_closeItem); _searchBar.Placeholder = AppResources.Search; @@ -60,7 +60,7 @@ namespace Bit.App.Pages { base.OnAppearing(); await _vm.InitAsync(); - if(!_hasFocused) + if (!_hasFocused) { _hasFocused = true; RequestFocus(_searchBar); @@ -71,7 +71,7 @@ namespace Bit.App.Pages { var oldLength = e.OldTextValue?.Length ?? 0; var newLength = e.NewTextValue?.Length ?? 0; - if(oldLength < 2 && newLength < 2 && oldLength < newLength) + if (oldLength < 2 && newLength < 2 && oldLength < newLength) { return; } @@ -90,7 +90,7 @@ namespace Bit.App.Pages protected override bool OnBackButtonPressed() { - if(string.IsNullOrWhiteSpace(_autofillUrl)) + if (string.IsNullOrWhiteSpace(_autofillUrl)) { return false; } @@ -100,11 +100,11 @@ namespace Bit.App.Pages private void GoBack() { - if(!DoOnce()) + if (!DoOnce()) { return; } - if(string.IsNullOrWhiteSpace(_autofillUrl)) + if (string.IsNullOrWhiteSpace(_autofillUrl)) { Navigation.PopModalAsync(false); } @@ -117,12 +117,12 @@ namespace Bit.App.Pages private async void RowSelected(object sender, SelectedItemChangedEventArgs e) { ((ListView)sender).SelectedItem = null; - if(!DoOnce()) + if (!DoOnce()) { return; } - if(e.SelectedItem is CipherView cipher) + if (e.SelectedItem is CipherView cipher) { await _vm.SelectCipherAsync(cipher); } diff --git a/src/App/Pages/Vault/CiphersPageViewModel.cs b/src/App/Pages/Vault/CiphersPageViewModel.cs index aa6584c59..e175fa3cb 100644 --- a/src/App/Pages/Vault/CiphersPageViewModel.cs +++ b/src/App/Pages/Vault/CiphersPageViewModel.cs @@ -75,7 +75,7 @@ namespace Bit.App.Pages { WebsiteIconsEnabled = !(await _stateService.GetAsync(Constants.DisableFaviconKey)) .GetValueOrDefault(); - if(!string.IsNullOrWhiteSpace((Page as CiphersPage).SearchBar.Text)) + if (!string.IsNullOrWhiteSpace((Page as CiphersPage).SearchBar.Text)) { Search((Page as CiphersPage).SearchBar.Text, 200); } @@ -89,13 +89,13 @@ namespace Bit.App.Pages { List ciphers = null; var searchable = !string.IsNullOrWhiteSpace(searchText) && searchText.Length > 1; - if(searchable) + if (searchable) { - if(timeout != null) + if (timeout != null) { await Task.Delay(timeout.Value); } - if(searchText != (Page as CiphersPage).SearchBar.Text) + if (searchText != (Page as CiphersPage).SearchBar.Text) { return; } @@ -108,12 +108,12 @@ namespace Bit.App.Pages ciphers = await _searchService.SearchCiphersAsync(searchText, Filter, null, cts.Token); cts.Token.ThrowIfCancellationRequested(); } - catch(OperationCanceledException) + catch (OperationCanceledException) { return; } } - if(ciphers == null) + if (ciphers == null) { ciphers = new List(); } @@ -130,10 +130,10 @@ namespace Bit.App.Pages public async Task SelectCipherAsync(CipherView cipher) { string selection = null; - if(!string.IsNullOrWhiteSpace(AutofillUrl)) + if (!string.IsNullOrWhiteSpace(AutofillUrl)) { var options = new List { AppResources.Autofill }; - if(cipher.Type == CipherType.Login && + if (cipher.Type == CipherType.Login && Xamarin.Essentials.Connectivity.NetworkAccess != Xamarin.Essentials.NetworkAccess.None) { options.Add(AppResources.AutofillAndSave); @@ -142,17 +142,17 @@ namespace Bit.App.Pages selection = await Page.DisplayActionSheet(AppResources.AutofillOrView, AppResources.Cancel, null, options.ToArray()); } - if(selection == AppResources.View || string.IsNullOrWhiteSpace(AutofillUrl)) + if (selection == AppResources.View || string.IsNullOrWhiteSpace(AutofillUrl)) { var page = new ViewPage(cipher.Id); 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(); - if(uris == null) + if (uris == null) { uris = new List(); } @@ -168,17 +168,17 @@ namespace Bit.App.Pages await _cipherService.SaveWithServerAsync(await _cipherService.EncryptAsync(cipher)); await _deviceActionService.HideLoadingAsync(); } - catch(ApiException e) + catch (ApiException e) { await _deviceActionService.HideLoadingAsync(); - if(e?.Error != null) + if (e?.Error != null) { await _platformUtilsService.ShowDialogAsync(e.Error.GetSingleMessage(), AppResources.AnErrorHasOccurred); } } } - if(_deviceActionService.SystemMajorVersion() < 21) + if (_deviceActionService.SystemMajorVersion() < 21) { await Utilities.AppHelpers.CipherListOptions(Page, cipher); } @@ -191,7 +191,7 @@ namespace Bit.App.Pages private async void CipherOptionsAsync(CipherView cipher) { - if((Page as BaseContentPage).DoOnce()) + if ((Page as BaseContentPage).DoOnce()) { await Utilities.AppHelpers.CipherListOptions(Page, cipher); } diff --git a/src/App/Pages/Vault/CollectionsPage.xaml.cs b/src/App/Pages/Vault/CollectionsPage.xaml.cs index aa75a1e23..56fa7036c 100644 --- a/src/App/Pages/Vault/CollectionsPage.xaml.cs +++ b/src/App/Pages/Vault/CollectionsPage.xaml.cs @@ -13,7 +13,7 @@ namespace Bit.App.Pages _vm.Page = this; _vm.CipherId = cipherId; SetActivityIndicator(); - if(Device.RuntimePlatform == Device.Android) + if (Device.RuntimePlatform == Device.Android) { ToolbarItems.RemoveAt(0); } @@ -32,7 +32,7 @@ namespace Bit.App.Pages private async void Save_Clicked(object sender, System.EventArgs e) { - if(DoOnce()) + if (DoOnce()) { await _vm.SubmitAsync(); } @@ -40,7 +40,7 @@ namespace Bit.App.Pages private async void Close_Clicked(object sender, System.EventArgs e) { - if(DoOnce()) + if (DoOnce()) { await Navigation.PopModalAsync(); } diff --git a/src/App/Pages/Vault/CollectionsPageViewModel.cs b/src/App/Pages/Vault/CollectionsPageViewModel.cs index fa1bf1841..e0b678de2 100644 --- a/src/App/Pages/Vault/CollectionsPageViewModel.cs +++ b/src/App/Pages/Vault/CollectionsPageViewModel.cs @@ -59,13 +59,13 @@ namespace Bit.App.Pages public async Task SubmitAsync() { 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, AppResources.Ok); 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, AppResources.InternetConnectionRequiredTitle); @@ -82,10 +82,10 @@ namespace Bit.App.Pages await Page.Navigation.PopModalAsync(); return true; } - catch(ApiException e) + catch (ApiException e) { await _deviceActionService.HideLoadingAsync(); - if(e?.Error != null) + if (e?.Error != null) { await _platformUtilsService.ShowDialogAsync(e.Error.GetSingleMessage(), AppResources.AnErrorHasOccurred); diff --git a/src/App/Pages/Vault/GroupingsPage/GroupingsPage.xaml.cs b/src/App/Pages/Vault/GroupingsPage/GroupingsPage.xaml.cs index 284ca9b93..70c9f24c5 100644 --- a/src/App/Pages/Vault/GroupingsPage/GroupingsPage.xaml.cs +++ b/src/App/Pages/Vault/GroupingsPage/GroupingsPage.xaml.cs @@ -48,12 +48,12 @@ namespace Bit.App.Pages _vm.FolderId = folderId; _vm.CollectionId = collectionId; _previousPage = previousPage; - if(pageTitle != null) + if (pageTitle != null) { _vm.PageTitle = pageTitle; } - if(Device.RuntimePlatform == Device.iOS) + if (Device.RuntimePlatform == Device.iOS) { _absLayout.Children.Remove(_fab); ToolbarItems.Add(_addItem); @@ -71,24 +71,24 @@ namespace Bit.App.Pages protected async override void OnAppearing() { base.OnAppearing(); - if(_syncService.SyncInProgress) + if (_syncService.SyncInProgress) { IsBusy = true; } _broadcasterService.Subscribe(_pageName, async (message) => { - if(message.Command == "syncStarted") + if (message.Command == "syncStarted") { Device.BeginInvokeOnMainThread(() => IsBusy = true); } - else if(message.Command == "syncCompleted") + else if (message.Command == "syncCompleted") { await Task.Delay(500); Device.BeginInvokeOnMainThread(() => { IsBusy = false; - if(_vm.LoadedOnce) + if (_vm.LoadedOnce) { var task = _vm.LoadAsync(); } @@ -99,13 +99,13 @@ namespace Bit.App.Pages var migratedFromV1 = await _storageService.GetAsync(Constants.MigratedFromV1); await LoadOnAppearedAsync(_mainLayout, false, async () => { - if(!_syncService.SyncInProgress || (await _cipherService.GetAllAsync()).Any()) + if (!_syncService.SyncInProgress || (await _cipherService.GetAllAsync()).Any()) { try { 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 _vm.LoadAsync(); @@ -114,18 +114,18 @@ namespace Bit.App.Pages else { await Task.Delay(5000); - if(!_vm.Loaded) + if (!_vm.Loaded) { await _vm.LoadAsync(); } } // 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 && Xamarin.Essentials.Connectivity.NetworkAccess != Xamarin.Essentials.NetworkAccess.None) { var triedV1ReSync = await _storageService.GetAsync(Constants.TriedV1Resync); - if(!triedV1ReSync.GetValueOrDefault()) + if (!triedV1ReSync.GetValueOrDefault()) { await _storageService.SaveAsync(Constants.TriedV1Resync, true); await _syncService.FullSyncAsync(true); @@ -134,7 +134,7 @@ namespace Bit.App.Pages await ShowPreviousPageAsync(); }, _mainContent); - if(!_vm.MainPage) + if (!_vm.MainPage) { return; } @@ -142,35 +142,35 @@ namespace Bit.App.Pages // Push registration var lastPushRegistration = await _storageService.GetAsync(Constants.PushLastRegistrationDateKey); lastPushRegistration = lastPushRegistration.GetValueOrDefault(DateTime.MinValue); - if(Device.RuntimePlatform == Device.iOS) + if (Device.RuntimePlatform == Device.iOS) { var pushPromptShow = await _storageService.GetAsync(Constants.PushInitialPromptShownKey); - if(!pushPromptShow.GetValueOrDefault(false)) + if (!pushPromptShow.GetValueOrDefault(false)) { await _storageService.SaveAsync(Constants.PushInitialPromptShownKey, true); await DisplayAlert(AppResources.EnableAutomaticSyncing, AppResources.PushNotificationAlert, AppResources.OkGotIt); } - if(!pushPromptShow.GetValueOrDefault(false) || + if (!pushPromptShow.GetValueOrDefault(false) || DateTime.UtcNow - lastPushRegistration > TimeSpan.FromDays(1)) { 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(); } - if(!_deviceActionService.AutofillAccessibilityServiceRunning() + if (!_deviceActionService.AutofillAccessibilityServiceRunning() && !_deviceActionService.AutofillServiceEnabled()) { - if(migratedFromV1.GetValueOrDefault()) + if (migratedFromV1.GetValueOrDefault()) { var migratedFromV1AutofillPromptShown = await _storageService.GetAsync( Constants.MigratedFromV1AutofillPromptShown); - if(!migratedFromV1AutofillPromptShown.GetValueOrDefault()) + if (!migratedFromV1AutofillPromptShown.GetValueOrDefault()) { await DisplayAlert(AppResources.Autofill, AppResources.AutofillServiceNotEnabled, AppResources.Ok); @@ -191,28 +191,28 @@ namespace Bit.App.Pages private async void RowSelected(object sender, SelectedItemChangedEventArgs e) { ((ListView)sender).SelectedItem = null; - if(!DoOnce()) + if (!DoOnce()) { return; } - if(!(e.SelectedItem is GroupingsPageListItem item)) + if (!(e.SelectedItem is GroupingsPageListItem item)) { return; } - if(item.Cipher != null) + if (item.Cipher != null) { await _vm.SelectCipherAsync(item.Cipher); } - else if(item.Folder != null) + else if (item.Folder != null) { await _vm.SelectFolderAsync(item.Folder); } - else if(item.Collection != null) + else if (item.Collection != null) { await _vm.SelectCollectionAsync(item.Collection); } - else if(item.Type != null) + else if (item.Type != null) { await _vm.SelectTypeAsync(item.Type.Value); } @@ -220,7 +220,7 @@ namespace Bit.App.Pages 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, _vm.Type != null); @@ -245,7 +245,7 @@ namespace Bit.App.Pages private async void AddButton_Clicked(object sender, EventArgs e) { - if(DoOnce()) + if (DoOnce()) { var page = new AddEditPage(null, _vm.Type, _vm.FolderId, _vm.CollectionId); await Navigation.PushModalAsync(new NavigationPage(page)); @@ -254,15 +254,15 @@ namespace Bit.App.Pages private async Task ShowPreviousPageAsync() { - if(_previousPage == null) + if (_previousPage == null) { 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))); } - 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))); } diff --git a/src/App/Pages/Vault/GroupingsPage/GroupingsPageListGroup.cs b/src/App/Pages/Vault/GroupingsPage/GroupingsPageListGroup.cs index 23d5c949e..1702aa85f 100644 --- a/src/App/Pages/Vault/GroupingsPage/GroupingsPageListGroup.cs +++ b/src/App/Pages/Vault/GroupingsPage/GroupingsPageListGroup.cs @@ -12,11 +12,11 @@ namespace Bit.App.Pages bool doUpper = true, bool first = false) { AddRange(groupItems); - if(string.IsNullOrWhiteSpace(name)) + if (string.IsNullOrWhiteSpace(name)) { Name = "-"; } - else if(doUpper) + else if (doUpper) { Name = name.ToUpperInvariant(); } diff --git a/src/App/Pages/Vault/GroupingsPage/GroupingsPageListItem.cs b/src/App/Pages/Vault/GroupingsPage/GroupingsPageListItem.cs index 6dfd33b78..a19c6ed69 100644 --- a/src/App/Pages/Vault/GroupingsPage/GroupingsPageListItem.cs +++ b/src/App/Pages/Vault/GroupingsPage/GroupingsPageListItem.cs @@ -20,21 +20,21 @@ namespace Bit.App.Pages { get { - if(_name != null) + if (_name != null) { return _name; } - if(Folder != null) + if (Folder != null) { _name = Folder.Name; } - else if(Collection != null) + else if (Collection != null) { _name = Collection.Name; } - else if(Type != null) + else if (Type != null) { - switch(Type.Value) + switch (Type.Value) { case CipherType.Login: _name = AppResources.TypeLogin; @@ -60,21 +60,21 @@ namespace Bit.App.Pages { get { - if(_icon != null) + if (_icon != null) { return _icon; } - if(Folder != null) + if (Folder != null) { _icon = Folder.Id == null ? "" : ""; } - else if(Collection != null) + else if (Collection != null) { _icon = ""; } - else if(Type != null) + else if (Type != null) { - switch(Type.Value) + switch (Type.Value) { case CipherType.Login: _icon = ""; diff --git a/src/App/Pages/Vault/GroupingsPage/GroupingsPageListItemSelector.cs b/src/App/Pages/Vault/GroupingsPage/GroupingsPageListItemSelector.cs index 4fea472ba..667aeee96 100644 --- a/src/App/Pages/Vault/GroupingsPage/GroupingsPageListItemSelector.cs +++ b/src/App/Pages/Vault/GroupingsPage/GroupingsPageListItemSelector.cs @@ -9,7 +9,7 @@ namespace Bit.App.Pages protected override DataTemplate OnSelectTemplate(object item, BindableObject container) { - if(item is GroupingsPageListItem listItem) + if (item is GroupingsPageListItem listItem) { return listItem.Cipher != null ? CipherTemplate : GroupTemplate; } diff --git a/src/App/Pages/Vault/GroupingsPage/GroupingsPageViewModel.cs b/src/App/Pages/Vault/GroupingsPage/GroupingsPageViewModel.cs index 0c1926270..01cf7e84e 100644 --- a/src/App/Pages/Vault/GroupingsPage/GroupingsPageViewModel.cs +++ b/src/App/Pages/Vault/GroupingsPage/GroupingsPageViewModel.cs @@ -134,16 +134,16 @@ namespace Bit.App.Pages public async Task LoadAsync() { - if(_doingLoad) + if (_doingLoad) { return; } var authed = await _userService.IsAuthenticatedAsync(); - if(!authed) + if (!authed) { return; } - if(await _lockService.IsLockedAsync()) + if (await _lockService.IsLockedAsync()) { return; } @@ -161,7 +161,7 @@ namespace Bit.App.Pages try { await LoadDataAsync(); - if(ShowNoFolderCiphers && (NestedFolders?.Any() ?? false)) + if (ShowNoFolderCiphers && (NestedFolders?.Any() ?? false)) { // Remove "No Folder" from folder listing NestedFolders = NestedFolders.GetRange(0, NestedFolders.Count - 1); @@ -169,13 +169,13 @@ namespace Bit.App.Pages var uppercaseGroupNames = _deviceActionService.DeviceType == DeviceType.iOS; var hasFavorites = FavoriteCiphers?.Any() ?? false; - if(hasFavorites) + if (hasFavorites) { var favListItems = FavoriteCiphers.Select(c => new GroupingsPageListItem { Cipher = c }).ToList(); groupedItems.Add(new GroupingsPageListGroup(favListItems, AppResources.Favorites, favListItems.Count, uppercaseGroupNames, true)); } - if(MainPage) + if (MainPage) { groupedItems.Add(new GroupingsPageListGroup( 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 => { @@ -220,7 +220,7 @@ namespace Bit.App.Pages groupedItems.Add(new GroupingsPageListGroup(folderListItems, AppResources.Folders, folderListItems.Count, uppercaseGroupNames, !MainPage)); } - if(NestedCollections?.Any() ?? false) + if (NestedCollections?.Any() ?? false) { var collectionListItems = NestedCollections.Select(c => new GroupingsPageListItem { @@ -231,13 +231,13 @@ namespace Bit.App.Pages groupedItems.Add(new GroupingsPageListGroup(collectionListItems, AppResources.Collections, collectionListItems.Count, uppercaseGroupNames, !MainPage)); } - if(Ciphers?.Any() ?? false) + if (Ciphers?.Any() ?? false) { var ciphersListItems = Ciphers.Select(c => new GroupingsPageListItem { Cipher = c }).ToList(); groupedItems.Add(new GroupingsPageListGroup(ciphersListItems, AppResources.Items, ciphersListItems.Count, uppercaseGroupNames, !MainPage && !groupedItems.Any())); } - if(ShowNoFolderCiphers) + if (ShowNoFolderCiphers) { var noFolderCiphersListItems = NoFolderCiphers.Select( c => new GroupingsPageListItem { Cipher = c }).ToList(); @@ -266,7 +266,7 @@ namespace Bit.App.Pages public async Task SelectTypeAsync(CipherType type) { string title = null; - switch(type) + switch (type) { case CipherType.Login: title = AppResources.Logins; @@ -303,7 +303,7 @@ namespace Bit.App.Pages { var confirmed = await _platformUtilsService.ShowDialogAsync(AppResources.ExitConfirmation, AppResources.Exit, AppResources.Yes, AppResources.Cancel); - if(confirmed) + if (confirmed) { _messagingService.Send("exit"); } @@ -311,7 +311,7 @@ namespace Bit.App.Pages 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, AppResources.InternetConnectionRequiredTitle); @@ -345,7 +345,7 @@ namespace Bit.App.Pages HasCollections = false; Filter = null; - if(MainPage) + if (MainPage) { Folders = await _folderService.GetAllDecryptedAsync(); NestedFolders = await _folderService.GetAllNestedAsync(); @@ -356,18 +356,18 @@ namespace Bit.App.Pages } else { - if(Type != null) + if (Type != null) { Filter = c => c.Type == Type.Value; } - else if(FolderId != null) + else if (FolderId != null) { NoDataText = AppResources.NoItemsFolder; var folderId = FolderId == "none" ? null : FolderId; - if(folderId != null) + if (folderId != null) { var folderNode = await _folderService.GetNestedAsync(folderId); - if(folderNode?.Node != null) + if (folderNode?.Node != null) { PageTitle = folderNode.Node.Name; NestedFolders = (folderNode.Children?.Count ?? 0) > 0 ? folderNode.Children : null; @@ -379,12 +379,12 @@ namespace Bit.App.Pages } Filter = c => c.FolderId == folderId; } - else if(CollectionId != null) + else if (CollectionId != null) { ShowAddCipherButton = false; NoDataText = AppResources.NoItemsCollection; var collectionNode = await _collectionService.GetNestedAsync(CollectionId); - if(collectionNode?.Node != null) + if (collectionNode?.Node != null) { PageTitle = collectionNode.Node.Name; 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; } - 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(); } FavoriteCiphers.Add(c); } - if(c.FolderId == null) + if (c.FolderId == null) { - if(NoFolderCiphers == null) + if (NoFolderCiphers == null) { NoFolderCiphers = new List(); } NoFolderCiphers.Add(c); } - if(_typeCounts.ContainsKey(c.Type)) + if (_typeCounts.ContainsKey(c.Type)) { _typeCounts[c.Type] = _typeCounts[c.Type] + 1; } @@ -430,7 +430,7 @@ namespace Bit.App.Pages } var fId = c.FolderId ?? "none"; - if(_folderCounts.ContainsKey(fId)) + if (_folderCounts.ContainsKey(fId)) { _folderCounts[fId] = _folderCounts[fId] + 1; } @@ -439,11 +439,11 @@ namespace Bit.App.Pages _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; } @@ -458,7 +458,7 @@ namespace Bit.App.Pages private async void CipherOptionsAsync(CipherView cipher) { - if((Page as BaseContentPage).DoOnce()) + if ((Page as BaseContentPage).DoOnce()) { await AppHelpers.CipherListOptions(Page, cipher); } diff --git a/src/App/Pages/Vault/PasswordHistoryPage.xaml.cs b/src/App/Pages/Vault/PasswordHistoryPage.xaml.cs index a96e8c8c1..ea444c3d6 100644 --- a/src/App/Pages/Vault/PasswordHistoryPage.xaml.cs +++ b/src/App/Pages/Vault/PasswordHistoryPage.xaml.cs @@ -14,7 +14,7 @@ namespace Bit.App.Pages _vm = BindingContext as PasswordHistoryPageViewModel; _vm.Page = this; _vm.CipherId = cipherId; - if(Device.RuntimePlatform == Device.Android) + if (Device.RuntimePlatform == Device.Android) { ToolbarItems.RemoveAt(0); } @@ -30,7 +30,7 @@ namespace Bit.App.Pages private async void Close_Clicked(object sender, System.EventArgs e) { - if(DoOnce()) + if (DoOnce()) { await Navigation.PopModalAsync(); } diff --git a/src/App/Pages/Vault/ScanPage.xaml.cs b/src/App/Pages/Vault/ScanPage.xaml.cs index fe5e2fd25..981bb391c 100644 --- a/src/App/Pages/Vault/ScanPage.xaml.cs +++ b/src/App/Pages/Vault/ScanPage.xaml.cs @@ -22,7 +22,7 @@ namespace Bit.App.Pages AutoRotate = false, TryInverted = true }; - if(Device.RuntimePlatform == Device.Android) + if (Device.RuntimePlatform == Device.Android) { ToolbarItems.RemoveAt(0); } @@ -35,7 +35,7 @@ namespace Bit.App.Pages _timerStarted = DateTime.Now; Device.StartTimer(new TimeSpan(0, 0, 2), () => { - if(_timerStarted == null || (DateTime.Now - _timerStarted) > _timerMaxLength) + if (_timerStarted == null || (DateTime.Now - _timerStarted) > _timerMaxLength) { return false; } @@ -57,20 +57,20 @@ namespace Bit.App.Pages _zxing.IsAnalyzing = false; _zxing.IsScanning = false; var text = result?.Text; - if(!string.IsNullOrWhiteSpace(text)) + if (!string.IsNullOrWhiteSpace(text)) { - if(text.StartsWith("otpauth://totp")) + if (text.StartsWith("otpauth://totp")) { _callback(text); 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)) { 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()); return; @@ -83,7 +83,7 @@ namespace Bit.App.Pages private async void Close_Clicked(object sender, System.EventArgs e) { - if(DoOnce()) + if (DoOnce()) { await Navigation.PopModalAsync(); } diff --git a/src/App/Pages/Vault/SharePage.xaml.cs b/src/App/Pages/Vault/SharePage.xaml.cs index 5e3510875..b97c203f4 100644 --- a/src/App/Pages/Vault/SharePage.xaml.cs +++ b/src/App/Pages/Vault/SharePage.xaml.cs @@ -15,7 +15,7 @@ namespace Bit.App.Pages _vm.Page = this; _vm.CipherId = cipherId; SetActivityIndicator(); - if(Device.RuntimePlatform == Device.Android) + if (Device.RuntimePlatform == Device.Android) { ToolbarItems.RemoveAt(0); } @@ -39,7 +39,7 @@ namespace Bit.App.Pages private async void Save_Clicked(object sender, System.EventArgs e) { - if(DoOnce()) + if (DoOnce()) { await _vm.SubmitAsync(); } @@ -47,7 +47,7 @@ namespace Bit.App.Pages private async void Close_Clicked(object sender, System.EventArgs e) { - if(DoOnce()) + if (DoOnce()) { await Navigation.PopModalAsync(); } diff --git a/src/App/Pages/Vault/SharePageViewModel.cs b/src/App/Pages/Vault/SharePageViewModel.cs index d4ed8c4a0..33c1852ae 100644 --- a/src/App/Pages/Vault/SharePageViewModel.cs +++ b/src/App/Pages/Vault/SharePageViewModel.cs @@ -45,7 +45,7 @@ namespace Bit.App.Pages get => _organizationSelectedIndex; set { - if(SetProperty(ref _organizationSelectedIndex, value)) + if (SetProperty(ref _organizationSelectedIndex, value)) { OrganizationChanged(); } @@ -75,7 +75,7 @@ namespace Bit.App.Pages var cipherDomain = await _cipherService.GetAsync(CipherId); _cipher = await cipherDomain.DecryptAsync(); - if(OrganizationId == null && OrganizationOptions.Any()) + if (OrganizationId == null && OrganizationOptions.Any()) { OrganizationId = OrganizationOptions.First().Value; } @@ -87,13 +87,13 @@ namespace Bit.App.Pages public async Task SubmitAsync() { 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, AppResources.Ok); 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, AppResources.InternetConnectionRequiredTitle); @@ -113,19 +113,19 @@ namespace Bit.App.Pages await Page.Navigation.PopModalAsync(); return true; } - catch(ApiException e) + catch (ApiException e) { await _deviceActionService.HideLoadingAsync(); - if(e?.Error != null) + if (e?.Error != null) { await _platformUtilsService.ShowDialogAsync(e.Error.GetSingleMessage(), AppResources.AnErrorHasOccurred); } } - catch(System.Exception e) + catch (System.Exception e) { await _deviceActionService.HideLoadingAsync(); - if(e.Message != null) + if (e.Message != null) { await _platformUtilsService.ShowDialogAsync(e.Message, AppResources.AnErrorHasOccurred); } @@ -135,7 +135,7 @@ namespace Bit.App.Pages private void OrganizationChanged() { - if(OrganizationSelectedIndex > -1) + if (OrganizationSelectedIndex > -1) { OrganizationId = OrganizationOptions[OrganizationSelectedIndex].Value; FilterCollections(); @@ -144,7 +144,7 @@ namespace Bit.App.Pages private void FilterCollections() { - if(OrganizationId == null || !_writeableCollections.Any()) + if (OrganizationId == null || !_writeableCollections.Any()) { Collections.ResetWithRange(new List()); } diff --git a/src/App/Pages/Vault/ViewPage.xaml.cs b/src/App/Pages/Vault/ViewPage.xaml.cs index a8e0bf9a7..dce5e8f37 100644 --- a/src/App/Pages/Vault/ViewPage.xaml.cs +++ b/src/App/Pages/Vault/ViewPage.xaml.cs @@ -24,7 +24,7 @@ namespace Bit.App.Pages _vm.CipherId = cipherId; SetActivityIndicator(_mainContent); - if(Device.RuntimePlatform == Device.iOS) + if (Device.RuntimePlatform == Device.iOS) { _absLayout.Children.Remove(_fab); ToolbarItems.Add(_closeItem); @@ -49,39 +49,39 @@ namespace Bit.App.Pages protected override async void OnAppearing() { base.OnAppearing(); - if(_syncService.SyncInProgress) + if (_syncService.SyncInProgress) { IsBusy = true; } _broadcasterService.Subscribe(nameof(ViewPage), async (message) => { - if(message.Command == "syncStarted") + if (message.Command == "syncStarted") { Device.BeginInvokeOnMainThread(() => IsBusy = true); } - else if(message.Command == "syncCompleted") + else if (message.Command == "syncCompleted") { await Task.Delay(500); Device.BeginInvokeOnMainThread(() => { IsBusy = false; - if(message.Data is Dictionary data && data.ContainsKey("successfully")) + if (message.Data is Dictionary data && data.ContainsKey("successfully")) { var success = data["successfully"] as bool?; - if(success.GetValueOrDefault()) + if (success.GetValueOrDefault()) { var task = _vm.LoadAsync(() => AdjustToolbar()); } } }); } - else if(message.Command == "selectSaveFileResult") + else if (message.Command == "selectSaveFileResult") { Device.BeginInvokeOnMainThread(() => { var data = message.Data as Tuple; - if(data == null) + if (data == null) { return; } @@ -92,7 +92,7 @@ namespace Bit.App.Pages await LoadOnAppearedAsync(_scrollView, true, async () => { var success = await _vm.LoadAsync(() => AdjustToolbar()); - if(!success) + if (!success) { await Navigation.PopModalAsync(); } @@ -109,7 +109,7 @@ namespace Bit.App.Pages private async void PasswordHistory_Tapped(object sender, System.EventArgs e) { - if(DoOnce()) + if (DoOnce()) { await Navigation.PushModalAsync(new NavigationPage(new PasswordHistoryPage(_vm.CipherId))); } @@ -117,7 +117,7 @@ namespace Bit.App.Pages private async void EditToolbarItem_Clicked(object sender, System.EventArgs e) { - if(DoOnce()) + if (DoOnce()) { await Navigation.PushModalAsync(new NavigationPage(new AddEditPage(_vm.CipherId))); } @@ -130,7 +130,7 @@ namespace Bit.App.Pages private async void Attachments_Clicked(object sender, System.EventArgs e) { - if(DoOnce()) + if (DoOnce()) { var page = new AttachmentsPage(_vm.CipherId); await Navigation.PushModalAsync(new NavigationPage(page)); @@ -139,7 +139,7 @@ namespace Bit.App.Pages private async void Share_Clicked(object sender, System.EventArgs e) { - if(DoOnce()) + if (DoOnce()) { var page = new SharePage(_vm.CipherId); await Navigation.PushModalAsync(new NavigationPage(page)); @@ -148,9 +148,9 @@ namespace Bit.App.Pages 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(); } @@ -159,7 +159,7 @@ namespace Bit.App.Pages private async void Collections_Clicked(object sender, System.EventArgs e) { - if(DoOnce()) + if (DoOnce()) { var page = new CollectionsPage(_vm.CipherId); await Navigation.PushModalAsync(new NavigationPage(page)); @@ -168,7 +168,7 @@ namespace Bit.App.Pages private async void Clone_Clicked(object sender, System.EventArgs e) { - if(DoOnce()) + if (DoOnce()) { var page = new AddEditPage(_vm.CipherId, cloneMode: true, viewPage: this); await Navigation.PushModalAsync(new NavigationPage(page)); @@ -177,13 +177,13 @@ namespace Bit.App.Pages private async void More_Clicked(object sender, System.EventArgs e) { - if(!DoOnce()) + if (!DoOnce()) { return; } var options = new List {AppResources.Attachments}; - if(_vm.Cipher.OrganizationId == null) + if (_vm.Cipher.OrganizationId == null) { options.Add(AppResources.Clone); options.Add(AppResources.Share); @@ -195,29 +195,29 @@ namespace Bit.App.Pages var selection = await DisplayActionSheet(AppResources.Options, AppResources.Cancel, AppResources.Delete, options.ToArray()); - if(selection == AppResources.Delete) + if (selection == AppResources.Delete) { - if(await _vm.DeleteAsync()) + if (await _vm.DeleteAsync()) { await Navigation.PopModalAsync(); } } - else if(selection == AppResources.Attachments) + else if (selection == AppResources.Attachments) { var page = new AttachmentsPage(_vm.CipherId); await Navigation.PushModalAsync(new NavigationPage(page)); } - else if(selection == AppResources.Collections) + else if (selection == AppResources.Collections) { var page = new CollectionsPage(_vm.CipherId); await Navigation.PushModalAsync(new NavigationPage(page)); } - else if(selection == AppResources.Share) + else if (selection == AppResources.Share) { var page = new SharePage(_vm.CipherId); await Navigation.PushModalAsync(new NavigationPage(page)); } - else if(selection == AppResources.Clone) + else if (selection == AppResources.Clone) { var page = new AddEditPage(_vm.CipherId, cloneMode: true, viewPage: this); await Navigation.PushModalAsync(new NavigationPage(page)); @@ -226,7 +226,7 @@ namespace Bit.App.Pages private async void Close_Clicked(object sender, System.EventArgs e) { - if(DoOnce()) + if (DoOnce()) { await Navigation.PopModalAsync(); } @@ -234,36 +234,36 @@ namespace Bit.App.Pages private void AdjustToolbar() { - if(Device.RuntimePlatform != Device.Android || _vm.Cipher == null) + if (Device.RuntimePlatform != Device.Android || _vm.Cipher == null) { return; } - if(_vm.Cipher.OrganizationId == null) + if (_vm.Cipher.OrganizationId == null) { - if(ToolbarItems.Contains(_collectionsItem)) + if (ToolbarItems.Contains(_collectionsItem)) { ToolbarItems.Remove(_collectionsItem); } - if(!ToolbarItems.Contains(_cloneItem)) + if (!ToolbarItems.Contains(_cloneItem)) { ToolbarItems.Insert(1, _cloneItem); } - if(!ToolbarItems.Contains(_shareItem)) + if (!ToolbarItems.Contains(_shareItem)) { ToolbarItems.Insert(2, _shareItem); } } else { - if(ToolbarItems.Contains(_cloneItem)) + if (ToolbarItems.Contains(_cloneItem)) { ToolbarItems.Remove(_cloneItem); } - if(ToolbarItems.Contains(_shareItem)) + if (ToolbarItems.Contains(_shareItem)) { ToolbarItems.Remove(_shareItem); } - if(!ToolbarItems.Contains(_collectionsItem)) + if (!ToolbarItems.Contains(_collectionsItem)) { ToolbarItems.Insert(1, _collectionsItem); } diff --git a/src/App/Pages/Vault/ViewPageViewModel.cs b/src/App/Pages/Vault/ViewPageViewModel.cs index 6a2b05110..31db301dd 100644 --- a/src/App/Pages/Vault/ViewPageViewModel.cs +++ b/src/App/Pages/Vault/ViewPageViewModel.cs @@ -215,7 +215,7 @@ namespace Bit.App.Pages { CleanUp(); var cipher = await _cipherService.GetAsync(CipherId); - if(cipher == null) + if (cipher == null) { finishedLoadingAction?.Invoke(); return false; @@ -224,7 +224,7 @@ namespace Bit.App.Pages CanAccessPremium = await _userService.CanAccessPremiumAsync(); Fields = Cipher.Fields?.Select(f => new ViewPageFieldViewModel(Cipher, f)).ToList(); - if(Cipher.Type == Core.Enums.CipherType.Login && !string.IsNullOrWhiteSpace(Cipher.Login.Totp) && + if (Cipher.Type == Core.Enums.CipherType.Login && !string.IsNullOrWhiteSpace(Cipher.Login.Totp) && (Cipher.OrganizationUseTotp || CanAccessPremium)) { await TotpUpdateCodeAsync(); @@ -233,7 +233,7 @@ namespace Bit.App.Pages _totpInterval = DateTime.UtcNow; Device.StartTimer(new TimeSpan(0, 0, 1), () => { - if(_totpInterval == null) + if (_totpInterval == null) { return false; } @@ -241,7 +241,7 @@ namespace Bit.App.Pages return true; }); } - if(_previousCipherId != CipherId) + if (_previousCipherId != CipherId) { var task = _eventService.CollectAsync(Core.Enums.EventType.Cipher_ClientViewed, CipherId); } @@ -258,7 +258,7 @@ namespace Bit.App.Pages public void TogglePassword() { ShowPassword = !ShowPassword; - if(ShowPassword) + if (ShowPassword) { var task = _eventService.CollectAsync(Core.Enums.EventType.Cipher_ClientToggledPasswordVisible, CipherId); } @@ -267,7 +267,7 @@ namespace Bit.App.Pages public void ToggleCardCode() { ShowCardCode = !ShowCardCode; - if(ShowCardCode) + if (ShowCardCode) { var task = _eventService.CollectAsync( Core.Enums.EventType.Cipher_ClientToggledCardCodeVisible, CipherId); @@ -276,7 +276,7 @@ namespace Bit.App.Pages public async Task DeleteAsync() { - if(Xamarin.Essentials.Connectivity.NetworkAccess == Xamarin.Essentials.NetworkAccess.None) + if (Xamarin.Essentials.Connectivity.NetworkAccess == Xamarin.Essentials.NetworkAccess.None) { await _platformUtilsService.ShowDialogAsync(AppResources.InternetConnectionRequiredMessage, AppResources.InternetConnectionRequiredTitle); @@ -284,7 +284,7 @@ namespace Bit.App.Pages } var confirmed = await _platformUtilsService.ShowDialogAsync(AppResources.DoYouReallyWantToDelete, null, AppResources.Yes, AppResources.Cancel); - if(!confirmed) + if (!confirmed) { return false; } @@ -297,10 +297,10 @@ namespace Bit.App.Pages _messagingService.Send("deletedCipher", Cipher); return true; } - catch(ApiException e) + catch (ApiException e) { await _deviceActionService.HideLoadingAsync(); - if(e?.Error != null) + if (e?.Error != null) { await _platformUtilsService.ShowDialogAsync(e.Error.GetSingleMessage(), AppResources.AnErrorHasOccurred); @@ -311,15 +311,15 @@ namespace Bit.App.Pages private async Task TotpUpdateCodeAsync() { - if(Cipher == null || Cipher.Type != Core.Enums.CipherType.Login || Cipher.Login.Totp == null) + if (Cipher == null || Cipher.Type != Core.Enums.CipherType.Login || Cipher.Login.Totp == null) { _totpInterval = null; return; } _totpCode = await _totpService.GetCodeAsync(Cipher.Login.Totp); - if(_totpCode != null) + if (_totpCode != null) { - if(_totpCode.Length > 4) + if (_totpCode.Length > 4) { var half = (int)Math.Floor(_totpCode.Length / 2M); TotpCodeFormatted = string.Format("{0} {1}", _totpCode.Substring(0, half), @@ -344,7 +344,7 @@ namespace Bit.App.Pages var totpSec = intervalSeconds - mod; TotpSec = totpSec.ToString(); TotpLow = totpSec < 7; - if(mod == 0) + if (mod == 0) { await TotpUpdateCodeAsync(); } @@ -352,15 +352,15 @@ namespace Bit.App.Pages private async void CheckPasswordAsync() { - if(!(Page as BaseContentPage).DoOnce()) + if (!(Page as BaseContentPage).DoOnce()) { return; } - if(string.IsNullOrWhiteSpace(Cipher.Login?.Password)) + if (string.IsNullOrWhiteSpace(Cipher.Login?.Password)) { return; } - if(Xamarin.Essentials.Connectivity.NetworkAccess == Xamarin.Essentials.NetworkAccess.None) + if (Xamarin.Essentials.Connectivity.NetworkAccess == Xamarin.Essentials.NetworkAccess.None) { await _platformUtilsService.ShowDialogAsync(AppResources.InternetConnectionRequiredMessage, AppResources.InternetConnectionRequiredTitle); @@ -369,7 +369,7 @@ namespace Bit.App.Pages await _deviceActionService.ShowLoadingAsync(AppResources.CheckingPassword); var matches = await _auditService.PasswordLeakedAsync(Cipher.Login.Password); await _deviceActionService.HideLoadingAsync(); - if(matches > 0) + if (matches > 0) { await _platformUtilsService.ShowDialogAsync(string.Format(AppResources.PasswordExposed, matches.ToString("N0"))); @@ -382,36 +382,36 @@ namespace Bit.App.Pages private async void DownloadAttachmentAsync(AttachmentView attachment) { - if(!(Page as BaseContentPage).DoOnce()) + if (!(Page as BaseContentPage).DoOnce()) { return; } - if(Xamarin.Essentials.Connectivity.NetworkAccess == Xamarin.Essentials.NetworkAccess.None) + if (Xamarin.Essentials.Connectivity.NetworkAccess == Xamarin.Essentials.NetworkAccess.None) { await _platformUtilsService.ShowDialogAsync(AppResources.InternetConnectionRequiredMessage, AppResources.InternetConnectionRequiredTitle); return; } - if(Cipher.OrganizationId == null && !CanAccessPremium) + if (Cipher.OrganizationId == null && !CanAccessPremium) { await _platformUtilsService.ShowDialogAsync(AppResources.PremiumRequired); return; } - if(attachment.FileSize >= 10485760) // 10 MB + if (attachment.FileSize >= 10485760) // 10 MB { var confirmed = await _platformUtilsService.ShowDialogAsync( string.Format(AppResources.AttachmentLargeWarning, attachment.SizeName), null, AppResources.Yes, AppResources.No); - if(!confirmed) + if (!confirmed) { return; } } var canOpenFile = true; - if(!_deviceActionService.CanOpenFile(attachment.FileName)) + if (!_deviceActionService.CanOpenFile(attachment.FileName)) { - if(Device.RuntimePlatform == Device.iOS) + if (Device.RuntimePlatform == Device.iOS) { // iOS is currently hardcoded to always return CanOpenFile == true, but should it ever return false // for any reason we want to be sure to catch it here. @@ -427,15 +427,15 @@ namespace Bit.App.Pages { var data = await _cipherService.DownloadAndDecryptAttachmentAsync(attachment, Cipher.OrganizationId); await _deviceActionService.HideLoadingAsync(); - if(data == null) + if (data == null) { await _platformUtilsService.ShowDialogAsync(AppResources.UnableToDownloadFile); return; } - if(Device.RuntimePlatform == Device.Android) + if (Device.RuntimePlatform == Device.Android) { - if(canOpenFile) + if (canOpenFile) { // We can open this attachment directly, so give the user the option to open or save PromptOpenOrSave(data, attachment); @@ -461,11 +461,11 @@ namespace Bit.App.Pages { var selection = await Page.DisplayActionSheet(attachment.FileName, AppResources.Cancel, null, AppResources.Open, AppResources.Save); - if(selection == AppResources.Open) + if (selection == AppResources.Open) { OpenAttachment(data, attachment); } - else if(selection == AppResources.Save) + else if (selection == AppResources.Save) { SaveAttachment(data, attachment); } @@ -473,7 +473,7 @@ namespace Bit.App.Pages public async void OpenAttachment(byte[] data, AttachmentView attachment) { - if(!_deviceActionService.OpenFile(data, attachment.Id, attachment.FileName)) + if (!_deviceActionService.OpenFile(data, attachment.Id, attachment.FileName)) { await _platformUtilsService.ShowDialogAsync(AppResources.UnableToOpenFile); return; @@ -484,7 +484,7 @@ namespace Bit.App.Pages { _attachmentData = data; _attachmentFilename = attachment.FileName; - if(!_deviceActionService.SaveFile(_attachmentData, null, _attachmentFilename, null)) + if (!_deviceActionService.SaveFile(_attachmentData, null, _attachmentFilename, null)) { ClearAttachmentData(); await _platformUtilsService.ShowDialogAsync(AppResources.UnableToSaveAttachment); @@ -493,7 +493,7 @@ namespace Bit.App.Pages public async void SaveFileSelected(string contentUri, string filename) { - if(_deviceActionService.SaveFile(_attachmentData, null, filename ?? _attachmentFilename, contentUri)) + if (_deviceActionService.SaveFile(_attachmentData, null, filename ?? _attachmentFilename, contentUri)) { ClearAttachmentData(); _platformUtilsService.ShowToast("success", null, AppResources.SaveAttachmentSuccess); @@ -513,56 +513,56 @@ namespace Bit.App.Pages private async void CopyAsync(string id, string text = null) { string name = null; - if(id == "LoginUsername") + if (id == "LoginUsername") { text = Cipher.Login.Username; name = AppResources.Username; } - else if(id == "LoginPassword") + else if (id == "LoginPassword") { text = Cipher.Login.Password; name = AppResources.Password; } - else if(id == "LoginTotp") + else if (id == "LoginTotp") { text = _totpCode; name = AppResources.VerificationCodeTotp; } - else if(id == "LoginUri") + else if (id == "LoginUri") { name = AppResources.URI; } - else if(id == "FieldValue" || id == "H_FieldValue") + else if (id == "FieldValue" || id == "H_FieldValue") { name = AppResources.Value; } - else if(id == "CardNumber") + else if (id == "CardNumber") { text = Cipher.Card.Number; name = AppResources.Number; } - else if(id == "CardCode") + else if (id == "CardCode") { text = Cipher.Card.Code; name = AppResources.SecurityCode; } - if(text != null) + if (text != null) { await _platformUtilsService.CopyToClipboardAsync(text); - if(!string.IsNullOrWhiteSpace(name)) + if (!string.IsNullOrWhiteSpace(name)) { _platformUtilsService.ShowToast("info", null, string.Format(AppResources.ValueHasBeenCopied, name)); } - if(id == "LoginPassword") + if (id == "LoginPassword") { await _eventService.CollectAsync(Core.Enums.EventType.Cipher_ClientCopiedPassword, CipherId); } - else if(id == "CardCode") + else if (id == "CardCode") { await _eventService.CollectAsync(Core.Enums.EventType.Cipher_ClientCopiedCardCode, CipherId); } - else if(id == "H_FieldValue") + else if (id == "H_FieldValue") { await _eventService.CollectAsync(Core.Enums.EventType.Cipher_ClientCopiedHiddenField, CipherId); } @@ -581,7 +581,7 @@ namespace Bit.App.Pages private void LaunchUri(LoginUriView uri) { - if(uri.CanLaunch && (Page as BaseContentPage).DoOnce()) + if (uri.CanLaunch && (Page as BaseContentPage).DoOnce()) { _platformUtilsService.LaunchUri(uri.LaunchUri); } @@ -638,7 +638,7 @@ namespace Bit.App.Pages public void ToggleHiddenValue() { ShowHiddenValue = !ShowHiddenValue; - if(ShowHiddenValue) + if (ShowHiddenValue) { var eventService = ServiceContainer.Resolve("eventService"); var task = eventService.CollectAsync( diff --git a/src/App/Services/MobileI18nService.cs b/src/App/Services/MobileI18nService.cs index cf3e8fc1b..f61d3dd57 100644 --- a/src/App/Services/MobileI18nService.cs +++ b/src/App/Services/MobileI18nService.cs @@ -31,7 +31,7 @@ namespace Bit.App.Services { get { - if(_stringComparer == null) + if (_stringComparer == null) { _stringComparer = StringComparer.Create(Culture, false); } @@ -42,7 +42,7 @@ namespace Bit.App.Services { get { - if(_localeNames == null) + if (_localeNames == null) { _localeNames = new Dictionary { @@ -92,12 +92,12 @@ namespace Bit.App.Services public void Init(CultureInfo culture = null) { - if(_inited) + if (_inited) { throw new Exception("I18n already inited."); } _inited = true; - if(culture != null) + if (culture != null) { Culture = culture; } @@ -113,28 +113,28 @@ namespace Bit.App.Services public string Translate(string id, string p1 = null, string p2 = null, string p3 = null) { - if(string.IsNullOrWhiteSpace(id)) + if (string.IsNullOrWhiteSpace(id)) { return string.Empty; } var result = _resourceManager.Value.GetString(id, Culture); - if(result == null) + if (result == null) { result = _resourceManager.Value.GetString(id, _defaultCulture); - if(result == null) + if (result == null) { result = $"{{{id}}}"; } } - if(p1 == null && p2 == null && p3 == null) + if (p1 == null && p2 == null && p3 == null) { return result; } - else if(p2 == null && p3 == null) + else if (p2 == null && p3 == null) { return string.Format(result, p1); } - else if(p3 == null) + else if (p3 == null) { return string.Format(result, p1, p2); } diff --git a/src/App/Services/MobilePlatformUtilsService.cs b/src/App/Services/MobilePlatformUtilsService.cs index ab55677d5..0b1206263 100644 --- a/src/App/Services/MobilePlatformUtilsService.cs +++ b/src/App/Services/MobilePlatformUtilsService.cs @@ -40,12 +40,12 @@ namespace Bit.App.Services { _broadcasterService.Subscribe(nameof(MobilePlatformUtilsService), (message) => { - if(message.Command == "showDialogResolve") + if (message.Command == "showDialogResolve") { var details = message.Data as Tuple; var dialogId = details.Item1; var confirmed = details.Item2; - if(_showDialogResolves.ContainsKey(dialogId)) + if (_showDialogResolves.ContainsKey(dialogId)) { var resolveObj = _showDialogResolves[dialogId].Item1; resolveObj.TrySetResult(confirmed); @@ -53,15 +53,15 @@ namespace Bit.App.Services // Clean up old tasks var deleteIds = new HashSet(); - foreach(var item in _showDialogResolves) + foreach (var item in _showDialogResolves) { var age = DateTime.UtcNow - item.Value.Item2; - if(age.TotalMilliseconds > DialogPromiseExpiration) + if (age.TotalMilliseconds > DialogPromiseExpiration) { deleteIds.Add(item.Key); } } - foreach(var id in deleteIds) + foreach (var id in deleteIds) { _showDialogResolves.Remove(id); } @@ -91,23 +91,23 @@ namespace Bit.App.Services public void LaunchUri(string uri, Dictionary options = null) { - if((uri.StartsWith("http://") || uri.StartsWith("https://")) && + if ((uri.StartsWith("http://") || uri.StartsWith("https://")) && Uri.TryCreate(uri, UriKind.Absolute, out var parsedUri)) { try { Browser.OpenAsync(uri, BrowserLaunchMode.External); } - catch(FeatureNotSupportedException) { } + catch (FeatureNotSupportedException) { } } else { var launched = false; - if(GetDevice() == Core.Enums.DeviceType.Android && uri.StartsWith("androidapp://")) + if (GetDevice() == Core.Enums.DeviceType.Android && uri.StartsWith("androidapp://")) { launched = _deviceActionService.LaunchApp(uri); } - if(!launched && (options?.ContainsKey("page") ?? false)) + if (!launched && (options?.ContainsKey("page") ?? false)) { (options["page"] as Page).DisplayAlert(null, "", ""); // TODO } @@ -141,7 +141,7 @@ namespace Bit.App.Services public void ShowToast(string type, string title, string[] text, Dictionary options = null) { - if(text.Length > 0) + if (text.Length > 0) { var longDuration = options != null && options.ContainsKey("longDuration") ? (bool)options["longDuration"] : false; @@ -153,7 +153,7 @@ namespace Bit.App.Services string cancelText = null, string type = null) { var dialogId = 0; - lock(_random) + lock (_random) { dialogId = _random.Next(0, int.MaxValue); } @@ -186,7 +186,7 @@ namespace Bit.App.Services var clearMs = options != null && options.ContainsKey("clearMs") ? (int?)options["clearMs"] : null; var clearing = options != null && options.ContainsKey("clearing") ? (bool)options["clearing"] : false; await Clipboard.SetTextAsync(text); - if(!clearing) + if (!clearing) { _messagingService.Send("copiedToClipboard", new Tuple(text, clearMs, clearing)); } @@ -205,7 +205,7 @@ namespace Bit.App.Services public async Task AuthenticateBiometricAsync(string text = null, string fallbackText = null, Action fallback = null) { - if(_deviceActionService.UseNativeBiometric()) + if (_deviceActionService.UseNativeBiometric()) { return await _deviceActionService.AuthenticateBiometricAsync(text); } @@ -213,7 +213,7 @@ namespace Bit.App.Services { try { - if(text == null) + if (text == null) { var supportsFace = await _deviceActionService.SupportsFaceBiometricAsync(); text = supportsFace ? AppResources.FaceIDDirection : AppResources.FingerprintDirection; @@ -224,11 +224,11 @@ namespace Bit.App.Services FallbackTitle = fallbackText }; var result = await CrossFingerprint.Current.AuthenticateAsync(fingerprintRequest); - if(result.Authenticated) + if (result.Authenticated) { return true; } - else if(result.Status == FingerprintAuthenticationResultStatus.FallbackRequested) + else if (result.Status == FingerprintAuthenticationResultStatus.FallbackRequested) { fallback?.Invoke(); } diff --git a/src/App/Services/MobileStorageService.cs b/src/App/Services/MobileStorageService.cs index 5ebe09e1d..f5b2914a8 100644 --- a/src/App/Services/MobileStorageService.cs +++ b/src/App/Services/MobileStorageService.cs @@ -49,19 +49,19 @@ namespace Bit.App.Services public async Task GetAsync(string key) { - if(_preferenceStorageKeys.Contains(key)) + if (_preferenceStorageKeys.Contains(key)) { var prefValue = await _preferencesStorageService.GetAsync(key); - if(prefValue != null || !_migrateToPreferences.Contains(key) || + if (prefValue != null || !_migrateToPreferences.Contains(key) || _haveMigratedToPreferences.Contains(key)) { return prefValue; } } var liteDbValue = await _liteDbStorageService.GetAsync(key); - if(_migrateToPreferences.Contains(key)) + if (_migrateToPreferences.Contains(key)) { - if(liteDbValue != null) + if (liteDbValue != null) { await _preferencesStorageService.SaveAsync(key, liteDbValue); await _liteDbStorageService.RemoveAsync(key); @@ -73,7 +73,7 @@ namespace Bit.App.Services public Task SaveAsync(string key, T obj) { - if(_preferenceStorageKeys.Contains(key)) + if (_preferenceStorageKeys.Contains(key)) { return _preferencesStorageService.SaveAsync(key, obj); } @@ -82,7 +82,7 @@ namespace Bit.App.Services public Task RemoveAsync(string key) { - if(_preferenceStorageKeys.Contains(key)) + if (_preferenceStorageKeys.Contains(key)) { return _preferencesStorageService.RemoveAsync(key); } diff --git a/src/App/Services/PreferencesStorageService.cs b/src/App/Services/PreferencesStorageService.cs index 758325977..ae0dc6609 100644 --- a/src/App/Services/PreferencesStorageService.cs +++ b/src/App/Services/PreferencesStorageService.cs @@ -25,38 +25,38 @@ namespace Bit.App.Services public Task GetAsync(string key) { var formattedKey = string.Format(KeyFormat, key); - if(!Xamarin.Essentials.Preferences.ContainsKey(formattedKey, _sharedName)) + if (!Xamarin.Essentials.Preferences.ContainsKey(formattedKey, _sharedName)) { return Task.FromResult(default(T)); } var objType = typeof(T); - if(objType == typeof(string)) + if (objType == typeof(string)) { var val = Xamarin.Essentials.Preferences.Get(formattedKey, default(string), _sharedName); return Task.FromResult((T)(object)val); } - else if(objType == typeof(bool) || objType == typeof(bool?)) + else if (objType == typeof(bool) || objType == typeof(bool?)) { var val = Xamarin.Essentials.Preferences.Get(formattedKey, default(bool), _sharedName); return Task.FromResult(ChangeType(val)); } - else if(objType == typeof(int) || objType == typeof(int?)) + else if (objType == typeof(int) || objType == typeof(int?)) { var val = Xamarin.Essentials.Preferences.Get(formattedKey, default(int), _sharedName); return Task.FromResult(ChangeType(val)); } - else if(objType == typeof(long) || objType == typeof(long?)) + else if (objType == typeof(long) || objType == typeof(long?)) { var val = Xamarin.Essentials.Preferences.Get(formattedKey, default(long), _sharedName); return Task.FromResult(ChangeType(val)); } - else if(objType == typeof(double) || objType == typeof(double?)) + else if (objType == typeof(double) || objType == typeof(double?)) { var val = Xamarin.Essentials.Preferences.Get(formattedKey, default(double), _sharedName); return Task.FromResult(ChangeType(val)); } - else if(objType == typeof(DateTime) || objType == typeof(DateTime?)) + else if (objType == typeof(DateTime) || objType == typeof(DateTime?)) { var val = Xamarin.Essentials.Preferences.Get(formattedKey, default(DateTime), _sharedName); return Task.FromResult(ChangeType(val)); @@ -70,34 +70,34 @@ namespace Bit.App.Services public Task SaveAsync(string key, T obj) { - if(obj == null) + if (obj == null) { return RemoveAsync(key); } var formattedKey = string.Format(KeyFormat, key); var objType = typeof(T); - if(objType == typeof(string)) + if (objType == typeof(string)) { Xamarin.Essentials.Preferences.Set(formattedKey, obj as string, _sharedName); } - else if(objType == typeof(bool) || objType == typeof(bool?)) + else if (objType == typeof(bool) || objType == typeof(bool?)) { Xamarin.Essentials.Preferences.Set(formattedKey, (obj as bool?).Value, _sharedName); } - else if(objType == typeof(int) || objType == typeof(int?)) + else if (objType == typeof(int) || objType == typeof(int?)) { Xamarin.Essentials.Preferences.Set(formattedKey, (obj as int?).Value, _sharedName); } - else if(objType == typeof(long) || objType == typeof(long?)) + else if (objType == typeof(long) || objType == typeof(long?)) { Xamarin.Essentials.Preferences.Set(formattedKey, (obj as long?).Value, _sharedName); } - else if(objType == typeof(double) || objType == typeof(double?)) + else if (objType == typeof(double) || objType == typeof(double?)) { Xamarin.Essentials.Preferences.Set(formattedKey, (obj as double?).Value, _sharedName); } - else if(objType == typeof(DateTime) || objType == typeof(DateTime?)) + else if (objType == typeof(DateTime) || objType == typeof(DateTime?)) { Xamarin.Essentials.Preferences.Set(formattedKey, (obj as DateTime?).Value, _sharedName); } @@ -112,7 +112,7 @@ namespace Bit.App.Services public Task RemoveAsync(string key) { var formattedKey = string.Format(KeyFormat, key); - if(Xamarin.Essentials.Preferences.ContainsKey(formattedKey, _sharedName)) + if (Xamarin.Essentials.Preferences.ContainsKey(formattedKey, _sharedName)) { Xamarin.Essentials.Preferences.Remove(formattedKey, _sharedName); } @@ -122,9 +122,9 @@ namespace Bit.App.Services private static T ChangeType(object value) { var t = typeof(T); - if(t.IsGenericType && t.GetGenericTypeDefinition().Equals(typeof(Nullable<>))) + if (t.IsGenericType && t.GetGenericTypeDefinition().Equals(typeof(Nullable<>))) { - if(value == null) + if (value == null) { return default(T); } diff --git a/src/App/Services/PushNotificationListenerService.cs b/src/App/Services/PushNotificationListenerService.cs index c06abc84e..dd6aa73c1 100644 --- a/src/App/Services/PushNotificationListenerService.cs +++ b/src/App/Services/PushNotificationListenerService.cs @@ -29,7 +29,7 @@ namespace Bit.App.Services public async Task OnMessageAsync(JObject value, string deviceType) { Resolve(); - if(value == null) + if (value == null) { return; } @@ -38,13 +38,13 @@ namespace Bit.App.Services Debug.WriteLine("Message Arrived: {0}", JsonConvert.SerializeObject(value)); NotificationResponse notification = null; - if(deviceType == Device.Android) + if (deviceType == Device.Android) { notification = value.ToObject(); } else { - if(!value.TryGetValue("data", StringComparison.OrdinalIgnoreCase, out JToken dataToken) || + if (!value.TryGetValue("data", StringComparison.OrdinalIgnoreCase, out JToken dataToken) || dataToken == null) { return; @@ -53,20 +53,20 @@ namespace Bit.App.Services } var appId = await _appIdService.GetAppIdAsync(); - if(notification?.Payload == null || notification.ContextId == appId) + if (notification?.Payload == null || notification.ContextId == appId) { return; } var myUserId = await _userService.GetUserIdAsync(); var isAuthenticated = await _userService.IsAuthenticatedAsync(); - switch(notification.Type) + switch (notification.Type) { case NotificationType.SyncCipherUpdate: case NotificationType.SyncCipherCreate: var cipherCreateUpdateMessage = JsonConvert.DeserializeObject( notification.Payload); - if(isAuthenticated && cipherCreateUpdateMessage.UserId == myUserId) + if (isAuthenticated && cipherCreateUpdateMessage.UserId == myUserId) { await _syncService.SyncUpsertCipherAsync(cipherCreateUpdateMessage, notification.Type == NotificationType.SyncCipherUpdate); @@ -76,7 +76,7 @@ namespace Bit.App.Services case NotificationType.SyncFolderCreate: var folderCreateUpdateMessage = JsonConvert.DeserializeObject( notification.Payload); - if(isAuthenticated && folderCreateUpdateMessage.UserId == myUserId) + if (isAuthenticated && folderCreateUpdateMessage.UserId == myUserId) { await _syncService.SyncUpsertFolderAsync(folderCreateUpdateMessage, notification.Type == NotificationType.SyncFolderUpdate); @@ -86,7 +86,7 @@ namespace Bit.App.Services case NotificationType.SyncCipherDelete: var loginDeleteMessage = JsonConvert.DeserializeObject( notification.Payload); - if(isAuthenticated && loginDeleteMessage.UserId == myUserId) + if (isAuthenticated && loginDeleteMessage.UserId == myUserId) { await _syncService.SyncDeleteCipherAsync(loginDeleteMessage); } @@ -94,7 +94,7 @@ namespace Bit.App.Services case NotificationType.SyncFolderDelete: var folderDeleteMessage = JsonConvert.DeserializeObject( notification.Payload); - if(isAuthenticated && folderDeleteMessage.UserId == myUserId) + if (isAuthenticated && folderDeleteMessage.UserId == myUserId) { await _syncService.SyncDeleteFolderAsync(folderDeleteMessage); } @@ -102,20 +102,20 @@ namespace Bit.App.Services case NotificationType.SyncCiphers: case NotificationType.SyncVault: case NotificationType.SyncSettings: - if(isAuthenticated) + if (isAuthenticated) { await _syncService.FullSyncAsync(false); } break; case NotificationType.SyncOrgKeys: - if(isAuthenticated) + if (isAuthenticated) { await _apiService.RefreshIdentityTokenAsync(); await _syncService.FullSyncAsync(true); } break; case NotificationType.LogOut: - if(isAuthenticated) + if (isAuthenticated) { _messagingService.Send("logout"); } @@ -130,7 +130,7 @@ namespace Bit.App.Services Resolve(); Debug.WriteLine(string.Format("Push Notification - Device Registered - Token : {0}", token)); var isAuthenticated = await _userService.IsAuthenticatedAsync(); - if(!isAuthenticated) + if (!isAuthenticated) { return; } @@ -142,12 +142,12 @@ namespace Bit.App.Services new Core.Models.Request.DeviceTokenRequest { PushToken = token }); Debug.WriteLine("Registered device with server."); await _storageService.SaveAsync(Constants.PushLastRegistrationDateKey, DateTime.UtcNow); - if(deviceType == Device.Android) + if (deviceType == Device.Android) { await _storageService.SaveAsync(Constants.PushCurrentTokenKey, token); } } - catch(ApiException) + catch (ApiException) { Debug.WriteLine("Failed to register device."); } @@ -170,7 +170,7 @@ namespace Bit.App.Services private void Resolve() { - if(_resolved) + if (_resolved) { return; } diff --git a/src/App/Services/SecureStorageService.cs b/src/App/Services/SecureStorageService.cs index 09434e021..5655cc17e 100644 --- a/src/App/Services/SecureStorageService.cs +++ b/src/App/Services/SecureStorageService.cs @@ -17,7 +17,7 @@ namespace Bit.App.Services { var formattedKey = string.Format(_keyFormat, key); var val = await Xamarin.Essentials.SecureStorage.GetAsync(formattedKey); - if(typeof(T) == typeof(string)) + if (typeof(T) == typeof(string)) { return (T)(object)val; } @@ -29,13 +29,13 @@ namespace Bit.App.Services public async Task SaveAsync(string key, T obj) { - if(obj == null) + if (obj == null) { await RemoveAsync(key); return; } var formattedKey = string.Format(_keyFormat, key); - if(typeof(T) == typeof(string)) + if (typeof(T) == typeof(string)) { await Xamarin.Essentials.SecureStorage.SetAsync(formattedKey, obj as string); } diff --git a/src/App/Utilities/AppHelpers.cs b/src/App/Utilities/AppHelpers.cs index d069f484a..9ec27fcb8 100644 --- a/src/App/Utilities/AppHelpers.cs +++ b/src/App/Utilities/AppHelpers.cs @@ -19,99 +19,99 @@ namespace Bit.App.Utilities var platformUtilsService = ServiceContainer.Resolve("platformUtilsService"); var eventService = ServiceContainer.Resolve("eventService"); var options = new List { AppResources.View, AppResources.Edit }; - if(cipher.Type == Core.Enums.CipherType.Login) + if (cipher.Type == Core.Enums.CipherType.Login) { - if(!string.IsNullOrWhiteSpace(cipher.Login.Username)) + if (!string.IsNullOrWhiteSpace(cipher.Login.Username)) { options.Add(AppResources.CopyUsername); } - if(!string.IsNullOrWhiteSpace(cipher.Login.Password)) + if (!string.IsNullOrWhiteSpace(cipher.Login.Password)) { options.Add(AppResources.CopyPassword); } - if(!string.IsNullOrWhiteSpace(cipher.Login.Totp)) + if (!string.IsNullOrWhiteSpace(cipher.Login.Totp)) { var userService = ServiceContainer.Resolve("userService"); var canAccessPremium = await userService.CanAccessPremiumAsync(); - if(canAccessPremium || cipher.OrganizationUseTotp) + if (canAccessPremium || cipher.OrganizationUseTotp) { options.Add(AppResources.CopyTotp); } } - if(cipher.Login.CanLaunch) + if (cipher.Login.CanLaunch) { options.Add(AppResources.Launch); } } - else if(cipher.Type == Core.Enums.CipherType.Card) + else if (cipher.Type == Core.Enums.CipherType.Card) { - if(!string.IsNullOrWhiteSpace(cipher.Card.Number)) + if (!string.IsNullOrWhiteSpace(cipher.Card.Number)) { options.Add(AppResources.CopyNumber); } - if(!string.IsNullOrWhiteSpace(cipher.Card.Code)) + if (!string.IsNullOrWhiteSpace(cipher.Card.Code)) { options.Add(AppResources.CopySecurityCode); } } - else if(cipher.Type == Core.Enums.CipherType.SecureNote) + else if (cipher.Type == Core.Enums.CipherType.SecureNote) { - if(!string.IsNullOrWhiteSpace(cipher.Notes)) + if (!string.IsNullOrWhiteSpace(cipher.Notes)) { options.Add(AppResources.CopyNotes); } } var selection = await page.DisplayActionSheet(cipher.Name, AppResources.Cancel, null, options.ToArray()); - if(selection == AppResources.View) + if (selection == AppResources.View) { await page.Navigation.PushModalAsync(new NavigationPage(new ViewPage(cipher.Id))); } - else if(selection == AppResources.Edit) + else if (selection == AppResources.Edit) { await page.Navigation.PushModalAsync(new NavigationPage(new AddEditPage(cipher.Id))); } - else if(selection == AppResources.CopyUsername) + else if (selection == AppResources.CopyUsername) { await platformUtilsService.CopyToClipboardAsync(cipher.Login.Username); platformUtilsService.ShowToast("info", null, string.Format(AppResources.ValueHasBeenCopied, AppResources.Username)); } - else if(selection == AppResources.CopyPassword) + else if (selection == AppResources.CopyPassword) { await platformUtilsService.CopyToClipboardAsync(cipher.Login.Password); platformUtilsService.ShowToast("info", null, string.Format(AppResources.ValueHasBeenCopied, AppResources.Password)); var task = eventService.CollectAsync(Core.Enums.EventType.Cipher_ClientCopiedPassword, cipher.Id); } - else if(selection == AppResources.CopyTotp) + else if (selection == AppResources.CopyTotp) { var totpService = ServiceContainer.Resolve("totpService"); var totp = await totpService.GetCodeAsync(cipher.Login.Totp); - if(!string.IsNullOrWhiteSpace(totp)) + if (!string.IsNullOrWhiteSpace(totp)) { await platformUtilsService.CopyToClipboardAsync(totp); platformUtilsService.ShowToast("info", null, string.Format(AppResources.ValueHasBeenCopied, AppResources.VerificationCodeTotp)); } } - else if(selection == AppResources.Launch) + else if (selection == AppResources.Launch) { platformUtilsService.LaunchUri(cipher.Login.LaunchUri); } - else if(selection == AppResources.CopyNumber) + else if (selection == AppResources.CopyNumber) { await platformUtilsService.CopyToClipboardAsync(cipher.Card.Number); platformUtilsService.ShowToast("info", null, string.Format(AppResources.ValueHasBeenCopied, AppResources.Number)); } - else if(selection == AppResources.CopySecurityCode) + else if (selection == AppResources.CopySecurityCode) { await platformUtilsService.CopyToClipboardAsync(cipher.Card.Code); platformUtilsService.ShowToast("info", null, string.Format(AppResources.ValueHasBeenCopied, AppResources.SecurityCode)); var task = eventService.CollectAsync(Core.Enums.EventType.Cipher_ClientCopiedCardCode, cipher.Id); } - else if(selection == AppResources.CopyNotes) + else if (selection == AppResources.CopyNotes) { await platformUtilsService.CopyToClipboardAsync(cipher.Notes); platformUtilsService.ShowToast("info", null, @@ -125,21 +125,21 @@ namespace Bit.App.Utilities { var currentBuild = deviceActionService.GetBuildNumber(); var lastBuild = await storageService.GetAsync(Constants.LastBuildKey); - if(lastBuild == null) + if (lastBuild == null) { // Installed var currentLock = await storageService.GetAsync(Constants.LockOptionKey); - if(currentLock == null) + if (currentLock == null) { await storageService.SaveAsync(Constants.LockOptionKey, 15); } } - else if(lastBuild != currentBuild) + else if (lastBuild != currentBuild) { // Updated var tasks = Task.Run(() => syncService.FullSyncAsync(true)); } - if(lastBuild != currentBuild) + if (lastBuild != currentBuild) { await storageService.SaveAsync(Constants.LastBuildKey, currentBuild); return true; @@ -149,18 +149,18 @@ namespace Bit.App.Utilities public static async Task SetPreconfiguredSettingsAsync(IDictionary configSettings) { - if(configSettings?.Any() ?? true) + if (configSettings?.Any() ?? true) { return; } - foreach(var setting in configSettings) + foreach (var setting in configSettings) { - switch(setting.Key) + switch (setting.Key) { case "baseEnvironmentUrl": var environmentService = ServiceContainer.Resolve("environmentService"); var settingValue = string.IsNullOrWhiteSpace(setting.Value) ? null : setting.Value; - if(environmentService.BaseUrl != settingValue) + if (environmentService.BaseUrl != settingValue) { await environmentService.SetUrlsAsync(new Core.Models.Data.EnvironmentUrlData { diff --git a/src/App/Utilities/ColoredPasswordConverter.cs b/src/App/Utilities/ColoredPasswordConverter.cs index d87827696..a3833453d 100644 --- a/src/App/Utilities/ColoredPasswordConverter.cs +++ b/src/App/Utilities/ColoredPasswordConverter.cs @@ -8,11 +8,11 @@ namespace Bit.App.Utilities public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { - if(targetType != typeof(string)) + if (targetType != typeof(string)) { throw new InvalidOperationException("The target must be a string."); } - if(value == null) + if (value == null) { return string.Empty; } diff --git a/src/App/Utilities/DateTimeConverter.cs b/src/App/Utilities/DateTimeConverter.cs index 6022caf2d..a73caf4a9 100644 --- a/src/App/Utilities/DateTimeConverter.cs +++ b/src/App/Utilities/DateTimeConverter.cs @@ -8,11 +8,11 @@ namespace Bit.App.Utilities public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { - if(targetType != typeof(string)) + if (targetType != typeof(string)) { throw new InvalidOperationException("The target must be a string."); } - if(value == null) + if (value == null) { return string.Empty; } diff --git a/src/App/Utilities/I18nExtension.cs b/src/App/Utilities/I18nExtension.cs index e3c721980..0cb6ed224 100644 --- a/src/App/Utilities/I18nExtension.cs +++ b/src/App/Utilities/I18nExtension.cs @@ -26,7 +26,7 @@ namespace Bit.App.Utilities { var val = _i18nService.T(Id, P1, P2, P3); /* - if(Header && Device.RuntimePlatform == Device.iOS) + if (Header && Device.RuntimePlatform == Device.iOS) { return val.ToUpper(); } diff --git a/src/App/Utilities/InverseBoolConverter.cs b/src/App/Utilities/InverseBoolConverter.cs index 439bbb7f7..b0ee98993 100644 --- a/src/App/Utilities/InverseBoolConverter.cs +++ b/src/App/Utilities/InverseBoolConverter.cs @@ -8,7 +8,7 @@ namespace Bit.App.Utilities public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { - if(targetType == typeof(bool)) + if (targetType == typeof(bool)) { return !((bool?)value).GetValueOrDefault(); } diff --git a/src/App/Utilities/IsNotNullConverter.cs b/src/App/Utilities/IsNotNullConverter.cs index d692e813c..5888ab362 100644 --- a/src/App/Utilities/IsNotNullConverter.cs +++ b/src/App/Utilities/IsNotNullConverter.cs @@ -8,7 +8,7 @@ namespace Bit.App.Utilities public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { - if(targetType == typeof(bool)) + if (targetType == typeof(bool)) { return value != null; } diff --git a/src/App/Utilities/IsNullConverter.cs b/src/App/Utilities/IsNullConverter.cs index 99ac14d1c..0d6f85964 100644 --- a/src/App/Utilities/IsNullConverter.cs +++ b/src/App/Utilities/IsNullConverter.cs @@ -8,7 +8,7 @@ namespace Bit.App.Utilities public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { - if(targetType == typeof(bool)) + if (targetType == typeof(bool)) { return value == null; } diff --git a/src/App/Utilities/PasswordFormatter.cs b/src/App/Utilities/PasswordFormatter.cs index 6b41ed9f9..5c2d7a5b3 100644 --- a/src/App/Utilities/PasswordFormatter.cs +++ b/src/App/Utilities/PasswordFormatter.cs @@ -24,7 +24,7 @@ namespace Bit.App.Utilities public static string FormatPassword(string password) { - if(password == null) + if (password == null) { return string.Empty; } @@ -38,7 +38,7 @@ namespace Bit.App.Utilities // iOS won't hide the zero-width space char without these div attrs, but Android won't respect // display:inline-block and adds a newline after the password. Hence, only iOS gets the div. - if(Device.RuntimePlatform == Device.iOS) + if (Device.RuntimePlatform == Device.iOS) { result += "
"; } @@ -47,15 +47,15 @@ namespace Bit.App.Utilities // state. var currentType = CharType.None; - foreach(var c in password) + foreach (var c in password) { // First, identify what the current char is. CharType charType; - if(char.IsLetter(c)) + if (char.IsLetter(c)) { charType = CharType.Normal; } - else if(char.IsDigit(c)) + else if (char.IsDigit(c)) { charType = CharType.Number; } @@ -65,7 +65,7 @@ namespace Bit.App.Utilities } // If the char type changed, build a new span to append the text to. - if(charType != currentType) + if (charType != currentType) { // Close off previous span. if (currentType != CharType.None) @@ -77,7 +77,7 @@ namespace Bit.App.Utilities // Switch the color if it is not a normal text. Otherwise leave the // default value. - switch(currentType) + switch (currentType) { // Apply color style to span. case CharType.Normal: @@ -92,7 +92,7 @@ namespace Bit.App.Utilities } } - if(currentType == CharType.Special) + if (currentType == CharType.Special) { result += HttpUtility.HtmlEncode(c); } @@ -112,7 +112,7 @@ namespace Bit.App.Utilities } // Close off iOS div - if(Device.RuntimePlatform == Device.iOS) + if (Device.RuntimePlatform == Device.iOS) { result += "
"; } diff --git a/src/App/Utilities/StringHasValueConverter.cs b/src/App/Utilities/StringHasValueConverter.cs index 0af574ebc..4410c9143 100644 --- a/src/App/Utilities/StringHasValueConverter.cs +++ b/src/App/Utilities/StringHasValueConverter.cs @@ -8,13 +8,13 @@ namespace Bit.App.Utilities public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { - if(targetType == typeof(bool)) + if (targetType == typeof(bool)) { - if(value == null) + if (value == null) { return false; } - if(value.GetType() == typeof(string)) + if (value.GetType() == typeof(string)) { return !string.IsNullOrWhiteSpace((string)value); } diff --git a/src/App/Utilities/ThemeManager.cs b/src/App/Utilities/ThemeManager.cs index 7164444ba..2017ff904 100644 --- a/src/App/Utilities/ThemeManager.cs +++ b/src/App/Utilities/ThemeManager.cs @@ -21,22 +21,22 @@ namespace Bit.App.Utilities Application.Current.Resources.MergedDictionaries.Add(new Variables()); // Themed variables - if(name == "dark") + if (name == "dark") { Application.Current.Resources.MergedDictionaries.Add(new Dark()); UsingLightTheme = false; } - else if(name == "black") + else if (name == "black") { Application.Current.Resources.MergedDictionaries.Add(new Black()); UsingLightTheme = false; } - else if(name == "nord") + else if (name == "nord") { Application.Current.Resources.MergedDictionaries.Add(new Nord()); UsingLightTheme = false; } - else if(name == "light") + else if (name == "light") { Application.Current.Resources.MergedDictionaries.Add(new Light()); UsingLightTheme = true; @@ -44,7 +44,7 @@ namespace Bit.App.Utilities else { var deviceActionService = ServiceContainer.Resolve("deviceActionService", true); - if(deviceActionService?.UsingDarkTheme() ?? false) + if (deviceActionService?.UsingDarkTheme() ?? false) { Application.Current.Resources.MergedDictionaries.Add(new Dark()); UsingLightTheme = false; @@ -60,11 +60,11 @@ namespace Bit.App.Utilities Application.Current.Resources.MergedDictionaries.Add(new Base()); // Platform styles - if(Device.RuntimePlatform == Device.Android) + if (Device.RuntimePlatform == Device.Android) { Application.Current.Resources.MergedDictionaries.Add(new Android()); } - else if(Device.RuntimePlatform == Device.iOS) + else if (Device.RuntimePlatform == Device.iOS) { Application.Current.Resources.MergedDictionaries.Add(new iOS()); } diff --git a/src/App/Utilities/UpperCaseConverter.cs b/src/App/Utilities/UpperCaseConverter.cs index 5f2882c31..592f95326 100644 --- a/src/App/Utilities/UpperCaseConverter.cs +++ b/src/App/Utilities/UpperCaseConverter.cs @@ -8,12 +8,12 @@ namespace Bit.App.Utilities { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { - if(targetType != typeof(string)) + if (targetType != typeof(string)) { throw new InvalidOperationException("The target must be a string."); } - if(value == null) + if (value == null) { return string.Empty; } diff --git a/src/Core/Models/Data/CipherData.cs b/src/Core/Models/Data/CipherData.cs index f56d82465..7e231f4fe 100644 --- a/src/Core/Models/Data/CipherData.cs +++ b/src/Core/Models/Data/CipherData.cs @@ -24,7 +24,7 @@ namespace Bit.Core.Models.Data Notes = response.Notes; CollectionIds = collectionIds?.ToList() ?? response.CollectionIds; - switch(Type) + switch (Type) { case Enums.CipherType.Login: Login = new LoginData(response.Login); diff --git a/src/Core/Models/Domain/Attachment.cs b/src/Core/Models/Domain/Attachment.cs index 9b9e3704a..a64fb10c9 100644 --- a/src/Core/Models/Domain/Attachment.cs +++ b/src/Core/Models/Domain/Attachment.cs @@ -40,7 +40,7 @@ namespace Bit.Core.Models.Domain "FileName" }, orgId); - if(Key != null) + if (Key != null) { var cryptoService = ServiceContainer.Resolve("cryptoService"); try diff --git a/src/Core/Models/Domain/Cipher.cs b/src/Core/Models/Domain/Cipher.cs index 3d0e8ca20..efdffd27c 100644 --- a/src/Core/Models/Domain/Cipher.cs +++ b/src/Core/Models/Domain/Cipher.cs @@ -30,7 +30,7 @@ namespace Bit.Core.Models.Domain CollectionIds = obj.CollectionIds != null ? new HashSet(obj.CollectionIds) : null; LocalData = localData; - switch(Type) + switch (Type) { case Enums.CipherType.Login: Login = new Login(obj.Login, alreadyEncrypted); @@ -82,7 +82,7 @@ namespace Bit.Core.Models.Domain "Notes" }, OrganizationId); - switch(Type) + switch (Type) { case Enums.CipherType.Login: model.Login = await Login.DecryptAsync(OrganizationId); @@ -100,7 +100,7 @@ namespace Bit.Core.Models.Domain break; } - if(Attachments?.Any() ?? false) + if (Attachments?.Any() ?? false) { model.Attachments = new List(); var tasks = new List(); @@ -109,13 +109,13 @@ namespace Bit.Core.Models.Domain var decAttachment = await attachment.DecryptAsync(OrganizationId); model.Attachments.Add(decAttachment); } - foreach(var attachment in Attachments) + foreach (var attachment in Attachments) { tasks.Add(decryptAndAddAttachmentAsync(attachment)); } await Task.WhenAll(tasks); } - if(Fields?.Any() ?? false) + if (Fields?.Any() ?? false) { model.Fields = new List(); var tasks = new List(); @@ -124,13 +124,13 @@ namespace Bit.Core.Models.Domain var decField = await field.DecryptAsync(OrganizationId); model.Fields.Add(decField); } - foreach(var field in Fields) + foreach (var field in Fields) { tasks.Add(decryptAndAddFieldAsync(field)); } await Task.WhenAll(tasks); } - if(PasswordHistory?.Any() ?? false) + if (PasswordHistory?.Any() ?? false) { model.PasswordHistory = new List(); var tasks = new List(); @@ -139,7 +139,7 @@ namespace Bit.Core.Models.Domain var decPh = await ph.DecryptAsync(OrganizationId); model.PasswordHistory.Add(decPh); } - foreach(var ph in PasswordHistory) + foreach (var ph in PasswordHistory) { tasks.Add(decryptAndAddHistoryAsync(ph)); } @@ -168,7 +168,7 @@ namespace Bit.Core.Models.Domain "Name", "Notes" }); - switch(c.Type) + switch (c.Type) { case Enums.CipherType.Login: c.Login = Login.ToLoginData(); diff --git a/src/Core/Models/Domain/CipherString.cs b/src/Core/Models/Domain/CipherString.cs index cb6c6e2ed..9a6956b83 100644 --- a/src/Core/Models/Domain/CipherString.cs +++ b/src/Core/Models/Domain/CipherString.cs @@ -12,12 +12,12 @@ namespace Bit.Core.Models.Domain public CipherString(EncryptionType encryptionType, string data, string iv = null, string mac = null) { - if(string.IsNullOrWhiteSpace(data)) + if (string.IsNullOrWhiteSpace(data)) { throw new ArgumentNullException(nameof(data)); } - if(!string.IsNullOrWhiteSpace(iv)) + if (!string.IsNullOrWhiteSpace(iv)) { EncryptedString = string.Format("{0}.{1}|{2}", (byte)encryptionType, iv, data); } @@ -26,7 +26,7 @@ namespace Bit.Core.Models.Domain EncryptedString = string.Format("{0}.{1}", (byte)encryptionType, data); } - if(!string.IsNullOrWhiteSpace(mac)) + if (!string.IsNullOrWhiteSpace(mac)) { EncryptedString = string.Format("{0}|{1}", EncryptedString, mac); } @@ -39,7 +39,7 @@ namespace Bit.Core.Models.Domain public CipherString(string encryptedString) { - if(string.IsNullOrWhiteSpace(encryptedString)) + if (string.IsNullOrWhiteSpace(encryptedString)) { throw new ArgumentException(nameof(encryptedString)); } @@ -48,7 +48,7 @@ namespace Bit.Core.Models.Domain var headerPieces = EncryptedString.Split('.'); string[] encPieces; - if(headerPieces.Length == 2 && Enum.TryParse(headerPieces[0], out EncryptionType encType)) + if (headerPieces.Length == 2 && Enum.TryParse(headerPieces[0], out EncryptionType encType)) { EncryptionType = encType; encPieces = headerPieces[1].Split('|'); @@ -60,11 +60,11 @@ namespace Bit.Core.Models.Domain EncryptionType.AesCbc256_B64; } - switch(EncryptionType) + switch (EncryptionType) { case EncryptionType.AesCbc128_HmacSha256_B64: case EncryptionType.AesCbc256_HmacSha256_B64: - if(encPieces.Length != 3) + if (encPieces.Length != 3) { return; } @@ -73,7 +73,7 @@ namespace Bit.Core.Models.Domain Mac = encPieces[2]; break; case EncryptionType.AesCbc256_B64: - if(encPieces.Length != 2) + if (encPieces.Length != 2) { return; } @@ -82,7 +82,7 @@ namespace Bit.Core.Models.Domain break; case EncryptionType.Rsa2048_OaepSha256_B64: case EncryptionType.Rsa2048_OaepSha1_B64: - if(encPieces.Length != 1) + if (encPieces.Length != 1) { return; } @@ -101,7 +101,7 @@ namespace Bit.Core.Models.Domain public async Task DecryptAsync(string orgId = null) { - if(_decryptedValue != null) + if (_decryptedValue != null) { return _decryptedValue; } diff --git a/src/Core/Models/Domain/Domain.cs b/src/Core/Models/Domain/Domain.cs index fc839f326..5ff7e3f0b 100644 --- a/src/Core/Models/Domain/Domain.cs +++ b/src/Core/Models/Domain/Domain.cs @@ -12,12 +12,12 @@ namespace Bit.Core.Models.Domain { var domainType = domain.GetType(); var dataObjType = dataObj.GetType(); - foreach(var prop in map) + foreach (var prop in map) { var dataObjPropInfo = dataObjType.GetProperty(prop); var dataObjProp = dataObjPropInfo.GetValue(dataObj); var domainPropInfo = domainType.GetProperty(prop); - if(alreadyEncrypted || (notEncList?.Contains(prop) ?? false)) + if (alreadyEncrypted || (notEncList?.Contains(prop) ?? false)) { domainPropInfo.SetValue(domain, dataObjProp, null); } @@ -36,12 +36,12 @@ namespace Bit.Core.Models.Domain { var domainType = domain.GetType(); var dataObjType = dataObj.GetType(); - foreach(var prop in map) + foreach (var prop in map) { var domainPropInfo = domainType.GetProperty(prop); var domainProp = domainPropInfo.GetValue(domain); var dataObjPropInfo = dataObjType.GetProperty(prop); - if(notCipherStringList?.Contains(prop) ?? false) + if (notCipherStringList?.Contains(prop) ?? false) { dataObjPropInfo.SetValue(dataObj, domainProp, null); } @@ -62,7 +62,7 @@ namespace Bit.Core.Models.Domain { var domainPropInfo = domainType.GetProperty(propName); string val = null; - if(domainPropInfo.GetValue(domain) is CipherString domainProp) + if (domainPropInfo.GetValue(domain) is CipherString domainProp) { val = await domainProp.DecryptAsync(orgId); } @@ -71,7 +71,7 @@ namespace Bit.Core.Models.Domain }; var tasks = new List(); - foreach(var prop in map) + foreach (var prop in map) { tasks.Add(decCsAndSetDec(prop)); } diff --git a/src/Core/Models/Domain/Login.cs b/src/Core/Models/Domain/Login.cs index adb2314a4..4ddaec160 100644 --- a/src/Core/Models/Domain/Login.cs +++ b/src/Core/Models/Domain/Login.cs @@ -37,10 +37,10 @@ namespace Bit.Core.Models.Domain "Password", "Totp" }, orgId); - if(Uris != null) + if (Uris != null) { view.Uris = new List(); - foreach(var uri in Uris) + foreach (var uri in Uris) { view.Uris.Add(await uri.DecryptAsync(orgId)); } @@ -58,7 +58,7 @@ namespace Bit.Core.Models.Domain "Password", "Totp" }); - if(Uris?.Any() ?? false) + if (Uris?.Any() ?? false) { l.Uris = Uris.Select(u => u.ToLoginUriData()).ToList(); } diff --git a/src/Core/Models/Domain/Organization.cs b/src/Core/Models/Domain/Organization.cs index cb2857605..96a807888 100644 --- a/src/Core/Models/Domain/Organization.cs +++ b/src/Core/Models/Domain/Organization.cs @@ -48,7 +48,7 @@ namespace Bit.Core.Models.Domain { get { - if(Type == OrganizationUserType.Owner) + if (Type == OrganizationUserType.Owner) { return true; } @@ -60,7 +60,7 @@ namespace Bit.Core.Models.Domain { get { - switch(Type) + switch (Type) { case OrganizationUserType.Owner: case OrganizationUserType.Admin: diff --git a/src/Core/Models/Domain/PasswordGenerationOptions.cs b/src/Core/Models/Domain/PasswordGenerationOptions.cs index 1a4687e1c..9f0717c2b 100644 --- a/src/Core/Models/Domain/PasswordGenerationOptions.cs +++ b/src/Core/Models/Domain/PasswordGenerationOptions.cs @@ -6,7 +6,7 @@ public PasswordGenerationOptions(bool defaultOptions) { - if(defaultOptions) + if (defaultOptions) { Length = 14; Ambiguous = false; diff --git a/src/Core/Models/Domain/SymmetricCryptoKey.cs b/src/Core/Models/Domain/SymmetricCryptoKey.cs index 9f2439b79..820823b26 100644 --- a/src/Core/Models/Domain/SymmetricCryptoKey.cs +++ b/src/Core/Models/Domain/SymmetricCryptoKey.cs @@ -8,18 +8,18 @@ namespace Bit.Core.Models.Domain { public SymmetricCryptoKey(byte[] key, EncryptionType? encType = null) { - if(key == null) + if (key == null) { throw new Exception("Must provide key."); } - if(encType == null) + if (encType == null) { - if(key.Length == 32) + if (key.Length == 32) { encType = EncryptionType.AesCbc256_B64; } - else if(key.Length == 64) + else if (key.Length == 64) { encType = EncryptionType.AesCbc256_HmacSha256_B64; } @@ -32,17 +32,17 @@ namespace Bit.Core.Models.Domain Key = key; EncType = encType.Value; - if(EncType == EncryptionType.AesCbc256_B64 && Key.Length == 32) + if (EncType == EncryptionType.AesCbc256_B64 && Key.Length == 32) { EncKey = Key; MacKey = null; } - else if(EncType == EncryptionType.AesCbc128_HmacSha256_B64 && Key.Length == 32) + else if (EncType == EncryptionType.AesCbc128_HmacSha256_B64 && Key.Length == 32) { EncKey = new ArraySegment(Key, 0, 16).ToArray(); MacKey = new ArraySegment(Key, 16, 16).ToArray(); } - else if(EncType == EncryptionType.AesCbc256_HmacSha256_B64 && Key.Length == 64) + else if (EncType == EncryptionType.AesCbc256_HmacSha256_B64 && Key.Length == 64) { EncKey = new ArraySegment(Key, 0, 32).ToArray(); MacKey = new ArraySegment(Key, 32, 32).ToArray(); @@ -52,15 +52,15 @@ namespace Bit.Core.Models.Domain throw new Exception("Unsupported encType/key length."); } - if(Key != null) + if (Key != null) { KeyB64 = Convert.ToBase64String(Key); } - if(EncKey != null) + if (EncKey != null) { EncKeyB64 = Convert.ToBase64String(EncKey); } - if(MacKey != null) + if (MacKey != null) { MacKeyB64 = Convert.ToBase64String(MacKey); } diff --git a/src/Core/Models/Export/Card.cs b/src/Core/Models/Export/Card.cs index baf73786d..b6938abbf 100644 --- a/src/Core/Models/Export/Card.cs +++ b/src/Core/Models/Export/Card.cs @@ -25,7 +25,7 @@ namespace Bit.Core.Models.Export public static CardView ToView(Card req, CardView view = null) { - if(view == null) + if (view == null) { view = new CardView(); } diff --git a/src/Core/Models/Export/Cipher.cs b/src/Core/Models/Export/Cipher.cs index d82f1d80c..2744f3032 100644 --- a/src/Core/Models/Export/Cipher.cs +++ b/src/Core/Models/Export/Cipher.cs @@ -21,7 +21,7 @@ namespace Bit.Core.Models.Export Fields = obj.Fields?.Select(f => new Field(f)).ToList(); - switch(obj.Type) + switch (obj.Type) { case CipherType.Login: Login = new Login(obj.Login); @@ -57,14 +57,14 @@ namespace Bit.Core.Models.Export public CipherView ToView(Cipher req, CipherView view = null) { - if(view == null) + if (view == null) { view = new CipherView(); } view.Type = req.Type; view.FolderId = req.FolderId; - if(view.OrganizationId == null) + if (view.OrganizationId == null) { view.OrganizationId = req.OrganizationId; } @@ -75,7 +75,7 @@ namespace Bit.Core.Models.Export view.Fields = req.Fields?.Select(f => Field.ToView(f)).ToList(); - switch(req.Type) + switch (req.Type) { case CipherType.Login: view.Login = Login.ToView(req.Login); diff --git a/src/Core/Models/Export/Collection.cs b/src/Core/Models/Export/Collection.cs index d9923548c..f233da185 100644 --- a/src/Core/Models/Export/Collection.cs +++ b/src/Core/Models/Export/Collection.cs @@ -19,14 +19,14 @@ namespace Bit.Core.Models.Export public CollectionView ToView(Collection req, CollectionView view = null) { - if(view == null) + if (view == null) { view = new CollectionView(); } view.Name = req.Name; view.ExternalId = req.ExternalId; - if(view.OrganizationId == null) + if (view.OrganizationId == null) { view.OrganizationId = req.OrganizationId; } diff --git a/src/Core/Models/Export/Field.cs b/src/Core/Models/Export/Field.cs index fa672121c..e2ce4fcc3 100644 --- a/src/Core/Models/Export/Field.cs +++ b/src/Core/Models/Export/Field.cs @@ -20,7 +20,7 @@ namespace Bit.Core.Models.Export public static FieldView ToView(Field req, FieldView view = null) { - if(view == null) + if (view == null) { view = new FieldView(); } diff --git a/src/Core/Models/Export/Folder.cs b/src/Core/Models/Export/Folder.cs index dba2aa802..40f0876d2 100644 --- a/src/Core/Models/Export/Folder.cs +++ b/src/Core/Models/Export/Folder.cs @@ -15,7 +15,7 @@ namespace Bit.Core.Models.Export public FolderView ToView(Folder req, FolderView view = null) { - if(view == null) + if (view == null) { view = new FolderView(); } diff --git a/src/Core/Models/Export/Identity.cs b/src/Core/Models/Export/Identity.cs index fbf74366f..08a78c559 100644 --- a/src/Core/Models/Export/Identity.cs +++ b/src/Core/Models/Export/Identity.cs @@ -49,7 +49,7 @@ namespace Bit.Core.Models.Export public static IdentityView ToView(Identity req, IdentityView view = null) { - if(view == null) + if (view == null) { view = new IdentityView(); } diff --git a/src/Core/Models/Export/Login.cs b/src/Core/Models/Export/Login.cs index 832a69e4c..433ff5511 100644 --- a/src/Core/Models/Export/Login.cs +++ b/src/Core/Models/Export/Login.cs @@ -24,7 +24,7 @@ namespace Bit.Core.Models.Export public static LoginView ToView(Login req, LoginView view = null) { - if(view == null) + if (view == null) { view = new LoginView(); } diff --git a/src/Core/Models/Export/LoginUri.cs b/src/Core/Models/Export/LoginUri.cs index db6cb3447..ef8bffe5f 100644 --- a/src/Core/Models/Export/LoginUri.cs +++ b/src/Core/Models/Export/LoginUri.cs @@ -18,7 +18,7 @@ namespace Bit.Core.Models.Export public static LoginUriView ToView(LoginUri req, LoginUriView view = null) { - if(view == null) + if (view == null) { view = new LoginUriView(); } diff --git a/src/Core/Models/Export/SecureNote.cs b/src/Core/Models/Export/SecureNote.cs index 59b2cc988..69d923804 100644 --- a/src/Core/Models/Export/SecureNote.cs +++ b/src/Core/Models/Export/SecureNote.cs @@ -16,7 +16,7 @@ namespace Bit.Core.Models.Export public SecureNoteView ToView(SecureNote req, SecureNoteView view = null) { - if(view == null) + if (view == null) { view = new SecureNoteView(); } diff --git a/src/Core/Models/Request/CipherRequest.cs b/src/Core/Models/Request/CipherRequest.cs index 49fba9c9a..b0f7cee97 100644 --- a/src/Core/Models/Request/CipherRequest.cs +++ b/src/Core/Models/Request/CipherRequest.cs @@ -17,7 +17,7 @@ namespace Bit.Core.Models.Request Notes = cipher.Notes?.EncryptedString; Favorite = cipher.Favorite; - switch(Type) + switch (Type) { case CipherType.Login: Login = new LoginApi @@ -87,11 +87,11 @@ namespace Bit.Core.Models.Request LastUsedDate = ph.LastUsedDate }).ToList(); - if(cipher.Attachments != null) + if (cipher.Attachments != null) { Attachments = new Dictionary(); Attachments2 = new Dictionary(); - foreach(var attachment in cipher.Attachments) + foreach (var attachment in cipher.Attachments) { var fileName = attachment.FileName?.EncryptedString; Attachments.Add(attachment.Id, fileName); diff --git a/src/Core/Models/Request/TokenRequest.cs b/src/Core/Models/Request/TokenRequest.cs index 072f549cc..2cf4f60dc 100644 --- a/src/Core/Models/Request/TokenRequest.cs +++ b/src/Core/Models/Request/TokenRequest.cs @@ -24,14 +24,14 @@ namespace Bit.Core.Models.Request ["scope"] = "api offline_access", ["client_id"] = clientId }; - if(Device != null) + if (Device != null) { obj.Add("deviceType", ((int)Device.Type).ToString()); obj.Add("deviceIdentifier", Device.Identifier); obj.Add("deviceName", Device.Name); obj.Add("devicePushToken", Device.PushToken); } - if(!string.IsNullOrWhiteSpace(Token) && Provider != null) + if (!string.IsNullOrWhiteSpace(Token) && Provider != null) { obj.Add("twoFactorToken", Token); obj.Add("twoFactorProvider", ((int)Provider.Value).ToString()); diff --git a/src/Core/Models/Response/ErrorResponse.cs b/src/Core/Models/Response/ErrorResponse.cs index bcfe650c6..56316dcbc 100644 --- a/src/Core/Models/Response/ErrorResponse.cs +++ b/src/Core/Models/Response/ErrorResponse.cs @@ -13,10 +13,10 @@ namespace Bit.Core.Models.Response public ErrorResponse(JObject response, HttpStatusCode status, bool identityResponse = false) { JObject errorModel = null; - if(response != null) + if (response != null) { var responseErrorModel = response.GetValue("ErrorModel", StringComparison.OrdinalIgnoreCase); - if(responseErrorModel != null && identityResponse) + if (responseErrorModel != null && identityResponse) { errorModel = responseErrorModel.Value(); ; } @@ -25,7 +25,7 @@ namespace Bit.Core.Models.Response errorModel = response; } } - if(errorModel != null) + if (errorModel != null) { var model = errorModel.ToObject(); Message = model.Message; @@ -33,7 +33,7 @@ namespace Bit.Core.Models.Response } else { - if((int)status == 429) + if ((int)status == 429) { Message = "Rate limit exceeded. Try again later."; } @@ -47,13 +47,13 @@ namespace Bit.Core.Models.Response public string GetSingleMessage() { - if(ValidationErrors == null) + if (ValidationErrors == null) { return Message; } - foreach(var error in ValidationErrors) + foreach (var error in ValidationErrors) { - if(error.Value?.Any() ?? false) + if (error.Value?.Any() ?? false) { return error.Value[0]; } diff --git a/src/Core/Models/View/AttachmentView.cs b/src/Core/Models/View/AttachmentView.cs index a0782d4fb..879ec583c 100644 --- a/src/Core/Models/View/AttachmentView.cs +++ b/src/Core/Models/View/AttachmentView.cs @@ -25,7 +25,7 @@ namespace Bit.Core.Models.View { get { - if(!string.IsNullOrWhiteSpace(Size) && long.TryParse(Size, out var s)) + if (!string.IsNullOrWhiteSpace(Size) && long.TryParse(Size, out var s)) { return s; } diff --git a/src/Core/Models/View/CardView.cs b/src/Core/Models/View/CardView.cs index da3f16ef7..6a9b3a5c8 100644 --- a/src/Core/Models/View/CardView.cs +++ b/src/Core/Models/View/CardView.cs @@ -43,12 +43,12 @@ namespace Bit.Core.Models.View { get { - if(_subTitle == null) + if (_subTitle == null) { _subTitle = Brand; - if(Number != null && Number.Length >= 4) + if (Number != null && Number.Length >= 4) { - if(!string.IsNullOrWhiteSpace(_subTitle)) + if (!string.IsNullOrWhiteSpace(_subTitle)) { _subTitle += ", "; } @@ -71,7 +71,7 @@ namespace Bit.Core.Models.View { var expMonthNull = string.IsNullOrWhiteSpace(ExpMonth); var expYearNull = string.IsNullOrWhiteSpace(ExpYear); - if(expMonthNull && expYearNull) + if (expMonthNull && expYearNull) { return null; } diff --git a/src/Core/Models/View/CipherView.cs b/src/Core/Models/View/CipherView.cs index 1ca6c3f90..5dd504441 100644 --- a/src/Core/Models/View/CipherView.cs +++ b/src/Core/Models/View/CipherView.cs @@ -49,7 +49,7 @@ namespace Bit.Core.Models.View { get { - switch(Type) + switch (Type) { case CipherType.Login: return Login.SubTitle; @@ -73,7 +73,7 @@ namespace Bit.Core.Models.View { get { - if(HasAttachments) + if (HasAttachments) { return Attachments.Any(a => a.Key == null); } @@ -85,11 +85,11 @@ namespace Bit.Core.Models.View { get { - if(Type != CipherType.Login || Login == null) + if (Type != CipherType.Login || Login == null) { return null; } - else if(string.IsNullOrWhiteSpace(Login.Password)) + else if (string.IsNullOrWhiteSpace(Login.Password)) { return null; } diff --git a/src/Core/Models/View/IdentityView.cs b/src/Core/Models/View/IdentityView.cs index 3d346537d..a6de1f86a 100644 --- a/src/Core/Models/View/IdentityView.cs +++ b/src/Core/Models/View/IdentityView.cs @@ -51,16 +51,16 @@ namespace Bit.Core.Models.View { get { - if(_subTitle == null && (FirstName != null || LastName != null)) + if (_subTitle == null && (FirstName != null || LastName != null)) { _subTitle = string.Empty; - if(FirstName != null) + if (FirstName != null) { _subTitle = FirstName; } - if(LastName != null) + if (LastName != null) { - if(_subTitle != string.Empty) + if (_subTitle != string.Empty) { _subTitle += " "; } @@ -75,23 +75,23 @@ namespace Bit.Core.Models.View { get { - if(!string.IsNullOrWhiteSpace(Title) || !string.IsNullOrWhiteSpace(FirstName) || + if (!string.IsNullOrWhiteSpace(Title) || !string.IsNullOrWhiteSpace(FirstName) || !string.IsNullOrWhiteSpace(MiddleName) || !string.IsNullOrWhiteSpace(LastName)) { var name = string.Empty; - if(!string.IsNullOrWhiteSpace(Title)) + if (!string.IsNullOrWhiteSpace(Title)) { name = string.Concat(name, Title, " "); } - if(!string.IsNullOrWhiteSpace(FirstName)) + if (!string.IsNullOrWhiteSpace(FirstName)) { name = string.Concat(name, FirstName, " "); } - if(!string.IsNullOrWhiteSpace(MiddleName)) + if (!string.IsNullOrWhiteSpace(MiddleName)) { name = string.Concat(name, MiddleName, " "); } - if(!string.IsNullOrWhiteSpace(LastName)) + if (!string.IsNullOrWhiteSpace(LastName)) { name = string.Concat(name, LastName); } @@ -106,17 +106,17 @@ namespace Bit.Core.Models.View get { var address = Address1; - if(!string.IsNullOrWhiteSpace(Address2)) + if (!string.IsNullOrWhiteSpace(Address2)) { - if(!string.IsNullOrWhiteSpace(address)) + if (!string.IsNullOrWhiteSpace(address)) { address += ", "; } address += Address2; } - if(!string.IsNullOrWhiteSpace(Address3)) + if (!string.IsNullOrWhiteSpace(Address3)) { - if(!string.IsNullOrWhiteSpace(address)) + if (!string.IsNullOrWhiteSpace(address)) { address += ", "; } @@ -130,7 +130,7 @@ namespace Bit.Core.Models.View { get { - if(string.IsNullOrWhiteSpace(City) && string.IsNullOrWhiteSpace(State) && + if (string.IsNullOrWhiteSpace(City) && string.IsNullOrWhiteSpace(State) && string.IsNullOrWhiteSpace(PostalCode)) { return null; diff --git a/src/Core/Models/View/LoginUriView.cs b/src/Core/Models/View/LoginUriView.cs index 8dc3e27e2..0552e5cbb 100644 --- a/src/Core/Models/View/LoginUriView.cs +++ b/src/Core/Models/View/LoginUriView.cs @@ -51,10 +51,10 @@ namespace Bit.Core.Models.View { get { - if(_domain == null && Uri != null) + if (_domain == null && Uri != null) { _domain = CoreHelpers.GetDomain(Uri); - if(_domain == string.Empty) + if (_domain == string.Empty) { _domain = null; } @@ -67,10 +67,10 @@ namespace Bit.Core.Models.View { get { - if(_hostname == null && Uri != null) + if (_hostname == null && Uri != null) { _hostname = CoreHelpers.GetHostname(Uri); - if(_hostname == string.Empty) + if (_hostname == string.Empty) { _hostname = null; } @@ -88,11 +88,11 @@ namespace Bit.Core.Models.View { get { - if(_canLaunch != null) + if (_canLaunch != null) { return _canLaunch.Value; } - if(Uri != null && Match != UriMatchType.RegularExpression) + if (Uri != null && Match != UriMatchType.RegularExpression) { var uri = LaunchUri; _canLaunch = _canLaunchWhitelist.Any(prefix => uri.StartsWith(prefix)); diff --git a/src/Core/Services/ApiService.cs b/src/Core/Services/ApiService.cs index 93362e8b4..046ffe084 100644 --- a/src/Core/Services/ApiService.cs +++ b/src/Core/Services/ApiService.cs @@ -37,7 +37,7 @@ namespace Bit.Core.Services _logoutCallbackAsync = logoutCallbackAsync; var device = (int)_platformUtilsService.GetDevice(); _httpClient.DefaultRequestHeaders.Add("Device-Type", device.ToString()); - if(!string.IsNullOrWhiteSpace(customUserAgent)) + if (!string.IsNullOrWhiteSpace(customUserAgent)) { _httpClient.DefaultRequestHeaders.UserAgent.ParseAdd(customUserAgent); } @@ -51,7 +51,7 @@ namespace Bit.Core.Services public void SetUrls(EnvironmentUrls urls) { UrlsSet = true; - if(!string.IsNullOrWhiteSpace(urls.Base)) + if (!string.IsNullOrWhiteSpace(urls.Base)) { ApiBaseUrl = urls.Base + "/api"; IdentityBaseUrl = urls.Base + "/identity"; @@ -64,15 +64,15 @@ namespace Bit.Core.Services EventsBaseUrl = urls.Events; // Production - if(string.IsNullOrWhiteSpace(ApiBaseUrl)) + if (string.IsNullOrWhiteSpace(ApiBaseUrl)) { ApiBaseUrl = "https://api.bitwarden.com"; } - if(string.IsNullOrWhiteSpace(IdentityBaseUrl)) + if (string.IsNullOrWhiteSpace(IdentityBaseUrl)) { IdentityBaseUrl = "https://identity.bitwarden.com"; } - if(string.IsNullOrWhiteSpace(EventsBaseUrl)) + if (string.IsNullOrWhiteSpace(EventsBaseUrl)) { EventsBaseUrl = "https://events.bitwarden.com"; } @@ -102,20 +102,20 @@ namespace Bit.Core.Services throw new ApiException(HandleWebError(e)); } JObject responseJObject = null; - if(IsJsonResponse(response)) + if (IsJsonResponse(response)) { var responseJsonString = await response.Content.ReadAsStringAsync(); responseJObject = JObject.Parse(responseJsonString); } - if(responseJObject != null) + if (responseJObject != null) { - if(response.IsSuccessStatusCode) + if (response.IsSuccessStatusCode) { return new Tuple( responseJObject.ToObject(), null); } - else if(response.StatusCode == HttpStatusCode.BadRequest && + else if (response.StatusCode == HttpStatusCode.BadRequest && responseJObject.ContainsKey("TwoFactorProviders2") && responseJObject["TwoFactorProviders2"] != null && responseJObject["TwoFactorProviders2"].HasValues) @@ -304,7 +304,7 @@ namespace Bit.Core.Services public async Task PostEventsCollectAsync(IEnumerable request) { - using(var requestMessage = new HttpRequestMessage()) + using (var requestMessage = new HttpRequestMessage()) { requestMessage.Version = new Version(1, 0); requestMessage.Method = HttpMethod.Post; @@ -322,7 +322,7 @@ namespace Bit.Core.Services { throw new ApiException(HandleWebError(e)); } - if(!response.IsSuccessStatusCode) + if (!response.IsSuccessStatusCode) { var error = await HandleErrorAsync(response, false); throw new ApiException(error); @@ -347,7 +347,7 @@ namespace Bit.Core.Services public async Task GetActiveBearerTokenAsync() { var accessToken = await _tokenService.GetTokenAsync(); - if(_tokenService.TokenNeedsRefresh()) + if (_tokenService.TokenNeedsRefresh()) { var tokenResponse = await DoRefreshTokenAsync(); accessToken = tokenResponse.AccessToken; @@ -358,20 +358,20 @@ namespace Bit.Core.Services public async Task SendAsync(HttpMethod method, string path, TRequest body, bool authed, bool hasResponse) { - using(var requestMessage = new HttpRequestMessage()) + using (var requestMessage = new HttpRequestMessage()) { requestMessage.Version = new Version(1, 0); requestMessage.Method = method; requestMessage.RequestUri = new Uri(string.Concat(ApiBaseUrl, path)); - if(body != null) + if (body != null) { var bodyType = body.GetType(); - if(bodyType == typeof(string)) + if (bodyType == typeof(string)) { requestMessage.Content = new StringContent((object)bodyType as string, Encoding.UTF8, "application/x-www-form-urlencoded; charset=utf-8"); } - else if(bodyType == typeof(MultipartFormDataContent)) + else if (bodyType == typeof(MultipartFormDataContent)) { requestMessage.Content = body as MultipartFormDataContent; } @@ -382,12 +382,12 @@ namespace Bit.Core.Services } } - if(authed) + if (authed) { var authHeader = await GetActiveBearerTokenAsync(); requestMessage.Headers.Add("Authorization", string.Concat("Bearer ", authHeader)); } - if(hasResponse) + if (hasResponse) { requestMessage.Headers.Add("Accept", "application/json"); } @@ -401,12 +401,12 @@ namespace Bit.Core.Services { throw new ApiException(HandleWebError(e)); } - if(hasResponse && response.IsSuccessStatusCode) + if (hasResponse && response.IsSuccessStatusCode) { var responseJsonString = await response.Content.ReadAsStringAsync(); return JsonConvert.DeserializeObject(responseJsonString); } - else if(!response.IsSuccessStatusCode) + else if (!response.IsSuccessStatusCode) { var error = await HandleErrorAsync(response, false); throw new ApiException(error); @@ -418,7 +418,7 @@ namespace Bit.Core.Services public async Task DoRefreshTokenAsync() { var refreshToken = await _tokenService.GetRefreshTokenAsync(); - if(string.IsNullOrWhiteSpace(refreshToken)) + if (string.IsNullOrWhiteSpace(refreshToken)) { throw new ApiException(); } @@ -447,7 +447,7 @@ namespace Bit.Core.Services { throw new ApiException(HandleWebError(e)); } - if(response.IsSuccessStatusCode) + if (response.IsSuccessStatusCode) { var responseJsonString = await response.Content.ReadAsStringAsync(); var tokenResponse = JsonConvert.DeserializeObject(responseJsonString); @@ -472,14 +472,14 @@ namespace Bit.Core.Services private async Task HandleErrorAsync(HttpResponseMessage response, bool tokenError) { - if((tokenError && response.StatusCode == HttpStatusCode.BadRequest) || + if ((tokenError && response.StatusCode == HttpStatusCode.BadRequest) || response.StatusCode == HttpStatusCode.Unauthorized || response.StatusCode == HttpStatusCode.Forbidden) { await _logoutCallbackAsync(true); return null; } JObject responseJObject = null; - if(IsJsonResponse(response)) + if (IsJsonResponse(response)) { var responseJsonString = await response.Content.ReadAsStringAsync(); responseJObject = JObject.Parse(responseJsonString); diff --git a/src/Core/Services/AppIdService.cs b/src/Core/Services/AppIdService.cs index a0207bf5f..ada27d857 100644 --- a/src/Core/Services/AppIdService.cs +++ b/src/Core/Services/AppIdService.cs @@ -26,7 +26,7 @@ namespace Bit.Core.Services private async Task MakeAndGetAppIdAsync(string key) { var existingId = await _storageService.GetAsync(key); - if(existingId != null) + if (existingId != null) { return existingId; } diff --git a/src/Core/Services/AuditService.cs b/src/Core/Services/AuditService.cs index 7724d3c0e..49bd709cd 100644 --- a/src/Core/Services/AuditService.cs +++ b/src/Core/Services/AuditService.cs @@ -36,7 +36,7 @@ namespace Bit.Core.Services var leakedHashes = await response.Content.ReadAsStringAsync(); var match = leakedHashes.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.None) .FirstOrDefault(v => v.Split(':')[0] == hashEnding); - if(match != null && int.TryParse(match.Split(':')[1], out var matchCount)) + if (match != null && int.TryParse(match.Split(':')[1], out var matchCount)) { return matchCount; } @@ -49,9 +49,9 @@ namespace Bit.Core.Services { return await _apiService.GetHibpBreachAsync(username); } - catch(ApiException e) + catch (ApiException e) { - if(e.Error != null && e.Error.StatusCode == System.Net.HttpStatusCode.NotFound) + if (e.Error != null && e.Error.StatusCode == System.Net.HttpStatusCode.NotFound) { return new List(); } diff --git a/src/Core/Services/AuthService.cs b/src/Core/Services/AuthService.cs index f02769077..e4378442d 100644 --- a/src/Core/Services/AuthService.cs +++ b/src/Core/Services/AuthService.cs @@ -149,32 +149,32 @@ namespace Bit.Core.Services public List GetSupportedTwoFactorProviders() { var providers = new List(); - if(TwoFactorProvidersData == null) + if (TwoFactorProvidersData == null) { return providers; } - if(TwoFactorProvidersData.ContainsKey(TwoFactorProviderType.OrganizationDuo) && + if (TwoFactorProvidersData.ContainsKey(TwoFactorProviderType.OrganizationDuo) && _platformUtilsService.SupportsDuo()) { providers.Add(TwoFactorProviders[TwoFactorProviderType.OrganizationDuo]); } - if(TwoFactorProvidersData.ContainsKey(TwoFactorProviderType.Authenticator)) + if (TwoFactorProvidersData.ContainsKey(TwoFactorProviderType.Authenticator)) { providers.Add(TwoFactorProviders[TwoFactorProviderType.Authenticator]); } - if(TwoFactorProvidersData.ContainsKey(TwoFactorProviderType.YubiKey)) + if (TwoFactorProvidersData.ContainsKey(TwoFactorProviderType.YubiKey)) { providers.Add(TwoFactorProviders[TwoFactorProviderType.YubiKey]); } - if(TwoFactorProvidersData.ContainsKey(TwoFactorProviderType.Duo) && _platformUtilsService.SupportsDuo()) + if (TwoFactorProvidersData.ContainsKey(TwoFactorProviderType.Duo) && _platformUtilsService.SupportsDuo()) { providers.Add(TwoFactorProviders[TwoFactorProviderType.Duo]); } - if(TwoFactorProvidersData.ContainsKey(TwoFactorProviderType.U2f) && _platformUtilsService.SupportsU2f()) + if (TwoFactorProvidersData.ContainsKey(TwoFactorProviderType.U2f) && _platformUtilsService.SupportsU2f()) { providers.Add(TwoFactorProviders[TwoFactorProviderType.U2f]); } - if(TwoFactorProvidersData.ContainsKey(TwoFactorProviderType.Email)) + if (TwoFactorProvidersData.ContainsKey(TwoFactorProviderType.Email)) { providers.Add(TwoFactorProviders[TwoFactorProviderType.Email]); } @@ -183,25 +183,25 @@ namespace Bit.Core.Services public TwoFactorProviderType? GetDefaultTwoFactorProvider(bool u2fSupported) { - if(TwoFactorProvidersData == null) + if (TwoFactorProvidersData == null) { return null; } - if(SelectedTwoFactorProviderType != null && + if (SelectedTwoFactorProviderType != null && TwoFactorProvidersData.ContainsKey(SelectedTwoFactorProviderType.Value)) { return SelectedTwoFactorProviderType.Value; } TwoFactorProviderType? providerType = null; var providerPriority = -1; - foreach(var providerKvp in TwoFactorProvidersData) + foreach (var providerKvp in TwoFactorProvidersData) { - if(TwoFactorProviders.ContainsKey(providerKvp.Key)) + if (TwoFactorProviders.ContainsKey(providerKvp.Key)) { var provider = TwoFactorProviders[providerKvp.Key]; - if(provider.Priority > providerPriority) + if (provider.Priority > providerPriority) { - if(providerKvp.Key == TwoFactorProviderType.U2f && !u2fSupported) + if (providerKvp.Key == TwoFactorProviderType.U2f && !u2fSupported) { continue; } @@ -223,15 +223,15 @@ namespace Bit.Core.Services try { var preloginResponse = await _apiService.PostPreloginAsync(new PreloginRequest { Email = email }); - if(preloginResponse != null) + if (preloginResponse != null) { _kdf = preloginResponse.Kdf; _kdfIterations = preloginResponse.KdfIterations; } } - catch(ApiException e) + catch (ApiException e) { - if(e.Error == null || e.Error.StatusCode != System.Net.HttpStatusCode.NotFound) + if (e.Error == null || e.Error.StatusCode != System.Net.HttpStatusCode.NotFound) { throw e; } @@ -252,13 +252,13 @@ namespace Bit.Core.Services Device = deviceRequest, Remember = false }; - if(twoFactorToken != null && twoFactorProvider != null) + if (twoFactorToken != null && twoFactorProvider != null) { request.Provider = twoFactorProvider; request.Token = twoFactorToken; request.Remember = remember.GetValueOrDefault(); } - else if(storedTwoFactorToken != null) + else if (storedTwoFactorToken != null) { request.Provider = TwoFactorProviderType.Remember; request.Token = storedTwoFactorToken; @@ -270,7 +270,7 @@ namespace Bit.Core.Services { TwoFactor = response.Item2 != null }; - if(result.TwoFactor) + if (result.TwoFactor) { // Two factor required. var twoFactorResponse = response.Item2; @@ -283,21 +283,21 @@ namespace Bit.Core.Services } var tokenResponse = response.Item1; - if(tokenResponse.TwoFactorToken != null) + if (tokenResponse.TwoFactorToken != null) { await _tokenService.SetTwoFactorTokenAsync(tokenResponse.TwoFactorToken, email); } await _tokenService.SetTokensAsync(tokenResponse.AccessToken, tokenResponse.RefreshToken); await _userService.SetInformationAsync(_tokenService.GetUserId(), _tokenService.GetEmail(), _kdf.Value, _kdfIterations.Value); - if(_setCryptoKeys) + if (_setCryptoKeys) { await _cryptoService.SetKeyAsync(key); await _cryptoService.SetKeyHashAsync(hashedPassword); await _cryptoService.SetEncKeyAsync(tokenResponse.Key); // User doesn't have a key pair yet (old account), let's generate one for them. - if(tokenResponse.PrivateKey == null) + if (tokenResponse.PrivateKey == null) { try { diff --git a/src/Core/Services/BroadcasterService.cs b/src/Core/Services/BroadcasterService.cs index 0c8613795..09079fb33 100644 --- a/src/Core/Services/BroadcasterService.cs +++ b/src/Core/Services/BroadcasterService.cs @@ -13,17 +13,17 @@ namespace Bit.App.Services public void Send(Message message, string id = null) { - lock(_myLock) + lock (_myLock) { - if(!string.IsNullOrWhiteSpace(id)) + if (!string.IsNullOrWhiteSpace(id)) { - if(_subscribers.ContainsKey(id)) + if (_subscribers.ContainsKey(id)) { Task.Run(() => _subscribers[id].Invoke(message)); } return; } - foreach(var sub in _subscribers) + foreach (var sub in _subscribers) { Task.Run(() => sub.Value.Invoke(message)); } @@ -32,9 +32,9 @@ namespace Bit.App.Services public void Subscribe(string id, Action messageCallback) { - lock(_myLock) + lock (_myLock) { - if(_subscribers.ContainsKey(id)) + if (_subscribers.ContainsKey(id)) { _subscribers[id] = messageCallback; } @@ -47,9 +47,9 @@ namespace Bit.App.Services public void Unsubscribe(string id) { - lock(_myLock) + lock (_myLock) { - if(_subscribers.ContainsKey(id)) + if (_subscribers.ContainsKey(id)) { _subscribers.Remove(id); } diff --git a/src/Core/Services/CipherService.cs b/src/Core/Services/CipherService.cs index d0a3a5a87..4809cd59c 100644 --- a/src/Core/Services/CipherService.cs +++ b/src/Core/Services/CipherService.cs @@ -63,14 +63,14 @@ namespace Bit.Core.Services get => _decryptedCipherCache; set { - if(value == null) + if (value == null) { _decryptedCipherCache?.Clear(); } _decryptedCipherCache = value; - if(_searchService != null) + if (_searchService != null) { - if(value == null) + if (value == null) { _searchService().ClearIndex(); } @@ -91,22 +91,22 @@ namespace Bit.Core.Services Cipher originalCipher = null) { // Adjust password history - if(model.Id != null) + if (model.Id != null) { - if(originalCipher == null) + if (originalCipher == null) { originalCipher = await GetAsync(model.Id); } - if(originalCipher != null) + if (originalCipher != null) { var existingCipher = await originalCipher.DecryptAsync(); - if(model.PasswordHistory == null) + if (model.PasswordHistory == null) { model.PasswordHistory = new List(); } - if(model.Type == CipherType.Login && existingCipher.Type == CipherType.Login) + if (model.Type == CipherType.Login && existingCipher.Type == CipherType.Login) { - if(!string.IsNullOrWhiteSpace(existingCipher.Login.Password) && + if (!string.IsNullOrWhiteSpace(existingCipher.Login.Password) && existingCipher.Login.Password != model.Login.Password) { var now = DateTime.UtcNow; @@ -123,7 +123,7 @@ namespace Bit.Core.Services model.Login.PasswordRevisionDate = existingCipher.Login.PasswordRevisionDate; } } - if(existingCipher.HasFields) + if (existingCipher.HasFields) { var existingHiddenFields = existingCipher.Fields.Where(f => f.Type == FieldType.Hidden && !string.IsNullOrWhiteSpace(f.Name) && @@ -131,10 +131,10 @@ namespace Bit.Core.Services var hiddenFields = model.Fields?.Where(f => f.Type == FieldType.Hidden && !string.IsNullOrWhiteSpace(f.Name)) ?? new List(); - foreach(var ef in existingHiddenFields) + foreach (var ef in existingHiddenFields) { var matchedField = hiddenFields.FirstOrDefault(f => f.Name == ef.Name); - if(matchedField == null || matchedField.Value != ef.Value) + if (matchedField == null || matchedField.Value != ef.Value) { var ph = new PasswordHistoryView { @@ -146,11 +146,11 @@ namespace Bit.Core.Services } } } - if(!model.PasswordHistory?.Any() ?? false) + if (!model.PasswordHistory?.Any() ?? false) { model.PasswordHistory = null; } - else if(model.PasswordHistory != null && model.PasswordHistory.Count > 5) + else if (model.PasswordHistory != null && model.PasswordHistory.Count > 5) { model.PasswordHistory = model.PasswordHistory.Take(5).ToList(); } @@ -166,10 +166,10 @@ namespace Bit.Core.Services CollectionIds = model.CollectionIds }; - if(key == null && cipher.OrganizationId != null) + if (key == null && cipher.OrganizationId != null) { key = await _cryptoService.GetOrgKeyAsync(cipher.OrganizationId); - if(key == null) + if (key == null) { throw new Exception("Cannot encrypt cipher for organization. No key."); } @@ -198,7 +198,7 @@ namespace Bit.Core.Services Keys_LocalData); var ciphers = await _storageService.GetAsync>( string.Format(Keys_CiphersFormat, userId)); - if(!ciphers?.ContainsKey(id) ?? true) + if (!ciphers?.ContainsKey(id) ?? true) { return null; } @@ -220,11 +220,11 @@ namespace Bit.Core.Services public Task> GetAllDecryptedAsync() { - if(DecryptedCipherCache != null) + if (DecryptedCipherCache != null) { return Task.FromResult(DecryptedCipherCache); } - if(_getAllDecryptedTask != null && !_getAllDecryptedTask.IsCompleted && !_getAllDecryptedTask.IsFaulted) + if (_getAllDecryptedTask != null && !_getAllDecryptedTask.IsCompleted && !_getAllDecryptedTask.IsFaulted) { return _getAllDecryptedTask; } @@ -233,7 +233,7 @@ namespace Bit.Core.Services try { var hashKey = await _cryptoService.HasKeyAsync(); - if(!hashKey) + if (!hashKey) { throw new Exception("No key."); } @@ -245,7 +245,7 @@ namespace Bit.Core.Services } var tasks = new List(); var ciphers = await GetAllAsync(); - foreach(var cipher in ciphers) + foreach (var cipher in ciphers) { tasks.Add(decryptAndAddCipherAsync(cipher)); } @@ -265,11 +265,11 @@ namespace Bit.Core.Services var ciphers = await GetAllDecryptedAsync(); return ciphers.Where(cipher => { - if(folder && cipher.FolderId == groupingId) + if (folder && cipher.FolderId == groupingId) { return true; } - if(!folder && cipher.CollectionIds != null && cipher.CollectionIds.Contains(groupingId)) + if (!folder && cipher.CollectionIds != null && cipher.CollectionIds.Contains(groupingId)) { return true; } @@ -286,7 +286,7 @@ namespace Bit.Core.Services public async Task, List, List>> GetAllDecryptedByUrlAsync( string url, List includeOtherTypes = null) { - if(string.IsNullOrWhiteSpace(url) && includeOtherTypes == null) + if (string.IsNullOrWhiteSpace(url) && includeOtherTypes == null) { return new Tuple, List, List>( new List(), new List(), new List()); @@ -317,43 +317,43 @@ namespace Bit.Core.Services var ciphers = await ciphersTask; var defaultMatch = (UriMatchType?)(await _storageService.GetAsync(Constants.DefaultUriMatch)); - if(defaultMatch == null) + if (defaultMatch == null) { defaultMatch = UriMatchType.Domain; } - foreach(var cipher in ciphers) + foreach (var cipher in ciphers) { - if(cipher.Type != CipherType.Login && (includeOtherTypes?.Any(t => t == cipher.Type) ?? false)) + if (cipher.Type != CipherType.Login && (includeOtherTypes?.Any(t => t == cipher.Type) ?? false)) { others.Add(cipher); continue; } - if(cipher.Type != CipherType.Login || cipher.Login?.Uris == null || !cipher.Login.Uris.Any()) + if (cipher.Type != CipherType.Login || cipher.Login?.Uris == null || !cipher.Login.Uris.Any()) { continue; } - foreach(var u in cipher.Login.Uris) + foreach (var u in cipher.Login.Uris) { - if(string.IsNullOrWhiteSpace(u.Uri)) + if (string.IsNullOrWhiteSpace(u.Uri)) { continue; } var match = false; - switch(u.Match) + switch (u.Match) { case null: case UriMatchType.Domain: match = CheckDefaultUriMatch(cipher, u, matchingLogins, matchingFuzzyLogins, matchingDomainsSet, matchingFuzzyDomainsSet, mobileApp, mobileAppSearchTerms); - if(match && u.Domain != null) + if (match && u.Domain != null) { - if(_domainMatchBlacklist.ContainsKey(u.Domain)) + if (_domainMatchBlacklist.ContainsKey(u.Domain)) { var domainUrlHost = CoreHelpers.GetHost(url); - if(_domainMatchBlacklist[u.Domain].Contains(domainUrlHost)) + if (_domainMatchBlacklist[u.Domain].Contains(domainUrlHost)) { match = false; } @@ -363,21 +363,21 @@ namespace Bit.Core.Services case UriMatchType.Host: var urlHost = CoreHelpers.GetHost(url); match = urlHost != null && urlHost == CoreHelpers.GetHost(u.Uri); - if(match) + if (match) { AddMatchingLogin(cipher, matchingLogins, matchingFuzzyLogins); } break; case UriMatchType.Exact: match = url == u.Uri; - if(match) + if (match) { AddMatchingLogin(cipher, matchingLogins, matchingFuzzyLogins); } break; case UriMatchType.StartsWith: match = url.StartsWith(u.Uri); - if(match) + if (match) { AddMatchingLogin(cipher, matchingLogins, matchingFuzzyLogins); } @@ -387,18 +387,18 @@ namespace Bit.Core.Services { var regex = new Regex(u.Uri, RegexOptions.IgnoreCase, TimeSpan.FromSeconds(1)); match = regex.IsMatch(url); - if(match) + if (match) { AddMatchingLogin(cipher, matchingLogins, matchingFuzzyLogins); } } - catch(ArgumentException) { } + catch (ArgumentException) { } break; case UriMatchType.Never: default: break; } - if(match) + if (match) { break; } @@ -418,15 +418,15 @@ namespace Bit.Core.Services { var ciphersLocalData = await _storageService.GetAsync>>( Keys_LocalData); - if(ciphersLocalData == null) + if (ciphersLocalData == null) { ciphersLocalData = new Dictionary>(); } - if(!ciphersLocalData.ContainsKey(id)) + if (!ciphersLocalData.ContainsKey(id)) { ciphersLocalData.Add(id, new Dictionary()); } - if(ciphersLocalData[id].ContainsKey("lastUsedDate")) + if (ciphersLocalData[id].ContainsKey("lastUsedDate")) { ciphersLocalData[id]["lastUsedDate"] = DateTime.UtcNow; } @@ -437,12 +437,12 @@ namespace Bit.Core.Services await _storageService.SaveAsync(Keys_LocalData, ciphersLocalData); // Update cache - if(DecryptedCipherCache == null) + if (DecryptedCipherCache == null) { return; } var cached = DecryptedCipherCache.FirstOrDefault(c => c.Id == id); - if(cached != null) + if (cached != null) { cached.LocalData = ciphersLocalData[id]; } @@ -450,12 +450,12 @@ namespace Bit.Core.Services public async Task SaveNeverDomainAsync(string domain) { - if(string.IsNullOrWhiteSpace(domain)) + if (string.IsNullOrWhiteSpace(domain)) { return; } var domains = await _storageService.GetAsync>(Keys_NeverDomains); - if(domains == null) + if (domains == null) { domains = new HashSet(); } @@ -466,9 +466,9 @@ namespace Bit.Core.Services public async Task SaveWithServerAsync(Cipher cipher) { CipherResponse response; - if(cipher.Id == null) + if (cipher.Id == null) { - if(cipher.CollectionIds != null) + if (cipher.CollectionIds != null) { var request = new CipherCreateRequest(cipher); response = await _apiService.PostCipherCreateAsync(request); @@ -493,11 +493,11 @@ namespace Bit.Core.Services public async Task ShareWithServerAsync(CipherView cipher, string organizationId, HashSet collectionIds) { var attachmentTasks = new List(); - if(cipher.Attachments != null) + if (cipher.Attachments != null) { - foreach(var attachment in cipher.Attachments) + foreach (var attachment in cipher.Attachments) { - if(attachment.Key == null) + if (attachment.Key == null) { attachmentTasks.Add(ShareAttachmentWithServerAsync(attachment, cipher.Id, organizationId)); } @@ -545,11 +545,11 @@ namespace Bit.Core.Services var userId = await _userService.GetUserIdAsync(); var storageKey = string.Format(Keys_CiphersFormat, userId); var ciphers = await _storageService.GetAsync>(storageKey); - if(ciphers == null) + if (ciphers == null) { ciphers = new Dictionary(); } - if(!ciphers.ContainsKey(cipher.Id)) + if (!ciphers.ContainsKey(cipher.Id)) { ciphers.Add(cipher.Id, null); } @@ -563,13 +563,13 @@ namespace Bit.Core.Services var userId = await _userService.GetUserIdAsync(); var storageKey = string.Format(Keys_CiphersFormat, userId); var ciphers = await _storageService.GetAsync>(storageKey); - if(ciphers == null) + if (ciphers == null) { ciphers = new Dictionary(); } - foreach(var c in cipher) + foreach (var c in cipher) { - if(!ciphers.ContainsKey(c.Id)) + if (!ciphers.ContainsKey(c.Id)) { ciphers.Add(c.Id, null); } @@ -597,11 +597,11 @@ namespace Bit.Core.Services var userId = await _userService.GetUserIdAsync(); var cipherKey = string.Format(Keys_CiphersFormat, userId); var ciphers = await _storageService.GetAsync>(cipherKey); - if(ciphers == null) + if (ciphers == null) { return; } - if(!ciphers.ContainsKey(id)) + if (!ciphers.ContainsKey(id)) { return; } @@ -615,13 +615,13 @@ namespace Bit.Core.Services var userId = await _userService.GetUserIdAsync(); var cipherKey = string.Format(Keys_CiphersFormat, userId); var ciphers = await _storageService.GetAsync>(cipherKey); - if(ciphers == null) + if (ciphers == null) { return; } - foreach(var id in ids) + foreach (var id in ids) { - if(!ciphers.ContainsKey(id)) + if (!ciphers.ContainsKey(id)) { return; } @@ -642,12 +642,12 @@ namespace Bit.Core.Services var userId = await _userService.GetUserIdAsync(); var cipherKey = string.Format(Keys_CiphersFormat, userId); var ciphers = await _storageService.GetAsync>(cipherKey); - if(ciphers == null || !ciphers.ContainsKey(id) || ciphers[id].Attachments == null) + if (ciphers == null || !ciphers.ContainsKey(id) || ciphers[id].Attachments == null) { return; } var attachment = ciphers[id].Attachments.FirstOrDefault(a => a.Id == attachmentId); - if(attachment != null) + if (attachment != null) { ciphers[id].Attachments.Remove(attachment); } @@ -662,7 +662,7 @@ namespace Bit.Core.Services await _apiService.DeleteCipherAttachmentAsync(id, attachmentId); await DeleteAttachmentAsync(id, attachmentId); } - catch(ApiException e) + catch (ApiException e) { await DeleteAttachmentAsync(id, attachmentId); throw e; @@ -674,12 +674,12 @@ namespace Bit.Core.Services try { var response = await _httpClient.GetAsync(new Uri(attachment.Url)); - if(!response.IsSuccessStatusCode) + if (!response.IsSuccessStatusCode) { return null; } var data = await response.Content.ReadAsByteArrayAsync(); - if(data == null) + if (data == null) { return null; } @@ -696,7 +696,7 @@ namespace Bit.Core.Services string organizationId) { var attachmentResponse = await _httpClient.GetAsync(attachmentView.Url); - if(!attachmentResponse.IsSuccessStatusCode) + if (!attachmentResponse.IsSuccessStatusCode) { throw new Exception("Failed to download attachment: " + attachmentResponse.StatusCode); } @@ -722,62 +722,62 @@ namespace Bit.Core.Services var loginUriString = loginUri.Uri; var loginUriDomain = loginUri.Domain; - if(matchingDomainsSet.Contains(loginUriString)) + if (matchingDomainsSet.Contains(loginUriString)) { AddMatchingLogin(cipher, matchingLogins, matchingFuzzyLogins); return true; } - else if(mobileApp && matchingFuzzyDomainsSet.Contains(loginUriString)) + else if (mobileApp && matchingFuzzyDomainsSet.Contains(loginUriString)) { AddMatchingFuzzyLogin(cipher, matchingLogins, matchingFuzzyLogins); return false; } - else if(!mobileApp) + else if (!mobileApp) { var info = InfoFromMobileAppUrl(loginUriString); - if(info?.Item1 != null && matchingDomainsSet.Contains(info.Item1)) + if (info?.Item1 != null && matchingDomainsSet.Contains(info.Item1)) { AddMatchingFuzzyLogin(cipher, matchingLogins, matchingFuzzyLogins); return false; } } - if(!loginUri.Uri.Contains("://") && loginUriString.Contains(".")) + if (!loginUri.Uri.Contains("://") && loginUriString.Contains(".")) { loginUriString = "http://" + loginUriString; } - if(loginUriDomain != null) + if (loginUriDomain != null) { loginUriDomain = loginUriDomain.ToLowerInvariant(); - if(matchingDomainsSet.Contains(loginUriDomain)) + if (matchingDomainsSet.Contains(loginUriDomain)) { AddMatchingLogin(cipher, matchingLogins, matchingFuzzyLogins); return true; } - else if(mobileApp && matchingFuzzyDomainsSet.Contains(loginUriDomain)) + else if (mobileApp && matchingFuzzyDomainsSet.Contains(loginUriDomain)) { AddMatchingFuzzyLogin(cipher, matchingLogins, matchingFuzzyLogins); return false; } } - if(mobileApp && (mobileAppSearchTerms?.Any() ?? false)) + if (mobileApp && (mobileAppSearchTerms?.Any() ?? false)) { var addedFromSearchTerm = false; var loginName = cipher.Name?.ToLowerInvariant(); - foreach(var term in mobileAppSearchTerms) + foreach (var term in mobileAppSearchTerms) { addedFromSearchTerm = (loginUriDomain != null && loginUriDomain.Contains(term)) || (loginName != null && loginName.Contains(term)); - if(!addedFromSearchTerm) + if (!addedFromSearchTerm) { var domainTerm = loginUriDomain?.Split('.')[0]; addedFromSearchTerm = (domainTerm != null && domainTerm.Length > 2 && term.Contains(domainTerm)) || (loginName != null && term.Contains(loginName)); } - if(addedFromSearchTerm) + if (addedFromSearchTerm) { AddMatchingFuzzyLogin(cipher, matchingLogins, matchingFuzzyLogins); return false; @@ -791,7 +791,7 @@ namespace Bit.Core.Services private void AddMatchingLogin(CipherView cipher, List matchingLogins, List matchingFuzzyLogins) { - if(matchingFuzzyLogins.Contains(cipher)) + if (matchingFuzzyLogins.Contains(cipher)) { matchingFuzzyLogins.Remove(cipher); } @@ -801,7 +801,7 @@ namespace Bit.Core.Services private void AddMatchingFuzzyLogin(CipherView cipher, List matchingLogins, List matchingFuzzyLogins) { - if(!matchingFuzzyLogins.Contains(cipher) && !matchingLogins.Contains(cipher)) + if (!matchingFuzzyLogins.Contains(cipher) && !matchingLogins.Contains(cipher)) { matchingFuzzyLogins.Add(cipher); } @@ -813,39 +813,39 @@ namespace Bit.Core.Services var matchingDomains = new HashSet(); var matchingFuzzyDomains = new HashSet(); var eqDomains = await _settingsService.GetEquivalentDomainsAsync(); - foreach(var eqDomain in eqDomains) + foreach (var eqDomain in eqDomains) { var eqDomainSet = new HashSet(eqDomain); - if(mobileApp) + if (mobileApp) { - if(eqDomainSet.Contains(url)) + if (eqDomainSet.Contains(url)) { - foreach(var d in eqDomain) + foreach (var d in eqDomain) { matchingDomains.Add(d); } } - else if(mobileAppWebUriString != null && eqDomainSet.Contains(mobileAppWebUriString)) + else if (mobileAppWebUriString != null && eqDomainSet.Contains(mobileAppWebUriString)) { - foreach(var d in eqDomain) + foreach (var d in eqDomain) { matchingFuzzyDomains.Add(d); } } } - else if(eqDomainSet.Contains(domain)) + else if (eqDomainSet.Contains(domain)) { - foreach(var d in eqDomain) + foreach (var d in eqDomain) { matchingDomains.Add(d); } } } - if(!matchingDomains.Any()) + if (!matchingDomains.Any()) { matchingDomains.Add(mobileApp ? url : domain); } - if(mobileApp && mobileAppWebUriString != null && + if (mobileApp && mobileAppWebUriString != null && !matchingFuzzyDomains.Any() && !matchingDomains.Contains(mobileAppWebUriString)) { matchingFuzzyDomains.Add(mobileAppWebUriString); @@ -855,11 +855,11 @@ namespace Bit.Core.Services private Tuple InfoFromMobileAppUrl(string mobileAppUrlString) { - if(UrlIsAndroidApp(mobileAppUrlString)) + if (UrlIsAndroidApp(mobileAppUrlString)) { return InfoFromAndroidAppUri(mobileAppUrlString); } - else if(UrlIsiOSApp(mobileAppUrlString)) + else if (UrlIsiOSApp(mobileAppUrlString)) { return InfoFromiOSAppUrl(mobileAppUrlString); } @@ -868,12 +868,12 @@ namespace Bit.Core.Services private Tuple InfoFromAndroidAppUri(string androidAppUrlString) { - if(!UrlIsAndroidApp(androidAppUrlString)) + if (!UrlIsAndroidApp(androidAppUrlString)) { return null; } var androidUrlParts = androidAppUrlString.Replace(Constants.AndroidAppProtocol, string.Empty).Split('.'); - if(androidUrlParts.Length >= 2) + if (androidUrlParts.Length >= 2) { var webUri = string.Join(".", androidUrlParts[1], androidUrlParts[0]); var searchTerms = androidUrlParts.Where(p => !_ignoredSearchTerms.Contains(p)) @@ -885,7 +885,7 @@ namespace Bit.Core.Services private Tuple InfoFromiOSAppUrl(string iosAppUrlString) { - if(!UrlIsiOSApp(iosAppUrlString)) + if (!UrlIsiOSApp(iosAppUrlString)) { return null; } @@ -920,7 +920,7 @@ namespace Bit.Core.Services var modelPropInfo = modelType.GetProperty(propName); var modelProp = modelPropInfo.GetValue(model) as string; CipherString val = null; - if(!string.IsNullOrWhiteSpace(modelProp)) + if (!string.IsNullOrWhiteSpace(modelProp)) { val = await _cryptoService.EncryptAsync(modelProp, key); } @@ -929,7 +929,7 @@ namespace Bit.Core.Services }; var tasks = new List(); - foreach(var prop in map) + foreach (var prop in map) { tasks.Add(makeAndSetCs(prop)); } @@ -939,7 +939,7 @@ namespace Bit.Core.Services private async Task EncryptAttachmentsAsync(List attachmentsModel, SymmetricCryptoKey key, Cipher cipher) { - if(!attachmentsModel?.Any() ?? true) + if (!attachmentsModel?.Any() ?? true) { cipher.Attachments = null; return; @@ -952,13 +952,13 @@ namespace Bit.Core.Services { "FileName" }, key); - if(model.Key != null) + if (model.Key != null) { attachment.Key = await _cryptoService.EncryptAsync(model.Key.Key, key); } encAttachments.Add(attachment); } - foreach(var model in attachmentsModel) + foreach (var model in attachmentsModel) { tasks.Add(encryptAndAddAttachmentAsync(model, new Attachment { @@ -974,7 +974,7 @@ namespace Bit.Core.Services private async Task EncryptCipherDataAsync(Cipher cipher, CipherView model, SymmetricCryptoKey key) { - switch(cipher.Type) + switch (cipher.Type) { case CipherType.Login: cipher.Login = new Login @@ -987,10 +987,10 @@ namespace Bit.Core.Services "Password", "Totp" }, key); - if(model.Login.Uris != null) + if (model.Login.Uris != null) { cipher.Login.Uris = new List(); - foreach(var uri in model.Login.Uris) + foreach (var uri in model.Login.Uris) { var loginUri = new LoginUri { @@ -1051,7 +1051,7 @@ namespace Bit.Core.Services private async Task EncryptFieldsAsync(List fieldsModel, SymmetricCryptoKey key, Cipher cipher) { - if(!fieldsModel?.Any() ?? true) + if (!fieldsModel?.Any() ?? true) { cipher.Fields = null; return; @@ -1067,14 +1067,14 @@ namespace Bit.Core.Services }, key); encFields.Add(field); } - foreach(var model in fieldsModel) + foreach (var model in fieldsModel) { var field = new Field { Type = model.Type }; // normalize boolean type field values - if(model.Type == FieldType.Boolean && model.Value != "true") + if (model.Type == FieldType.Boolean && model.Value != "true") { model.Value = "false"; } @@ -1087,7 +1087,7 @@ namespace Bit.Core.Services private async Task EncryptPasswordHistoriesAsync(List phModels, SymmetricCryptoKey key, Cipher cipher) { - if(!phModels?.Any() ?? true) + if (!phModels?.Any() ?? true) { cipher.PasswordHistory = null; return; @@ -1102,7 +1102,7 @@ namespace Bit.Core.Services }, key); encPhs.Add(ph); } - foreach(var model in phModels) + foreach (var model in phModels) { tasks.Add(encryptAndAddHistoryAsync(model, new PasswordHistory { @@ -1126,28 +1126,28 @@ namespace Bit.Core.Services { var aName = a?.Name; var bName = b?.Name; - if(aName == null && bName != null) + if (aName == null && bName != null) { return -1; } - if(aName != null && bName == null) + if (aName != null && bName == null) { return 1; } - if(aName == null && bName == null) + if (aName == null && bName == null) { return 0; } var result = _i18nService.StringComparer.Compare(aName, bName); - if(result != 0 || a.Type != CipherType.Login || b.Type != CipherType.Login) + if (result != 0 || a.Type != CipherType.Login || b.Type != CipherType.Login) { return result; } - if(a.Login.Username != null) + if (a.Login.Username != null) { aName += a.Login.Username; } - if(b.Login.Username != null) + if (b.Login.Username != null) { bName += b.Login.Username; } @@ -1165,19 +1165,19 @@ namespace Bit.Core.Services b.LocalData["lastUsedDate"] as DateTime? : null; var bothNotNull = aLastUsed != null && bLastUsed != null; - if(bothNotNull && aLastUsed.Value < bLastUsed.Value) + if (bothNotNull && aLastUsed.Value < bLastUsed.Value) { return 1; } - if(aLastUsed != null && bLastUsed == null) + if (aLastUsed != null && bLastUsed == null) { return -1; } - if(bothNotNull && aLastUsed.Value > bLastUsed.Value) + if (bothNotNull && aLastUsed.Value > bLastUsed.Value) { return -1; } - if(bLastUsed != null && aLastUsed == null) + if (bLastUsed != null && aLastUsed == null) { return 1; } @@ -1199,7 +1199,7 @@ namespace Bit.Core.Services public int Compare(CipherView a, CipherView b) { var result = _cipherLastUsedComparer.Compare(a, b); - if(result != 0) + if (result != 0) { return result; } diff --git a/src/Core/Services/CollectionService.cs b/src/Core/Services/CollectionService.cs index 95db22c9b..aadce803e 100644 --- a/src/Core/Services/CollectionService.cs +++ b/src/Core/Services/CollectionService.cs @@ -41,12 +41,12 @@ namespace Bit.Core.Services public async Task EncryptAsync(CollectionView model) { - if(model.OrganizationId == null) + if (model.OrganizationId == null) { throw new Exception("Collection has no organization id."); } var key = await _cryptoService.GetOrgKeyAsync(model.OrganizationId); - if(key == null) + if (key == null) { throw new Exception("No key for this collection's organization."); } @@ -62,7 +62,7 @@ namespace Bit.Core.Services public async Task> DecryptManyAsync(List collections) { - if(collections == null) + if (collections == null) { return new List(); } @@ -73,7 +73,7 @@ namespace Bit.Core.Services decCollections.Add(c); } var tasks = new List(); - foreach(var collection in collections) + foreach (var collection in collections) { tasks.Add(decryptAndAddCollectionAsync(collection)); } @@ -86,7 +86,7 @@ namespace Bit.Core.Services var userId = await _userService.GetUserIdAsync(); var collections = await _storageService.GetAsync>( string.Format(Keys_CollectionsFormat, userId)); - if(!collections?.ContainsKey(id) ?? true) + if (!collections?.ContainsKey(id) ?? true) { return null; } @@ -105,12 +105,12 @@ namespace Bit.Core.Services // TODO: sequentialize? public async Task> GetAllDecryptedAsync() { - if(_decryptedCollectionCache != null) + if (_decryptedCollectionCache != null) { return _decryptedCollectionCache; } var hasKey = await _cryptoService.HasKeyAsync(); - if(!hasKey) + if (!hasKey) { throw new Exception("No key."); } @@ -121,12 +121,12 @@ namespace Bit.Core.Services public async Task>> GetAllNestedAsync(List collections = null) { - if(collections == null) + if (collections == null) { collections = await GetAllDecryptedAsync(); } var nodes = new List>(); - foreach(var c in collections) + foreach (var c in collections) { var collectionCopy = new CollectionView { @@ -151,11 +151,11 @@ namespace Bit.Core.Services var userId = await _userService.GetUserIdAsync(); var storageKey = string.Format(Keys_CollectionsFormat, userId); var collections = await _storageService.GetAsync>(storageKey); - if(collections == null) + if (collections == null) { collections = new Dictionary(); } - if(!collections.ContainsKey(collection.Id)) + if (!collections.ContainsKey(collection.Id)) { collections.Add(collection.Id, null); } @@ -169,13 +169,13 @@ namespace Bit.Core.Services var userId = await _userService.GetUserIdAsync(); var storageKey = string.Format(Keys_CollectionsFormat, userId); var collections = await _storageService.GetAsync>(storageKey); - if(collections == null) + if (collections == null) { collections = new Dictionary(); } - foreach(var c in collection) + foreach (var c in collection) { - if(!collections.ContainsKey(c.Id)) + if (!collections.ContainsKey(c.Id)) { collections.Add(c.Id, null); } @@ -203,7 +203,7 @@ namespace Bit.Core.Services var userId = await _userService.GetUserIdAsync(); var collectionKey = string.Format(Keys_CollectionsFormat, userId); var collections = await _storageService.GetAsync>(collectionKey); - if(collections == null || !collections.ContainsKey(id)) + if (collections == null || !collections.ContainsKey(id)) { return; } @@ -225,15 +225,15 @@ namespace Bit.Core.Services { var aName = a?.Name; var bName = b?.Name; - if(aName == null && bName != null) + if (aName == null && bName != null) { return -1; } - if(aName != null && bName == null) + if (aName != null && bName == null) { return 1; } - if(aName == null && bName == null) + if (aName == null && bName == null) { return 0; } diff --git a/src/Core/Services/CryptoService.cs b/src/Core/Services/CryptoService.cs index df4d5f6c2..6bcfd9c16 100644 --- a/src/Core/Services/CryptoService.cs +++ b/src/Core/Services/CryptoService.cs @@ -49,7 +49,7 @@ namespace Bit.Core.Services _key = key; var option = await _storageService.GetAsync(Constants.LockOptionKey); var fingerprint = await _storageService.GetAsync(Constants.FingerprintUnlockKey); - if(option.HasValue && !fingerprint.GetValueOrDefault()) + if (option.HasValue && !fingerprint.GetValueOrDefault()) { // If we have a lock option set, we do not store the key return; @@ -65,7 +65,7 @@ namespace Bit.Core.Services public async Task SetEncKeyAsync(string encKey) { - if(encKey == null) + if (encKey == null) { return; } @@ -75,7 +75,7 @@ namespace Bit.Core.Services public async Task SetEncPrivateKeyAsync(string encPrivateKey) { - if(encPrivateKey == null) + if (encPrivateKey == null) { return; } @@ -92,12 +92,12 @@ namespace Bit.Core.Services public async Task GetKeyAsync() { - if(_key != null) + if (_key != null) { return _key; } var key = await _secureStorageService.GetAsync(Keys_Key); - if(key != null) + if (key != null) { _key = new SymmetricCryptoKey(Convert.FromBase64String(key)); } @@ -106,12 +106,12 @@ namespace Bit.Core.Services public async Task GetKeyHashAsync() { - if(_keyHash != null) + if (_keyHash != null) { return _keyHash; } var keyHash = await _storageService.GetAsync(Keys_KeyHash); - if(keyHash != null) + if (keyHash != null) { _keyHash = keyHash; } @@ -120,11 +120,11 @@ namespace Bit.Core.Services public Task GetEncKeyAsync(SymmetricCryptoKey key = null) { - if(_encKey != null) + if (_encKey != null) { return Task.FromResult(_encKey); } - if(_getEncKeysTask != null && !_getEncKeysTask.IsCompleted && !_getEncKeysTask.IsFaulted) + if (_getEncKeysTask != null && !_getEncKeysTask.IsCompleted && !_getEncKeysTask.IsFaulted) { return _getEncKeysTask; } @@ -133,27 +133,27 @@ namespace Bit.Core.Services try { var encKey = await _storageService.GetAsync(Keys_EncKey); - if(encKey == null) + if (encKey == null) { return null; } - if(key == null) + if (key == null) { key = await GetKeyAsync(); } - if(key == null) + if (key == null) { return null; } byte[] decEncKey = null; var encKeyCipher = new CipherString(encKey); - if(encKeyCipher.EncryptionType == EncryptionType.AesCbc256_B64) + if (encKeyCipher.EncryptionType == EncryptionType.AesCbc256_B64) { decEncKey = await DecryptToBytesAsync(encKeyCipher, key); } - else if(encKeyCipher.EncryptionType == EncryptionType.AesCbc256_HmacSha256_B64) + else if (encKeyCipher.EncryptionType == EncryptionType.AesCbc256_HmacSha256_B64) { var newKey = await StretchKeyAsync(key); decEncKey = await DecryptToBytesAsync(encKeyCipher, newKey); @@ -163,7 +163,7 @@ namespace Bit.Core.Services throw new Exception("Unsupported encKey type."); } - if(decEncKey == null) + if (decEncKey == null) { return null; } @@ -181,12 +181,12 @@ namespace Bit.Core.Services public async Task GetPublicKeyAsync() { - if(_publicKey != null) + if (_publicKey != null) { return _publicKey; } var privateKey = await GetPrivateKeyAsync(); - if(privateKey == null) + if (privateKey == null) { return null; } @@ -196,12 +196,12 @@ namespace Bit.Core.Services public async Task GetPrivateKeyAsync() { - if(_privateKey != null) + if (_privateKey != null) { return _privateKey; } var encPrivateKey = await _storageService.GetAsync(Keys_EncPrivateKey); - if(encPrivateKey == null) + if (encPrivateKey == null) { return null; } @@ -211,11 +211,11 @@ namespace Bit.Core.Services public async Task> GetFingerprintAsync(string userId, byte[] publicKey = null) { - if(publicKey == null) + if (publicKey == null) { publicKey = await GetPublicKeyAsync(); } - if(publicKey == null) + if (publicKey == null) { throw new Exception("No public key available."); } @@ -226,11 +226,11 @@ namespace Bit.Core.Services public Task> GetOrgKeysAsync() { - if(_orgKeys != null && _orgKeys.Count > 0) + if (_orgKeys != null && _orgKeys.Count > 0) { return Task.FromResult(_orgKeys); } - if(_getOrgKeysTask != null && !_getOrgKeysTask.IsCompleted && !_getOrgKeysTask.IsFaulted) + if (_getOrgKeysTask != null && !_getOrgKeysTask.IsCompleted && !_getOrgKeysTask.IsFaulted) { return _getOrgKeysTask; } @@ -239,20 +239,20 @@ namespace Bit.Core.Services try { var encOrgKeys = await _storageService.GetAsync>(Keys_EncOrgKeys); - if(encOrgKeys == null) + if (encOrgKeys == null) { return null; } var orgKeys = new Dictionary(); var setKey = false; - foreach(var org in encOrgKeys) + foreach (var org in encOrgKeys) { var decValue = await RsaDecryptAsync(org.Value); orgKeys.Add(org.Key, new SymmetricCryptoKey(decValue)); setKey = true; } - if(setKey) + if (setKey) { _orgKeys = orgKeys; } @@ -269,12 +269,12 @@ namespace Bit.Core.Services public async Task GetOrgKeyAsync(string orgId) { - if(string.IsNullOrWhiteSpace(orgId)) + if (string.IsNullOrWhiteSpace(orgId)) { return null; } var orgKeys = await GetOrgKeysAsync(); - if(orgKeys == null || !orgKeys.ContainsKey(orgId)) + if (orgKeys == null || !orgKeys.ContainsKey(orgId)) { return null; } @@ -308,7 +308,7 @@ namespace Bit.Core.Services public async Task ClearEncKeyAsync(bool memoryOnly = false) { _encKey = null; - if(!memoryOnly) + if (!memoryOnly) { await _storageService.RemoveAsync(Keys_EncKey); } @@ -317,7 +317,7 @@ namespace Bit.Core.Services public async Task ClearKeyPairAsync(bool memoryOnly = false) { _publicKey = _privateKey = null; - if(!memoryOnly) + if (!memoryOnly) { await _storageService.RemoveAsync(Keys_EncPrivateKey); } @@ -326,7 +326,7 @@ namespace Bit.Core.Services public async Task ClearOrgKeysAsync(bool memoryOnly = false) { _orgKeys = null; - if(!memoryOnly) + if (!memoryOnly) { await _storageService.RemoveAsync(Keys_EncOrgKeys); } @@ -355,7 +355,7 @@ namespace Bit.Core.Services var key = await GetKeyAsync(); var option = await _storageService.GetAsync(Constants.LockOptionKey); var fingerprint = await _storageService.GetAsync(Constants.FingerprintUnlockKey); - if(!fingerprint.GetValueOrDefault() && (option != null || option == 0)) + if (!fingerprint.GetValueOrDefault() && (option != null || option == 0)) { await ClearKeyAsync(); _key = key; @@ -368,13 +368,13 @@ namespace Bit.Core.Services KdfType? kdf, int? kdfIterations) { byte[] key = null; - if(kdf == null || kdf == KdfType.PBKDF2_SHA256) + if (kdf == null || kdf == KdfType.PBKDF2_SHA256) { - if(kdfIterations == null) + if (kdfIterations == null) { kdfIterations = 5000; } - if(kdfIterations < 5000) + if (kdfIterations < 5000) { throw new Exception("PBKDF2 iteration minimum is 5000."); } @@ -391,10 +391,10 @@ namespace Bit.Core.Services public async Task MakeKeyFromPinAsync(string pin, string salt, KdfType kdf, int kdfIterations, CipherString protectedKeyCs = null) { - if(protectedKeyCs == null) + if (protectedKeyCs == null) { var pinProtectedKey = await _storageService.GetAsync(Constants.PinProtectedKey); - if(pinProtectedKey == null) + if (pinProtectedKey == null) { throw new Exception("No PIN protected key found."); } @@ -429,11 +429,11 @@ namespace Bit.Core.Services public async Task HashPasswordAsync(string password, SymmetricCryptoKey key) { - if(key == null) + if (key == null) { key = await GetKeyAsync(); } - if(password == null || key == null) + if (password == null || key == null) { throw new Exception("Invalid parameters."); } @@ -456,7 +456,7 @@ namespace Bit.Core.Services public async Task EncryptAsync(string plainValue, SymmetricCryptoKey key = null) { - if(plainValue == null) + if (plainValue == null) { return null; } @@ -465,7 +465,7 @@ namespace Bit.Core.Services public async Task EncryptAsync(byte[] plainValue, SymmetricCryptoKey key = null) { - if(plainValue == null) + if (plainValue == null) { return null; } @@ -480,14 +480,14 @@ namespace Bit.Core.Services { var encValue = await AesEncryptAsync(plainValue, key); var macLen = 0; - if(encValue.Mac != null) + if (encValue.Mac != null) { macLen = encValue.Mac.Length; } var encBytes = new byte[1 + encValue.Iv.Length + macLen + encValue.Data.Length]; Buffer.BlockCopy(new byte[] { (byte)encValue.Key.EncType }, 0, encBytes, 0, 1); Buffer.BlockCopy(encValue.Iv, 0, encBytes, 1, encValue.Iv.Length); - if(encValue.Mac != null) + if (encValue.Mac != null) { Buffer.BlockCopy(encValue.Mac, 0, encBytes, 1 + encValue.Iv.Length, encValue.Mac.Length); } @@ -497,11 +497,11 @@ namespace Bit.Core.Services public async Task RsaEncryptAsync(byte[] data, byte[] publicKey = null) { - if(publicKey == null) + if (publicKey == null) { publicKey = await GetPublicKeyAsync(); } - if(publicKey == null) + if (publicKey == null) { throw new Exception("Public key unavailable."); } @@ -525,7 +525,7 @@ namespace Bit.Core.Services public async Task DecryptFromBytesAsync(byte[] encBytes, SymmetricCryptoKey key) { - if(encBytes == null) + if (encBytes == null) { throw new Exception("no encBytes."); } @@ -535,11 +535,11 @@ namespace Bit.Core.Services byte[] ivBytes = null; byte[] macBytes = null; - switch(encType) + switch (encType) { case EncryptionType.AesCbc128_HmacSha256_B64: case EncryptionType.AesCbc256_HmacSha256_B64: - if(encBytes.Length < 49) // 1 + 16 + 32 + ctLength + if (encBytes.Length < 49) // 1 + 16 + 32 + ctLength { return null; } @@ -548,7 +548,7 @@ namespace Bit.Core.Services ctBytes = new ArraySegment(encBytes, 49, encBytes.Length - 49).ToArray(); break; case EncryptionType.AesCbc256_B64: - if(encBytes.Length < 17) // 1 + 16 + ctLength + if (encBytes.Length < 17) // 1 + 16 + ctLength { return null; } @@ -573,7 +573,7 @@ namespace Bit.Core.Services do { ui = await _cryptoFunctionService.RandomNumberAsync(); - } while(ui >= upperBound); + } while (ui >= upperBound); return (int)(min + (ui % diff)); } @@ -587,7 +587,7 @@ namespace Bit.Core.Services Iv = await _cryptoFunctionService.RandomBytesAsync(16) }; obj.Data = await _cryptoFunctionService.AesEncryptAsync(data, obj.Iv, obj.Key.EncKey); - if(obj.Key.MacKey != null) + if (obj.Key.MacKey != null) { var macData = new byte[obj.Iv.Length + obj.Data.Length]; Buffer.BlockCopy(obj.Iv, 0, macData, 0, obj.Iv.Length); @@ -602,12 +602,12 @@ namespace Bit.Core.Services { var keyForEnc = await GetKeyForEncryptionAsync(key); var theKey = ResolveLegacyKey(encType, keyForEnc); - if(theKey.MacKey != null && mac == null) + if (theKey.MacKey != null && mac == null) { // Mac required. return null; } - if(theKey.EncType != encType) + if (theKey.EncType != encType) { // encType unavailable. return null; @@ -623,23 +623,23 @@ namespace Bit.Core.Services Buffer.BlockCopy(dataBytes, 0, macDataBytes, ivBytes.Length, dataBytes.Length); byte[] macKey = null; - if(theKey.MacKey != null) + if (theKey.MacKey != null) { macKey = theKey.MacKey; } byte[] macBytes = null; - if(mac != null) + if (mac != null) { macBytes = Convert.FromBase64String(mac); } // Compute mac - if(macKey != null && macBytes != null) + if (macKey != null && macBytes != null) { var computedMac = await _cryptoFunctionService.HmacAsync(macDataBytes, macKey, CryptoHashAlgorithm.Sha256); var macsEqual = await _cryptoFunctionService.CompareAsync(macBytes, computedMac); - if(!macsEqual) + if (!macsEqual) { // Mac failed return null; @@ -656,19 +656,19 @@ namespace Bit.Core.Services var keyForEnc = await GetKeyForEncryptionAsync(key); var theKey = ResolveLegacyKey(encType, keyForEnc); - if(theKey.MacKey != null && mac == null) + if (theKey.MacKey != null && mac == null) { // Mac required. return null; } - if(theKey.EncType != encType) + if (theKey.EncType != encType) { // encType unavailable. return null; } // Compute mac - if(theKey.MacKey != null && mac != null) + if (theKey.MacKey != null && mac != null) { var macData = new byte[iv.Length + data.Length]; Buffer.BlockCopy(iv, 0, macData, 0, iv.Length); @@ -676,12 +676,12 @@ namespace Bit.Core.Services var computedMac = await _cryptoFunctionService.HmacAsync(macData, theKey.MacKey, CryptoHashAlgorithm.Sha256); - if(computedMac == null) + if (computedMac == null) { return null; } var macsMatch = await _cryptoFunctionService.CompareAsync(mac, computedMac); - if(!macsMatch) + if (!macsMatch) { // Mac failed return null; @@ -697,35 +697,35 @@ namespace Bit.Core.Services EncryptionType? encType = null; string[] encPieces = null; - if(headerPieces.Length == 1) + if (headerPieces.Length == 1) { encType = EncryptionType.Rsa2048_OaepSha256_B64; encPieces = new string[] { headerPieces[0] }; } - else if(headerPieces.Length == 2 && Enum.TryParse(headerPieces[0], out EncryptionType type)) + else if (headerPieces.Length == 2 && Enum.TryParse(headerPieces[0], out EncryptionType type)) { encType = type; encPieces = headerPieces[1].Split('|'); } - if(!encType.HasValue) + if (!encType.HasValue) { throw new Exception("encType unavailable."); } - if(encPieces == null || encPieces.Length == 0) + if (encPieces == null || encPieces.Length == 0) { throw new Exception("encPieces unavailable."); } var data = Convert.FromBase64String(encPieces[0]); var privateKey = await GetPrivateKeyAsync(); - if(privateKey == null) + if (privateKey == null) { throw new Exception("No private key."); } var alg = CryptoHashAlgorithm.Sha1; - switch(encType.Value) + switch (encType.Value) { case EncryptionType.Rsa2048_OaepSha256_B64: case EncryptionType.Rsa2048_OaepSha256_HmacSha256_B64: @@ -743,12 +743,12 @@ namespace Bit.Core.Services private async Task GetKeyForEncryptionAsync(SymmetricCryptoKey key = null) { - if(key != null) + if (key != null) { return key; } var encKey = await GetEncKeyAsync(); - if(encKey != null) + if (encKey != null) { return encKey; } @@ -757,10 +757,10 @@ namespace Bit.Core.Services private SymmetricCryptoKey ResolveLegacyKey(EncryptionType encKey, SymmetricCryptoKey key) { - if(encKey == EncryptionType.AesCbc128_HmacSha256_B64 && key.EncType == EncryptionType.AesCbc256_B64) + if (encKey == EncryptionType.AesCbc128_HmacSha256_B64 && key.EncType == EncryptionType.AesCbc256_B64) { // Old encrypt-then-mac scheme, make a new key - if(_legacyEtmKey == null) + if (_legacyEtmKey == null) { _legacyEtmKey = new SymmetricCryptoKey(key.Key, EncryptionType.AesCbc128_HmacSha256_B64); } @@ -786,7 +786,7 @@ namespace Bit.Core.Services var okm = new byte[size]; var previousT = new byte[0]; var n = (int)Math.Ceiling((double)size / hashLen); - for(var i = 0; i < n; i++) + for (var i = 0; i < n; i++) { var t = new byte[previousT.Length + info.Length + 1]; previousT.CopyTo(t, 0); @@ -805,7 +805,7 @@ namespace Bit.Core.Services var numWords = (int)Math.Ceiling(minimumEntropy / entropyPerWord); var entropyAvailable = hash.Length * 4; - if(numWords * entropyPerWord > entropyAvailable) + if (numWords * entropyPerWord > entropyAvailable) { throw new Exception("Output entropy of hash function is too small"); } @@ -813,7 +813,7 @@ namespace Bit.Core.Services var phrase = new List(); var hashHex = string.Concat("0", BitConverter.ToString(hash).Replace("-", "")); var hashNumber = BigInteger.Parse(hashHex, System.Globalization.NumberStyles.HexNumber); - while(numWords-- > 0) + while (numWords-- > 0) { var remainder = (int)(hashNumber % wordLength); hashNumber = hashNumber / wordLength; @@ -826,12 +826,12 @@ namespace Bit.Core.Services byte[] encKey) { CipherString encKeyEnc = null; - if(key.Key.Length == 32) + if (key.Key.Length == 32) { var newKey = await StretchKeyAsync(key); encKeyEnc = await EncryptAsync(encKey, newKey); } - else if(key.Key.Length == 64) + else if (key.Key.Length == 64) { encKeyEnc = await EncryptAsync(encKey, key); } diff --git a/src/Core/Services/EnvironmentService.cs b/src/Core/Services/EnvironmentService.cs index 6440e13c9..315e27126 100644 --- a/src/Core/Services/EnvironmentService.cs +++ b/src/Core/Services/EnvironmentService.cs @@ -29,11 +29,11 @@ namespace Bit.Core.Services public string GetWebVaultUrl() { - if(!string.IsNullOrWhiteSpace(WebVaultUrl)) + if (!string.IsNullOrWhiteSpace(WebVaultUrl)) { return WebVaultUrl; } - else if(!string.IsNullOrWhiteSpace(BaseUrl)) + else if (!string.IsNullOrWhiteSpace(BaseUrl)) { return BaseUrl; } @@ -43,12 +43,12 @@ namespace Bit.Core.Services public async Task SetUrlsFromStorageAsync() { var urls = await _storageService.GetAsync(Constants.EnvironmentUrlsKey); - if(urls == null) + if (urls == null) { urls = new EnvironmentUrlData(); } var envUrls = new EnvironmentUrls(); - if(!string.IsNullOrWhiteSpace(urls.Base)) + if (!string.IsNullOrWhiteSpace(urls.Base)) { BaseUrl = envUrls.Base = urls.Base; _apiService.SetUrls(envUrls); @@ -82,7 +82,7 @@ namespace Bit.Core.Services EventsUrl = urls.Events; var envUrls = new EnvironmentUrls(); - if(!string.IsNullOrWhiteSpace(BaseUrl)) + if (!string.IsNullOrWhiteSpace(BaseUrl)) { envUrls.Base = BaseUrl; } @@ -99,12 +99,12 @@ namespace Bit.Core.Services private string FormatUrl(string url) { - if(string.IsNullOrWhiteSpace(url)) + if (string.IsNullOrWhiteSpace(url)) { return null; } url = Regex.Replace(url, "\\/+$", string.Empty); - if(!url.StartsWith("http://") && !url.StartsWith("https://")) + if (!url.StartsWith("http://") && !url.StartsWith("https://")) { url = string.Concat("https://", url); } diff --git a/src/Core/Services/EventService.cs b/src/Core/Services/EventService.cs index 44b0011d1..3a599d17a 100644 --- a/src/Core/Services/EventService.cs +++ b/src/Core/Services/EventService.cs @@ -32,30 +32,30 @@ namespace Bit.Core.Services public async Task CollectAsync(EventType eventType, string cipherId = null, bool uploadImmediately = false) { var authed = await _userService.IsAuthenticatedAsync(); - if(!authed) + if (!authed) { return; } var organizations = await _userService.GetAllOrganizationAsync(); - if(organizations == null) + if (organizations == null) { return; } var orgIds = new HashSet(organizations.Where(o => o.UseEvents).Select(o => o.Id)); - if(!orgIds.Any()) + if (!orgIds.Any()) { return; } - if(cipherId != null) + if (cipherId != null) { var cipher = await _cipherService.GetAsync(cipherId); - if(cipher?.OrganizationId == null || !orgIds.Contains(cipher.OrganizationId)) + if (cipher?.OrganizationId == null || !orgIds.Contains(cipher.OrganizationId)) { return; } } var eventCollection = await _storageService.GetAsync>(Constants.EventCollectionKey); - if(eventCollection == null) + if (eventCollection == null) { eventCollection = new List(); } @@ -66,7 +66,7 @@ namespace Bit.Core.Services Date = DateTime.UtcNow }); await _storageService.SaveAsync(Constants.EventCollectionKey, eventCollection); - if(uploadImmediately) + if (uploadImmediately) { await UploadEventsAsync(); } @@ -75,12 +75,12 @@ namespace Bit.Core.Services public async Task UploadEventsAsync() { var authed = await _userService.IsAuthenticatedAsync(); - if(!authed) + if (!authed) { return; } var eventCollection = await _storageService.GetAsync>(Constants.EventCollectionKey); - if(eventCollection == null || !eventCollection.Any()) + if (eventCollection == null || !eventCollection.Any()) { return; } @@ -95,7 +95,7 @@ namespace Bit.Core.Services await _apiService.PostEventsCollectAsync(request); await ClearEventsAsync(); } - catch(ApiException) { } + catch (ApiException) { } } public async Task ClearEventsAsync() diff --git a/src/Core/Services/ExportService.cs b/src/Core/Services/ExportService.cs index a92c9e65c..38bee7ba0 100644 --- a/src/Core/Services/ExportService.cs +++ b/src/Core/Services/ExportService.cs @@ -38,20 +38,20 @@ namespace Bit.Core.Services _decryptedFolders = await _folderService.GetAllDecryptedAsync(); _decryptedCiphers = await _cipherService.GetAllDecryptedAsync(); - if(format == "csv") + if (format == "csv") { var foldersMap = _decryptedFolders.Where(f => f.Id != null).ToDictionary(f => f.Id); var exportCiphers = new List(); - foreach(var c in _decryptedCiphers) + foreach (var c in _decryptedCiphers) { // only export logins and secure notes - if(c.Type != CipherType.Login && c.Type != CipherType.SecureNote) + if (c.Type != CipherType.Login && c.Type != CipherType.SecureNote) { continue; } - if(c.OrganizationId != null) + if (c.OrganizationId != null) { continue; } @@ -115,11 +115,11 @@ namespace Bit.Core.Services cipher.LoginPassword = null; cipher.LoginTotp = null; - if(c.Fields != null) + if (c.Fields != null) { - foreach(var f in c.Fields) + foreach (var f in c.Fields) { - if(cipher.Fields == null) + if (cipher.Fields == null) { cipher.Fields = ""; } @@ -132,7 +132,7 @@ namespace Bit.Core.Services } } - switch(c.Type) + switch (c.Type) { case CipherType.Login: cipher.Type = "login"; @@ -140,11 +140,11 @@ namespace Bit.Core.Services cipher.LoginPassword = c.Login.Password; cipher.LoginTotp = c.Login.Totp; - if(c.Login.Uris != null) + if (c.Login.Uris != null) { - foreach(var u in c.Login.Uris) + foreach (var u in c.Login.Uris) { - if(cipher.LoginUris == null) + if (cipher.LoginUris == null) { cipher.LoginUris = ""; } diff --git a/src/Core/Services/FolderService.cs b/src/Core/Services/FolderService.cs index 7215f8a46..6eb38ef23 100644 --- a/src/Core/Services/FolderService.cs +++ b/src/Core/Services/FolderService.cs @@ -63,7 +63,7 @@ namespace Bit.Core.Services var userId = await _userService.GetUserIdAsync(); var folders = await _storageService.GetAsync>( string.Format(Keys_FoldersFormat, userId)); - if(!folders?.ContainsKey(id) ?? true) + if (!folders?.ContainsKey(id) ?? true) { return null; } @@ -82,12 +82,12 @@ namespace Bit.Core.Services // TODO: sequentialize? public async Task> GetAllDecryptedAsync() { - if(_decryptedFolderCache != null) + if (_decryptedFolderCache != null) { return _decryptedFolderCache; } var hasKey = await _cryptoService.HasKeyAsync(); - if(!hasKey) + if (!hasKey) { throw new Exception("No key."); } @@ -99,7 +99,7 @@ namespace Bit.Core.Services } var tasks = new List(); var folders = await GetAllAsync(); - foreach(var folder in folders) + foreach (var folder in folders) { tasks.Add(decryptAndAddFolderAsync(folder)); } @@ -120,7 +120,7 @@ namespace Bit.Core.Services { var folders = await GetAllDecryptedAsync(); var nodes = new List>(); - foreach(var f in folders) + foreach (var f in folders) { var folderCopy = new FolderView { @@ -144,7 +144,7 @@ namespace Bit.Core.Services { var request = new FolderRequest(folder); FolderResponse response; - if(folder.Id == null) + if (folder.Id == null) { response = await _apiService.PostFolderAsync(request); folder.Id = response.Id; @@ -163,11 +163,11 @@ namespace Bit.Core.Services var userId = await _userService.GetUserIdAsync(); var storageKey = string.Format(Keys_FoldersFormat, userId); var folders = await _storageService.GetAsync>(storageKey); - if(folders == null) + if (folders == null) { folders = new Dictionary(); } - if(!folders.ContainsKey(folder.Id)) + if (!folders.ContainsKey(folder.Id)) { folders.Add(folder.Id, null); } @@ -181,13 +181,13 @@ namespace Bit.Core.Services var userId = await _userService.GetUserIdAsync(); var storageKey = string.Format(Keys_FoldersFormat, userId); var folders = await _storageService.GetAsync>(storageKey); - if(folders == null) + if (folders == null) { folders = new Dictionary(); } - foreach(var f in folder) + foreach (var f in folder) { - if(!folders.ContainsKey(f.Id)) + if (!folders.ContainsKey(f.Id)) { folders.Add(f.Id, null); } @@ -215,7 +215,7 @@ namespace Bit.Core.Services var userId = await _userService.GetUserIdAsync(); var folderKey = string.Format(Keys_FoldersFormat, userId); var folders = await _storageService.GetAsync>(folderKey); - if(folders == null || !folders.ContainsKey(id)) + if (folders == null || !folders.ContainsKey(id)) { return; } @@ -226,18 +226,18 @@ namespace Bit.Core.Services // Items in a deleted folder are re-assigned to "No Folder" var ciphers = await _storageService.GetAsync>( string.Format(Keys_CiphersFormat, userId)); - if(ciphers != null) + if (ciphers != null) { var updates = new List(); - foreach(var c in ciphers) + foreach (var c in ciphers) { - if(c.Value.FolderId == id) + if (c.Value.FolderId == id) { c.Value.FolderId = null; updates.Add(c.Value); } } - if(updates.Any()) + if (updates.Any()) { await _cipherService.UpsertAsync(updates); } @@ -263,15 +263,15 @@ namespace Bit.Core.Services { var aName = a?.Name; var bName = b?.Name; - if(aName == null && bName != null) + if (aName == null && bName != null) { return -1; } - if(aName != null && bName == null) + if (aName != null && bName == null) { return 1; } - if(aName == null && bName == null) + if (aName == null && bName == null) { return 0; } diff --git a/src/Core/Services/InMemoryStorageService.cs b/src/Core/Services/InMemoryStorageService.cs index 1c6ed114b..fa15fc71b 100644 --- a/src/Core/Services/InMemoryStorageService.cs +++ b/src/Core/Services/InMemoryStorageService.cs @@ -11,7 +11,7 @@ namespace Bit.Core.Services public Task GetAsync(string key) { - if(!_dict.ContainsKey(key)) + if (!_dict.ContainsKey(key)) { return Task.FromResult(default(T)); } @@ -20,7 +20,7 @@ namespace Bit.Core.Services public Task SaveAsync(string key, T obj) { - if(obj == null) + if (obj == null) { return RemoveAsync(key); } @@ -30,7 +30,7 @@ namespace Bit.Core.Services public Task RemoveAsync(string key) { - if(_dict.ContainsKey(key)) + if (_dict.ContainsKey(key)) { _dict.Remove(key); } diff --git a/src/Core/Services/LiteDbStorageService.cs b/src/Core/Services/LiteDbStorageService.cs index 767f456c1..6990e06fd 100644 --- a/src/Core/Services/LiteDbStorageService.cs +++ b/src/Core/Services/LiteDbStorageService.cs @@ -24,11 +24,11 @@ namespace Bit.Core.Services public Task InitAsync() { - if(_collection != null) + if (_collection != null) { return Task.FromResult(0); } - if(_initTask != null) + if (_initTask != null) { return _initTask; } @@ -51,7 +51,7 @@ namespace Bit.Core.Services { await InitAsync(); var item = _collection.Find(i => i.Id == key).FirstOrDefault(); - if(item == null) + if (item == null) { return default(T); } diff --git a/src/Core/Services/LockService.cs b/src/Core/Services/LockService.cs index a06b116b0..088143d69 100644 --- a/src/Core/Services/LockService.cs +++ b/src/Core/Services/LockService.cs @@ -48,10 +48,10 @@ namespace Bit.Core.Services public async Task IsLockedAsync() { var hasKey = await _cryptoService.HasKeyAsync(); - if(hasKey) + if (hasKey) { var fingerprintSet = await IsFingerprintLockSetAsync(); - if(fingerprintSet && FingerprintLocked) + if (fingerprintSet && FingerprintLocked) { return true; } @@ -61,35 +61,35 @@ namespace Bit.Core.Services public async Task CheckLockAsync() { - if(_platformUtilsService.IsViewOpen()) + if (_platformUtilsService.IsViewOpen()) { return; } var authed = await _userService.IsAuthenticatedAsync(); - if(!authed) + if (!authed) { return; } - if(await IsLockedAsync()) + if (await IsLockedAsync()) { return; } var lockOption = _platformUtilsService.LockTimeout(); - if(lockOption == null) + if (lockOption == null) { lockOption = await _storageService.GetAsync(Constants.LockOptionKey); } - if(lockOption.GetValueOrDefault(-1) < 0) + if (lockOption.GetValueOrDefault(-1) < 0) { return; } var lastActive = await _storageService.GetAsync(Constants.LastActiveKey); - if(lastActive == null) + if (lastActive == null) { return; } var diff = DateTime.UtcNow - lastActive.Value; - if(diff.TotalSeconds >= lockOption.Value) + if (diff.TotalSeconds >= lockOption.Value) { // need to lock now await LockAsync(true); @@ -99,14 +99,14 @@ namespace Bit.Core.Services public async Task LockAsync(bool allowSoftLock = false, bool userInitiated = false) { var authed = await _userService.IsAuthenticatedAsync(); - if(!authed) + if (!authed) { return; } - if(allowSoftLock) + if (allowSoftLock) { FingerprintLocked = await IsFingerprintLockSetAsync(); - if(FingerprintLocked) + if (FingerprintLocked) { _messagingService.Send("locked", userInitiated); _lockedCallback?.Invoke(userInitiated); diff --git a/src/Core/Services/PasswordGenerationService.cs b/src/Core/Services/PasswordGenerationService.cs index 9023265a6..3487b8d83 100644 --- a/src/Core/Services/PasswordGenerationService.cs +++ b/src/Core/Services/PasswordGenerationService.cs @@ -45,7 +45,7 @@ namespace Bit.Core.Services { // Overload defaults with given options options.Merge(_defaultOptions); - if(options.Type == "passphrase") + if (options.Type == "passphrase") { return await GeneratePassphraseAsync(options); } @@ -54,35 +54,35 @@ namespace Bit.Core.Services SanitizePasswordLength(options, true); var positionsBuilder = new StringBuilder(); - if(options.Lowercase.GetValueOrDefault() && options.MinLowercase.GetValueOrDefault() > 0) + if (options.Lowercase.GetValueOrDefault() && options.MinLowercase.GetValueOrDefault() > 0) { - for(int i = 0; i < options.MinLowercase.GetValueOrDefault(); i++) + for (int i = 0; i < options.MinLowercase.GetValueOrDefault(); i++) { positionsBuilder.Append("l"); } } - if(options.Uppercase.GetValueOrDefault() && options.MinUppercase.GetValueOrDefault() > 0) + if (options.Uppercase.GetValueOrDefault() && options.MinUppercase.GetValueOrDefault() > 0) { - for(int i = 0; i < options.MinUppercase.GetValueOrDefault(); i++) + for (int i = 0; i < options.MinUppercase.GetValueOrDefault(); i++) { positionsBuilder.Append("u"); } } - if(options.Number.GetValueOrDefault() && options.MinNumber.GetValueOrDefault() > 0) + if (options.Number.GetValueOrDefault() && options.MinNumber.GetValueOrDefault() > 0) { - for(int i = 0; i < options.MinNumber.GetValueOrDefault(); i++) + for (int i = 0; i < options.MinNumber.GetValueOrDefault(); i++) { positionsBuilder.Append("n"); } } - if(options.Special.GetValueOrDefault() && options.MinSpecial.GetValueOrDefault() > 0) + if (options.Special.GetValueOrDefault() && options.MinSpecial.GetValueOrDefault() > 0) { - for(int i = 0; i < options.MinSpecial.GetValueOrDefault(); i++) + for (int i = 0; i < options.MinSpecial.GetValueOrDefault(); i++) { positionsBuilder.Append("s"); } } - while(positionsBuilder.Length < options.Length.GetValueOrDefault()) + while (positionsBuilder.Length < options.Length.GetValueOrDefault()) { positionsBuilder.Append("a"); } @@ -94,46 +94,46 @@ namespace Bit.Core.Services // Build out other character sets var allCharSet = string.Empty; var lowercaseCharSet = LowercaseCharSet; - if(options.Ambiguous.GetValueOrDefault()) + if (options.Ambiguous.GetValueOrDefault()) { lowercaseCharSet = string.Concat(lowercaseCharSet, "l"); } - if(options.Lowercase.GetValueOrDefault()) + if (options.Lowercase.GetValueOrDefault()) { allCharSet = string.Concat(allCharSet, lowercaseCharSet); } var uppercaseCharSet = UppercaseCharSet; - if(options.Ambiguous.GetValueOrDefault()) + if (options.Ambiguous.GetValueOrDefault()) { uppercaseCharSet = string.Concat(uppercaseCharSet, "IO"); } - if(options.Uppercase.GetValueOrDefault()) + if (options.Uppercase.GetValueOrDefault()) { allCharSet = string.Concat(allCharSet, uppercaseCharSet); } var numberCharSet = NumberCharSet; - if(options.Ambiguous.GetValueOrDefault()) + if (options.Ambiguous.GetValueOrDefault()) { numberCharSet = string.Concat(numberCharSet, "01"); } - if(options.Number.GetValueOrDefault()) + if (options.Number.GetValueOrDefault()) { allCharSet = string.Concat(allCharSet, numberCharSet); } var specialCharSet = SpecialCharSet; - if(options.Special.GetValueOrDefault()) + if (options.Special.GetValueOrDefault()) { allCharSet = string.Concat(allCharSet, specialCharSet); } var password = new StringBuilder(); - for(var i = 0; i < options.Length.GetValueOrDefault(); i++) + for (var i = 0; i < options.Length.GetValueOrDefault(); i++) { var positionChars = string.Empty; - switch(positions[i]) + switch (positions[i]) { case 'l': positionChars = lowercaseCharSet; @@ -162,28 +162,28 @@ namespace Bit.Core.Services public async Task GeneratePassphraseAsync(PasswordGenerationOptions options) { options.Merge(_defaultOptions); - if(options.NumWords.GetValueOrDefault() <= 2) + if (options.NumWords.GetValueOrDefault() <= 2) { options.NumWords = _defaultOptions.NumWords; } - if(options.WordSeparator == null || options.WordSeparator.Length == 0 || options.WordSeparator.Length > 1) + if (options.WordSeparator == null || options.WordSeparator.Length == 0 || options.WordSeparator.Length > 1) { options.WordSeparator = " "; } - if(options.Capitalize == null) + if (options.Capitalize == null) { options.Capitalize = false; } - if(options.IncludeNumber == null) + if (options.IncludeNumber == null) { options.IncludeNumber = false; } var listLength = EEFLongWordList.Instance.List.Count - 1; var wordList = new List(); - for(int i = 0; i < options.NumWords.GetValueOrDefault(); i++) + for (int i = 0; i < options.NumWords.GetValueOrDefault(); i++) { var wordIndex = await _cryptoService.RandomNumberAsync(0, listLength); - if(options.Capitalize.GetValueOrDefault()) + if (options.Capitalize.GetValueOrDefault()) { wordList.Add(Capitalize(EEFLongWordList.Instance.List[wordIndex])); } @@ -192,7 +192,7 @@ namespace Bit.Core.Services wordList.Add(EEFLongWordList.Instance.List[wordIndex]); } } - if(options.IncludeNumber.GetValueOrDefault()) + if (options.IncludeNumber.GetValueOrDefault()) { await AppendRandomNumberToRandomWordAsync(wordList); } @@ -201,10 +201,10 @@ namespace Bit.Core.Services public async Task<(PasswordGenerationOptions, PasswordGeneratorPolicyOptions)> GetOptionsAsync() { - if(_optionsCache == null) + if (_optionsCache == null) { var options = await _storageService.GetAsync(Keys_Options); - if(options == null) + if (options == null) { _optionsCache = _defaultOptions; } @@ -225,66 +225,66 @@ namespace Bit.Core.Services EnforcePasswordGeneratorPoliciesOnOptionsAsync(PasswordGenerationOptions options) { var enforcedPolicyOptions = await GetPasswordGeneratorPolicyOptions(); - if(enforcedPolicyOptions != null) + if (enforcedPolicyOptions != null) { - if(options.Length < enforcedPolicyOptions.MinLength) + if (options.Length < enforcedPolicyOptions.MinLength) { options.Length = enforcedPolicyOptions.MinLength; } - if(enforcedPolicyOptions.UseUppercase) + if (enforcedPolicyOptions.UseUppercase) { options.Uppercase = true; } - if(enforcedPolicyOptions.UseLowercase) + if (enforcedPolicyOptions.UseLowercase) { options.Lowercase = true; } - if(enforcedPolicyOptions.UseNumbers) + if (enforcedPolicyOptions.UseNumbers) { options.Number = true; } - if(options.MinNumber < enforcedPolicyOptions.NumberCount) + if (options.MinNumber < enforcedPolicyOptions.NumberCount) { options.MinNumber = enforcedPolicyOptions.NumberCount; } - if(enforcedPolicyOptions.UseSpecial) + if (enforcedPolicyOptions.UseSpecial) { options.Special = true; } - if(options.MinSpecial < enforcedPolicyOptions.SpecialCount) + if (options.MinSpecial < enforcedPolicyOptions.SpecialCount) { options.MinSpecial = enforcedPolicyOptions.SpecialCount; } // Must normalize these fields because the receiving call expects all options to pass the current rules - if(options.MinSpecial + options.MinNumber > options.Length) + if (options.MinSpecial + options.MinNumber > options.Length) { options.MinSpecial = options.Length - options.MinNumber; } - if(options.NumWords < enforcedPolicyOptions.MinNumberOfWords) + if (options.NumWords < enforcedPolicyOptions.MinNumberOfWords) { options.NumWords = enforcedPolicyOptions.MinNumberOfWords; } - if(enforcedPolicyOptions.Capitalize) + if (enforcedPolicyOptions.Capitalize) { options.Capitalize = true; } - if(enforcedPolicyOptions.IncludeNumber) + if (enforcedPolicyOptions.IncludeNumber) { options.IncludeNumber = true; } // Force default type if password/passphrase selected via policy - if(enforcedPolicyOptions.DefaultType == "password" || enforcedPolicyOptions.DefaultType == "passphrase") + if (enforcedPolicyOptions.DefaultType == "password" || enforcedPolicyOptions.DefaultType == "passphrase") { options.Type = enforcedPolicyOptions.DefaultType; } @@ -303,85 +303,85 @@ namespace Bit.Core.Services var policies = await _policyService.GetAll(PolicyType.PasswordGenerator); PasswordGeneratorPolicyOptions enforcedOptions = null; - if(policies == null || !policies.Any()) + if (policies == null || !policies.Any()) { return enforcedOptions; } - foreach(var currentPolicy in policies) + foreach (var currentPolicy in policies) { - if(!currentPolicy.Enabled || currentPolicy.Data == null) + if (!currentPolicy.Enabled || currentPolicy.Data == null) { continue; } - if(enforcedOptions == null) + if (enforcedOptions == null) { enforcedOptions = new PasswordGeneratorPolicyOptions(); } var defaultType = GetPolicyString(currentPolicy, "defaultType"); - if(defaultType != null && enforcedOptions.DefaultType != "password") + if (defaultType != null && enforcedOptions.DefaultType != "password") { enforcedOptions.DefaultType = defaultType; } var minLength = GetPolicyInt(currentPolicy, "minLength"); - if(minLength != null && (int)(long)minLength > enforcedOptions.MinLength) + if (minLength != null && (int)(long)minLength > enforcedOptions.MinLength) { enforcedOptions.MinLength = (int)(long)minLength; } var useUpper = GetPolicyBool(currentPolicy, "useUpper"); - if(useUpper != null && (bool)useUpper) + if (useUpper != null && (bool)useUpper) { enforcedOptions.UseUppercase = true; } var useLower = GetPolicyBool(currentPolicy, "useLower"); - if(useLower != null && (bool)useLower) + if (useLower != null && (bool)useLower) { enforcedOptions.UseLowercase = true; } var useNumbers = GetPolicyBool(currentPolicy, "useNumbers"); - if(useNumbers != null && (bool)useNumbers) + if (useNumbers != null && (bool)useNumbers) { enforcedOptions.UseNumbers = true; } var minNumbers = GetPolicyInt(currentPolicy, "minNumbers"); - if(minNumbers != null && (int)(long)minNumbers > enforcedOptions.NumberCount) + if (minNumbers != null && (int)(long)minNumbers > enforcedOptions.NumberCount) { enforcedOptions.NumberCount = (int)(long)minNumbers; } var useSpecial = GetPolicyBool(currentPolicy, "useSpecial"); - if(useSpecial != null && (bool)useSpecial) + if (useSpecial != null && (bool)useSpecial) { enforcedOptions.UseSpecial = true; } var minSpecial = GetPolicyInt(currentPolicy, "minSpecial"); - if(minSpecial != null && (int)(long)minSpecial > enforcedOptions.SpecialCount) + if (minSpecial != null && (int)(long)minSpecial > enforcedOptions.SpecialCount) { enforcedOptions.SpecialCount = (int)(long)minSpecial; } var minNumberWords = GetPolicyInt(currentPolicy, "minNumberWords"); - if(minNumberWords != null && (int)(long)minNumberWords > enforcedOptions.MinNumberOfWords) + if (minNumberWords != null && (int)(long)minNumberWords > enforcedOptions.MinNumberOfWords) { enforcedOptions.MinNumberOfWords = (int)(long)minNumberWords; } var capitalize = GetPolicyBool(currentPolicy, "capitalize"); - if(capitalize != null && (bool)capitalize) + if (capitalize != null && (bool)capitalize) { enforcedOptions.Capitalize = true; } var includeNumber = GetPolicyBool(currentPolicy, "includeNumber"); - if(includeNumber != null && (bool)includeNumber) + if (includeNumber != null && (bool)includeNumber) { enforcedOptions.IncludeNumber = true; } @@ -392,10 +392,10 @@ namespace Bit.Core.Services private int? GetPolicyInt(Policy policy, string key) { - if(policy.Data.ContainsKey(key)) + if (policy.Data.ContainsKey(key)) { var value = policy.Data[key]; - if(value != null) + if (value != null) { return (int)(long)value; } @@ -405,10 +405,10 @@ namespace Bit.Core.Services private bool? GetPolicyBool(Policy policy, string key) { - if(policy.Data.ContainsKey(key)) + if (policy.Data.ContainsKey(key)) { var value = policy.Data[key]; - if(value != null) + if (value != null) { return (bool)value; } @@ -418,10 +418,10 @@ namespace Bit.Core.Services private string GetPolicyString(Policy policy, string key) { - if(policy.Data.ContainsKey(key)) + if (policy.Data.ContainsKey(key)) { var value = policy.Data[key]; - if(value != null) + if (value != null) { return (string)value; } @@ -438,11 +438,11 @@ namespace Bit.Core.Services public async Task> GetHistoryAsync() { var hasKey = await _cryptoService.HasKeyAsync(); - if(!hasKey) + if (!hasKey) { return new List(); } - if(_history == null) + if (_history == null) { var encrypted = await _storageService.GetAsync>(Keys_History); _history = await DecryptHistoryAsync(encrypted); @@ -453,20 +453,20 @@ namespace Bit.Core.Services public async Task AddHistoryAsync(string password, CancellationToken token = default(CancellationToken)) { var hasKey = await _cryptoService.HasKeyAsync(); - if(!hasKey) + if (!hasKey) { return; } var currentHistory = await GetHistoryAsync(); // Prevent duplicates - if(MatchesPrevious(password, currentHistory)) + if (MatchesPrevious(password, currentHistory)) { return; } token.ThrowIfCancellationRequested(); currentHistory.Insert(0, new GeneratedPasswordHistory { Password = password, Date = DateTime.UtcNow }); // Remove old items. - if(currentHistory.Count > MaxPasswordsInHistory) + if (currentHistory.Count > MaxPasswordsInHistory) { currentHistory.RemoveAt(currentHistory.Count - 1); } @@ -492,83 +492,83 @@ namespace Bit.Core.Services options.MinLowercase = 0; options.MinUppercase = 0; - if(!options.Uppercase.GetValueOrDefault() && !options.Lowercase.GetValueOrDefault() && + if (!options.Uppercase.GetValueOrDefault() && !options.Lowercase.GetValueOrDefault() && !options.Number.GetValueOrDefault() && !options.Special.GetValueOrDefault()) { options.Lowercase = true; } var length = options.Length.GetValueOrDefault(); - if(length < 5) + if (length < 5) { options.Length = 5; } - else if(length > 128) + else if (length > 128) { options.Length = 128; } - if(options.Length < enforcedPolicyOptions.MinLength) + if (options.Length < enforcedPolicyOptions.MinLength) { options.Length = enforcedPolicyOptions.MinLength; } - if(options.MinNumber == null) + if (options.MinNumber == null) { options.MinNumber = 0; } - else if(options.MinNumber > options.Length) + else if (options.MinNumber > options.Length) { options.MinNumber = options.Length; } - else if(options.MinNumber > 9) + else if (options.MinNumber > 9) { options.MinNumber = 9; } - if(options.MinNumber < enforcedPolicyOptions.NumberCount) + if (options.MinNumber < enforcedPolicyOptions.NumberCount) { options.MinNumber = enforcedPolicyOptions.NumberCount; } - if(options.MinSpecial == null) + if (options.MinSpecial == null) { options.MinSpecial = 0; } - else if(options.MinSpecial > options.Length) + else if (options.MinSpecial > options.Length) { options.MinSpecial = options.Length; } - else if(options.MinSpecial > 9) + else if (options.MinSpecial > 9) { options.MinSpecial = 9; } - if(options.MinSpecial < enforcedPolicyOptions.SpecialCount) + if (options.MinSpecial < enforcedPolicyOptions.SpecialCount) { options.MinSpecial = enforcedPolicyOptions.SpecialCount; } - if(options.MinSpecial + options.MinNumber > options.Length) + if (options.MinSpecial + options.MinNumber > options.Length) { options.MinSpecial = options.Length - options.MinNumber; } - if(options.NumWords == null || options.Length < 3) + if (options.NumWords == null || options.Length < 3) { options.NumWords = 3; } - else if(options.NumWords > 20) + else if (options.NumWords > 20) { options.NumWords = 20; } - if(options.NumWords < enforcedPolicyOptions.MinNumberOfWords) + if (options.NumWords < enforcedPolicyOptions.MinNumberOfWords) { options.NumWords = enforcedPolicyOptions.MinNumberOfWords; } - if(options.WordSeparator != null && options.WordSeparator.Length > 1) + if (options.WordSeparator != null && options.WordSeparator.Length > 1) { options.WordSeparator = options.WordSeparator[0].ToString(); } @@ -580,18 +580,18 @@ namespace Bit.Core.Services private async Task> EncryptHistoryAsync(List history) { - if(!history?.Any() ?? true) + if (!history?.Any() ?? true) { return new List(); } var tasks = history.Select(async item => { - if(item == null) + if (item == null) { return null; } var encrypted = await _cryptoService.EncryptAsync(item.Password); - if(encrypted == null) + if (encrypted == null) { return null; } @@ -607,7 +607,7 @@ namespace Bit.Core.Services private async Task> DecryptHistoryAsync(List history) { - if(!history?.Any() ?? true) + if (!history?.Any() ?? true) { return new List(); } @@ -626,7 +626,7 @@ namespace Bit.Core.Services private bool MatchesPrevious(string password, List history) { - if(!history?.Any() ?? true) + if (!history?.Any() ?? true) { return false; } @@ -640,7 +640,7 @@ namespace Bit.Core.Services private async Task AppendRandomNumberToRandomWordAsync(List wordList) { - if(wordList == null || wordList.Count <= 0) + if (wordList == null || wordList.Count <= 0) { return; } @@ -656,57 +656,57 @@ namespace Bit.Core.Services var minNumberCalc = options.MinNumber; var minSpecialCalc = options.MinNumber; - if(options.Uppercase.GetValueOrDefault() && options.MinUppercase.GetValueOrDefault() <= 0) + if (options.Uppercase.GetValueOrDefault() && options.MinUppercase.GetValueOrDefault() <= 0) { minUppercaseCalc = 1; } - else if(!options.Uppercase.GetValueOrDefault()) + else if (!options.Uppercase.GetValueOrDefault()) { minUppercaseCalc = 0; } - if(options.Lowercase.GetValueOrDefault() && options.MinLowercase.GetValueOrDefault() <= 0) + if (options.Lowercase.GetValueOrDefault() && options.MinLowercase.GetValueOrDefault() <= 0) { minLowercaseCalc = 1; } - else if(!options.Lowercase.GetValueOrDefault()) + else if (!options.Lowercase.GetValueOrDefault()) { minLowercaseCalc = 0; } - if(options.Number.GetValueOrDefault() && options.MinNumber.GetValueOrDefault() <= 0) + if (options.Number.GetValueOrDefault() && options.MinNumber.GetValueOrDefault() <= 0) { minNumberCalc = 1; } - else if(!options.Number.GetValueOrDefault()) + else if (!options.Number.GetValueOrDefault()) { minNumberCalc = 0; } - if(options.Special.GetValueOrDefault() && options.MinSpecial.GetValueOrDefault() <= 0) + if (options.Special.GetValueOrDefault() && options.MinSpecial.GetValueOrDefault() <= 0) { minSpecialCalc = 1; } - else if(!options.Special.GetValueOrDefault()) + else if (!options.Special.GetValueOrDefault()) { minSpecialCalc = 0; } // This should never happen but is a final safety net - if(options.Length.GetValueOrDefault() < 1) + if (options.Length.GetValueOrDefault() < 1) { options.Length = 10; } var minLength = minUppercaseCalc + minLowercaseCalc + minNumberCalc + minSpecialCalc; // Normalize and Generation both require this modification - if(options.Length < minLength) + if (options.Length < minLength) { options.Length = minLength; } // Apply other changes if the options object passed in is for generation - if(forGeneration) + if (forGeneration) { options.MinUppercase = minUppercaseCalc; options.MinLowercase = minLowercaseCalc; diff --git a/src/Core/Services/PclCryptoFunctionService.cs b/src/Core/Services/PclCryptoFunctionService.cs index d5c929ea1..503f4fe3e 100644 --- a/src/Core/Services/PclCryptoFunctionService.cs +++ b/src/Core/Services/PclCryptoFunctionService.cs @@ -36,7 +36,7 @@ namespace Bit.Core.Services public Task Pbkdf2Async(byte[] password, byte[] salt, CryptoHashAlgorithm algorithm, int iterations) { - if(algorithm != CryptoHashAlgorithm.Sha256 && algorithm != CryptoHashAlgorithm.Sha512) + if (algorithm != CryptoHashAlgorithm.Sha256 && algorithm != CryptoHashAlgorithm.Sha512) { throw new ArgumentException("Unsupported PBKDF2 algorithm."); } @@ -71,14 +71,14 @@ namespace Bit.Core.Services var mac1 = hasher.GetValueAndReset(); hasher.Append(b); var mac2 = hasher.GetValueAndReset(); - if(mac1.Length != mac2.Length) + if (mac1.Length != mac2.Length) { return false; } - for(int i = 0; i < mac2.Length; i++) + for (int i = 0; i < mac2.Length; i++) { - if(mac1[i] != mac2[i]) + if (mac1[i] != mac2[i]) { return false; } @@ -126,7 +126,7 @@ namespace Bit.Core.Services public Task> RsaGenerateKeyPairAsync(int length) { - if(length != 1024 && length != 2048 && length != 4096) + if (length != 1024 && length != 2048 && length != 4096) { throw new ArgumentException("Invalid key pair length."); } @@ -161,7 +161,7 @@ namespace Bit.Core.Services private HashAlgorithm ToHashAlgorithm(CryptoHashAlgorithm algorithm) { - switch(algorithm) + switch (algorithm) { case CryptoHashAlgorithm.Sha1: return HashAlgorithm.Sha1; @@ -178,7 +178,7 @@ namespace Bit.Core.Services private MacAlgorithm ToMacAlgorithm(CryptoHashAlgorithm algorithm) { - switch(algorithm) + switch (algorithm) { case CryptoHashAlgorithm.Sha1: return MacAlgorithm.HmacSha1; @@ -193,7 +193,7 @@ namespace Bit.Core.Services private AsymmetricAlgorithm ToAsymmetricAlgorithm(CryptoHashAlgorithm algorithm) { - switch(algorithm) + switch (algorithm) { case CryptoHashAlgorithm.Sha1: return AsymmetricAlgorithm.RsaOaepSha1; diff --git a/src/Core/Services/PolicyService.cs b/src/Core/Services/PolicyService.cs index f4f1bf041..4b3fd0881 100644 --- a/src/Core/Services/PolicyService.cs +++ b/src/Core/Services/PolicyService.cs @@ -32,19 +32,19 @@ namespace Bit.Core.Services public async Task> GetAll(PolicyType? type) { - if(_policyCache == null) + if (_policyCache == null) { var userId = await _userService.GetUserIdAsync(); var policies = await _storageService.GetAsync>( string.Format(Keys_PoliciesPrefix, userId)); - if(policies == null) + if (policies == null) { return null; } _policyCache = policies.Select(p => new Policy(policies[p.Key])); } - if(type != null) + if (type != null) { return _policyCache.Where(p => p.Type == type).ToList(); } diff --git a/src/Core/Services/SearchService.cs b/src/Core/Services/SearchService.cs index e448f58c2..1f5447474 100644 --- a/src/Core/Services/SearchService.cs +++ b/src/Core/Services/SearchService.cs @@ -38,27 +38,27 @@ namespace Bit.Core.Services List ciphers = null, CancellationToken ct = default(CancellationToken)) { var results = new List(); - if(query != null) + if (query != null) { query = query.Trim().ToLower(); } - if(query == string.Empty) + if (query == string.Empty) { query = null; } - if(ciphers == null) + if (ciphers == null) { ciphers = await _cipherService.GetAllDecryptedAsync(); } ct.ThrowIfCancellationRequested(); - if(filter != null) + if (filter != null) { ciphers = ciphers.Where(filter).ToList(); } ct.ThrowIfCancellationRequested(); - if(!IsSearchable(query)) + if (!IsSearchable(query)) { return ciphers; } @@ -75,19 +75,19 @@ namespace Bit.Core.Services return ciphers.Where(c => { ct.ThrowIfCancellationRequested(); - if(c.Name?.ToLower().Contains(query) ?? false) + if (c.Name?.ToLower().Contains(query) ?? false) { return true; } - if(query.Length >= 8 && c.Id.StartsWith(query)) + if (query.Length >= 8 && c.Id.StartsWith(query)) { return true; } - if(c.SubTitle?.ToLower().Contains(query) ?? false) + if (c.SubTitle?.ToLower().Contains(query) ?? false) { return true; } - if(c.Login?.Uri?.ToLower()?.Contains(query) ?? false) + if (c.Login?.Uri?.ToLower()?.Contains(query) ?? false) { return true; } diff --git a/src/Core/Services/SettingsService.cs b/src/Core/Services/SettingsService.cs index 8994ddd01..c0e776009 100644 --- a/src/Core/Services/SettingsService.cs +++ b/src/Core/Services/SettingsService.cs @@ -34,7 +34,7 @@ namespace Bit.Core.Services public async Task>> GetEquivalentDomainsAsync() { var settings = await GetSettingsAsync(); - if(settings != null && settings.ContainsKey(Keys_EquivalentDomains)) + if (settings != null && settings.ContainsKey(Keys_EquivalentDomains)) { var jArray = (settings[Keys_EquivalentDomains] as JArray); return jArray?.ToObject>>() ?? new List>(); @@ -57,7 +57,7 @@ namespace Bit.Core.Services private async Task> GetSettingsAsync() { - if(_settingsCache == null) + if (_settingsCache == null) { var userId = await _userService.GetUserIdAsync(); _settingsCache = await _storageService.GetAsync>( @@ -70,11 +70,11 @@ namespace Bit.Core.Services { var userId = await _userService.GetUserIdAsync(); var settings = await GetSettingsAsync(); - if(settings == null) + if (settings == null) { settings = new Dictionary(); } - if(settings.ContainsKey(key)) + if (settings.ContainsKey(key)) { settings[key] = value; } diff --git a/src/Core/Services/StateService.cs b/src/Core/Services/StateService.cs index c7096ec32..a40bd6fb7 100644 --- a/src/Core/Services/StateService.cs +++ b/src/Core/Services/StateService.cs @@ -15,7 +15,7 @@ namespace Bit.Core.Services public Task SaveAsync(string key, T obj) { - if(_state.ContainsKey(key)) + if (_state.ContainsKey(key)) { _state[key] = obj; } @@ -28,7 +28,7 @@ namespace Bit.Core.Services public Task RemoveAsync(string key) { - if(_state.ContainsKey(key)) + if (_state.ContainsKey(key)) { _state.Remove(key); } diff --git a/src/Core/Services/SyncService.cs b/src/Core/Services/SyncService.cs index 9a739d500..bd29b2c8c 100644 --- a/src/Core/Services/SyncService.cs +++ b/src/Core/Services/SyncService.cs @@ -57,7 +57,7 @@ namespace Bit.Core.Services public async Task GetLastSyncAsync() { var userId = await _userService.GetUserIdAsync(); - if(userId == null) + if (userId == null) { return null; } @@ -67,7 +67,7 @@ namespace Bit.Core.Services public async Task SetLastSyncAsync(DateTime date) { var userId = await _userService.GetUserIdAsync(); - if(userId == null) + if (userId == null) { return; } @@ -78,7 +78,7 @@ namespace Bit.Core.Services { SyncStarted(); var isAuthenticated = await _userService.IsAuthenticatedAsync(); - if(!isAuthenticated) + if (!isAuthenticated) { return SyncCompleted(false); } @@ -86,11 +86,11 @@ namespace Bit.Core.Services var needsSyncResult = await NeedsSyncingAsync(forceSync); var needsSync = needsSyncResult.Item1; var skipped = needsSyncResult.Item2; - if(skipped) + if (skipped) { return SyncCompleted(false); } - if(!needsSync) + if (!needsSync) { await SetLastSyncAsync(now); return SyncCompleted(false); @@ -110,7 +110,7 @@ namespace Bit.Core.Services } catch { - if(allowThrowOnError) + if (allowThrowOnError) { throw; } @@ -124,16 +124,16 @@ namespace Bit.Core.Services public async Task SyncUpsertFolderAsync(SyncFolderNotification notification, bool isEdit) { SyncStarted(); - if(await _userService.IsAuthenticatedAsync()) + if (await _userService.IsAuthenticatedAsync()) { try { var localFolder = await _folderService.GetAsync(notification.Id); - if((!isEdit && localFolder == null) || + if ((!isEdit && localFolder == null) || (isEdit && localFolder != null && localFolder.RevisionDate < notification.RevisionDate)) { var remoteFolder = await _apiService.GetFolderAsync(notification.Id); - if(remoteFolder != null) + if (remoteFolder != null) { var userId = await _userService.GetUserIdAsync(); await _folderService.UpsertAsync(new FolderData(remoteFolder, userId)); @@ -153,7 +153,7 @@ namespace Bit.Core.Services public async Task SyncDeleteFolderAsync(SyncFolderNotification notification) { SyncStarted(); - if(await _userService.IsAuthenticatedAsync()) + if (await _userService.IsAuthenticatedAsync()) { await _folderService.DeleteAsync(notification.Id); _messagingService.Send("syncedDeletedFolder", new Dictionary @@ -168,28 +168,28 @@ namespace Bit.Core.Services public async Task SyncUpsertCipherAsync(SyncCipherNotification notification, bool isEdit) { SyncStarted(); - if(await _userService.IsAuthenticatedAsync()) + if (await _userService.IsAuthenticatedAsync()) { try { var shouldUpdate = true; var localCipher = await _cipherService.GetAsync(notification.Id); - if(localCipher != null && localCipher.RevisionDate >= notification.RevisionDate) + if (localCipher != null && localCipher.RevisionDate >= notification.RevisionDate) { shouldUpdate = false; } var checkCollections = false; - if(shouldUpdate) + if (shouldUpdate) { - if(isEdit) + if (isEdit) { shouldUpdate = localCipher != null; checkCollections = true; } else { - if(notification.CollectionIds == null || notification.OrganizationId == null) + if (notification.CollectionIds == null || notification.OrganizationId == null) { shouldUpdate = localCipher == null; } @@ -201,15 +201,15 @@ namespace Bit.Core.Services } } - if(!shouldUpdate && checkCollections && notification.OrganizationId != null && + if (!shouldUpdate && checkCollections && notification.OrganizationId != null && notification.CollectionIds != null && notification.CollectionIds.Any()) { var collections = await _collectionService.GetAllAsync(); - if(collections != null) + if (collections != null) { - foreach(var c in collections) + foreach (var c in collections) { - if(notification.CollectionIds.Contains(c.Id)) + if (notification.CollectionIds.Contains(c.Id)) { shouldUpdate = true; break; @@ -218,10 +218,10 @@ namespace Bit.Core.Services } } - if(shouldUpdate) + if (shouldUpdate) { var remoteCipher = await _apiService.GetCipherAsync(notification.Id); - if(remoteCipher != null) + if (remoteCipher != null) { var userId = await _userService.GetUserIdAsync(); await _cipherService.UpsertAsync(new CipherData(remoteCipher, userId)); @@ -233,9 +233,9 @@ namespace Bit.Core.Services } } } - catch(ApiException e) + catch (ApiException e) { - if(e.Error != null && e.Error.StatusCode == System.Net.HttpStatusCode.NotFound && isEdit) + if (e.Error != null && e.Error.StatusCode == System.Net.HttpStatusCode.NotFound && isEdit) { await _cipherService.DeleteAsync(notification.Id); _messagingService.Send("syncedDeletedCipher", new Dictionary @@ -252,7 +252,7 @@ namespace Bit.Core.Services public async Task SyncDeleteCipherAsync(SyncCipherNotification notification) { SyncStarted(); - if(await _userService.IsAuthenticatedAsync()) + if (await _userService.IsAuthenticatedAsync()) { await _cipherService.DeleteAsync(notification.Id); _messagingService.Send("syncedDeletedCipher", new Dictionary @@ -281,12 +281,12 @@ namespace Bit.Core.Services private async Task> NeedsSyncingAsync(bool forceSync) { - if(forceSync) + if (forceSync) { return new Tuple(true, false); } var lastSync = await GetLastSyncAsync(); - if(lastSync == null || lastSync == DateTime.MinValue) + if (lastSync == null || lastSync == DateTime.MinValue) { return new Tuple(true, false); } @@ -294,7 +294,7 @@ namespace Bit.Core.Services { var response = await _apiService.GetAccountRevisionDateAsync(); var d = CoreHelpers.Epoc.AddMilliseconds(response); - if(d <= lastSync.Value) + if (d <= lastSync.Value) { return new Tuple(false, false); } @@ -309,9 +309,9 @@ namespace Bit.Core.Services private async Task SyncProfileAsync(ProfileResponse response) { var stamp = await _userService.GetSecurityStampAsync(); - if(stamp != null && stamp != response.SecurityStamp) + if (stamp != null && stamp != response.SecurityStamp) { - if(_logoutCallbackAsync != null) + if (_logoutCallbackAsync != null) { await _logoutCallbackAsync(true); } @@ -346,15 +346,15 @@ namespace Bit.Core.Services private async Task SyncSettingsAsync(string userId, DomainsResponse response) { var eqDomains = new List>(); - if(response != null && response.EquivalentDomains != null) + if (response != null && response.EquivalentDomains != null) { eqDomains = eqDomains.Concat(response.EquivalentDomains).ToList(); } - if(response != null && response.GlobalEquivalentDomains != null) + if (response != null && response.GlobalEquivalentDomains != null) { - foreach(var global in response.GlobalEquivalentDomains) + foreach (var global in response.GlobalEquivalentDomains) { - if(global.Domains.Any()) + if (global.Domains.Any()) { eqDomains.Add(global.Domains); } diff --git a/src/Core/Services/TokenService.cs b/src/Core/Services/TokenService.cs index 2597bb944..1ce9f0dd2 100644 --- a/src/Core/Services/TokenService.cs +++ b/src/Core/Services/TokenService.cs @@ -40,7 +40,7 @@ namespace Bit.Core.Services public async Task GetTokenAsync() { - if(_token != null) + if (_token != null) { return _token; } @@ -56,7 +56,7 @@ namespace Bit.Core.Services public async Task GetRefreshTokenAsync() { - if(_refreshToken != null) + if (_refreshToken != null) { return _refreshToken; } @@ -91,21 +91,21 @@ namespace Bit.Core.Services public JObject DecodeToken() { - if(_decodedToken != null) + if (_decodedToken != null) { return _decodedToken; } - if(_token == null) + if (_token == null) { throw new InvalidOperationException("Token not found."); } var parts = _token.Split('.'); - if(parts.Length != 3) + if (parts.Length != 3) { throw new InvalidOperationException("JWT must have 3 parts."); } var decodedBytes = Base64UrlDecode(parts[1]); - if(decodedBytes == null || decodedBytes.Length < 1) + if (decodedBytes == null || decodedBytes.Length < 1) { throw new InvalidOperationException("Cannot decode the token."); } @@ -116,7 +116,7 @@ namespace Bit.Core.Services public DateTime? GetTokenExpirationDate() { var decoded = DecodeToken(); - if(decoded?["exp"] == null) + if (decoded?["exp"] == null) { return null; } @@ -126,7 +126,7 @@ namespace Bit.Core.Services public int TokenSecondsRemaining() { var d = GetTokenExpirationDate(); - if(d == null) + if (d == null) { return 0; } @@ -143,7 +143,7 @@ namespace Bit.Core.Services public string GetUserId() { var decoded = DecodeToken(); - if(decoded?["sub"] == null) + if (decoded?["sub"] == null) { throw new Exception("No user id found."); } @@ -153,7 +153,7 @@ namespace Bit.Core.Services public string GetEmail() { var decoded = DecodeToken(); - if(decoded?["email"] == null) + if (decoded?["email"] == null) { throw new Exception("No email found."); } @@ -163,7 +163,7 @@ namespace Bit.Core.Services public bool GetEmailVerified() { var decoded = DecodeToken(); - if(decoded?["email_verified"] == null) + if (decoded?["email_verified"] == null) { throw new Exception("No email verification found."); } @@ -173,7 +173,7 @@ namespace Bit.Core.Services public string GetName() { var decoded = DecodeToken(); - if(decoded?["name"] == null) + if (decoded?["name"] == null) { return null; } @@ -183,7 +183,7 @@ namespace Bit.Core.Services public bool GetPremium() { var decoded = DecodeToken(); - if(decoded?["premium"] == null) + if (decoded?["premium"] == null) { return false; } @@ -193,7 +193,7 @@ namespace Bit.Core.Services public string GetIssuer() { var decoded = DecodeToken(); - if(decoded?["iss"] == null) + if (decoded?["iss"] == null) { throw new Exception("No issuer found."); } @@ -208,7 +208,7 @@ namespace Bit.Core.Services // 63rd char of encoding output = output.Replace('_', '/'); // Pad with trailing '='s - switch(output.Length % 4) + switch (output.Length % 4) { case 0: // No pad chars in this case diff --git a/src/Core/Services/TotpService.cs b/src/Core/Services/TotpService.cs index 21c006539..0cf4dce15 100644 --- a/src/Core/Services/TotpService.cs +++ b/src/Core/Services/TotpService.cs @@ -23,7 +23,7 @@ namespace Bit.Core.Services public async Task GetCodeAsync(string key) { - if(string.IsNullOrWhiteSpace(key)) + if (string.IsNullOrWhiteSpace(key)) { return null; } @@ -34,64 +34,64 @@ namespace Bit.Core.Services var isOtpAuth = key?.ToLowerInvariant().StartsWith("otpauth://") ?? false; var isSteamAuth = key?.ToLowerInvariant().StartsWith("steam://") ?? false; - if(isOtpAuth) + if (isOtpAuth) { var qsParams = CoreHelpers.GetQueryParams(key); - if(qsParams.ContainsKey("digits") && qsParams["digits"] != null && + if (qsParams.ContainsKey("digits") && qsParams["digits"] != null && int.TryParse(qsParams["digits"].Trim(), out var digitParam)) { - if(digitParam > 10) + if (digitParam > 10) { digits = 10; } - else if(digitParam > 0) + else if (digitParam > 0) { digits = digitParam; } } - if(qsParams.ContainsKey("period") && qsParams["period"] != null && + if (qsParams.ContainsKey("period") && qsParams["period"] != null && int.TryParse(qsParams["period"].Trim(), out var periodParam) && periodParam > 0) { period = periodParam; } - if(qsParams.ContainsKey("secret") && qsParams["secret"] != null) + if (qsParams.ContainsKey("secret") && qsParams["secret"] != null) { keyB32 = qsParams["secret"]; } - if(qsParams.ContainsKey("algorithm") && qsParams["algorithm"] != null) + if (qsParams.ContainsKey("algorithm") && qsParams["algorithm"] != null) { var algParam = qsParams["algorithm"].ToLowerInvariant(); - if(algParam == "sha256") + if (algParam == "sha256") { alg = CryptoHashAlgorithm.Sha256; } - else if(algParam == "sha512") + else if (algParam == "sha512") { alg = CryptoHashAlgorithm.Sha512; } } } - else if(isSteamAuth) + else if (isSteamAuth) { digits = 5; keyB32 = key.Substring(8); } var keyBytes = Base32.FromBase32(keyB32); - if(keyBytes == null || keyBytes.Length == 0) + if (keyBytes == null || keyBytes.Length == 0) { return null; } var now = CoreHelpers.EpocUtcNow() / 1000; var time = now / period; var timeBytes = BitConverter.GetBytes(time); - if(BitConverter.IsLittleEndian) + if (BitConverter.IsLittleEndian) { Array.Reverse(timeBytes, 0, timeBytes.Length); } var hash = await _cryptoFunctionService.HmacAsync(timeBytes, keyBytes, alg); - if(hash.Length == 0) + if (hash.Length == 0) { return null; } @@ -101,10 +101,10 @@ namespace Bit.Core.Services ((hash[offset + 2] & 0xff) << 8) | (hash[offset + 3] & 0xff); string otp = string.Empty; - if(isSteamAuth) + if (isSteamAuth) { var fullCode = binary & 0x7fffffff; - for(var i = 0; i < digits; i++) + for (var i = 0; i < digits; i++) { otp += SteamChars[fullCode % SteamChars.Length]; fullCode = (int)Math.Truncate(fullCode / (double)SteamChars.Length); @@ -121,10 +121,10 @@ namespace Bit.Core.Services public int GetTimeInterval(string key) { var period = 30; - if(key != null && key.ToLowerInvariant().StartsWith("otpauth://")) + if (key != null && key.ToLowerInvariant().StartsWith("otpauth://")) { var qsParams = CoreHelpers.GetQueryParams(key); - if(qsParams.ContainsKey("period") && qsParams["period"] != null && + if (qsParams.ContainsKey("period") && qsParams["period"] != null && int.TryParse(qsParams["period"].Trim(), out var periodParam) && periodParam > 0) { period = periodParam; diff --git a/src/Core/Services/UserService.cs b/src/Core/Services/UserService.cs index fc2597214..92e799671 100644 --- a/src/Core/Services/UserService.cs +++ b/src/Core/Services/UserService.cs @@ -53,7 +53,7 @@ namespace Bit.Core.Services public async Task GetUserIdAsync() { - if(_userId == null) + if (_userId == null) { _userId = await _storageService.GetAsync(Keys_UserId); } @@ -62,7 +62,7 @@ namespace Bit.Core.Services public async Task GetEmailAsync() { - if(_email == null) + if (_email == null) { _email = await _storageService.GetAsync(Keys_UserEmail); } @@ -71,7 +71,7 @@ namespace Bit.Core.Services public async Task GetSecurityStampAsync() { - if(_stamp == null) + if (_stamp == null) { _stamp = await _storageService.GetAsync(Keys_Stamp); } @@ -80,7 +80,7 @@ namespace Bit.Core.Services public async Task GetKdfAsync() { - if(_kdf == null) + if (_kdf == null) { _kdf = (KdfType?)(await _storageService.GetAsync(Keys_Kdf)); } @@ -89,7 +89,7 @@ namespace Bit.Core.Services public async Task GetKdfIterationsAsync() { - if(_kdfIterations == null) + if (_kdfIterations == null) { _kdfIterations = await _storageService.GetAsync(Keys_KdfIterations); } @@ -114,7 +114,7 @@ namespace Bit.Core.Services public async Task IsAuthenticatedAsync() { var token = await _tokenService.GetTokenAsync(); - if(token == null) + if (token == null) { return false; } @@ -125,7 +125,7 @@ namespace Bit.Core.Services public async Task CanAccessPremiumAsync() { var tokenPremium = _tokenService.GetPremium(); - if(tokenPremium) + if (tokenPremium) { return true; } @@ -138,7 +138,7 @@ namespace Bit.Core.Services var userId = await GetUserIdAsync(); var organizations = await _storageService.GetAsync>( string.Format(Keys_OrganizationsFormat, userId)); - if(organizations == null || !organizations.ContainsKey(id)) + if (organizations == null || !organizations.ContainsKey(id)) { return null; } diff --git a/src/Core/Utilities/Base32.cs b/src/Core/Utilities/Base32.cs index 310f026f1..04c8bf5cd 100644 --- a/src/Core/Utilities/Base32.cs +++ b/src/Core/Utilities/Base32.cs @@ -10,16 +10,16 @@ namespace Bit.Core.Utilities public static byte[] FromBase32(string input) { - if(input == null) + if (input == null) { throw new ArgumentNullException(nameof(input)); } input = input.ToUpperInvariant(); var cleanedInput = string.Empty; - foreach(var c in input) + foreach (var c in input) { - if(_base32Chars.IndexOf(c) < 0) + if (_base32Chars.IndexOf(c) < 0) { continue; } @@ -28,7 +28,7 @@ namespace Bit.Core.Utilities } input = cleanedInput; - if(input.Length == 0) + if (input.Length == 0) { return new byte[0]; } @@ -39,10 +39,10 @@ namespace Bit.Core.Utilities var outputBits = 0; var outputIndex = 0; - while(outputIndex < output.Length) + while (outputIndex < output.Length) { var byteIndex = _base32Chars.IndexOf(input[inputIndex]); - if(byteIndex < 0) + if (byteIndex < 0) { throw new FormatException(); } @@ -52,14 +52,14 @@ namespace Bit.Core.Utilities output[outputIndex] |= (byte)(byteIndex >> (5 - (bitIndex + bits))); bitIndex += bits; - if(bitIndex >= 5) + if (bitIndex >= 5) { inputIndex++; bitIndex = 0; } outputBits += bits; - if(outputBits >= 8) + if (outputBits >= 8) { outputIndex++; outputBits = 0; diff --git a/src/Core/Utilities/CoreHelpers.cs b/src/Core/Utilities/CoreHelpers.cs index c947e48eb..562733867 100644 --- a/src/Core/Utilities/CoreHelpers.cs +++ b/src/Core/Utilities/CoreHelpers.cs @@ -42,9 +42,9 @@ namespace Bit.Core.Utilities public static string GetHost(string uriString) { var uri = GetUri(uriString); - if(uri != null) + if (uri != null) { - if(uri.IsDefaultPort) + if (uri.IsDefaultPort) { return uri.Host; } @@ -59,18 +59,18 @@ namespace Bit.Core.Utilities public static string GetDomain(string uriString) { var uri = GetUri(uriString); - if(uri == null) + if (uri == null) { return null; } - if(uri.Host == "localhost" || Regex.IsMatch(uri.Host, IpRegex)) + if (uri.Host == "localhost" || Regex.IsMatch(uri.Host, IpRegex)) { return uri.Host; } try { - if(DomainName.TryParseBaseDomain(uri.Host, out var baseDomain)) + if (DomainName.TryParseBaseDomain(uri.Host, out var baseDomain)) { return baseDomain ?? uri.Host; } @@ -81,16 +81,16 @@ namespace Bit.Core.Utilities private static Uri GetUri(string uriString) { - if(string.IsNullOrWhiteSpace(uriString)) + if (string.IsNullOrWhiteSpace(uriString)) { return null; } var httpUrl = uriString.StartsWith("https://") || uriString.StartsWith("http://"); - if(!httpUrl && !uriString.Contains("://") && Regex.IsMatch(uriString, TldEndingRegex)) + if (!httpUrl && !uriString.Contains("://") && Regex.IsMatch(uriString, TldEndingRegex)) { uriString = "http://" + uriString; } - if(Uri.TryCreate(uriString, UriKind.Absolute, out var uri)) + if (Uri.TryCreate(uriString, UriKind.Absolute, out var uri)) { return uri; } @@ -100,20 +100,20 @@ namespace Bit.Core.Utilities public static void NestedTraverse(List> nodeTree, int partIndex, string[] parts, T obj, T parent, char delimiter) where T : ITreeNodeObject { - if(parts.Length <= partIndex) + if (parts.Length <= partIndex) { return; } var end = partIndex == parts.Length - 1; var partName = parts[partIndex]; - foreach(var n in nodeTree) + foreach (var n in nodeTree) { - if(n.Node.Name != parts[partIndex]) + if (n.Node.Name != parts[partIndex]) { continue; } - if(end && n.Node.Id != obj.Id) + if (end && n.Node.Id != obj.Id) { // Another node with the same name. nodeTree.Add(new TreeNode(obj, partName, parent)); @@ -122,9 +122,9 @@ namespace Bit.Core.Utilities NestedTraverse(n.Children, partIndex + 1, parts, obj, n.Node, delimiter); return; } - if(!nodeTree.Any(n => n.Node.Name == partName)) + if (!nodeTree.Any(n => n.Node.Name == partName)) { - if(end) + if (end) { nodeTree.Add(new TreeNode(obj, partName, parent)); return; @@ -139,16 +139,16 @@ namespace Bit.Core.Utilities public static TreeNode GetTreeNodeObject(List> nodeTree, string id) where T : ITreeNodeObject { - foreach(var n in nodeTree) + foreach (var n in nodeTree) { - if(n.Node.Id == id) + if (n.Node.Id == id) { return n; } - else if(n.Children != null) + else if (n.Children != null) { var node = GetTreeNodeObject(n.Children, id); - if(node != null) + if (node != null) { return node; } @@ -160,20 +160,20 @@ namespace Bit.Core.Utilities public static Dictionary GetQueryParams(string urlString) { var dict = new Dictionary(); - if(!Uri.TryCreate(urlString, UriKind.Absolute, out var uri) || string.IsNullOrWhiteSpace(uri.Query)) + if (!Uri.TryCreate(urlString, UriKind.Absolute, out var uri) || string.IsNullOrWhiteSpace(uri.Query)) { return dict; } var pairs = uri.Query.Substring(1).Split('&'); - foreach(var pair in pairs) + foreach (var pair in pairs) { var parts = pair.Split('='); - if(parts.Length < 1) + if (parts.Length < 1) { continue; } var key = System.Net.WebUtility.UrlDecode(parts[0]).ToLower(); - if(!dict.ContainsKey(key)) + if (!dict.ContainsKey(key)) { dict.Add(key, parts[1] == null ? string.Empty : System.Net.WebUtility.UrlDecode(parts[1])); } @@ -184,7 +184,7 @@ namespace Bit.Core.Utilities public static string SerializeJson(object obj, bool ignoreNulls = false) { var jsonSerializationSettings = new JsonSerializerSettings(); - if(ignoreNulls) + if (ignoreNulls) { jsonSerializationSettings.NullValueHandling = NullValueHandling.Ignore; } @@ -199,7 +199,7 @@ namespace Bit.Core.Utilities public static T DeserializeJson(string json, bool ignoreNulls = false) { var jsonSerializationSettings = new JsonSerializerSettings(); - if(ignoreNulls) + if (ignoreNulls) { jsonSerializationSettings.NullValueHandling = NullValueHandling.Ignore; } diff --git a/src/Core/Utilities/DomainName.cs b/src/Core/Utilities/DomainName.cs index 955d6d3e8..bbc155f04 100644 --- a/src/Core/Utilities/DomainName.cs +++ b/src/Core/Utilities/DomainName.cs @@ -76,7 +76,7 @@ namespace Bit.Core.Utilities MatchingRule = null; // If the fqdn is empty, we have a problem already - if(domainString.Trim() == string.Empty) + if (domainString.Trim() == string.Empty) { throw new ArgumentException("The domain cannot be blank"); } @@ -85,7 +85,7 @@ namespace Bit.Core.Utilities MatchingRule = FindMatchingTLDRule(domainString); // At this point, no rules match, we have a problem - if(MatchingRule == null) + if (MatchingRule == null) { throw new FormatException("The domain does not have a recognized TLD"); } @@ -95,7 +95,7 @@ namespace Bit.Core.Utilities var tldIndex = 0; // First, determine what type of rule we have, and set the TLD accordingly - switch(MatchingRule.Type) + switch (MatchingRule.Type) { case TLDRule.RuleType.Normal: tldIndex = domainString.LastIndexOf("." + MatchingRule.Name); @@ -125,13 +125,13 @@ namespace Bit.Core.Utilities // If we have 0 parts left, there is just a tld and no domain or subdomain // If we have 1 part, it's the domain, and there is no subdomain // If we have 2+ parts, the last part is the domain, the other parts (combined) are the subdomain - if(lstRemainingParts.Count > 0) + if (lstRemainingParts.Count > 0) { // Set the domain: SLD = lstRemainingParts[lstRemainingParts.Count - 1]; // Set the subdomain, if there is one to set: - if(lstRemainingParts.Count > 1) + if (lstRemainingParts.Count > 1) { // We strip off the trailing period, too SubDomain = tempSudomainAndDomain.Substring(0, tempSudomainAndDomain.Length - SLD.Length - 1); @@ -154,22 +154,22 @@ namespace Bit.Core.Utilities // Our 'matches' collection: var ruleMatches = new List(); - foreach(string domainPart in lstDomainParts) + foreach (string domainPart in lstDomainParts) { // Add on our next domain part: checkAgainst = string.Format("{0}.{1}", domainPart, checkAgainst); // If we end in a period, strip it off: - if(checkAgainst.EndsWith(".")) + if (checkAgainst.EndsWith(".")) { checkAgainst = checkAgainst.Substring(0, checkAgainst.Length - 1); } var rules = Enum.GetValues(typeof(TLDRule.RuleType)).Cast(); - foreach(var rule in rules) + foreach (var rule in rules) { // Try to match rule: - if(TLDRulesCache.Instance.TLDRuleLists[rule].TryGetValue(checkAgainst, out TLDRule result)) + if (TLDRulesCache.Instance.TLDRuleLists[rule].TryGetValue(checkAgainst, out TLDRule result)) { ruleMatches.Add(result); } @@ -185,7 +185,7 @@ namespace Bit.Core.Utilities // Take the top result (our primary match): TLDRule primaryMatch = results.Take(1).SingleOrDefault(); - if(primaryMatch != null) + if (primaryMatch != null) { //Debug.WriteLine(string.Format("Looks like our match is: {0}, which is a(n) {1} rule.", // primaryMatch.Name, primaryMatch.Type)); @@ -206,12 +206,12 @@ namespace Bit.Core.Utilities public TLDRule(string ruleInfo) { // Parse the rule and set properties accordingly: - if(ruleInfo.StartsWith("*")) + if (ruleInfo.StartsWith("*")) { Type = RuleType.Wildcard; Name = ruleInfo.Substring(2); } - else if(ruleInfo.StartsWith("!")) + else if (ruleInfo.StartsWith("!")) { Type = RuleType.Exception; Name = ruleInfo.Substring(1); @@ -225,7 +225,7 @@ namespace Bit.Core.Utilities public int CompareTo(TLDRule other) { - if(other == null) + if (other == null) { return -1; } @@ -258,11 +258,11 @@ namespace Bit.Core.Utilities { get { - if(_uniqueInstance == null) + if (_uniqueInstance == null) { - lock(_syncObj) + lock (_syncObj) { - if(_uniqueInstance == null) + if (_uniqueInstance == null) { _uniqueInstance = new TLDRulesCache(); } @@ -286,7 +286,7 @@ namespace Bit.Core.Utilities public static void Reset() { - lock(_syncObj) + lock (_syncObj) { _uniqueInstance = null; } @@ -296,7 +296,7 @@ namespace Bit.Core.Utilities { var results = new Dictionary>(); var rules = Enum.GetValues(typeof(TLDRule.RuleType)).Cast(); - foreach(var rule in rules) + foreach (var rule in rules) { results[rule] = new Dictionary(StringComparer.CurrentCultureIgnoreCase); } @@ -307,14 +307,14 @@ namespace Bit.Core.Utilities // b.) Blank var filteredRuleString = ruleStrings.Where(ruleString => !ruleString.StartsWith("//") && ruleString.Trim().Length != 0); - foreach(var ruleString in filteredRuleString) + foreach (var ruleString in filteredRuleString) { var result = new TLDRule(ruleString); results[result.Type][result.Name] = result; } // Return our results: - if(CoreHelpers.InDebugMode()) + if (CoreHelpers.InDebugMode()) { Debug.WriteLine(string.Format("Loaded {0} rules into cache.", results.Values.Sum(r => r.Values.Count))); @@ -327,9 +327,9 @@ namespace Bit.Core.Utilities var assembly = typeof(TLDRulesCache).GetTypeInfo().Assembly; var stream = assembly.GetManifestResourceStream("Bit.Core.Resources.public_suffix_list.dat"); string line; - using(var reader = new StreamReader(stream)) + using (var reader = new StreamReader(stream)) { - while((line = reader.ReadLine()) != null) + while ((line = reader.ReadLine()) != null) { yield return line; } diff --git a/src/Core/Utilities/EEFLongWordList.cs b/src/Core/Utilities/EEFLongWordList.cs index eb744c7b9..a01931beb 100644 --- a/src/Core/Utilities/EEFLongWordList.cs +++ b/src/Core/Utilities/EEFLongWordList.cs @@ -19,11 +19,11 @@ namespace Bit.Core.Utilities { get { - if(_uniqueInstance == null) + if (_uniqueInstance == null) { - lock(_syncObj) + lock (_syncObj) { - if(_uniqueInstance == null) + if (_uniqueInstance == null) { _uniqueInstance = new EEFLongWordList(); } @@ -40,9 +40,9 @@ namespace Bit.Core.Utilities var assembly = typeof(EEFLongWordList).GetTypeInfo().Assembly; var stream = assembly.GetManifestResourceStream("Bit.Core.Resources.eff_long_word_list.txt"); string line; - using(var reader = new StreamReader(stream)) + using (var reader = new StreamReader(stream)) { - while((line = reader.ReadLine()) != null) + while ((line = reader.ReadLine()) != null) { yield return line; } diff --git a/src/Core/Utilities/ExtendedObservableCollection.cs b/src/Core/Utilities/ExtendedObservableCollection.cs index a49f37bfe..69d0de5f8 100644 --- a/src/Core/Utilities/ExtendedObservableCollection.cs +++ b/src/Core/Utilities/ExtendedObservableCollection.cs @@ -18,7 +18,7 @@ namespace Bit.Core.Utilities public void AddRange(IEnumerable range) { - foreach(var item in range) + foreach (var item in range) { Items.Add(item); } @@ -32,10 +32,10 @@ namespace Bit.Core.Utilities { // Maybe a fix for https://forums.xamarin.com/discussion/19114/invalid-number-of-rows-in-section // Items.Clear(); - if(Items.Count > 0) + if (Items.Count > 0) { var count = Items.Count; - for(var i = 0; i < count; i++) + for (var i = 0; i < count; i++) { Items.RemoveAt(0); } diff --git a/src/Core/Utilities/ExtendedViewModel.cs b/src/Core/Utilities/ExtendedViewModel.cs index 123d502da..fd394ea34 100644 --- a/src/Core/Utilities/ExtendedViewModel.cs +++ b/src/Core/Utilities/ExtendedViewModel.cs @@ -12,7 +12,7 @@ namespace Bit.Core.Utilities protected bool SetProperty(ref T backingStore, T value, Action onChanged = null, [CallerMemberName]string propertyName = "", string[] additionalPropertyNames = null) { - if(EqualityComparer.Default.Equals(backingStore, value)) + if (EqualityComparer.Default.Equals(backingStore, value)) { return false; } @@ -26,9 +26,9 @@ namespace Bit.Core.Utilities protected void TriggerPropertyChanged(string propertyName, string[] additionalPropertyNames = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); - if(PropertyChanged != null && additionalPropertyNames != null) + if (PropertyChanged != null && additionalPropertyNames != null) { - foreach(var prop in additionalPropertyNames) + foreach (var prop in additionalPropertyNames) { PropertyChanged.Invoke(this, new PropertyChangedEventArgs(prop)); } diff --git a/src/Core/Utilities/ServiceContainer.cs b/src/Core/Utilities/ServiceContainer.cs index 10f2e58ef..c6a8938d7 100644 --- a/src/Core/Utilities/ServiceContainer.cs +++ b/src/Core/Utilities/ServiceContainer.cs @@ -13,7 +13,7 @@ namespace Bit.Core.Utilities public static void Init(string customUserAgent = null) { - if(Inited) + if (Inited) { return; } @@ -91,7 +91,7 @@ namespace Bit.Core.Utilities public static void Register(string serviceName, T obj) { - if(RegisteredServices.ContainsKey(serviceName)) + if (RegisteredServices.ContainsKey(serviceName)) { throw new Exception($"Service {serviceName} has already been registered."); } @@ -100,11 +100,11 @@ namespace Bit.Core.Utilities public static T Resolve(string serviceName, bool dontThrow = false) { - if(RegisteredServices.ContainsKey(serviceName)) + if (RegisteredServices.ContainsKey(serviceName)) { return (T)RegisteredServices[serviceName]; } - if(dontThrow) + if (dontThrow) { return (T)(object)null; } diff --git a/src/iOS.Autofill/CredentialProviderViewController.cs b/src/iOS.Autofill/CredentialProviderViewController.cs index 67ad2a47a..064ef5417 100644 --- a/src/iOS.Autofill/CredentialProviderViewController.cs +++ b/src/iOS.Autofill/CredentialProviderViewController.cs @@ -39,26 +39,26 @@ namespace Bit.iOS.Autofill { InitAppIfNeeded(); _context.ServiceIdentifiers = serviceIdentifiers; - if(serviceIdentifiers.Length > 0) + if (serviceIdentifiers.Length > 0) { var uri = serviceIdentifiers[0].Identifier; - if(serviceIdentifiers[0].Type == ASCredentialServiceIdentifierType.Domain) + if (serviceIdentifiers[0].Type == ASCredentialServiceIdentifierType.Domain) { uri = string.Concat("https://", uri); } _context.UrlString = uri; } - if(!CheckAuthed()) + if (!CheckAuthed()) { return; } - if(IsLocked()) + if (IsLocked()) { PerformSegue("lockPasswordSegue", this); } else { - if(_context.ServiceIdentifiers == null || _context.ServiceIdentifiers.Length == 0) + if (_context.ServiceIdentifiers == null || _context.ServiceIdentifiers.Length == 0) { PerformSegue("loginSearchSegue", this); } @@ -72,7 +72,7 @@ namespace Bit.iOS.Autofill public override void ProvideCredentialWithoutUserInteraction(ASPasswordCredentialIdentity credentialIdentity) { InitAppIfNeeded(); - if(!IsAuthed() || IsLocked()) + if (!IsAuthed() || IsLocked()) { var err = new NSError(new NSString("ASExtensionErrorDomain"), Convert.ToInt32(ASExtensionErrorCode.UserInteractionRequired), null); @@ -86,7 +86,7 @@ namespace Bit.iOS.Autofill public override void PrepareInterfaceToProvideCredential(ASPasswordCredentialIdentity credentialIdentity) { InitAppIfNeeded(); - if(!CheckAuthed()) + if (!CheckAuthed()) { return; } @@ -98,7 +98,7 @@ namespace Bit.iOS.Autofill { InitAppIfNeeded(); _context.Configuring = true; - if(!CheckAuthed()) + if (!CheckAuthed()) { return; } @@ -108,14 +108,14 @@ namespace Bit.iOS.Autofill public void CompleteRequest(string id = null, string username = null, string password = null, string totp = null) { - if((_context?.Configuring ?? true) && string.IsNullOrWhiteSpace(password)) + if ((_context?.Configuring ?? true) && string.IsNullOrWhiteSpace(password)) { ServiceContainer.Reset(); ExtensionContext?.CompleteExtensionConfigurationRequest(); return; } - if(_context == null || string.IsNullOrWhiteSpace(username) || string.IsNullOrWhiteSpace(password)) + if (_context == null || string.IsNullOrWhiteSpace(username) || string.IsNullOrWhiteSpace(password)) { ServiceContainer.Reset(); var err = new NSError(new NSString("ASExtensionErrorDomain"), @@ -124,7 +124,7 @@ namespace Bit.iOS.Autofill return; } - if(!string.IsNullOrWhiteSpace(totp)) + if (!string.IsNullOrWhiteSpace(totp)) { UIPasteboard.General.String = totp; } @@ -132,7 +132,7 @@ namespace Bit.iOS.Autofill var cred = new ASPasswordCredential(username, password); NSRunLoop.Main.BeginInvokeOnMainThread(async () => { - if(!string.IsNullOrWhiteSpace(id)) + if (!string.IsNullOrWhiteSpace(id)) { var eventService = ServiceContainer.Resolve("eventService"); await eventService.CollectAsync(Bit.Core.Enums.EventType.Cipher_ClientAutofilled, id); @@ -144,23 +144,23 @@ namespace Bit.iOS.Autofill public override void PrepareForSegue(UIStoryboardSegue segue, NSObject sender) { - if(segue.DestinationViewController is UINavigationController navController) + if (segue.DestinationViewController is UINavigationController navController) { - if(navController.TopViewController is LoginListViewController listLoginController) + if (navController.TopViewController is LoginListViewController listLoginController) { listLoginController.Context = _context; listLoginController.CPViewController = this; } - else if(navController.TopViewController is LoginSearchViewController listSearchController) + else if (navController.TopViewController is LoginSearchViewController listSearchController) { listSearchController.Context = _context; listSearchController.CPViewController = this; } - else if(navController.TopViewController is LockPasswordViewController passwordViewController) + else if (navController.TopViewController is LockPasswordViewController passwordViewController) { passwordViewController.CPViewController = this; } - else if(navController.TopViewController is SetupViewController setupViewController) + else if (navController.TopViewController is SetupViewController setupViewController) { setupViewController.CPViewController = this; } @@ -171,17 +171,17 @@ namespace Bit.iOS.Autofill { DismissViewController(false, async () => { - if(_context.CredentialIdentity != null) + if (_context.CredentialIdentity != null) { await ProvideCredentialAsync(); return; } - if(_context.Configuring) + if (_context.Configuring) { PerformSegue("setupSegue", this); return; } - if(_context.ServiceIdentifiers == null || _context.ServiceIdentifiers.Length == 0) + if (_context.ServiceIdentifiers == null || _context.ServiceIdentifiers.Length == 0) { PerformSegue("loginSearchSegue", this); } @@ -196,7 +196,7 @@ namespace Bit.iOS.Autofill { var cipherService = ServiceContainer.Resolve("cipherService", true); var cipher = await cipherService?.GetAsync(_context.CredentialIdentity.RecordIdentifier); - if(cipher == null || cipher.Type != Bit.Core.Enums.CipherType.Login) + if (cipher == null || cipher.Type != Bit.Core.Enums.CipherType.Login) { var err = new NSError(new NSString("ASExtensionErrorDomain"), Convert.ToInt32(ASExtensionErrorCode.CredentialIdentityNotFound), null); @@ -208,11 +208,11 @@ namespace Bit.iOS.Autofill var decCipher = await cipher.DecryptAsync(); string totpCode = null; var disableTotpCopy = await storageService.GetAsync(Bit.Core.Constants.DisableAutoTotpCopyKey); - if(!disableTotpCopy.GetValueOrDefault(false)) + if (!disableTotpCopy.GetValueOrDefault(false)) { var userService = ServiceContainer.Resolve("userService"); var canAccessPremiumAsync = await userService.CanAccessPremiumAsync(); - if(!string.IsNullOrWhiteSpace(decCipher.Login.Totp) && + if (!string.IsNullOrWhiteSpace(decCipher.Login.Totp) && (canAccessPremiumAsync || cipher.OrganizationUseTotp)) { var totpService = ServiceContainer.Resolve("totpService"); @@ -225,7 +225,7 @@ namespace Bit.iOS.Autofill private void CheckLock(Action notLockedAction) { - if(IsLocked()) + if (IsLocked()) { PerformSegue("lockPasswordSegue", this); } @@ -237,7 +237,7 @@ namespace Bit.iOS.Autofill private bool CheckAuthed() { - if(!IsAuthed()) + if (!IsAuthed()) { var alert = Dialogs.CreateAlert(null, AppResources.MustLogInMainAppAutofill, AppResources.Ok, (a) => { @@ -263,14 +263,14 @@ namespace Bit.iOS.Autofill private void InitApp() { - if(ServiceContainer.RegisteredServices.Count > 0) + if (ServiceContainer.RegisteredServices.Count > 0) { ServiceContainer.Reset(); } iOSCoreHelpers.RegisterLocalServices(); var deviceActionService = ServiceContainer.Resolve("deviceActionService"); ServiceContainer.Init(deviceActionService.DeviceUserAgent); - if(!_initedHockeyApp) + if (!_initedHockeyApp) { iOSCoreHelpers.RegisterHockeyApp(); _initedHockeyApp = true; @@ -281,7 +281,7 @@ namespace Bit.iOS.Autofill private void InitAppIfNeeded() { - if(ServiceContainer.RegisteredServices == null || ServiceContainer.RegisteredServices.Count == 0) + if (ServiceContainer.RegisteredServices == null || ServiceContainer.RegisteredServices.Count == 0) { InitApp(); } diff --git a/src/iOS.Autofill/LoginAddViewController.cs b/src/iOS.Autofill/LoginAddViewController.cs index 3d0f9e3c5..8e04326bb 100644 --- a/src/iOS.Autofill/LoginAddViewController.cs +++ b/src/iOS.Autofill/LoginAddViewController.cs @@ -35,9 +35,9 @@ namespace Bit.iOS.Autofill public override void PrepareForSegue(UIStoryboardSegue segue, NSObject sender) { - if(segue.DestinationViewController is UINavigationController navController) + if (segue.DestinationViewController is UINavigationController navController) { - if(navController.TopViewController is PasswordGeneratorViewController passwordGeneratorController) + if (navController.TopViewController is PasswordGeneratorViewController passwordGeneratorController) { passwordGeneratorController.PasswordOptions = Context.PasswordOptions; passwordGeneratorController.Parent = this; diff --git a/src/iOS.Autofill/LoginListViewController.cs b/src/iOS.Autofill/LoginListViewController.cs index e6d0d71fa..8c2207889 100644 --- a/src/iOS.Autofill/LoginListViewController.cs +++ b/src/iOS.Autofill/LoginListViewController.cs @@ -35,7 +35,7 @@ namespace Bit.iOS.Autofill var storageService = ServiceContainer.Resolve("storageService"); var needsAutofillReplacement = await storageService.GetAsync( Core.Constants.AutofillNeedsIdentityReplacementKey); - if(needsAutofillReplacement.GetValueOrDefault()) + if (needsAutofillReplacement.GetValueOrDefault()) { await ASHelpers.ReplaceAllIdentities(); } @@ -58,14 +58,14 @@ namespace Bit.iOS.Autofill public override void PrepareForSegue(UIStoryboardSegue segue, NSObject sender) { - if(segue.DestinationViewController is UINavigationController navController) + if (segue.DestinationViewController is UINavigationController navController) { - if(navController.TopViewController is LoginAddViewController addLoginController) + if (navController.TopViewController is LoginAddViewController addLoginController) { addLoginController.Context = Context; addLoginController.LoginListController = this; } - if(navController.TopViewController is LoginSearchViewController searchLoginController) + if (navController.TopViewController is LoginSearchViewController searchLoginController) { searchLoginController.Context = Context; searchLoginController.CPViewController = CPViewController; diff --git a/src/iOS.Autofill/LoginSearchViewController.cs b/src/iOS.Autofill/LoginSearchViewController.cs index cb3cb6577..78b28c84f 100644 --- a/src/iOS.Autofill/LoginSearchViewController.cs +++ b/src/iOS.Autofill/LoginSearchViewController.cs @@ -27,7 +27,7 @@ namespace Bit.iOS.Autofill CancelBarButton.Title = AppResources.Cancel; SearchBar.Placeholder = AppResources.Search; SearchBar.BackgroundColor = SearchBar.BarTintColor = ThemeHelpers.ListHeaderBackgroundColor; - if(!ThemeHelpers.LightTheme) + if (!ThemeHelpers.LightTheme) { SearchBar.KeyboardAppearance = UIKeyboardAppearance.Dark; } @@ -47,7 +47,7 @@ namespace Bit.iOS.Autofill partial void CancelBarButton_Activated(UIBarButtonItem sender) { - if(FromList) + if (FromList) { DismissViewController(true, null); } @@ -64,9 +64,9 @@ namespace Bit.iOS.Autofill public override void PrepareForSegue(UIStoryboardSegue segue, NSObject sender) { - if(segue.DestinationViewController is UINavigationController navController) + if (segue.DestinationViewController is UINavigationController navController) { - if(navController.TopViewController is LoginAddViewController addLoginController) + if (navController.TopViewController is LoginAddViewController addLoginController) { addLoginController.Context = Context; addLoginController.LoginSearchController = this; diff --git a/src/iOS.Autofill/Utilities/AutofillHelpers.cs b/src/iOS.Autofill/Utilities/AutofillHelpers.cs index 79866cd09..cc57e1905 100644 --- a/src/iOS.Autofill/Utilities/AutofillHelpers.cs +++ b/src/iOS.Autofill/Utilities/AutofillHelpers.cs @@ -19,28 +19,28 @@ namespace Bit.iOS.Autofill.Utilities tableView.DeselectRow(indexPath, true); tableView.EndEditing(true); - if(tableSource.Items == null || tableSource.Items.Count() == 0) + if (tableSource.Items == null || tableSource.Items.Count() == 0) { controller.PerformSegue(loginAddSegue, tableSource); return; } var item = tableSource.Items.ElementAt(indexPath.Row); - if(item == null) + if (item == null) { cpViewController.CompleteRequest(); return; } - if(!string.IsNullOrWhiteSpace(item.Username) && !string.IsNullOrWhiteSpace(item.Password)) + if (!string.IsNullOrWhiteSpace(item.Username) && !string.IsNullOrWhiteSpace(item.Password)) { string totp = null; var storageService = ServiceContainer.Resolve("storageService"); var disableTotpCopy = await storageService.GetAsync(Bit.Core.Constants.DisableAutoTotpCopyKey); - if(!disableTotpCopy.GetValueOrDefault(false)) + if (!disableTotpCopy.GetValueOrDefault(false)) { var userService = ServiceContainer.Resolve("userService"); var canAccessPremiumAsync = await userService.CanAccessPremiumAsync(); - if(!string.IsNullOrWhiteSpace(item.Totp) && + if (!string.IsNullOrWhiteSpace(item.Totp) && (canAccessPremiumAsync || item.CipherView.OrganizationUseTotp)) { var totpService = ServiceContainer.Resolve("totpService"); @@ -49,11 +49,11 @@ namespace Bit.iOS.Autofill.Utilities } cpViewController.CompleteRequest(item.Id, item.Username, item.Password, totp); } - else if(!string.IsNullOrWhiteSpace(item.Username) || !string.IsNullOrWhiteSpace(item.Password) || + else if (!string.IsNullOrWhiteSpace(item.Username) || !string.IsNullOrWhiteSpace(item.Password) || !string.IsNullOrWhiteSpace(item.Totp)) { var sheet = Dialogs.CreateActionSheet(item.Name, controller); - if(!string.IsNullOrWhiteSpace(item.Username)) + if (!string.IsNullOrWhiteSpace(item.Username)) { sheet.AddAction(UIAlertAction.Create(AppResources.CopyUsername, UIAlertActionStyle.Default, a => { @@ -67,7 +67,7 @@ namespace Bit.iOS.Autofill.Utilities })); } - if(!string.IsNullOrWhiteSpace(item.Password)) + if (!string.IsNullOrWhiteSpace(item.Password)) { sheet.AddAction(UIAlertAction.Create(AppResources.CopyPassword, UIAlertActionStyle.Default, a => { @@ -82,12 +82,12 @@ namespace Bit.iOS.Autofill.Utilities })); } - if(!string.IsNullOrWhiteSpace(item.Totp)) + if (!string.IsNullOrWhiteSpace(item.Totp)) { sheet.AddAction(UIAlertAction.Create(AppResources.CopyTotp, UIAlertActionStyle.Default, async a => { var totp = await tableSource.GetTotpAsync(item); - if(string.IsNullOrWhiteSpace(totp)) + if (string.IsNullOrWhiteSpace(totp)) { return; } diff --git a/src/iOS.Core/Controllers/ExtendedUITableViewCell.cs b/src/iOS.Core/Controllers/ExtendedUITableViewCell.cs index b7156c038..4c76d62c4 100644 --- a/src/iOS.Core/Controllers/ExtendedUITableViewCell.cs +++ b/src/iOS.Core/Controllers/ExtendedUITableViewCell.cs @@ -8,7 +8,7 @@ namespace Bit.iOS.Core.Controllers public ExtendedUITableViewCell() { BackgroundColor = ThemeHelpers.BackgroundColor; - if(!ThemeHelpers.LightTheme) + if (!ThemeHelpers.LightTheme) { SelectionStyle = UITableViewCellSelectionStyle.None; } @@ -18,7 +18,7 @@ namespace Bit.iOS.Core.Controllers : base(style, reusedId) { BackgroundColor = ThemeHelpers.BackgroundColor; - if(!ThemeHelpers.LightTheme) + if (!ThemeHelpers.LightTheme) { SelectionStyle = UITableViewCellSelectionStyle.None; } diff --git a/src/iOS.Core/Controllers/ExtendedUITableViewController.cs b/src/iOS.Core/Controllers/ExtendedUITableViewController.cs index afaa46ec9..8b491907d 100644 --- a/src/iOS.Core/Controllers/ExtendedUITableViewController.cs +++ b/src/iOS.Core/Controllers/ExtendedUITableViewController.cs @@ -22,16 +22,16 @@ namespace Bit.iOS.Core.Controllers public override void ViewDidLoad() { base.ViewDidLoad(); - if(View != null) + if (View != null) { View.BackgroundColor = ThemeHelpers.BackgroundColor; } - if(TableView != null) + if (TableView != null) { TableView.BackgroundColor = ThemeHelpers.BackgroundColor; TableView.SeparatorColor = ThemeHelpers.SeparatorColor; } - if(NavigationController?.NavigationBar != null) + if (NavigationController?.NavigationBar != null) { NavigationController.NavigationBar.BarTintColor = ThemeHelpers.NavBarBackgroundColor; NavigationController.NavigationBar.BackgroundColor = ThemeHelpers.NavBarBackgroundColor; diff --git a/src/iOS.Core/Controllers/ExtendedUITableViewSource.cs b/src/iOS.Core/Controllers/ExtendedUITableViewSource.cs index 5f1170d9c..c6cb79794 100644 --- a/src/iOS.Core/Controllers/ExtendedUITableViewSource.cs +++ b/src/iOS.Core/Controllers/ExtendedUITableViewSource.cs @@ -8,9 +8,9 @@ namespace Bit.iOS.Core.Views { public override void WillDisplayHeaderView(UITableView tableView, UIView headerView, nint section) { - if(headerView != null && headerView is UITableViewHeaderFooterView hv) + if (headerView != null && headerView is UITableViewHeaderFooterView hv) { - if(hv.TextLabel != null) + if (hv.TextLabel != null) { hv.TextLabel.TextColor = ThemeHelpers.MutedColor; } @@ -19,9 +19,9 @@ namespace Bit.iOS.Core.Views public override void WillDisplayFooterView(UITableView tableView, UIView footerView, nint section) { - if(footerView != null && footerView is UITableViewHeaderFooterView fv) + if (footerView != null && footerView is UITableViewHeaderFooterView fv) { - if(fv.TextLabel != null) + if (fv.TextLabel != null) { fv.TextLabel.TextColor = ThemeHelpers.MutedColor; } diff --git a/src/iOS.Core/Controllers/ExtendedUIViewController.cs b/src/iOS.Core/Controllers/ExtendedUIViewController.cs index 78bbef018..cf26ab478 100644 --- a/src/iOS.Core/Controllers/ExtendedUIViewController.cs +++ b/src/iOS.Core/Controllers/ExtendedUIViewController.cs @@ -22,11 +22,11 @@ namespace Bit.iOS.Core.Controllers public override void ViewDidLoad() { base.ViewDidLoad(); - if(View != null) + if (View != null) { View.BackgroundColor = ThemeHelpers.BackgroundColor; } - if(NavigationController?.NavigationBar != null) + if (NavigationController?.NavigationBar != null) { NavigationController.NavigationBar.BarTintColor = ThemeHelpers.NavBarBackgroundColor; NavigationController.NavigationBar.BackgroundColor = ThemeHelpers.NavBarBackgroundColor; diff --git a/src/iOS.Core/Controllers/LockPasswordViewController.cs b/src/iOS.Core/Controllers/LockPasswordViewController.cs index 5015f4f92..80029e700 100644 --- a/src/iOS.Core/Controllers/LockPasswordViewController.cs +++ b/src/iOS.Core/Controllers/LockPasswordViewController.cs @@ -68,7 +68,7 @@ namespace Bit.iOS.Core.Controllers CheckPasswordAsync().GetAwaiter().GetResult(); return true; }; - if(_pinLock) + if (_pinLock) { MasterPasswordCell.TextField.KeyboardType = UIKeyboardType.NumberPad; } @@ -80,7 +80,7 @@ namespace Bit.iOS.Core.Controllers base.ViewDidLoad(); - if(_fingerprintLock) + if (_fingerprintLock) { var tasks = Task.Run(async () => { @@ -93,7 +93,7 @@ namespace Bit.iOS.Core.Controllers public override void ViewDidAppear(bool animated) { base.ViewDidAppear(animated); - if(!_fingerprintLock) + if (!_fingerprintLock) { MasterPasswordCell.TextField.BecomeFirstResponder(); } @@ -101,7 +101,7 @@ namespace Bit.iOS.Core.Controllers protected async Task CheckPasswordAsync() { - if(string.IsNullOrWhiteSpace(MasterPasswordCell.TextField.Text)) + if (string.IsNullOrWhiteSpace(MasterPasswordCell.TextField.Text)) { var alert = Dialogs.CreateAlert(AppResources.AnErrorHasOccurred, string.Format(AppResources.ValidationFieldRequired, @@ -116,12 +116,12 @@ namespace Bit.iOS.Core.Controllers var kdfIterations = await _userService.GetKdfIterationsAsync(); var inputtedValue = MasterPasswordCell.TextField.Text; - if(_pinLock) + if (_pinLock) { var failed = true; try { - if(_pinSet.Item1) + if (_pinSet.Item1) { var key = await _cryptoService.MakeKeyFromPinAsync(inputtedValue, email, kdf.GetValueOrDefault(KdfType.PBKDF2_SHA256), kdfIterations.GetValueOrDefault(5000), @@ -130,7 +130,7 @@ namespace Bit.iOS.Core.Controllers var protectedPin = await _storageService.GetAsync(Bit.Core.Constants.ProtectedPin); var decPin = await _cryptoService.DecryptToUtf8Async(new CipherString(protectedPin), encKey); failed = decPin != inputtedValue; - if(!failed) + if (!failed) { await SetKeyAndContinueAsync(key); } @@ -147,10 +147,10 @@ namespace Bit.iOS.Core.Controllers { failed = true; } - if(failed) + if (failed) { _invalidPinAttempts++; - if(_invalidPinAttempts >= 5) + if (_invalidPinAttempts >= 5) { Cancel?.Invoke(); return; @@ -163,19 +163,19 @@ namespace Bit.iOS.Core.Controllers var key2 = await _cryptoService.MakeKeyAsync(inputtedValue, email, kdf, kdfIterations); var keyHash = await _cryptoService.HashPasswordAsync(inputtedValue, key2); var storedKeyHash = await _cryptoService.GetKeyHashAsync(); - if(storedKeyHash == null) + if (storedKeyHash == null) { var oldKey = await _secureStorageService.GetAsync("oldKey"); - if(key2.KeyB64 == oldKey) + if (key2.KeyB64 == oldKey) { await _secureStorageService.RemoveAsync("oldKey"); await _cryptoService.SetKeyHashAsync(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(Bit.Core.Constants.ProtectedPin); var encKey = await _cryptoService.GetEncKeyAsync(key2); @@ -196,7 +196,7 @@ namespace Bit.iOS.Core.Controllers private async Task SetKeyAndContinueAsync(SymmetricCryptoKey key) { var hasKey = await _cryptoService.HasKeyAsync(); - if(!hasKey) + if (!hasKey) { await _cryptoService.SetKeyAsync(key); } @@ -212,7 +212,7 @@ namespace Bit.iOS.Core.Controllers public async Task PromptFingerprintAsync() { - if(!_fingerprintLock) + if (!_fingerprintLock) { return; } @@ -220,7 +220,7 @@ namespace Bit.iOS.Core.Controllers _pinLock ? AppResources.PIN : AppResources.MasterPassword, () => MasterPasswordCell.TextField.BecomeFirstResponder()); _lockService.FingerprintLocked = !success; - if(success) + if (success) { DoContinue(); } @@ -250,16 +250,16 @@ namespace Bit.iOS.Core.Controllers public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath) { - if(indexPath.Section == 0) + if (indexPath.Section == 0) { - if(indexPath.Row == 0) + if (indexPath.Row == 0) { return _controller.MasterPasswordCell; } } - else if(indexPath.Section == 1) + else if (indexPath.Section == 1) { - if(indexPath.Row == 0) + if (indexPath.Row == 0) { var fingerprintButtonText = _controller._deviceActionService.SupportsFaceBiometric() ? AppResources.UseFaceIDToUnlock : AppResources.UseFingerprintToUnlock; @@ -284,7 +284,7 @@ namespace Bit.iOS.Core.Controllers public override nint RowsInSection(UITableView tableview, nint section) { - if(section <= 1) + if (section <= 1) { return 1; } @@ -305,17 +305,17 @@ namespace Bit.iOS.Core.Controllers { tableView.DeselectRow(indexPath, true); tableView.EndEditing(true); - if(indexPath.Section == 1 && indexPath.Row == 0) + if (indexPath.Section == 1 && indexPath.Row == 0) { var task = _controller.PromptFingerprintAsync(); return; } var cell = tableView.CellAt(indexPath); - if(cell == null) + if (cell == null) { return; } - if(cell is ISelectable selectableCell) + if (cell is ISelectable selectableCell) { selectableCell.Select(); } diff --git a/src/iOS.Core/Controllers/LoginAddViewController.cs b/src/iOS.Core/Controllers/LoginAddViewController.cs index 647fe74a0..2274aa37d 100644 --- a/src/iOS.Core/Controllers/LoginAddViewController.cs +++ b/src/iOS.Core/Controllers/LoginAddViewController.cs @@ -116,21 +116,21 @@ namespace Bit.iOS.Core.Controllers protected async Task SaveAsync() { /* - if(!_connectivity.IsConnected) + if (!_connectivity.IsConnected) { AlertNoConnection(); return; } */ - if(string.IsNullOrWhiteSpace(PasswordCell?.TextField?.Text)) + if (string.IsNullOrWhiteSpace(PasswordCell?.TextField?.Text)) { DisplayAlert(AppResources.AnErrorHasOccurred, string.Format(AppResources.ValidationFieldRequired, AppResources.Password), AppResources.Ok); return; } - if(string.IsNullOrWhiteSpace(NameCell?.TextField?.Text)) + if (string.IsNullOrWhiteSpace(NameCell?.TextField?.Text)) { DisplayAlert(AppResources.AnErrorHasOccurred, string.Format(AppResources.ValidationFieldRequired, AppResources.Name), AppResources.Ok); @@ -155,7 +155,7 @@ namespace Bit.iOS.Core.Controllers } }; - if(!string.IsNullOrWhiteSpace(UriCell?.TextField?.Text)) + if (!string.IsNullOrWhiteSpace(UriCell?.TextField?.Text)) { cipher.Login.Uris = new List { @@ -174,10 +174,10 @@ namespace Bit.iOS.Core.Controllers await _cipherService.SaveWithServerAsync(cipherDomain); await loadingAlert.DismissViewControllerAsync(true); await _storageService.SaveAsync(Bit.Core.Constants.ClearCiphersCacheKey, true); - if(await ASHelpers.IdentitiesCanIncremental()) + if (await ASHelpers.IdentitiesCanIncremental()) { var identity = await ASHelpers.GetCipherIdentityAsync(cipherDomain.Id); - if(identity != null) + if (identity != null) { await ASCredentialIdentityStore.SharedStore.SaveCredentialIdentitiesAsync( new ASPasswordCredentialIdentity[] { identity }); @@ -189,9 +189,9 @@ namespace Bit.iOS.Core.Controllers } Success(cipherDomain.Id); } - catch(ApiException e) + catch (ApiException e) { - if(e?.Error != null) + if (e?.Error != null) { DisplayAlert(AppResources.AnErrorHasOccurred, e.Error.GetSingleMessage(), AppResources.Ok); } @@ -221,41 +221,41 @@ namespace Bit.iOS.Core.Controllers public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath) { - if(indexPath.Section == 0) + if (indexPath.Section == 0) { - if(indexPath.Row == 0) + if (indexPath.Row == 0) { return _controller.NameCell; } - else if(indexPath.Row == 1) + else if (indexPath.Row == 1) { return _controller.UsernameCell; } - else if(indexPath.Row == 2) + else if (indexPath.Row == 2) { return _controller.PasswordCell; } - else if(indexPath.Row == 3) + else if (indexPath.Row == 3) { return _controller.GeneratePasswordCell; } } - else if(indexPath.Section == 1) + else if (indexPath.Section == 1) { return _controller.UriCell; } - else if(indexPath.Section == 2) + else if (indexPath.Section == 2) { - if(indexPath.Row == 0) + if (indexPath.Row == 0) { return _controller.FolderCell; } - else if(indexPath.Row == 1) + else if (indexPath.Row == 1) { return _controller.FavoriteCell; } } - else if(indexPath.Section == 3) + else if (indexPath.Section == 3) { return _controller.NotesCell; } @@ -275,15 +275,15 @@ namespace Bit.iOS.Core.Controllers public override nint RowsInSection(UITableView tableview, nint section) { - if(section == 0) + if (section == 0) { return 4; } - else if(section == 1) + else if (section == 1) { return 1; } - else if(section == 2) + else if (section == 2) { return 2; } @@ -300,11 +300,11 @@ namespace Bit.iOS.Core.Controllers public override string TitleForHeader(UITableView tableView, nint section) { - if(section == 0) + if (section == 0) { return AppResources.ItemInformation; } - else if(section == 3) + else if (section == 3) { return AppResources.Notes; } @@ -317,19 +317,19 @@ namespace Bit.iOS.Core.Controllers tableView.DeselectRow(indexPath, true); tableView.EndEditing(true); - if(indexPath.Section == 0 && indexPath.Row == 3) + if (indexPath.Section == 0 && indexPath.Row == 3) { _controller.PerformSegue("passwordGeneratorSegue", this); } var cell = tableView.CellAt(indexPath); - if(cell == null) + if (cell == null) { return; } var selectableCell = cell as ISelectable; - if(selectableCell != null) + if (selectableCell != null) { selectableCell.Select(); } diff --git a/src/iOS.Core/Controllers/PasswordGeneratorViewController.cs b/src/iOS.Core/Controllers/PasswordGeneratorViewController.cs index 16222c5b6..f420bd173 100644 --- a/src/iOS.Core/Controllers/PasswordGeneratorViewController.cs +++ b/src/iOS.Core/Controllers/PasswordGeneratorViewController.cs @@ -56,12 +56,12 @@ namespace Bit.iOS.Core.Controllers BasePasswordLabel.TextColor = ThemeHelpers.TextColor; var controller = ChildViewControllers.LastOrDefault(); - if(controller != null) + if (controller != null) { OptionsTableViewController = controller as UITableViewController; } - if(OptionsTableViewController != null) + if (OptionsTableViewController != null) { OptionsTableViewController.TableView.RowHeight = UITableView.AutomaticDimension; OptionsTableViewController.TableView.EstimatedRowHeight = 70; @@ -89,14 +89,14 @@ namespace Bit.iOS.Core.Controllers LengthCell.ValueChanged += Options_ValueChanged; // Adjust based on context password options - if(PasswordOptions != null) + if (PasswordOptions != null) { - if(PasswordOptions.RequireDigits) + if (PasswordOptions.RequireDigits) { NumbersCell.Switch.On = true; NumbersCell.Switch.Enabled = false; - if(MinNumbersCell.Value < 1) + if (MinNumbersCell.Value < 1) { MinNumbersCell.Value = 1; } @@ -104,12 +104,12 @@ namespace Bit.iOS.Core.Controllers MinNumbersCell.Stepper.MinimumValue = 1; } - if(PasswordOptions.RequireSymbols) + if (PasswordOptions.RequireSymbols) { SpecialCell.Switch.On = true; SpecialCell.Switch.Enabled = false; - if(MinSpecialCell.Value < 1) + if (MinSpecialCell.Value < 1) { MinSpecialCell.Value = 1; } @@ -117,11 +117,11 @@ namespace Bit.iOS.Core.Controllers MinSpecialCell.Stepper.MinimumValue = 1; } - if(PasswordOptions.MinLength < PasswordOptions.MaxLength) + if (PasswordOptions.MinLength < PasswordOptions.MaxLength) { - if(PasswordOptions.MinLength > 0 && PasswordOptions.MinLength > LengthCell.Slider.MinValue) + if (PasswordOptions.MinLength > 0 && PasswordOptions.MinLength > LengthCell.Slider.MinValue) { - if(LengthCell.Value < PasswordOptions.MinLength) + if (LengthCell.Value < PasswordOptions.MinLength) { LengthCell.Slider.Value = PasswordOptions.MinLength; } @@ -129,9 +129,9 @@ namespace Bit.iOS.Core.Controllers LengthCell.Slider.MinValue = PasswordOptions.MinLength; } - if(PasswordOptions.MaxLength > 5 && PasswordOptions.MaxLength < LengthCell.Slider.MaxValue) + if (PasswordOptions.MaxLength > 5 && PasswordOptions.MaxLength < LengthCell.Slider.MaxValue) { - if(LengthCell.Value > PasswordOptions.MaxLength) + if (LengthCell.Value > PasswordOptions.MaxLength) { LengthCell.Slider.Value = PasswordOptions.MaxLength; } @@ -147,7 +147,7 @@ namespace Bit.iOS.Core.Controllers private void Options_ValueChanged(object sender, EventArgs e) { - if(InvalidState()) + if (InvalidState()) { LowercaseCell.Switch.On = true; } @@ -186,46 +186,46 @@ namespace Bit.iOS.Core.Controllers public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath) { - if(indexPath.Section == 0) + if (indexPath.Section == 0) { var cell = new ExtendedUITableViewCell(); cell.TextLabel.TextColor = ThemeHelpers.PrimaryColor; - if(indexPath.Row == 0) + if (indexPath.Row == 0) { cell.TextLabel.Text = AppResources.RegeneratePassword; } - else if(indexPath.Row == 1) + else if (indexPath.Row == 1) { cell.TextLabel.Text = AppResources.CopyPassword; } return cell; } - if(indexPath.Row == 0) + if (indexPath.Row == 0) { return _controller.LengthCell; } - else if(indexPath.Row == 1) + else if (indexPath.Row == 1) { return _controller.UppercaseCell; } - else if(indexPath.Row == 2) + else if (indexPath.Row == 2) { return _controller.LowercaseCell; } - else if(indexPath.Row == 3) + else if (indexPath.Row == 3) { return _controller.NumbersCell; } - else if(indexPath.Row == 4) + else if (indexPath.Row == 4) { return _controller.SpecialCell; } - else if(indexPath.Row == 5) + else if (indexPath.Row == 5) { return _controller.MinNumbersCell; } - else if(indexPath.Row == 6) + else if (indexPath.Row == 6) { return _controller.MinSpecialCell; } @@ -245,7 +245,7 @@ namespace Bit.iOS.Core.Controllers public override nint RowsInSection(UITableView tableview, nint section) { - if(section == 0) + if (section == 0) { return 2; } @@ -255,7 +255,7 @@ namespace Bit.iOS.Core.Controllers public override nfloat GetHeightForHeader(UITableView tableView, nint section) { - if(section == 0) + if (section == 0) { return 0.00001f; } @@ -265,7 +265,7 @@ namespace Bit.iOS.Core.Controllers public override UIView GetViewForHeader(UITableView tableView, nint section) { - if(section == 0) + if (section == 0) { return new UIView(CGRect.Empty) { @@ -278,7 +278,7 @@ namespace Bit.iOS.Core.Controllers public override string TitleForHeader(UITableView tableView, nint section) { - if(section == 1) + if (section == 1) { return AppResources.Options; } @@ -288,7 +288,7 @@ namespace Bit.iOS.Core.Controllers public override string TitleForFooter(UITableView tableView, nint section) { - if(section == 1) + if (section == 1) { return AppResources.OptionDefaults; } @@ -298,13 +298,13 @@ namespace Bit.iOS.Core.Controllers public override void RowSelected(UITableView tableView, NSIndexPath indexPath) { - if(indexPath.Section == 0) + if (indexPath.Section == 0) { - if(indexPath.Row == 0) + if (indexPath.Row == 0) { var task = _controller.GeneratePasswordAsync(); } - else if(indexPath.Row == 1) + else if (indexPath.Row == 1) { UIPasteboard clipboard = UIPasteboard.General; clipboard.String = _controller.BasePasswordLabel.Text; diff --git a/src/iOS.Core/Models/AppExtensionContext.cs b/src/iOS.Core/Models/AppExtensionContext.cs index 7b288e18e..439979d96 100644 --- a/src/iOS.Core/Models/AppExtensionContext.cs +++ b/src/iOS.Core/Models/AppExtensionContext.cs @@ -10,7 +10,7 @@ namespace Bit.iOS.Core.Models { get { - if(string.IsNullOrWhiteSpace(UrlString) || !Uri.TryCreate(UrlString, UriKind.Absolute, out Uri uri)) + if (string.IsNullOrWhiteSpace(UrlString) || !Uri.TryCreate(UrlString, UriKind.Absolute, out Uri uri)) { return null; } @@ -27,18 +27,18 @@ namespace Bit.iOS.Core.Models set { _uriString = value; - if(string.IsNullOrWhiteSpace(_uriString)) + if (string.IsNullOrWhiteSpace(_uriString)) { return; } - if(!_uriString.StartsWith(Bit.Core.Constants.iOSAppProtocol) && _uriString.Contains(".")) + if (!_uriString.StartsWith(Bit.Core.Constants.iOSAppProtocol) && _uriString.Contains(".")) { - if(!_uriString.Contains("://") && !_uriString.Contains(" ")) + if (!_uriString.Contains("://") && !_uriString.Contains(" ")) { _uriString = string.Concat("http://", _uriString); } } - if(!_uriString.StartsWith("http") && !_uriString.StartsWith(Bit.Core.Constants.iOSAppProtocol)) + if (!_uriString.StartsWith("http") && !_uriString.StartsWith(Bit.Core.Constants.iOSAppProtocol)) { _uriString = string.Concat(Bit.Core.Constants.iOSAppProtocol, _uriString); } diff --git a/src/iOS.Core/Models/FillScript.cs b/src/iOS.Core/Models/FillScript.cs index 4353e1a16..af4d0611e 100644 --- a/src/iOS.Core/Models/FillScript.cs +++ b/src/iOS.Core/Models/FillScript.cs @@ -14,7 +14,7 @@ namespace Bit.iOS.Core.Models public FillScript(PageDetails pageDetails, string fillUsername, string fillPassword, List> fillFields) { - if(pageDetails == null) + if (pageDetails == null) { return; } @@ -23,18 +23,18 @@ namespace Bit.iOS.Core.Models var filledFields = new Dictionary(); - if(fillFields?.Any() ?? false) + if (fillFields?.Any() ?? false) { var fieldNames = fillFields.Select(f => f.Item1?.ToLower()).ToArray(); - foreach(var field in pageDetails.Fields.Where(f => f.Viewable)) + foreach (var field in pageDetails.Fields.Where(f => f.Viewable)) { - if(filledFields.ContainsKey(field.OpId)) + if (filledFields.ContainsKey(field.OpId)) { continue; } var matchingIndex = FindMatchingFieldIndex(field, fieldNames); - if(matchingIndex > -1) + if (matchingIndex > -1) { filledFields.Add(field.OpId, field); Script.Add(new List { "click_on_opid", field.OpId }); @@ -43,7 +43,7 @@ namespace Bit.iOS.Core.Models } } - if(string.IsNullOrWhiteSpace(fillPassword)) + if (string.IsNullOrWhiteSpace(fillPassword)) { // No password for this login. Maybe they just wanted to auto-fill some custom fields? SetFillScriptForFocus(filledFields); @@ -54,39 +54,39 @@ namespace Bit.iOS.Core.Models List passwords = new List(); var passwordFields = pageDetails.Fields.Where(f => f.Type == "password" && f.Viewable).ToArray(); - if(!passwordFields.Any()) + if (!passwordFields.Any()) { // not able to find any viewable password fields. maybe there are some "hidden" ones? passwordFields = pageDetails.Fields.Where(f => f.Type == "password").ToArray(); } - foreach(var form in pageDetails.Forms) + foreach (var form in pageDetails.Forms) { var passwordFieldsForForm = passwordFields.Where(f => f.Form == form.Key).ToArray(); passwords.AddRange(passwordFieldsForForm); - if(string.IsNullOrWhiteSpace(fillUsername)) + if (string.IsNullOrWhiteSpace(fillUsername)) { continue; } - foreach(var pf in passwordFieldsForForm) + foreach (var pf in passwordFieldsForForm) { var username = FindUsernameField(pageDetails, pf, false, true); - if(username == null) + if (username == null) { // not able to find any viewable username fields. maybe there are some "hidden" ones? username = FindUsernameField(pageDetails, pf, true, true); } - if(username != null) + if (username != null) { usernames.Add(username); } } } - if(passwordFields.Any() && !passwords.Any()) + if (passwordFields.Any() && !passwords.Any()) { // The page does not have any forms with password fields. Use the first password field on the page and the // input field just before it as the username. @@ -94,29 +94,29 @@ namespace Bit.iOS.Core.Models var pf = passwordFields.First(); passwords.Add(pf); - if(!string.IsNullOrWhiteSpace(fillUsername) && pf.ElementNumber > 0) + if (!string.IsNullOrWhiteSpace(fillUsername) && pf.ElementNumber > 0) { var username = FindUsernameField(pageDetails, pf, false, false); - if(username == null) + if (username == null) { // not able to find any viewable username fields. maybe there are some "hidden" ones? username = FindUsernameField(pageDetails, pf, true, false); } - if(username != null) + if (username != null) { usernames.Add(username); } } } - if(!passwordFields.Any()) + if (!passwordFields.Any()) { // No password fields on this page. Let's try to just fuzzy fill the username. var usernameFieldNamesList = _usernameFieldNames.ToList(); - foreach(var f in pageDetails.Fields) + foreach (var f in pageDetails.Fields) { - if(f.Viewable && (f.Type == "text" || f.Type == "email" || f.Type == "tel") && + if (f.Viewable && (f.Type == "text" || f.Type == "email" || f.Type == "tel") && FieldIsFuzzyMatch(f, usernameFieldNamesList)) { usernames.Add(f); @@ -124,14 +124,14 @@ namespace Bit.iOS.Core.Models } } - foreach(var username in usernames.Where(u => !filledFields.ContainsKey(u.OpId))) + foreach (var username in usernames.Where(u => !filledFields.ContainsKey(u.OpId))) { filledFields.Add(username.OpId, username); Script.Add(new List { "click_on_opid", username.OpId }); Script.Add(new List { "fill_by_opid", username.OpId, fillUsername }); } - foreach(var password in passwords.Where(p => !filledFields.ContainsKey(p.OpId))) + foreach (var password in passwords.Where(p => !filledFields.ContainsKey(p.OpId))) { filledFields.Add(password.OpId, password); Script.Add(new List { "click_on_opid", password.OpId }); @@ -157,21 +157,21 @@ namespace Bit.iOS.Core.Models { PageDetails.Field usernameField = null; - foreach(var f in pageDetails.Fields) + foreach (var f in pageDetails.Fields) { - if(f.ElementNumber >= passwordField.ElementNumber) + if (f.ElementNumber >= passwordField.ElementNumber) { break; } - if((!checkForm || f.Form == passwordField.Form) + if ((!checkForm || f.Form == passwordField.Form) && (canBeHidden || f.Viewable) && f.ElementNumber < passwordField.ElementNumber && (f.Type == "text" || f.Type == "email" || f.Type == "tel")) { usernameField = f; - if(FindMatchingFieldIndex(f, _usernameFieldNames) > -1) + if (FindMatchingFieldIndex(f, _usernameFieldNames) > -1) { // We found an exact match. No need to keep looking. break; @@ -185,19 +185,19 @@ namespace Bit.iOS.Core.Models private int FindMatchingFieldIndex(PageDetails.Field field, string[] names) { var matchingIndex = -1; - if(!string.IsNullOrWhiteSpace(field.HtmlId)) + if (!string.IsNullOrWhiteSpace(field.HtmlId)) { matchingIndex = Array.IndexOf(names, field.HtmlId.ToLower()); } - if(matchingIndex < 0 && !string.IsNullOrWhiteSpace(field.HtmlName)) + if (matchingIndex < 0 && !string.IsNullOrWhiteSpace(field.HtmlName)) { matchingIndex = Array.IndexOf(names, field.HtmlName.ToLower()); } - if(matchingIndex < 0 && !string.IsNullOrWhiteSpace(field.LabelTag)) + if (matchingIndex < 0 && !string.IsNullOrWhiteSpace(field.LabelTag)) { matchingIndex = Array.IndexOf(names, CleanLabel(field.LabelTag)); } - if(matchingIndex < 0 && !string.IsNullOrWhiteSpace(field.Placeholder)) + if (matchingIndex < 0 && !string.IsNullOrWhiteSpace(field.Placeholder)) { matchingIndex = Array.IndexOf(names, field.Placeholder.ToLower()); } @@ -207,19 +207,19 @@ namespace Bit.iOS.Core.Models private bool FieldIsFuzzyMatch(PageDetails.Field field, List names) { - if(!string.IsNullOrWhiteSpace(field.HtmlId) && FuzzyMatch(names, field.HtmlId.ToLower())) + if (!string.IsNullOrWhiteSpace(field.HtmlId) && FuzzyMatch(names, field.HtmlId.ToLower())) { return true; } - if(!string.IsNullOrWhiteSpace(field.HtmlName) && FuzzyMatch(names, field.HtmlName.ToLower())) + if (!string.IsNullOrWhiteSpace(field.HtmlName) && FuzzyMatch(names, field.HtmlName.ToLower())) { return true; } - if(!string.IsNullOrWhiteSpace(field.LabelTag) && FuzzyMatch(names, CleanLabel(field.LabelTag))) + if (!string.IsNullOrWhiteSpace(field.LabelTag) && FuzzyMatch(names, CleanLabel(field.LabelTag))) { return true; } - if(!string.IsNullOrWhiteSpace(field.Placeholder) && FuzzyMatch(names, field.Placeholder.ToLower())) + if (!string.IsNullOrWhiteSpace(field.Placeholder) && FuzzyMatch(names, field.Placeholder.ToLower())) { return true; } @@ -229,7 +229,7 @@ namespace Bit.iOS.Core.Models private bool FuzzyMatch(List options, string value) { - if((!options?.Any() ?? true) || string.IsNullOrWhiteSpace(value)) + if ((!options?.Any() ?? true) || string.IsNullOrWhiteSpace(value)) { return false; } @@ -239,18 +239,18 @@ namespace Bit.iOS.Core.Models private void SetFillScriptForFocus(IDictionary filledFields) { - if(!filledFields.Any()) + if (!filledFields.Any()) { return; } PageDetails.Field lastField = null, lastPasswordField = null; - foreach(var field in filledFields) + foreach (var field in filledFields) { - if(field.Value.Viewable) + if (field.Value.Viewable) { lastField = field.Value; - if(field.Value.Type == "password") + if (field.Value.Type == "password") { lastPasswordField = field.Value; } @@ -258,11 +258,11 @@ namespace Bit.iOS.Core.Models } // Prioritize password field over others. - if(lastPasswordField != null) + if (lastPasswordField != null) { Script.Add(new List { "focus_by_opid", lastPasswordField.OpId }); } - else if(lastField != null) + else if (lastField != null) { Script.Add(new List { "focus_by_opid", lastField.OpId }); } diff --git a/src/iOS.Core/Services/CryptoPrimitiveService.cs b/src/iOS.Core/Services/CryptoPrimitiveService.cs index 93cb6d97c..9d97fa647 100644 --- a/src/iOS.Core/Services/CryptoPrimitiveService.cs +++ b/src/iOS.Core/Services/CryptoPrimitiveService.cs @@ -14,12 +14,12 @@ namespace Bit.iOS.Core.Services { uint keySize = 32; uint pseudoRandomAlgorithm = 3; // kCCPRFHmacAlgSHA256 - if(algorithm == CryptoHashAlgorithm.Sha512) + if (algorithm == CryptoHashAlgorithm.Sha512) { keySize = 64; pseudoRandomAlgorithm = 5; // kCCPRFHmacAlgSHA512 } - else if(algorithm != CryptoHashAlgorithm.Sha256) + else if (algorithm != CryptoHashAlgorithm.Sha256) { throw new ArgumentException("Unsupported PBKDF2 algorithm."); } diff --git a/src/iOS.Core/Services/DeviceActionService.cs b/src/iOS.Core/Services/DeviceActionService.cs index 4569b6f07..a311b8a5c 100644 --- a/src/iOS.Core/Services/DeviceActionService.cs +++ b/src/iOS.Core/Services/DeviceActionService.cs @@ -41,7 +41,7 @@ namespace Bit.iOS.Core.Services { get { - if(string.IsNullOrWhiteSpace(_userAgent)) + if (string.IsNullOrWhiteSpace(_userAgent)) { _userAgent = $"Bitwarden_Mobile/{Xamarin.Essentials.AppInfo.VersionString} " + $"(iOS {UIDevice.CurrentDevice.SystemVersion}; Model {UIDevice.CurrentDevice.Model})"; @@ -59,7 +59,7 @@ namespace Bit.iOS.Core.Services public void Toast(string text, bool longDuration = false) { - if(!_toast?.Dismissed ?? false) + if (!_toast?.Dismissed ?? false) { _toast.Dismiss(false); } @@ -67,7 +67,7 @@ namespace Bit.iOS.Core.Services { Duration = TimeSpan.FromSeconds(longDuration ? 5 : 3) }; - if(TabBarVisible()) + if (TabBarVisible()) { _toast.BottomMargin = 55; } @@ -81,7 +81,7 @@ namespace Bit.iOS.Core.Services public Task ShowLoadingAsync(string text) { - if(_progressAlert != null) + if (_progressAlert != null) { HideLoadingAsync().GetAwaiter().GetResult(); } @@ -105,7 +105,7 @@ namespace Bit.iOS.Core.Services public Task HideLoadingAsync() { var result = new TaskCompletionSource(); - if(_progressAlert == null) + if (_progressAlert == null) { result.TrySetResult(0); } @@ -144,9 +144,9 @@ namespace Bit.iOS.Core.Services var url = new NSUrl(GetTempPath()); var tmpFiles = NSFileManager.DefaultManager.GetDirectoryContent(url, null, NSDirectoryEnumerationOptions.SkipsHiddenFiles, out NSError error); - if(error == null && tmpFiles.Length > 0) + if (error == null && tmpFiles.Length > 0) { - foreach(var item in tmpFiles) + foreach (var item in tmpFiles) { NSFileManager.DefaultManager.Remove(item, out NSError itemError); } @@ -180,7 +180,7 @@ namespace Bit.iOS.Core.Services }); picker.DidPickDocumentPicker += (sender, e) => { - if(SystemMajorVersion() < 11) + if (SystemMajorVersion() < 11) { e.DocumentPicker.DidPickDocument += DocumentPicker_DidPickDocument; } @@ -191,7 +191,7 @@ namespace Bit.iOS.Core.Services controller.PresentViewController(e.DocumentPicker, true, null); }; var root = UIApplication.SharedApplication.KeyWindow.RootViewController; - if(picker.PopoverPresentationController != null && root != null) + if (picker.PopoverPresentationController != null && root != null) { picker.PopoverPresentationController.SourceView = root.View; picker.PopoverPresentationController.SourceRect = root.View.Bounds; @@ -221,11 +221,11 @@ namespace Bit.iOS.Core.Services { input = x; input.Text = text ?? string.Empty; - if(numericKeyboard) + if (numericKeyboard) { input.KeyboardType = UIKeyboardType.NumberPad; } - if(!ThemeHelpers.LightTheme) + if (!ThemeHelpers.LightTheme) { input.KeyboardAppearance = UIKeyboardAppearance.Dark; } @@ -238,7 +238,7 @@ namespace Bit.iOS.Core.Services public void RateApp() { string uri = null; - if(SystemMajorVersion() < 11) + if (SystemMajorVersion() < 11) { uri = "itms-apps://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews" + "?id=1137397744&onlyLatestVersion=true&pageNumber=0&sortOrdering=1&type=Purple+Software"; @@ -252,13 +252,13 @@ namespace Bit.iOS.Core.Services public bool SupportsFaceBiometric() { - if(SystemMajorVersion() < 11) + if (SystemMajorVersion() < 11) { return false; } - using(var context = new LAContext()) + using (var context = new LAContext()) { - if(!context.CanEvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, out var e)) + if (!context.CanEvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, out var e)) { return false; } @@ -311,7 +311,7 @@ namespace Bit.iOS.Core.Services public int SystemMajorVersion() { var versionParts = UIDevice.CurrentDevice.SystemVersion.Split('.'); - if(versionParts.Length > 0 && int.TryParse(versionParts[0], out var version)) + if (versionParts.Length > 0 && int.TryParse(versionParts[0], out var version)) { return version; } @@ -328,14 +328,14 @@ namespace Bit.iOS.Core.Services { var result = new TaskCompletionSource(); var alert = UIAlertController.Create(title ?? string.Empty, message, UIAlertControllerStyle.Alert); - if(!string.IsNullOrWhiteSpace(cancel)) + if (!string.IsNullOrWhiteSpace(cancel)) { alert.AddAction(UIAlertAction.Create(cancel, UIAlertActionStyle.Cancel, x => { result.TrySetResult(cancel); })); } - foreach(var button in buttons) + foreach (var button in buttons) { alert.AddAction(UIAlertAction.Create(button, UIAlertActionStyle.Default, x => { @@ -391,7 +391,7 @@ namespace Bit.iOS.Core.Services { try { - if(SystemMajorVersion() > 12) + if (SystemMajorVersion() > 12) { return UIScreen.MainScreen.TraitCollection.UserInterfaceStyle == UIUserInterfaceStyle.Dark; } @@ -402,10 +402,10 @@ namespace Bit.iOS.Core.Services private void ImagePicker_FinishedPickingMedia(object sender, UIImagePickerMediaPickedEventArgs e) { - if(sender is UIImagePickerController picker) + if (sender is UIImagePickerController picker) { string fileName = null; - if(e.Info.TryGetValue(UIImagePickerController.ReferenceUrl, out NSObject urlObj)) + if (e.Info.TryGetValue(UIImagePickerController.ReferenceUrl, out NSObject urlObj)) { var result = PHAsset.FetchAssets(new NSUrl[] { (urlObj as NSUrl) }, null); fileName = result?.firstObject?.ValueForKey(new NSString("filename"))?.ToString(); @@ -413,9 +413,9 @@ namespace Bit.iOS.Core.Services fileName = fileName ?? $"photo_{DateTime.UtcNow.ToString("yyyyMMddHHmmss")}.jpg"; var lowerFilename = fileName?.ToLowerInvariant(); byte[] data; - if(lowerFilename != null && (lowerFilename.EndsWith(".jpg") || lowerFilename.EndsWith(".jpeg"))) + if (lowerFilename != null && (lowerFilename.EndsWith(".jpg") || lowerFilename.EndsWith(".jpeg"))) { - using(var imageData = e.OriginalImage.AsJPEG()) + using (var imageData = e.OriginalImage.AsJPEG()) { data = new byte[imageData.Length]; System.Runtime.InteropServices.Marshal.Copy(imageData.Bytes, data, 0, @@ -424,7 +424,7 @@ namespace Bit.iOS.Core.Services } else { - using(var imageData = e.OriginalImage.AsPNG()) + using (var imageData = e.OriginalImage.AsPNG()) { data = new byte[imageData.Length]; System.Runtime.InteropServices.Marshal.Copy(imageData.Bytes, data, 0, @@ -438,7 +438,7 @@ namespace Bit.iOS.Core.Services private void ImagePicker_Canceled(object sender, EventArgs e) { - if(sender is UIImagePickerController picker) + if (sender is UIImagePickerController picker) { picker.DismissViewController(true, null); } @@ -457,15 +457,15 @@ namespace Bit.iOS.Core.Services private UIViewController GetVisibleViewController(UIViewController controller = null) { controller = controller ?? UIApplication.SharedApplication.KeyWindow.RootViewController; - if(controller.PresentedViewController == null) + if (controller.PresentedViewController == null) { return controller; } - if(controller.PresentedViewController is UINavigationController) + if (controller.PresentedViewController is UINavigationController) { return ((UINavigationController)controller.PresentedViewController).VisibleViewController; } - if(controller.PresentedViewController is UITabBarController) + if (controller.PresentedViewController is UITabBarController) { return ((UITabBarController)controller.PresentedViewController).SelectedViewController; } @@ -476,7 +476,7 @@ namespace Bit.iOS.Core.Services { var window = UIApplication.SharedApplication.KeyWindow; var vc = window.RootViewController; - while(vc.PresentedViewController != null) + while (vc.PresentedViewController != null) { vc = vc.PresentedViewController; } @@ -502,10 +502,10 @@ namespace Bit.iOS.Core.Services url.StartAccessingSecurityScopedResource(); var doc = new UIDocument(url); var fileName = doc.LocalizedName; - if(string.IsNullOrWhiteSpace(fileName)) + if (string.IsNullOrWhiteSpace(fileName)) { var path = doc.FileUrl?.ToString(); - if(path != null) + if (path != null) { path = WebUtility.UrlDecode(path); var split = path.LastIndexOf('/'); diff --git a/src/iOS.Core/Services/KeyChainStorageService.cs b/src/iOS.Core/Services/KeyChainStorageService.cs index 2166a443f..0e9fd0824 100644 --- a/src/iOS.Core/Services/KeyChainStorageService.cs +++ b/src/iOS.Core/Services/KeyChainStorageService.cs @@ -33,10 +33,10 @@ namespace Bit.iOS.Core.Services var appId = await _getAppId.Invoke(); var formattedKey = string.Format(_keyFormat, appId, key); byte[] dataBytes = null; - using(var existingRecord = GetKeyRecord(formattedKey)) - using(var record = SecKeyChain.QueryAsRecord(existingRecord, out var resultCode)) + using (var existingRecord = GetKeyRecord(formattedKey)) + using (var record = SecKeyChain.QueryAsRecord(existingRecord, out var resultCode)) { - if(resultCode == SecStatusCode.ItemNotFound || resultCode == SecStatusCode.InteractionNotAllowed) + if (resultCode == SecStatusCode.ItemNotFound || resultCode == SecStatusCode.InteractionNotAllowed) { return (T)(object)null; } @@ -46,7 +46,7 @@ namespace Bit.iOS.Core.Services } var dataString = Encoding.UTF8.GetString(dataBytes); - if(typeof(T) == typeof(string)) + if (typeof(T) == typeof(string)) { return (T)(object)dataString; } @@ -58,14 +58,14 @@ namespace Bit.iOS.Core.Services public async Task SaveAsync(string key, T obj) { - if(obj == null) + if (obj == null) { await RemoveAsync(key); return; } string dataString = null; - if(typeof(T) == typeof(string)) + if (typeof(T) == typeof(string)) { dataString = obj as string; } @@ -77,8 +77,8 @@ namespace Bit.iOS.Core.Services var appId = await _getAppId.Invoke(); var formattedKey = string.Format(_keyFormat, appId, key); var dataBytes = Encoding.UTF8.GetBytes(dataString); - using(var data = NSData.FromArray(dataBytes)) - using(var newRecord = GetKeyRecord(formattedKey, data)) + using (var data = NSData.FromArray(dataBytes)) + using (var newRecord = GetKeyRecord(formattedKey, data)) { await RemoveAsync(key); CheckError(SecKeyChain.Add(newRecord)); @@ -89,9 +89,9 @@ namespace Bit.iOS.Core.Services { var appId = await _getAppId.Invoke(); var formattedKey = string.Format(_keyFormat, appId, key); - using(var record = GetExistingRecord(formattedKey)) + using (var record = GetExistingRecord(formattedKey)) { - if(record != null) + if (record != null) { CheckError(SecKeyChain.Remove(record)); } @@ -106,7 +106,7 @@ namespace Bit.iOS.Core.Services Account = key, AccessGroup = _group }; - if(data != null) + if (data != null) { record.Generic = data; } @@ -122,7 +122,7 @@ namespace Bit.iOS.Core.Services private void CheckError(SecStatusCode resultCode, [CallerMemberName] string caller = null) { - if(resultCode != SecStatusCode.Success) + if (resultCode != SecStatusCode.Success) { throw new Exception(string.Format("Failed to execute {0}. Result code: {1}", caller, resultCode)); } diff --git a/src/iOS.Core/Services/LocalizeService.cs b/src/iOS.Core/Services/LocalizeService.cs index 0c0bef664..fa62965dc 100644 --- a/src/iOS.Core/Services/LocalizeService.cs +++ b/src/iOS.Core/Services/LocalizeService.cs @@ -11,7 +11,7 @@ namespace Bit.iOS.Core.Services public CultureInfo GetCurrentCultureInfo() { var netLanguage = "en"; - if(NSLocale.PreferredLanguages.Length > 0) + if (NSLocale.PreferredLanguages.Length > 0) { var pref = NSLocale.PreferredLanguages[0]; @@ -24,7 +24,7 @@ namespace Bit.iOS.Core.Services { ci = new CultureInfo(netLanguage); } - catch(CultureNotFoundException e1) + catch (CultureNotFoundException e1) { // iOS locale not valid .NET culture (eg. "en-ES" : English in Spain) // fallback to first characters, in this case "en" @@ -34,7 +34,7 @@ namespace Bit.iOS.Core.Services Console.WriteLine(netLanguage + " failed, trying " + fallback + " (" + e1.Message + ")"); ci = new CultureInfo(fallback); } - catch(CultureNotFoundException e2) + catch (CultureNotFoundException e2) { // iOS language not valid .NET culture, falling back to English Console.WriteLine(netLanguage + " couldn't be set, using 'en' (" + e2.Message + ")"); @@ -49,18 +49,18 @@ namespace Bit.iOS.Core.Services { Console.WriteLine("iOS Language:" + iOSLanguage); var netLanguage = iOSLanguage; - if(iOSLanguage.StartsWith("zh-Hant") || iOSLanguage.StartsWith("zh-HK")) + if (iOSLanguage.StartsWith("zh-Hant") || iOSLanguage.StartsWith("zh-HK")) { netLanguage = "zh-Hant"; } - else if(iOSLanguage.StartsWith("zh")) + else if (iOSLanguage.StartsWith("zh")) { netLanguage = "zh-Hans"; } else { // Certain languages need to be converted to CultureInfo equivalent - switch(iOSLanguage) + switch (iOSLanguage) { case "ms-MY": // "Malaysian (Malaysia)" not supported .NET culture case "ms-SG": // "Malaysian (Singapore)" not supported .NET culture @@ -83,7 +83,7 @@ namespace Bit.iOS.Core.Services Console.WriteLine(".NET Fallback Language:" + platCulture.LanguageCode); // Use the first part of the identifier (two chars, usually); var netLanguage = platCulture.LanguageCode; - switch(platCulture.LanguageCode) + switch (platCulture.LanguageCode) { case "pt": netLanguage = "pt-PT"; // fallback to Portuguese (Portugal) diff --git a/src/iOS.Core/Utilities/ASHelpers.cs b/src/iOS.Core/Utilities/ASHelpers.cs index d0260e055..6f92dca66 100644 --- a/src/iOS.Core/Utilities/ASHelpers.cs +++ b/src/iOS.Core/Utilities/ASHelpers.cs @@ -12,11 +12,11 @@ namespace Bit.iOS.Core.Utilities { public static async Task ReplaceAllIdentities() { - if(await AutofillEnabled()) + if (await AutofillEnabled()) { var storageService = ServiceContainer.Resolve("storageService"); var lockService = ServiceContainer.Resolve("lockService"); - if(await lockService.IsLockedAsync()) + if (await lockService.IsLockedAsync()) { await storageService.SaveAsync(Constants.AutofillNeedsIdentityReplacementKey, true); return; @@ -24,15 +24,15 @@ namespace Bit.iOS.Core.Utilities var cipherService = ServiceContainer.Resolve("cipherService"); var identities = new List(); var ciphers = await cipherService.GetAllDecryptedAsync(); - foreach(var cipher in ciphers) + foreach (var cipher in ciphers) { var identity = ToCredentialIdentity(cipher); - if(identity != null) + if (identity != null) { identities.Add(identity); } } - if(identities.Any()) + if (identities.Any()) { await ASCredentialIdentityStore.SharedStore?.ReplaceCredentialIdentitiesAsync(identities.ToArray()); await storageService.SaveAsync(Constants.AutofillNeedsIdentityReplacementKey, false); @@ -56,7 +56,7 @@ namespace Bit.iOS.Core.Utilities { var cipherService = ServiceContainer.Resolve("cipherService"); var cipher = await cipherService.GetAsync(cipherId); - if(cipher == null) + if (cipher == null) { return null; } @@ -66,17 +66,17 @@ namespace Bit.iOS.Core.Utilities public static ASPasswordCredentialIdentity ToCredentialIdentity(CipherView cipher) { - if(!cipher?.Login?.Uris?.Any() ?? true) + if (!cipher?.Login?.Uris?.Any() ?? true) { return null; } var uri = cipher.Login.Uris.FirstOrDefault(u => u.Match != Bit.Core.Enums.UriMatchType.Never)?.Uri; - if(string.IsNullOrWhiteSpace(uri)) + if (string.IsNullOrWhiteSpace(uri)) { return null; } var username = cipher.Login.Username; - if(string.IsNullOrWhiteSpace(username)) + if (string.IsNullOrWhiteSpace(username)) { return null; } diff --git a/src/iOS.Core/Utilities/Dialogs.cs b/src/iOS.Core/Utilities/Dialogs.cs index 817013632..a332cd397 100644 --- a/src/iOS.Core/Utilities/Dialogs.cs +++ b/src/iOS.Core/Utilities/Dialogs.cs @@ -39,7 +39,7 @@ namespace Bit.iOS.Core.Utilities public static UIAlertController CreateActionSheet(string title, UIViewController controller) { var sheet = UIAlertController.Create(title, null, UIAlertControllerStyle.ActionSheet); - if(UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) + if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { var x = controller.View.Bounds.Width / 2; var y = controller.View.Bounds.Bottom; diff --git a/src/iOS.Core/Utilities/ThemeHelpers.cs b/src/iOS.Core/Utilities/ThemeHelpers.cs index 3c5f113a2..3be5b6415 100644 --- a/src/iOS.Core/Utilities/ThemeHelpers.cs +++ b/src/iOS.Core/Utilities/ThemeHelpers.cs @@ -26,7 +26,7 @@ namespace Bit.iOS.Core.Utilities UINavigationBar.Appearance.ShadowImage = new UIImage(); UINavigationBar.Appearance.SetBackgroundImage(new UIImage(), UIBarMetrics.Default); UIStepper.Appearance.TintColor = MutedColor; - if(!LightTheme) + if (!LightTheme) { UISwitch.Appearance.TintColor = MutedColor; } @@ -59,12 +59,12 @@ namespace Bit.iOS.Core.Utilities private static void SetThemeVariables(string theme) { LightTheme = false; - if(string.IsNullOrWhiteSpace(theme) && UsingOsDarkTheme) + if (string.IsNullOrWhiteSpace(theme) && UsingOsDarkTheme) { theme = "dark"; } - if(theme == "dark") + if (theme == "dark") { var whiteColor = Xamarin.Forms.Color.FromHex("#ffffff").ToUIColor(); MutedColor = Xamarin.Forms.Color.FromHex("#a3a3a3").ToUIColor(); @@ -79,7 +79,7 @@ namespace Bit.iOS.Core.Utilities NavBarBackgroundColor = Xamarin.Forms.Color.FromHex("#212121").ToUIColor(); NavBarTextColor = whiteColor; } - else if(theme == "black") + else if (theme == "black") { var blackColor = Xamarin.Forms.Color.FromHex("#000000").ToUIColor(); var whiteColor = Xamarin.Forms.Color.FromHex("#ffffff").ToUIColor(); @@ -95,7 +95,7 @@ namespace Bit.iOS.Core.Utilities NavBarBackgroundColor = blackColor; NavBarTextColor = whiteColor; } - else if(theme == "nord") + else if (theme == "nord") { MutedColor = Xamarin.Forms.Color.FromHex("#d8dee9").ToUIColor(); SuccessColor = Xamarin.Forms.Color.FromHex("#a3be8c").ToUIColor(); diff --git a/src/iOS.Core/Utilities/iOSCoreHelpers.cs b/src/iOS.Core/Utilities/iOSCoreHelpers.cs index 2a273c921..fc657ff0d 100644 --- a/src/iOS.Core/Utilities/iOSCoreHelpers.cs +++ b/src/iOS.Core/Utilities/iOSCoreHelpers.cs @@ -32,7 +32,7 @@ namespace Bit.iOS.Core.Utilities public static void RegisterLocalServices() { - if(ServiceContainer.Resolve("logService", true) == null) + if (ServiceContainer.Resolve("logService", true) == null) { ServiceContainer.Register("logService", new ConsoleLogService()); } @@ -87,7 +87,7 @@ namespace Bit.iOS.Core.Utilities await ServiceContainer.Resolve("stateService").SaveAsync( Bit.Core.Constants.DisableFaviconKey, disableFavicon); await ServiceContainer.Resolve("environmentService").SetUrlsFromStorageAsync(); - if(postBootstrapFunc != null) + if (postBootstrapFunc != null) { await postBootstrapFunc.Invoke(); } diff --git a/src/iOS.Core/Views/ExtensionSearchDelegate.cs b/src/iOS.Core/Views/ExtensionSearchDelegate.cs index 317d55138..3fa4ff64a 100644 --- a/src/iOS.Core/Views/ExtensionSearchDelegate.cs +++ b/src/iOS.Core/Views/ExtensionSearchDelegate.cs @@ -23,10 +23,10 @@ namespace Bit.iOS.Core.Views { NSRunLoop.Main.BeginInvokeOnMainThread(async () => { - if(!string.IsNullOrWhiteSpace(searchText)) + if (!string.IsNullOrWhiteSpace(searchText)) { await Task.Delay(300); - if(searchText != searchBar.Text) + if (searchText != searchBar.Text) { return; } @@ -40,7 +40,7 @@ namespace Bit.iOS.Core.Views ((ExtensionTableSource)_tableView.Source).FilterResults(searchText, cts.Token); _tableView.ReloadData(); } - catch(OperationCanceledException) { } + catch (OperationCanceledException) { } _filterResultsCancellationTokenSource = cts; }); }, cts.Token); diff --git a/src/iOS.Core/Views/ExtensionTableSource.cs b/src/iOS.Core/Views/ExtensionTableSource.cs index f39203dfb..4dac3d72e 100644 --- a/src/iOS.Core/Views/ExtensionTableSource.cs +++ b/src/iOS.Core/Views/ExtensionTableSource.cs @@ -44,14 +44,14 @@ namespace Bit.iOS.Core.Views { var combinedLogins = new List(); - if(urlFilter) + if (urlFilter) { var logins = await _cipherService.GetAllDecryptedByUrlAsync(_context.UrlString); - if(logins?.Item1 != null) + if (logins?.Item1 != null) { combinedLogins.AddRange(logins.Item1); } - if(logins?.Item2 != null) + if (logins?.Item2 != null) { combinedLogins.AddRange(logins.Item2); } @@ -73,7 +73,7 @@ namespace Bit.iOS.Core.Views { ct.ThrowIfCancellationRequested(); - if(string.IsNullOrWhiteSpace(searchFilter)) + if (string.IsNullOrWhiteSpace(searchFilter)) { Items = _allItems.ToList(); } @@ -95,7 +95,7 @@ namespace Bit.iOS.Core.Views public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath) { - if(Items == null || Items.Count() == 0) + if (Items == null || Items.Count() == 0) { var noDataCell = new ExtendedUITableViewCell(UITableViewCellStyle.Default, "NoDataCell"); noDataCell.TextLabel.Text = AppResources.NoItemsTap; @@ -109,7 +109,7 @@ namespace Bit.iOS.Core.Views var cell = tableView.DequeueReusableCell(CellIdentifier); // if there are no cells to reuse, create a new one - if(cell == null) + if (cell == null) { Debug.WriteLine("BW Log, Make new cell for list."); cell = new ExtendedUITableViewCell(UITableViewCellStyle.Subtitle, CellIdentifier); @@ -121,7 +121,7 @@ namespace Bit.iOS.Core.Views public override void WillDisplay(UITableView tableView, UITableViewCell cell, NSIndexPath indexPath) { - if(Items == null || Items.Count() == 0 || cell == null) + if (Items == null || Items.Count() == 0 || cell == null) { return; } @@ -135,9 +135,9 @@ namespace Bit.iOS.Core.Views { string totp = null; var accessPremium = await _userService.CanAccessPremiumAsync(); - if(accessPremium || (item?.CipherView.OrganizationUseTotp ?? false)) + if (accessPremium || (item?.CipherView.OrganizationUseTotp ?? false)) { - if(item != null && !string.IsNullOrWhiteSpace(item.Totp)) + if (item != null && !string.IsNullOrWhiteSpace(item.Totp)) { totp = await _totpService.GetCodeAsync(item.Totp); } diff --git a/src/iOS.Core/Views/FormEntryTableViewCell.cs b/src/iOS.Core/Views/FormEntryTableViewCell.cs index 1a9376564..a11be7390 100644 --- a/src/iOS.Core/Views/FormEntryTableViewCell.cs +++ b/src/iOS.Core/Views/FormEntryTableViewCell.cs @@ -17,7 +17,7 @@ namespace Bit.iOS.Core.Views var descriptor = UIFontDescriptor.PreferredBody; var pointSize = descriptor.PointSize; - if(labelName != null && !useLabelAsPlaceholder) + if (labelName != null && !useLabelAsPlaceholder) { Label = new UILabel { @@ -30,7 +30,7 @@ namespace Bit.iOS.Core.Views ContentView.Add(Label); } - if(useTextView) + if (useTextView) { TextView = new UITextView { @@ -41,7 +41,7 @@ namespace Bit.iOS.Core.Views BackgroundColor = ThemeHelpers.BackgroundColor }; - if(!ThemeHelpers.LightTheme) + if (!ThemeHelpers.LightTheme) { TextView.KeyboardAppearance = UIKeyboardAppearance.Dark; } @@ -53,7 +53,7 @@ namespace Bit.iOS.Core.Views NSLayoutConstraint.Create(ContentView, NSLayoutAttribute.Bottom, NSLayoutRelation.Equal, TextView, NSLayoutAttribute.Bottom, 1f, 10f) }); - if(labelName != null && !useLabelAsPlaceholder) + if (labelName != null && !useLabelAsPlaceholder) { ContentView.AddConstraint( NSLayoutConstraint.Create(TextView, NSLayoutAttribute.Top, NSLayoutRelation.Equal, Label, NSLayoutAttribute.Bottom, 1f, 10f)); @@ -64,7 +64,7 @@ namespace Bit.iOS.Core.Views NSLayoutConstraint.Create(TextView, NSLayoutAttribute.Top, NSLayoutRelation.Equal, ContentView, NSLayoutAttribute.Top, 1f, 10f)); } - if(height.HasValue) + if (height.HasValue) { ContentView.AddConstraint( NSLayoutConstraint.Create(TextView, NSLayoutAttribute.Height, NSLayoutRelation.Equal, null, NSLayoutAttribute.NoAttribute, 1f, height.Value)); @@ -83,12 +83,12 @@ namespace Bit.iOS.Core.Views BackgroundColor = ThemeHelpers.BackgroundColor }; - if(!ThemeHelpers.LightTheme) + if (!ThemeHelpers.LightTheme) { TextField.KeyboardAppearance = UIKeyboardAppearance.Dark; } - if(useLabelAsPlaceholder) + if (useLabelAsPlaceholder) { TextField.Placeholder = labelName; } @@ -100,7 +100,7 @@ namespace Bit.iOS.Core.Views NSLayoutConstraint.Create(ContentView, NSLayoutAttribute.Bottom, NSLayoutRelation.Equal, TextField, NSLayoutAttribute.Bottom, 1f, 10f) }); - if(labelName != null && !useLabelAsPlaceholder) + if (labelName != null && !useLabelAsPlaceholder) { ContentView.AddConstraint( NSLayoutConstraint.Create(TextField, NSLayoutAttribute.Top, NSLayoutRelation.Equal, Label, NSLayoutAttribute.Bottom, 1f, 10f)); @@ -111,14 +111,14 @@ namespace Bit.iOS.Core.Views NSLayoutConstraint.Create(TextField, NSLayoutAttribute.Top, NSLayoutRelation.Equal, ContentView, NSLayoutAttribute.Top, 1f, 10f)); } - if(height.HasValue) + if (height.HasValue) { ContentView.AddConstraint( NSLayoutConstraint.Create(TextField, NSLayoutAttribute.Height, NSLayoutRelation.Equal, null, NSLayoutAttribute.NoAttribute, 1f, height.Value)); } } - if(labelName != null && !useLabelAsPlaceholder) + if (labelName != null && !useLabelAsPlaceholder) { ContentView.AddConstraints(new NSLayoutConstraint[] { NSLayoutConstraint.Create(Label, NSLayoutAttribute.Leading, NSLayoutRelation.Equal, ContentView, NSLayoutAttribute.Leading, 1f, 15f), @@ -134,11 +134,11 @@ namespace Bit.iOS.Core.Views public void Select() { - if(TextView != null) + if (TextView != null) { TextView.BecomeFirstResponder(); } - else if(TextField != null) + else if (TextField != null) { TextField.BecomeFirstResponder(); } diff --git a/src/iOS.Core/Views/PickerTableViewCell.cs b/src/iOS.Core/Views/PickerTableViewCell.cs index 265662548..59df6ca22 100644 --- a/src/iOS.Core/Views/PickerTableViewCell.cs +++ b/src/iOS.Core/Views/PickerTableViewCell.cs @@ -41,7 +41,7 @@ namespace Bit.iOS.Core.Views BackgroundColor = ThemeHelpers.BackgroundColor }; - if(!ThemeHelpers.LightTheme) + if (!ThemeHelpers.LightTheme) { TextField.KeyboardAppearance = UIKeyboardAppearance.Dark; } @@ -56,7 +56,7 @@ namespace Bit.iOS.Core.Views var doneButton = new UIBarButtonItem(UIBarButtonSystemItem.Done, (o, a) => { var s = (PickerSource)Picker.Model; - if(s.SelectedIndex == -1 && Items != null && Items.Count > 0) + if (s.SelectedIndex == -1 && Items != null && Items.Count > 0) { UpdatePickerSelectedIndex(0); } @@ -81,7 +81,7 @@ namespace Bit.iOS.Core.Views NSLayoutConstraint.Create(ContentView, NSLayoutAttribute.Trailing, NSLayoutRelation.Equal, Label, NSLayoutAttribute.Trailing, 1f, 15f) }); - if(height.HasValue) + if (height.HasValue) { ContentView.AddConstraint( NSLayoutConstraint.Create(TextField, NSLayoutAttribute.Height, NSLayoutRelation.Equal, null, NSLayoutAttribute.NoAttribute, 1f, height.Value)); @@ -120,7 +120,7 @@ namespace Bit.iOS.Core.Views { TextField.Text = SelectedIndex == -1 || Items == null ? "" : Items[SelectedIndex]; Picker.ReloadAllComponents(); - if(Items == null || Items.Count == 0) + if (Items == null || Items.Count == 0) { return; } @@ -187,7 +187,7 @@ namespace Bit.iOS.Core.Views public override void Selected(UIPickerView picker, nint row, nint component) { - if(_cell.Items.Count == 0) + if (_cell.Items.Count == 0) { SelectedItem = null; SelectedIndex = -1; diff --git a/src/iOS.Core/Views/SliderTableViewCell.cs b/src/iOS.Core/Views/SliderTableViewCell.cs index f31d54f45..97725eb34 100644 --- a/src/iOS.Core/Views/SliderTableViewCell.cs +++ b/src/iOS.Core/Views/SliderTableViewCell.cs @@ -38,7 +38,7 @@ namespace Bit.iOS.Core.Views Value = newValue; - if(valueChanged) + if (valueChanged) { ValueChanged?.Invoke(this, null); } diff --git a/src/iOS.Core/Views/SwitchTableViewCell.cs b/src/iOS.Core/Views/SwitchTableViewCell.cs index a4a5e8388..9a75ce67b 100644 --- a/src/iOS.Core/Views/SwitchTableViewCell.cs +++ b/src/iOS.Core/Views/SwitchTableViewCell.cs @@ -12,7 +12,7 @@ namespace Bit.iOS.Core.Views { TextLabel.Text = labelName; TextLabel.TextColor = ThemeHelpers.TextColor; - if(!ThemeHelpers.LightTheme) + if (!ThemeHelpers.LightTheme) { Switch.TintColor = ThemeHelpers.MutedColor; } diff --git a/src/iOS.Core/Views/Toast.cs b/src/iOS.Core/Views/Toast.cs index 4e1e38a6b..ed5f0b906 100644 --- a/src/iOS.Core/Views/Toast.cs +++ b/src/iOS.Core/Views/Toast.cs @@ -21,7 +21,7 @@ namespace Bit.iOS.Core.Views var bgColor = UIColor.DarkGray; var nordTheme = Application.Current?.Resources != null && ((Color)Application.Current.Resources["BackgroundColor"]) == Color.FromHex("#3b4252"); - if(nordTheme) + if (nordTheme) { bgColor = Color.FromHex("#4c566a").ToUIColor(); } @@ -70,7 +70,7 @@ namespace Bit.iOS.Core.Views public void Show() { - if(Superview != null) + if (Superview != null) { return; } @@ -79,7 +79,7 @@ namespace Bit.iOS.Core.Views LayoutIfNeeded(); var localSuperView = UIApplication.SharedApplication.KeyWindow; - if(localSuperView != null) + if (localSuperView != null) { localSuperView.AddSubview(this); @@ -115,7 +115,7 @@ namespace Bit.iOS.Core.Views public void Dismiss(bool animated = true) { - if(Dismissed) + if (Dismissed) { return; } @@ -124,7 +124,7 @@ namespace Bit.iOS.Core.Views _dismissTimer?.Invalidate(); _dismissTimer = null; - if(!animated) + if (!animated) { RemoveFromSuperview(); DismissCallback?.Invoke(); diff --git a/src/iOS.Extension/LoadingViewController.cs b/src/iOS.Extension/LoadingViewController.cs index 2af8566f7..1a7c748de 100644 --- a/src/iOS.Extension/LoadingViewController.cs +++ b/src/iOS.Extension/LoadingViewController.cs @@ -32,12 +32,12 @@ namespace Bit.iOS.Extension Logo.Image = new UIImage(ThemeHelpers.LightTheme ? "logo.png" : "logo_white.png"); View.BackgroundColor = ThemeHelpers.SplashBackgroundColor; _context.ExtContext = ExtensionContext; - foreach(var item in ExtensionContext.InputItems) + foreach (var item in ExtensionContext.InputItems) { var processed = false; - foreach(var itemProvider in item.Attachments) + foreach (var itemProvider in item.Attachments) { - if(ProcessWebUrlProvider(itemProvider) + if (ProcessWebUrlProvider(itemProvider) || ProcessFindLoginProvider(itemProvider) || ProcessFindLoginBrowserProvider(itemProvider, Constants.UTTypeAppExtensionFillBrowserAction) || ProcessFindLoginBrowserProvider(itemProvider, Constants.UTTypeAppExtensionFillWebViewAction) @@ -49,7 +49,7 @@ namespace Bit.iOS.Extension break; } } - if(processed) + if (processed) { break; } @@ -59,7 +59,7 @@ namespace Bit.iOS.Extension public override void ViewDidAppear(bool animated) { base.ViewDidAppear(animated); - if(!IsAuthed()) + if (!IsAuthed()) { var alert = Dialogs.CreateAlert(null, AppResources.MustLogInMainApp, AppResources.Ok, (a) => { @@ -68,12 +68,12 @@ namespace Bit.iOS.Extension PresentViewController(alert, true, null); return; } - if(_context.ProviderType == Constants.UTTypeAppExtensionSetup) + if (_context.ProviderType == Constants.UTTypeAppExtensionSetup) { PerformSegue("setupSegue", this); return; } - if(IsLocked()) + if (IsLocked()) { PerformSegue("lockPasswordSegue", this); } @@ -85,23 +85,23 @@ namespace Bit.iOS.Extension public override void PrepareForSegue(UIStoryboardSegue segue, NSObject sender) { - if(segue.DestinationViewController is UINavigationController navController) + if (segue.DestinationViewController is UINavigationController navController) { - if(navController.TopViewController is LoginListViewController listLoginController) + if (navController.TopViewController is LoginListViewController listLoginController) { listLoginController.Context = _context; listLoginController.LoadingController = this; } - else if(navController.TopViewController is LoginAddViewController addLoginController) + else if (navController.TopViewController is LoginAddViewController addLoginController) { addLoginController.Context = _context; addLoginController.LoadingController = this; } - else if(navController.TopViewController is LockPasswordViewController passwordViewController) + else if (navController.TopViewController is LockPasswordViewController passwordViewController) { passwordViewController.LoadingController = this; } - else if(navController.TopViewController is SetupViewController setupViewController) + else if (navController.TopViewController is SetupViewController setupViewController) { setupViewController.Context = _context; setupViewController.LoadingController = this; @@ -118,11 +118,11 @@ namespace Bit.iOS.Extension private void ContinueOn() { Debug.WriteLine("BW Log, Segue to setup, login add or list."); - if(_context.ProviderType == Constants.UTTypeAppExtensionSaveLoginAction) + if (_context.ProviderType == Constants.UTTypeAppExtensionSaveLoginAction) { PerformSegue("newLoginSegue", this); } - else if(_context.ProviderType == Constants.UTTypeAppExtensionSetup) + else if (_context.ProviderType == Constants.UTTypeAppExtensionSetup) { PerformSegue("setupSegue", this); } @@ -136,40 +136,40 @@ namespace Bit.iOS.Extension List> fields, string totp) { NSDictionary itemData = null; - if(_context.ProviderType == UTType.PropertyList) + if (_context.ProviderType == UTType.PropertyList) { var fillScript = new FillScript(_context.Details, username, password, fields); var scriptJson = CoreHelpers.SerializeJson(fillScript, true); var scriptDict = new NSDictionary(Constants.AppExtensionWebViewPageFillScript, scriptJson); itemData = new NSDictionary(NSJavaScriptExtension.FinalizeArgumentKey, scriptDict); } - else if(_context.ProviderType == Constants.UTTypeAppExtensionFindLoginAction) + else if (_context.ProviderType == Constants.UTTypeAppExtensionFindLoginAction) { itemData = new NSDictionary( Constants.AppExtensionUsernameKey, username, Constants.AppExtensionPasswordKey, password); } - else if(_context.ProviderType == Constants.UTTypeAppExtensionFillBrowserAction + else if (_context.ProviderType == Constants.UTTypeAppExtensionFillBrowserAction || _context.ProviderType == Constants.UTTypeAppExtensionFillWebViewAction) { var fillScript = new FillScript(_context.Details, username, password, fields); var scriptJson = CoreHelpers.SerializeJson(fillScript, true); itemData = new NSDictionary(Constants.AppExtensionWebViewPageFillScript, scriptJson); } - else if(_context.ProviderType == Constants.UTTypeAppExtensionSaveLoginAction) + else if (_context.ProviderType == Constants.UTTypeAppExtensionSaveLoginAction) { itemData = new NSDictionary( Constants.AppExtensionUsernameKey, username, Constants.AppExtensionPasswordKey, password); } - else if(_context.ProviderType == Constants.UTTypeAppExtensionChangePasswordAction) + else if (_context.ProviderType == Constants.UTTypeAppExtensionChangePasswordAction) { itemData = new NSDictionary( Constants.AppExtensionPasswordKey, string.Empty, Constants.AppExtensionOldPasswordKey, password); } - if(!string.IsNullOrWhiteSpace(totp)) + if (!string.IsNullOrWhiteSpace(totp)) { UIPasteboard.General.String = totp; } @@ -184,7 +184,7 @@ namespace Bit.iOS.Extension var returningItems = new NSExtensionItem[] { resultsItem }; NSRunLoop.Main.BeginInvokeOnMainThread(async () => { - if(!string.IsNullOrWhiteSpace(id) && itemData != null) + if (!string.IsNullOrWhiteSpace(id) && itemData != null) { var eventService = ServiceContainer.Resolve("eventService"); await eventService.CollectAsync(Bit.Core.Enums.EventType.Cipher_ClientAutofilled, id); @@ -197,24 +197,24 @@ namespace Bit.iOS.Extension private bool ProcessItemProvider(NSItemProvider itemProvider, string type, Action dictAction, Action urlAction = null) { - if(!itemProvider.HasItemConformingTo(type)) + if (!itemProvider.HasItemConformingTo(type)) { return false; } itemProvider.LoadItem(type, null, (NSObject list, NSError error) => { - if(list == null) + if (list == null) { return; } _context.ProviderType = type; - if(list is NSDictionary dict && dictAction != null) + if (list is NSDictionary dict && dictAction != null) { dictAction(dict); } - else if(list is NSUrl && urlAction != null) + else if (list is NSUrl && urlAction != null) { var url = list as NSUrl; urlAction(url); @@ -234,7 +234,7 @@ namespace Bit.iOS.Extension Debug.WriteLine("BW LOG, Notes: " + _context.Notes); Debug.WriteLine("BW LOG, Details: " + _context.Details); - if(_context.PasswordOptions != null) + if (_context.PasswordOptions != null) { Debug.WriteLine("BW LOG, PasswordOptions Min Length: " + _context.PasswordOptions.MinLength); Debug.WriteLine("BW LOG, PasswordOptions Max Length: " + _context.PasswordOptions.MaxLength); @@ -252,7 +252,7 @@ namespace Bit.iOS.Extension return ProcessItemProvider(itemProvider, UTType.PropertyList, dict => { var result = dict[NSJavaScriptExtension.PreprocessingResultsKey]; - if(result == null) + if (result == null) { return; } @@ -268,7 +268,7 @@ namespace Bit.iOS.Extension { var version = dict[Constants.AppExtensionVersionNumberKey] as NSNumber; var url = dict[Constants.AppExtensionUrlStringKey] as NSString; - if(url != null) + if (url != null) { _context.UrlString = url; } @@ -281,14 +281,14 @@ namespace Bit.iOS.Extension { var version = dict[Constants.AppExtensionVersionNumberKey] as NSNumber; var url = dict[Constants.AppExtensionUrlStringKey] as NSString; - if(url != null) + if (url != null) { _context.UrlString = url; } _context.Details = DeserializeDictionary(dict[Constants.AppExtensionWebViewPageDetails] as NSDictionary); }, url => { - if(url != null) + if (url != null) { _context.UrlString = url.AbsoluteString; } @@ -307,7 +307,7 @@ namespace Bit.iOS.Extension var password = dict[Constants.AppExtensionPasswordKey] as NSString; var notes = dict[Constants.AppExtensionNotesKey] as NSString; var fields = dict[Constants.AppExtensionFieldsKey] as NSDictionary; - if(url != null) + if (url != null) { _context.UrlString = url; } @@ -332,7 +332,7 @@ namespace Bit.iOS.Extension var oldPassword = dict[Constants.AppExtensionOldPasswordKey] as NSString; var notes = dict[Constants.AppExtensionNotesKey] as NSString; var fields = dict[Constants.AppExtensionFieldsKey] as NSDictionary; - if(url != null) + if (url != null) { _context.UrlString = url; } @@ -347,7 +347,7 @@ namespace Bit.iOS.Extension private bool ProcessExtensionSetupProvider(NSItemProvider itemProvider) { - if(itemProvider.HasItemConformingTo(Constants.UTTypeAppExtensionSetup)) + if (itemProvider.HasItemConformingTo(Constants.UTTypeAppExtensionSetup)) { _context.ProviderType = Constants.UTTypeAppExtensionSetup; return true; @@ -357,11 +357,11 @@ namespace Bit.iOS.Extension private T DeserializeDictionary(NSDictionary dict) { - if(dict != null) + if (dict != null) { var jsonData = NSJsonSerialization.Serialize( dict, NSJsonWritingOptions.PrettyPrinted, out NSError jsonError); - if(jsonData != null) + if (jsonData != null) { var jsonString = new NSString(jsonData, NSStringEncoding.UTF8); return DeserializeString(jsonString); @@ -372,7 +372,7 @@ namespace Bit.iOS.Extension private T DeserializeString(NSString jsonString) { - if(jsonString != null) + if (jsonString != null) { var convertedObject = CoreHelpers.DeserializeJson(jsonString.ToString()); return convertedObject; @@ -382,14 +382,14 @@ namespace Bit.iOS.Extension private void InitApp() { - if(ServiceContainer.RegisteredServices.Count > 0) + if (ServiceContainer.RegisteredServices.Count > 0) { ServiceContainer.Reset(); } iOSCoreHelpers.RegisterLocalServices(); var deviceActionService = ServiceContainer.Resolve("deviceActionService"); ServiceContainer.Init(deviceActionService.DeviceUserAgent); - if(!_initedHockeyApp) + if (!_initedHockeyApp) { iOSCoreHelpers.RegisterHockeyApp(); _initedHockeyApp = true; diff --git a/src/iOS.Extension/LoginAddViewController.cs b/src/iOS.Extension/LoginAddViewController.cs index 6aa27b35e..012744bc6 100644 --- a/src/iOS.Extension/LoginAddViewController.cs +++ b/src/iOS.Extension/LoginAddViewController.cs @@ -27,11 +27,11 @@ namespace Bit.iOS.Extension public override Action Success => id => { - if(LoginListController != null) + if (LoginListController != null) { LoginListController.DismissModal(); } - else if(LoadingController != null) + else if (LoadingController != null) { LoadingController.CompleteUsernamePasswordRequest(id, UsernameCell.TextField.Text, PasswordCell.TextField.Text, null, null); @@ -40,7 +40,7 @@ namespace Bit.iOS.Extension partial void CancelBarButton_Activated(UIBarButtonItem sender) { - if(LoginListController != null) + if (LoginListController != null) { DismissViewController(true, null); } @@ -57,9 +57,9 @@ namespace Bit.iOS.Extension public override void PrepareForSegue(UIStoryboardSegue segue, NSObject sender) { - if(segue.DestinationViewController is UINavigationController navController) + if (segue.DestinationViewController is UINavigationController navController) { - if(navController.TopViewController is PasswordGeneratorViewController passwordGeneratorController) + if (navController.TopViewController is PasswordGeneratorViewController passwordGeneratorController) { passwordGeneratorController.PasswordOptions = Context.PasswordOptions; passwordGeneratorController.Parent = this; diff --git a/src/iOS.Extension/LoginListViewController.cs b/src/iOS.Extension/LoginListViewController.cs index 6a1306108..88c097bfe 100644 --- a/src/iOS.Extension/LoginListViewController.cs +++ b/src/iOS.Extension/LoginListViewController.cs @@ -29,7 +29,7 @@ namespace Bit.iOS.Extension AddBarButton.TintColor = ThemeHelpers.NavBarTextColor; CancelBarButton.TintColor = ThemeHelpers.NavBarTextColor; NavItem.Title = AppResources.Items; - if(!CanAutoFill()) + if (!CanAutoFill()) { CancelBarButton.Title = AppResources.Close; } @@ -45,7 +45,7 @@ namespace Bit.iOS.Extension public bool CanAutoFill() { - if(Context.ProviderType != Constants.UTTypeAppExtensionFillBrowserAction + if (Context.ProviderType != Constants.UTTypeAppExtensionFillBrowserAction && Context.ProviderType != Constants.UTTypeAppExtensionFillWebViewAction && Context.ProviderType != UTType.PropertyList) { @@ -67,9 +67,9 @@ namespace Bit.iOS.Extension public override void PrepareForSegue(UIStoryboardSegue segue, NSObject sender) { - if(segue.DestinationViewController is UINavigationController navController) + if (segue.DestinationViewController is UINavigationController navController) { - if(navController.TopViewController is LoginAddViewController addLoginController) + if (navController.TopViewController is LoginAddViewController addLoginController) { addLoginController.Context = Context; addLoginController.LoginListController = this; @@ -101,37 +101,37 @@ namespace Bit.iOS.Extension tableView.DeselectRow(indexPath, true); tableView.EndEditing(true); - if(Items == null || Items.Count() == 0) + if (Items == null || Items.Count() == 0) { _controller.PerformSegue("loginAddSegue", this); return; } var item = Items.ElementAt(indexPath.Row); - if(item == null) + if (item == null) { _controller.LoadingController.CompleteRequest(null, null); return; } - if(_controller.CanAutoFill() && !string.IsNullOrWhiteSpace(item.Password)) + if (_controller.CanAutoFill() && !string.IsNullOrWhiteSpace(item.Password)) { string totp = null; var storageService = ServiceContainer.Resolve("storageService"); var disableTotpCopy = storageService.GetAsync( Bit.Core.Constants.DisableAutoTotpCopyKey).GetAwaiter().GetResult(); - if(!disableTotpCopy.GetValueOrDefault(false)) + if (!disableTotpCopy.GetValueOrDefault(false)) { totp = GetTotpAsync(item).GetAwaiter().GetResult(); } _controller.LoadingController.CompleteUsernamePasswordRequest( item.Id, item.Username, item.Password, item.Fields, totp); } - else if(!string.IsNullOrWhiteSpace(item.Username) || !string.IsNullOrWhiteSpace(item.Password) || + else if (!string.IsNullOrWhiteSpace(item.Username) || !string.IsNullOrWhiteSpace(item.Password) || !string.IsNullOrWhiteSpace(item.Totp)) { var sheet = Dialogs.CreateActionSheet(item.Name, _controller); - if(!string.IsNullOrWhiteSpace(item.Username)) + if (!string.IsNullOrWhiteSpace(item.Username)) { sheet.AddAction(UIAlertAction.Create(AppResources.CopyUsername, UIAlertActionStyle.Default, a => { @@ -144,7 +144,7 @@ namespace Bit.iOS.Extension }); })); } - if(!string.IsNullOrWhiteSpace(item.Password)) + if (!string.IsNullOrWhiteSpace(item.Password)) { sheet.AddAction(UIAlertAction.Create(AppResources.CopyPassword, UIAlertActionStyle.Default, a => { @@ -158,13 +158,13 @@ namespace Bit.iOS.Extension }); })); } - if(!string.IsNullOrWhiteSpace(item.Totp)) + if (!string.IsNullOrWhiteSpace(item.Totp)) { sheet.AddAction(UIAlertAction.Create(AppResources.CopyTotp, UIAlertActionStyle.Default, async a => { var totp = await GetTotpAsync(item); - if(string.IsNullOrWhiteSpace(totp)) + if (string.IsNullOrWhiteSpace(totp)) { return; } diff --git a/src/iOS/AppDelegate.cs b/src/iOS/AppDelegate.cs index f808a46d4..558eebd01 100644 --- a/src/iOS/AppDelegate.cs +++ b/src/iOS/AppDelegate.cs @@ -59,27 +59,27 @@ namespace Bit.iOS _broadcasterService.Subscribe(nameof(AppDelegate), async (message) => { - if(message.Command == "scheduleLockTimer") + if (message.Command == "scheduleLockTimer") { LockTimer((int)message.Data); } - else if(message.Command == "cancelLockTimer") + else if (message.Command == "cancelLockTimer") { CancelLockTimer(); } - else if(message.Command == "startEventTimer") + else if (message.Command == "startEventTimer") { StartEventTimer(); } - else if(message.Command == "stopEventTimer") + else if (message.Command == "stopEventTimer") { var task = StopEventTimerAsync(); } - else if(message.Command == "updatedTheme") + else if (message.Command == "updatedTheme") { // ThemeManager.SetThemeStyle(message.Data as string); } - else if(message.Command == "copiedToClipboard") + else if (message.Command == "copiedToClipboard") { Device.BeginInvokeOnMainThread(() => @@ -87,50 +87,50 @@ namespace Bit.iOS var task = ClearClipboardTimerAsync(message.Data as Tuple); }); } - else if(message.Command == "listenYubiKeyOTP") + else if (message.Command == "listenYubiKeyOTP") { ListenYubiKey((bool)message.Data); } - else if(message.Command == "unlocked") + else if (message.Command == "unlocked") { var needsAutofillReplacement = await _storageService.GetAsync( Core.Constants.AutofillNeedsIdentityReplacementKey); - if(needsAutofillReplacement.GetValueOrDefault()) + if (needsAutofillReplacement.GetValueOrDefault()) { await ASHelpers.ReplaceAllIdentities(); } } - else if(message.Command == "showAppExtension") + else if (message.Command == "showAppExtension") { Device.BeginInvokeOnMainThread(() => ShowAppExtension((ExtensionPageViewModel)message.Data)); } - else if(message.Command == "showStatusBar") + else if (message.Command == "showStatusBar") { Device.BeginInvokeOnMainThread(() => UIApplication.SharedApplication.SetStatusBarHidden(!(bool)message.Data, false)); } - else if(message.Command == "syncCompleted") + else if (message.Command == "syncCompleted") { - if(message.Data is Dictionary data && data.ContainsKey("successfully")) + if (message.Data is Dictionary data && data.ContainsKey("successfully")) { var success = data["successfully"] as bool?; - if(success.GetValueOrDefault() && _deviceActionService.SystemMajorVersion() >= 12) + if (success.GetValueOrDefault() && _deviceActionService.SystemMajorVersion() >= 12) { await ASHelpers.ReplaceAllIdentities(); } } } - else if(message.Command == "addedCipher" || message.Command == "editedCipher") + else if (message.Command == "addedCipher" || message.Command == "editedCipher") { - if(_deviceActionService.SystemMajorVersion() >= 12) + if (_deviceActionService.SystemMajorVersion() >= 12) { - if(await ASHelpers.IdentitiesCanIncremental()) + if (await ASHelpers.IdentitiesCanIncremental()) { var cipherId = message.Data as string; - if(message.Command == "addedCipher" && !string.IsNullOrWhiteSpace(cipherId)) + if (message.Command == "addedCipher" && !string.IsNullOrWhiteSpace(cipherId)) { var identity = await ASHelpers.GetCipherIdentityAsync(cipherId); - if(identity == null) + if (identity == null) { return; } @@ -142,15 +142,15 @@ namespace Bit.iOS await ASHelpers.ReplaceAllIdentities(); } } - else if(message.Command == "deletedCipher") + else if (message.Command == "deletedCipher") { - if(_deviceActionService.SystemMajorVersion() >= 12) + if (_deviceActionService.SystemMajorVersion() >= 12) { - if(await ASHelpers.IdentitiesCanIncremental()) + if (await ASHelpers.IdentitiesCanIncremental()) { var identity = ASHelpers.ToCredentialIdentity( message.Data as Bit.Core.Models.View.CipherView); - if(identity == null) + if (identity == null) { return; } @@ -161,9 +161,9 @@ namespace Bit.iOS await ASHelpers.ReplaceAllIdentities(); } } - else if(message.Command == "loggedOut") + else if (message.Command == "loggedOut") { - if(_deviceActionService.SystemMajorVersion() >= 12) + if (_deviceActionService.SystemMajorVersion() >= 12) { await ASCredentialIdentityStore.SharedStore?.RemoveAllCredentialIdentitiesAsync(); } @@ -205,7 +205,7 @@ namespace Bit.iOS base.OnActivated(uiApplication); UIApplication.SharedApplication.ApplicationIconBadgeNumber = 0; var view = UIApplication.SharedApplication.KeyWindow.ViewWithTag(4321); - if(view != null) + if (view != null) { view.RemoveFromSuperview(); UIApplication.SharedApplication.SetStatusBarHidden(false, false); @@ -253,7 +253,7 @@ namespace Bit.iOS public void InitApp() { - if(ServiceContainer.RegisteredServices.Count > 0) + if (ServiceContainer.RegisteredServices.Count > 0) { return; } @@ -297,12 +297,12 @@ namespace Bit.iOS private void ListenYubiKey(bool listen) { - if(_deviceActionService.SupportsNfc()) + if (_deviceActionService.SupportsNfc()) { _nfcSession?.InvalidateSession(); _nfcSession?.Dispose(); _nfcSession = null; - if(listen) + if (listen) { _nfcSession = new NFCNdefReaderSession(_nfcDelegate, null, true) { @@ -315,7 +315,7 @@ namespace Bit.iOS private void LockTimer(int lockOptionMinutes) { - if(_lockBackgroundTaskId > 0) + if (_lockBackgroundTaskId > 0) { UIApplication.SharedApplication.EndBackgroundTask(_lockBackgroundTaskId); _lockBackgroundTaskId = 0; @@ -340,7 +340,7 @@ namespace Bit.iOS _lockTimer?.Invalidate(); _lockTimer?.Dispose(); _lockTimer = null; - if(_lockBackgroundTaskId > 0) + if (_lockBackgroundTaskId > 0) { UIApplication.SharedApplication.EndBackgroundTask(_lockBackgroundTaskId); _lockBackgroundTaskId = 0; @@ -355,7 +355,7 @@ namespace Bit.iOS _lockTimer?.Invalidate(); _lockTimer?.Dispose(); _lockTimer = null; - if(_lockBackgroundTaskId > 0) + if (_lockBackgroundTaskId > 0) { UIApplication.SharedApplication.EndBackgroundTask(_lockBackgroundTaskId); _lockBackgroundTaskId = 0; @@ -364,24 +364,24 @@ namespace Bit.iOS private async Task ClearClipboardTimerAsync(Tuple data) { - if(data.Item3) + if (data.Item3) { return; } var clearMs = data.Item2; - if(clearMs == null) + if (clearMs == null) { var clearSeconds = await _storageService.GetAsync(Constants.ClearClipboardKey); - if(clearSeconds != null) + if (clearSeconds != null) { clearMs = clearSeconds.Value * 1000; } } - if(clearMs == null) + if (clearMs == null) { return; } - if(_clipboardBackgroundTaskId > 0) + if (_clipboardBackgroundTaskId > 0) { UIApplication.SharedApplication.EndBackgroundTask(_clipboardBackgroundTaskId); _clipboardBackgroundTaskId = 0; @@ -401,14 +401,14 @@ namespace Bit.iOS Device.BeginInvokeOnMainThread(() => { var changeNow = UIPasteboard.General.ChangeCount; - if(changeNow == 0 || lastClipboardChangeCount == changeNow) + if (changeNow == 0 || lastClipboardChangeCount == changeNow) { UIPasteboard.General.String = string.Empty; } _clipboardTimer?.Invalidate(); _clipboardTimer?.Dispose(); _clipboardTimer = null; - if(_clipboardBackgroundTaskId > 0) + if (_clipboardBackgroundTaskId > 0) { UIApplication.SharedApplication.EndBackgroundTask(_clipboardBackgroundTaskId); _clipboardBackgroundTaskId = 0; @@ -432,7 +432,7 @@ namespace Bit.iOS } }; var modal = UIApplication.SharedApplication.KeyWindow.RootViewController.ModalViewController; - if(activityViewController.PopoverPresentationController != null) + if (activityViewController.PopoverPresentationController != null) { activityViewController.PopoverPresentationController.SourceView = modal.View; var frame = UIScreen.MainScreen.Bounds; @@ -461,7 +461,7 @@ namespace Bit.iOS _eventTimer?.Invalidate(); _eventTimer?.Dispose(); _eventTimer = null; - if(_eventBackgroundTaskId > 0) + if (_eventBackgroundTaskId > 0) { UIApplication.SharedApplication.EndBackgroundTask(_eventBackgroundTaskId); _eventBackgroundTaskId = 0; @@ -480,10 +480,10 @@ namespace Bit.iOS { var userDefaults = NSUserDefaults.StandardUserDefaults; var managedSettings = userDefaults.DictionaryForKey("com.apple.configuration.managed"); - if(managedSettings != null && managedSettings.Count > 0) + if (managedSettings != null && managedSettings.Count > 0) { var dict = new Dictionary(); - foreach(var setting in managedSettings) + foreach (var setting in managedSettings) { dict.Add(setting.Key.ToString(), setting.Value?.ToString()); } diff --git a/src/iOS/NFCReaderDelegate.cs b/src/iOS/NFCReaderDelegate.cs index d3b843d7c..116dcb765 100644 --- a/src/iOS/NFCReaderDelegate.cs +++ b/src/iOS/NFCReaderDelegate.cs @@ -19,9 +19,9 @@ namespace Bit.iOS public override void DidDetect(NFCNdefReaderSession session, NFCNdefMessage[] messages) { var results = new List(); - foreach(var message in messages) + foreach (var message in messages) { - foreach(var record in message.Records) + foreach (var record in message.Records) { try { @@ -31,10 +31,10 @@ namespace Bit.iOS } } - foreach(var result in results) + foreach (var result in results) { var matches = _otpPattern.Matches(result); - if(matches.Count > 0 && matches[0].Groups.Count > 1) + if (matches.Count > 0 && matches[0].Groups.Count > 1) { var otp = matches[0].Groups[1].ToString(); _callback.Invoke(true, otp); diff --git a/src/iOS/Renderers/CustomButtonRenderer.cs b/src/iOS/Renderers/CustomButtonRenderer.cs index 6d0569235..4914d5c56 100644 --- a/src/iOS/Renderers/CustomButtonRenderer.cs +++ b/src/iOS/Renderers/CustomButtonRenderer.cs @@ -13,7 +13,7 @@ namespace Bit.iOS.Renderers protected override void OnElementChanged(ElementChangedEventArgs