Exemplo n.º 1
0
        public static async Task <List <FilledItem> > GetFillItemsAsync(Parser parser, ICipherService service)
        {
            var items = new List <FilledItem>();

            if (parser.FieldCollection.FillableForLogin)
            {
                var ciphers = await service.GetAllAsync(parser.Uri);

                if (ciphers.Item1.Any() || ciphers.Item2.Any())
                {
                    var allCiphers = ciphers.Item1.ToList();
                    allCiphers.AddRange(ciphers.Item2.ToList());
                    foreach (var cipher in allCiphers)
                    {
                        items.Add(new FilledItem(cipher));
                    }
                }
            }
            else if (parser.FieldCollection.FillableForCard)
            {
                var ciphers = await service.GetAllAsync();

                foreach (var cipher in ciphers.Where(c => c.Type == CipherType.Card))
                {
                    items.Add(new FilledItem(cipher));
                }
            }

            return(items);
        }
        public async Task LoadItemsAsync(bool urlFilter = true, string searchFilter = null)
        {
            var combinedLogins = new List <Cipher>();

            if (urlFilter)
            {
                var logins = await _cipherService.GetAllAsync(_context.UrlString);

                if (logins?.Item1 != null)
                {
                    combinedLogins.AddRange(logins.Item1);
                }
                if (logins?.Item2 != null)
                {
                    combinedLogins.AddRange(logins.Item2);
                }
            }
            else
            {
                var logins = await _cipherService.GetAllAsync();

                combinedLogins.AddRange(logins);
            }

            _allItems = combinedLogins
                        .Where(c => c.Type == App.Enums.CipherType.Login)
                        .Select(s => new CipherViewModel(s))
                        .OrderBy(s => s.Name)
                        .ThenBy(s => s.Username)
                        .ToList() ?? new List <CipherViewModel>();
            FilterResults(searchFilter, new CancellationToken());
        }
Exemplo n.º 3
0
        private CancellationTokenSource FetchAndLoadVault()
        {
            var cts = new CancellationTokenSource();

            if (PresentationSections.Count > 0 && _syncService.SyncInProgress)
            {
                return(cts);
            }

            _filterResultsCancellationTokenSource?.Cancel();

            Task.Run(async() =>
            {
                IEnumerable <Models.Cipher> ciphers;
                if (_folder || !string.IsNullOrWhiteSpace(_folderId))
                {
                    ciphers = await _cipherService.GetAllByFolderAsync(_folderId);
                }
                else if (!string.IsNullOrWhiteSpace(_collectionId))
                {
                    ciphers = await _cipherService.GetAllByCollectionAsync(_collectionId);
                }
                else if (_favorites)
                {
                    ciphers = await _cipherService.GetAllAsync(true);
                }
                else
                {
                    ciphers = await _cipherService.GetAllAsync();
                }

                Ciphers = ciphers
                          .Select(s => new Cipher(s, _appSettingsService))
                          .OrderBy(s =>
                {
                    if (string.IsNullOrWhiteSpace(s.Name))
                    {
                        return(2);
                    }

                    return(s.Name.Length > 0 && Char.IsDigit(s.Name[0]) ? 0 : (Char.IsLetter(s.Name[0]) ? 1 : 2));
                })
                          .ThenBy(s => s.Name)
                          .ThenBy(s => s.Subtitle)
                          .ToArray();

                try
                {
                    FilterResults(Search.Text, cts.Token);
                }
                catch (OperationCanceledException) { }
            }, cts.Token);

            return(cts);
        }
Exemplo n.º 4
0
            public async Task LoadItemsAsync()
            {
                var combinedLogins = new List <Cipher>();

                var logins = await _cipherService.GetAllAsync(_context.UrlString);

                if (logins?.Item1 != null)
                {
                    combinedLogins.AddRange(logins.Item1);
                }
                if (logins?.Item2 != null)
                {
                    combinedLogins.AddRange(logins.Item2);
                }

                _tableItems = combinedLogins.Select(s => new CipherViewModel(s))
                              .OrderBy(s => s.Name)
                              .ThenBy(s => s.Username)
                              .ToList() ?? new List <CipherViewModel>();
            }
Exemplo n.º 5
0
        public static async Task ReplaceAllIdentities(ICipherService cipherService)
        {
            if (await AutofillEnabled())
            {
                var identities = new List <ASPasswordCredentialIdentity>();
                var ciphers    = await cipherService.GetAllAsync();

                foreach (var cipher in ciphers)
                {
                    var identity = ToCredentialIdentity(cipher);
                    if (identity != null)
                    {
                        identities.Add(identity);
                    }
                }
                if (identities.Any())
                {
                    await ASCredentialIdentityStore.SharedStore.ReplaceCredentialIdentitiesAsync(identities.ToArray());
                }
            }
        }
Exemplo n.º 6
0
        protected async override void OnAppearing()
        {
            base.OnAppearing();
            if (_syncService.SyncInProgress)
            {
                IsBusy = true;
            }

            _broadcasterService.Subscribe(_pageName, async(message) =>
            {
                if (message.Command == "syncStarted")
                {
                    Device.BeginInvokeOnMainThread(() => IsBusy = true);
                }
                else if (message.Command == "syncCompleted")
                {
                    await Task.Delay(500);
                    Device.BeginInvokeOnMainThread(() =>
                    {
                        IsBusy = false;
                        if (_vm.LoadedOnce)
                        {
                            var task = _vm.LoadAsync();
                        }
                    });
                }
            });

            var migratedFromV1 = await _storageService.GetAsync <bool?>(Constants.MigratedFromV1);

            await LoadOnAppearedAsync(_mainLayout, false, async() =>
            {
                if (!_syncService.SyncInProgress || (await _cipherService.GetAllAsync()).Any())
                {
                    try
                    {
                        await _vm.LoadAsync();
                    }
                    catch (Exception e) when(e.Message.Contains("No key."))
                    {
                        await Task.Delay(1000);
                        await _vm.LoadAsync();
                    }
                }
                else
                {
                    await Task.Delay(5000);
                    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() &&
                    !_vm.HasCiphers &&
                    Xamarin.Essentials.Connectivity.NetworkAccess != Xamarin.Essentials.NetworkAccess.None)
                {
                    var triedV1ReSync = await _storageService.GetAsync <bool?>(Constants.TriedV1Resync);
                    if (!triedV1ReSync.GetValueOrDefault())
                    {
                        await _storageService.SaveAsync(Constants.TriedV1Resync, true);
                        await _syncService.FullSyncAsync(true);
                    }
                }
                await ShowPreviousPageAsync();
                AdjustToolbar();
            }, _mainContent);

            if (!_vm.MainPage)
            {
                return;
            }

            // Push registration
            var lastPushRegistration = await _storageService.GetAsync <DateTime?>(Constants.PushLastRegistrationDateKey);

            lastPushRegistration = lastPushRegistration.GetValueOrDefault(DateTime.MinValue);
            if (Device.RuntimePlatform == Device.iOS)
            {
                var pushPromptShow = await _storageService.GetAsync <bool?>(Constants.PushInitialPromptShownKey);

                if (!pushPromptShow.GetValueOrDefault(false))
                {
                    await _storageService.SaveAsync(Constants.PushInitialPromptShownKey, true);
                    await DisplayAlert(AppResources.EnableAutomaticSyncing, AppResources.PushNotificationAlert,
                                       AppResources.OkGotIt);
                }
                if (!pushPromptShow.GetValueOrDefault(false) ||
                    DateTime.UtcNow - lastPushRegistration > TimeSpan.FromDays(1))
                {
                    await _pushNotificationService.RegisterAsync();
                }
            }
            else if (Device.RuntimePlatform == Device.Android)
            {
                if (DateTime.UtcNow - lastPushRegistration > TimeSpan.FromDays(1))
                {
                    await _pushNotificationService.RegisterAsync();
                }
                if (!_deviceActionService.AutofillAccessibilityServiceRunning() &&
                    !_deviceActionService.AutofillServiceEnabled())
                {
                    if (migratedFromV1.GetValueOrDefault())
                    {
                        var migratedFromV1AutofillPromptShown = await _storageService.GetAsync <bool?>(
                            Constants.MigratedFromV1AutofillPromptShown);

                        if (!migratedFromV1AutofillPromptShown.GetValueOrDefault())
                        {
                            await DisplayAlert(AppResources.Autofill,
                                               AppResources.AutofillServiceNotEnabled, AppResources.Ok);
                        }
                    }
                }
                await _storageService.SaveAsync(Constants.MigratedFromV1AutofillPromptShown, true);
            }
        }
Exemplo n.º 7
0
        protected async override void OnAppearing()
        {
            base.OnAppearing();
            if (_syncService.SyncInProgress)
            {
                IsBusy = true;
            }

            _accountAvatar?.OnAppearing();
            if (_vm.MainPage)
            {
                _vm.AvatarImageSource = await GetAvatarImageSourceAsync();
            }

            _broadcasterService.Subscribe(_pageName, async(message) =>
            {
                try
                {
                    if (message.Command == "syncStarted")
                    {
                        Device.BeginInvokeOnMainThread(() => IsBusy = true);
                    }
                    else if (message.Command == "syncCompleted")
                    {
                        await Task.Delay(500);
                        Device.BeginInvokeOnMainThread(() =>
                        {
                            IsBusy = false;
                            if (_vm.LoadedOnce)
                            {
                                var task = _vm.LoadAsync();
                            }
                        });
                    }
                }
                catch (Exception ex)
                {
                    LoggerHelper.LogEvenIfCantBeResolved(ex);
                }
            });

            await LoadOnAppearedAsync(_mainLayout, false, async() =>
            {
                if (!_syncService.SyncInProgress || (await _cipherService.GetAllAsync()).Any())
                {
                    try
                    {
                        await _vm.LoadAsync();
                    }
                    catch (Exception e) when(e.Message.Contains("No key."))
                    {
                        await Task.Delay(1000);
                        await _vm.LoadAsync();
                    }
                }
                else
                {
                    await Task.Delay(5000);
                    if (!_vm.Loaded)
                    {
                        await _vm.LoadAsync();
                    }
                }
                await ShowPreviousPageAsync();
                AdjustToolbar();
            }, _mainContent);

            if (!_vm.MainPage)
            {
                return;
            }

            // Push registration
            var lastPushRegistration = await _stateService.GetPushLastRegistrationDateAsync();

            lastPushRegistration = lastPushRegistration.GetValueOrDefault(DateTime.MinValue);
            if (Device.RuntimePlatform == Device.iOS)
            {
                var pushPromptShow = await _stateService.GetPushInitialPromptShownAsync();

                if (!pushPromptShow.GetValueOrDefault(false))
                {
                    await _stateService.SetPushInitialPromptShownAsync(true);
                    await DisplayAlert(AppResources.EnableAutomaticSyncing, AppResources.PushNotificationAlert,
                                       AppResources.OkGotIt);
                }
                if (!pushPromptShow.GetValueOrDefault(false) ||
                    DateTime.UtcNow - lastPushRegistration > TimeSpan.FromDays(1))
                {
                    await _pushNotificationService.RegisterAsync();
                }
            }
            else if (Device.RuntimePlatform == Device.Android)
            {
                if (DateTime.UtcNow - lastPushRegistration > TimeSpan.FromDays(1))
                {
                    await _pushNotificationService.RegisterAsync();
                }
            }
        }
Exemplo n.º 8
0
        private async Task SyncCiphersAsync(IDictionary <string, CipherResponse> serverCiphers)
        {
            if (!_authService.IsAuthenticated)
            {
                return;
            }

            var localCiphers = (await _cipherService.GetAllAsync()
                                .ConfigureAwait(false))
                               .GroupBy(s => s.Id)
                               .Select(s => s.First())
                               .ToDictionary(s => s.Id);

            var localAttachments = (await _attachmentRepository.GetAllByUserIdAsync(_authService.UserId)
                                    .ConfigureAwait(false))
                                   .GroupBy(a => a.LoginId)
                                   .ToDictionary(g => g.Key);

            var cipherCollections = new List <CipherCollectionData>();

            foreach (var serverCipher in serverCiphers)
            {
                if (!_authService.IsAuthenticated)
                {
                    return;
                }

                var collectionForThisCipher = serverCipher.Value.CollectionIds?.Select(cid => new CipherCollectionData
                {
                    CipherId     = serverCipher.Value.Id,
                    CollectionId = cid,
                    UserId       = _authService.UserId
                }).ToList();

                if (collectionForThisCipher != null && collectionForThisCipher.Any())
                {
                    cipherCollections.AddRange(collectionForThisCipher);
                }

                try
                {
                    var localCipher = localCiphers.ContainsKey(serverCipher.Value.Id) ?
                                      localCiphers[serverCipher.Value.Id] : null;

                    var data = new CipherData(serverCipher.Value, _authService.UserId);
                    await _cipherService.UpsertDataAsync(data).ConfigureAwait(false);

                    if (serverCipher.Value.Attachments != null)
                    {
                        var attachmentData = serverCipher.Value.Attachments.Select(a => new AttachmentData(a, data.Id));
                        await _cipherService.UpsertAttachmentDataAsync(attachmentData).ConfigureAwait(false);
                    }

                    if (localCipher != null && localAttachments != null && localAttachments.ContainsKey(localCipher.Id))
                    {
                        foreach (var attachment in localAttachments[localCipher.Id]
                                 .Where(a => !serverCipher.Value.Attachments.Any(sa => sa.Id == a.Id)))
                        {
                            try
                            {
                                await _cipherService.DeleteAttachmentDataAsync(attachment.Id).ConfigureAwait(false);
                            }
                            catch (SQLite.SQLiteException) { }
                        }
                    }
                }
                catch (SQLite.SQLiteException) { }
            }

            foreach (var cipher in localCiphers.Where(local => !serverCiphers.ContainsKey(local.Key)))
            {
                try
                {
                    await _cipherService.DeleteDataAsync(cipher.Value.Id).ConfigureAwait(false);
                }
                catch (SQLite.SQLiteException) { }
            }

            try
            {
                await _cipherCollectionRepository.DeleteByUserIdAsync(_authService.UserId).ConfigureAwait(false);
            }
            catch (SQLite.SQLiteException) { }

            foreach (var cipherCollection in cipherCollections)
            {
                try
                {
                    await _cipherCollectionRepository.InsertAsync(cipherCollection).ConfigureAwait(false);
                }
                catch (SQLite.SQLiteException) { }
            }
        }